diff --git a/.gitignore b/.gitignore index 53eaa2196..b99f352e7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target **/*.rs.bk +.something/ diff --git a/node_modules/.bin/he b/node_modules/.bin/he new file mode 120000 index 000000000..2a8eb5e0c --- /dev/null +++ b/node_modules/.bin/he @@ -0,0 +1 @@ +../he/bin/he \ No newline at end of file diff --git a/node_modules/.bin/http-server b/node_modules/.bin/http-server new file mode 120000 index 000000000..cb3b6668b --- /dev/null +++ b/node_modules/.bin/http-server @@ -0,0 +1 @@ +../http-server/bin/http-server \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 000000000..fbb7ee0ee --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 120000 index 000000000..e2be547bc --- /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/opener b/node_modules/.bin/opener new file mode 120000 index 000000000..891b847f9 --- /dev/null +++ b/node_modules/.bin/opener @@ -0,0 +1 @@ +../opener/bin/opener-bin.js \ No newline at end of file diff --git a/node_modules/.bin/playwright b/node_modules/.bin/playwright new file mode 120000 index 000000000..c30d07fab --- /dev/null +++ b/node_modules/.bin/playwright @@ -0,0 +1 @@ +../@playwright/test/cli.js \ No newline at end of file diff --git a/node_modules/.bin/playwright-core b/node_modules/.bin/playwright-core new file mode 120000 index 000000000..08d6c281e --- /dev/null +++ b/node_modules/.bin/playwright-core @@ -0,0 +1 @@ +../playwright-core/cli.js \ No newline at end of file diff --git a/node_modules/.bin/rolldown b/node_modules/.bin/rolldown new file mode 120000 index 000000000..7725012ce --- /dev/null +++ b/node_modules/.bin/rolldown @@ -0,0 +1 @@ +../rolldown/bin/cli.mjs \ No newline at end of file diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 120000 index 000000000..6d1e3beaf --- /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/vitest b/node_modules/.bin/vitest new file mode 120000 index 000000000..227349794 --- /dev/null +++ b/node_modules/.bin/vitest @@ -0,0 +1 @@ +../vitest/vitest.mjs \ No newline at end of file diff --git a/node_modules/.bin/why-is-node-running b/node_modules/.bin/why-is-node-running new file mode 120000 index 000000000..f08a594c7 --- /dev/null +++ b/node_modules/.bin/why-is-node-running @@ -0,0 +1 @@ +../why-is-node-running/cli.js \ 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 000000000..3b480599b --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,1451 @@ +{ + "name": "workspace", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@axe-core/playwright": { + "version": "4.11.3", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.11.3.tgz", + "integrity": "sha512-h/kfksv4F0cVIDlKpT4700OehdRgpvuVskuQ2nb7/JmtWUXpe9ftHAPtwyXGvVSsa6SJ64A9ER7Zrzc/sIvC4w==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "axe-core": "~4.11.4" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@oxc-project/types": { + "version": "0.127.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.127.0.tgz", + "integrity": "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@playwright/test": { + "version": "1.59.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz", + "integrity": "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==", + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.59.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.17.tgz", + "integrity": "sha512-cLnjV3xfo7KslbU41Z7z8BH/E1y5mzUYzAqih1d1MDaIGZRCMqTijqLv76/P7fyHuvUcfGsIpqCdddbxLLK9rA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.17.tgz", + "integrity": "sha512-0phclDw1spsL7dUB37sIARuis2tAgomCJXAHZlpt8PXZ4Ba0dRP1e+66lsRqrfhISeN9bEGNjQs+T/Fbd7oYGw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.17.tgz", + "integrity": "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.5.tgz", + "integrity": "sha512-PWBaRY5JoKuRnHlUHfpV/KohFylaDZTupcXN1H9vYryNLOnitSw60Mw9IAE2r67NbwwzBw/Cc/8q9BK3kIX8Kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.5", + "@vitest/utils": "4.1.5", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.5.tgz", + "integrity": "sha512-/x2EmFC4mT4NNzqvC3fmesuV97w5FC903KPmey4gsnJiMQ3Be1IlDKVaDaG8iqaLFHqJ2FVEkxZk5VmeLjIItw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.5", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.5.tgz", + "integrity": "sha512-7I3q6l5qr03dVfMX2wCo9FxwSJbPdwKjy2uu/YPpU3wfHvIL4QHwVRp57OfGrDFeUJ8/8QdfBKIV12FTtLn00g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.5.tgz", + "integrity": "sha512-2D+o7Pr82IEO46YPpoA/YU0neeyr6FTerQb5Ro7BUnBuv6NQtT/kmVnczngiMEBhzgqz2UZYl5gArejsyERDSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.5", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.5.tgz", + "integrity": "sha512-zypXEt4KH/XgKGPUz4eC2AvErYx0My5hfL8oDb1HzGFpEk1P62bxSohdyOmvz+d9UJwanI68MKwr2EquOaOgMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.5", + "@vitest/utils": "4.1.5", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.5.tgz", + "integrity": "sha512-2lNOsh6+R2Idnf1TCZqSwYlKN2E/iDlD8sgU59kYVl+OMDmvldO1VDk39smRfpUNwYpNRVn3w4YfuC7KfbBnkQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.5.tgz", + "integrity": "sha512-76wdkrmfXfqGjueGgnb45ITPyUi1ycZ4IHgC2bhPDUfWHklY/q3MdLOAB+TF1e6xfl8NxNY0ZYaPCFNWSsw3Ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.5", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "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, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/axe-core": { + "version": "4.11.4", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.4.tgz", + "integrity": "sha512-KunSNx+TVpkAw/6ULfhnx+HWRecjqZGTOyquAoWHYLRSdK1tB5Ihce1ZW+UY3fj33bYAFWPu7W/GRSmmrCGuxA==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "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, + "license": "MIT", + "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/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, + "license": "MIT", + "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, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", + "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "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, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", + "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-server": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.1.tgz", + "integrity": "sha512-+cbxadF40UXd9T01zUHgA+rlo2Bg1Srer4+B4NwIHdaGxAGGv59nYRnGGDJ9LBk7alpS0US+J+bLLdQOOkJq4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "basic-auth": "^2.0.1", + "chalk": "^4.1.2", + "corser": "^2.0.1", + "he": "^1.2.0", + "html-encoding-sniffer": "^3.0.0", + "http-proxy": "^1.18.1", + "mime": "^1.6.0", + "minimist": "^1.2.6", + "opener": "^1.5.1", + "portfinder": "^1.0.28", + "secure-compare": "3.0.1", + "union": "~0.5.0", + "url-join": "^4.0.1" + }, + "bin": { + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.12", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "dev": true, + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.59.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz", + "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.59.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.59.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz", + "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/portfinder": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", + "integrity": "sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "async": "^3.2.6", + "debug": "^4.3.6" + }, + "engines": { + "node": ">= 10.12" + } + }, + "node_modules/postcss": { + "version": "8.5.13", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz", + "integrity": "sha512-qif0+jGGZoLWdHey3UFHHWP0H7Gbmsk8T5VEqyYFbWqPr1XqvLGBbk/sl8V5exGmcYJklJOhOQq1pV9IcsiFag==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.17", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.17.tgz", + "integrity": "sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.127.0", + "@rolldown/pluginutils": "1.0.0-rc.17" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.17", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.17", + "@rolldown/binding-darwin-x64": "1.0.0-rc.17", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.17", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.17", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.17", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.17", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.17", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.17", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.17", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.17", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.17" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "dev": true, + "license": "MIT" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", + "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==", + "dev": true, + "license": "MIT" + }, + "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, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.2.tgz", + "integrity": "sha512-dAqSqE/RabpBKI8+h26GfLq6Vb3JVXs30XYQjdMjaj/c2tS8IYYMbIzP599KtRj7c57/wYApb3QjgRgXmrCukA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dev": true, + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/url-join": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", + "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.0.10", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.10.tgz", + "integrity": "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.10", + "rolldown": "1.0.0-rc.17", + "tinyglobby": "^0.2.16" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.5.tgz", + "integrity": "sha512-9Xx1v3/ih3m9hN+SbfkUyy0JAs72ap3r7joc87XL6jwF0jGg6mFBvQ1SrwaX+h8BlkX6Hz9shdd1uo6AF+ZGpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.5", + "@vitest/mocker": "4.1.5", + "@vitest/pretty-format": "4.1.5", + "@vitest/runner": "4.1.5", + "@vitest/snapshot": "4.1.5", + "@vitest/spy": "4.1.5", + "@vitest/utils": "4.1.5", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.5", + "@vitest/browser-preview": "4.1.5", + "@vitest/browser-webdriverio": "4.1.5", + "@vitest/coverage-istanbul": "4.1.5", + "@vitest/coverage-v8": "4.1.5", + "@vitest/ui": "4.1.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/whatwg-encoding": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", + "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + } + } +} diff --git a/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json b/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json new file mode 100644 index 000000000..9474a5d66 --- /dev/null +++ b/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json @@ -0,0 +1 @@ +{"version":"4.1.5","results":[[":tests/integration/quick_start.spec.ts",{"duration":4.270094999999998,"failed":false}]]} \ No newline at end of file diff --git a/node_modules/@axe-core/playwright/LICENSE b/node_modules/@axe-core/playwright/LICENSE new file mode 100644 index 000000000..f0e5c79e1 --- /dev/null +++ b/node_modules/@axe-core/playwright/LICENSE @@ -0,0 +1,362 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/node_modules/@axe-core/playwright/README.md b/node_modules/@axe-core/playwright/README.md new file mode 100644 index 000000000..65dc22848 --- /dev/null +++ b/node_modules/@axe-core/playwright/README.md @@ -0,0 +1,155 @@ +# @axe-core/playwright + +> Provides a chainable axe API for playwright and automatically injects into all frames + +This package does not follow Semantic Versioning (SemVer) but instead uses the major and minor version (but not patch version) of axe-core that the package uses. For example, if the API version is v4.7.2, then the axe-core version used by the package will be v4.7.x. The patch version of this package may include bug fixes and new API features but will not introduce breaking changes. + +## Getting Started + +Install [Node.js](https://docs.npmjs.com/getting-started/installing-node) if you haven't already. + +Install Playwright: `npm install playwright` + +Install @axe-core/playwright: `npm install @axe-core/playwright` + +## Usage + +This module uses a chainable API to assist in injecting, configuring, and analyzing axe with [Playwright](https://playwright.dev/). As such, it is required to pass an instance of Playwright. + +Here is an example of a script that will drive Playwright to a page, perform an analysis, and then log results to the console. + +```js +const { AxeBuilder } = require('@axe-core/playwright'); +const playwright = require('playwright'); + +(async () => { + const browser = await playwright.chromium.launch({ headless: true }); + const context = await browser.newContext(); + const page = await context.newPage(); + await page.goto('https://dequeuniversity.com/demo/mars/'); + + try { + const results = await new AxeBuilder({ page }).analyze(); + console.log(results); + } catch (e) { + // do something with the error + } + + await browser.close(); +})(); +``` + +## AxeBuilder({ page: Playwright.Page }) + +Constructor for the AxeBuilder helper. You must pass an instance of Playwright as the first argument. + +```js +const builder = new AxeBuilder({ page }); +``` + +### AxeBuilder#analyze(): Promise + +Performs analysis and passes any encountered error and/or the result object. + +```js +new AxeBuilder({ page }) + .analyze() + .then(results => { + console.log(results); + }) + .catch(e => { + // Do something with error + }); +``` + +### AxeBuilder#include(selector: String | String[]) + +Adds a CSS selector to the list of elements to include in analysis + +```js +new AxeBuilder({ page }).include('.results-panel'); +``` + +Method chaining is also available, add multiple CSS selectors to the list of elements to include in analysis + +```js +new AxeBuilder({ page }) + .include('.selector-one') + .include('.selector-two') + .include('.selector-three'); +``` + +Note: arrays with more than one index when passing multiple CSS selectors are not currently supported example: ` .include(['#foo', '#bar', '#baz'])` + +### AxeBuilder#exclude(selector: String | String[]) + +Add a CSS selector to the list of elements to exclude from analysis + +```js +new AxeBuilder({ page }).exclude('.another-element'); +``` + +Method chaining is also available, add multiple CSS selectors to the list of elements to exclude from analysis + +```js +new AxeBuilder({ page }) + .exclude('.selector-one') + .exclude('.selector-two') + .exclude('.selector-three'); +``` + +Note: arrays with more than one index when passing multiple CSS selectors are not currently supported example: ` .exclude(['#foo', '#bar', '#baz'])` + +### AxeBuilder#options(options: [axe.RunOptions](https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter)) + +Specifies options to be used by `axe.run`. Will override any other configured options. including calls to `AxeBuilder#withRules()` and `AxeBuilder#withTags()`. See [axe-core API documentation](https://github.com/dequelabs/axe-core/blob/master/doc/API.md) for information on its structure. + +```js +new AxeBuilder({ page }).options({ checks: { 'valid-lang': ['orcish'] } }); +``` + +### AxeBuilder#withRules(rules: String|Array) + +Limits analysis to only those with the specified rule IDs. Accepts a String of a single rule ID or an Array of multiple rule IDs. Subsequent calls to `AxeBuilder#options`, `AxeBuilder#withRules` or `AxeBuilder#withRules` will override specified options. + +```js +new AxeBuilder({ page }).withRules('html-lang'); +``` + +```js +new AxeBuilder({ page }).withRules(['html-lang', 'image-alt']); +``` + +### AxeBuilder#withTags(tags: String|Array) + +Limits analysis to only those with the specified rule IDs. Accepts a String of a single tag or an Array of multiple tags. Subsequent calls to `AxeBuilder#options`, `AxeBuilder#withRules` or `AxeBuilder#withRules` will override specified options. + +```js +new AxeBuilder({ page }).withTags('wcag2a'); +``` + +```js +new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa']); +``` + +### AxeBuilder#disableRules(rules: String|Array) + +Skips verification of the rules provided. Accepts a String of a single rule ID or an Array of multiple rule IDs. Subsequent calls to `AxeBuilder#options`, `AxeBuilder#disableRules` will override specified options. + +```js +new AxeBuilder({ page }).disableRules('color-contrast'); +``` + +### AxeBuilder#setLegacyMode(legacyMode: boolean = true) + +Set the frame testing method to "legacy mode". In this mode, axe will not open a blank page in which to aggregate its results. This can be used in an environment where opening a blank page is causes issues. + +With legacy mode turned on, axe will fall back to its test solution prior to the 4.3 release, but with cross-origin frame testing disabled. The `frame-tested` rule will report which frames were untested. + +**Important** Use of `.setLegacyMode()` is a last resort. If you find there is no other solution, please [report this as an issue](https://github.com/dequelabs/axe-core-npm/issues/). + +```js +const axe = new AxeBuilder({ page }).setLegacyMode(); +const result = await axe.analyze(); +axe.setLegacyMode(false); // Disables legacy mode +``` diff --git a/node_modules/@axe-core/playwright/dist/index.d.mts b/node_modules/@axe-core/playwright/dist/index.d.mts new file mode 100644 index 000000000..1a0addc02 --- /dev/null +++ b/node_modules/@axe-core/playwright/dist/index.d.mts @@ -0,0 +1,34 @@ +import { SerialFrameSelector, RunOptions, AxeResults } from 'axe-core'; +import { Page } from 'playwright-core'; + +interface AxePlaywrightParams { + page: Page; + axeSource?: string; +} + +declare class AxeBuilder { + private page; + private includes; + private excludes; + private option; + private axeSource; + private legacyMode; + private errorUrl; + constructor({ page, axeSource }: AxePlaywrightParams); + include(selector: SerialFrameSelector): this; + exclude(selector: SerialFrameSelector): this; + options(options: RunOptions): this; + withRules(rules: string | string[]): this; + withTags(tags: string | string[]): this; + disableRules(rules: string | string[]): this; + setLegacyMode(legacyMode?: boolean): this; + analyze(): Promise; + private inject; + private script; + private runLegacy; + private runPartialRecursive; + private finishRun; + private axeConfigure; +} + +export { AxeBuilder, AxeBuilder as default }; diff --git a/node_modules/@axe-core/playwright/dist/index.d.ts b/node_modules/@axe-core/playwright/dist/index.d.ts new file mode 100644 index 000000000..1a0addc02 --- /dev/null +++ b/node_modules/@axe-core/playwright/dist/index.d.ts @@ -0,0 +1,34 @@ +import { SerialFrameSelector, RunOptions, AxeResults } from 'axe-core'; +import { Page } from 'playwright-core'; + +interface AxePlaywrightParams { + page: Page; + axeSource?: string; +} + +declare class AxeBuilder { + private page; + private includes; + private excludes; + private option; + private axeSource; + private legacyMode; + private errorUrl; + constructor({ page, axeSource }: AxePlaywrightParams); + include(selector: SerialFrameSelector): this; + exclude(selector: SerialFrameSelector): this; + options(options: RunOptions): this; + withRules(rules: string | string[]): this; + withTags(tags: string | string[]): this; + disableRules(rules: string | string[]): this; + setLegacyMode(legacyMode?: boolean): this; + analyze(): Promise; + private inject; + private script; + private runLegacy; + private runPartialRecursive; + private finishRun; + private axeConfigure; +} + +export { AxeBuilder, AxeBuilder as default }; diff --git a/node_modules/@axe-core/playwright/dist/index.js b/node_modules/@axe-core/playwright/dist/index.js new file mode 100644 index 000000000..99e7175ed --- /dev/null +++ b/node_modules/@axe-core/playwright/dist/index.js @@ -0,0 +1,400 @@ +"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( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + 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 index_exports = {}; +__export(index_exports, { + AxeBuilder: () => AxeBuilder, + default: () => AxeBuilder +}); +module.exports = __toCommonJS(index_exports); +var import_assert = __toESM(require("assert")); +var import_axe_core = __toESM(require("axe-core")); + +// src/utils.ts +var normalizeContext = (includes, excludes) => { + const base = { + exclude: [], + include: [] + }; + if (excludes.length && Array.isArray(base.exclude)) { + base.exclude.push(...excludes); + } + if (includes.length) { + base.include = includes; + } + return base; +}; +var analyzePage = ({ + context, + options +}) => { + const axeCore = window.axe; + return axeCore.run(context || document, options || {}).then((results) => { + return { error: null, results }; + }).catch((err) => { + return { error: err.message, results: null }; + }); +}; + +// src/browser.ts +var axeGetFrameContexts = ({ + context +}) => { + return window.axe.utils.getFrameContexts(context); +}; +var axeShadowSelect = ({ + frameSelector +}) => { + return window.axe.utils.shadowSelect(frameSelector); +}; +var axeRunPartial = ({ + context, + options +}) => { + return window.axe.runPartial(context, options); +}; +var axeFinishRun = ({ + options +}) => { + return window.axe.finishRun(JSON.parse(window.partialResults), options); +}; +function chunkResultString(chunk) { + if (!window.partialResults) { + window.partialResults = ""; + } + window.partialResults += chunk; +} + +// src/AxePartialRunner.ts +var AxePartialRunner = class { + constructor(partialPromise, initiator = false) { + this.initiator = initiator; + this.partialPromise = caught(partialPromise); + } + partialPromise; + childRunners = []; + addChildResults(childResultRunner) { + this.childRunners.push(childResultRunner); + } + async getPartials() { + try { + const parentPartial = await this.partialPromise; + const childPromises = this.childRunners.map((childRunner) => { + return childRunner ? caught(childRunner.getPartials()) : [null]; + }); + const childPartials = (await Promise.all(childPromises)).flat(1); + return [parentPartial, ...childPartials]; + } catch (e) { + if (this.initiator) { + throw e; + } + return [null]; + } + } +}; +var caught = /* @__PURE__ */ ((f) => { + return (p) => (p.catch(f), p); +})(() => { +}); + +// src/index.ts +var { source } = import_axe_core.default; +var AxeBuilder = class { + page; + includes; + excludes; + option; + axeSource; + legacyMode = false; + errorUrl; + constructor({ page, axeSource }) { + this.page = page; + this.includes = []; + this.excludes = []; + this.option = {}; + this.axeSource = axeSource; + this.errorUrl = "https://github.com/dequelabs/axe-core-npm/blob/develop/packages/playwright/error-handling.md"; + } + /** + * Selector to include in analysis. + * This may be called any number of times. + * @param String selector + * @returns this + */ + include(selector) { + this.includes.push(selector); + return this; + } + /** + * Selector to exclude in analysis. + * This may be called any number of times. + * @param String selector + * @returns this + */ + exclude(selector) { + this.excludes.push(selector); + return this; + } + /** + * Set options to be passed into axe-core + * @param RunOptions options + * @returns AxeBuilder + */ + options(options) { + this.option = options; + return this; + } + /** + * Limit analysis to only the specified rules. + * Cannot be used with `AxeBuilder#withTags` + * @param String|Array rules + * @returns this + */ + withRules(rules) { + rules = Array.isArray(rules) ? rules : [rules]; + this.option = this.option || {}; + this.option.runOnly = { + type: "rule", + values: rules + }; + return this; + } + /** + * Limit analysis to only specified tags. + * Cannot be used with `AxeBuilder#withRules` + * @param String|Array tags + * @returns this + */ + withTags(tags) { + tags = Array.isArray(tags) ? tags : [tags]; + this.option = this.option || {}; + this.option.runOnly = { + type: "tag", + values: tags + }; + return this; + } + /** + * Set the list of rules to skip when running an analysis. + * @param String|Array rules + * @returns this + */ + disableRules(rules) { + rules = Array.isArray(rules) ? rules : [rules]; + this.option = this.option || {}; + this.option.rules = {}; + for (const rule of rules) { + this.option.rules[rule] = { enabled: false }; + } + return this; + } + /** + * Use frameMessenger with + * + * This disables use of axe.runPartial() which is called in each frame, and + * axe.finishRun() which is called in a blank page. This uses axe.run() instead, + * but with the restriction that cross-origin frames will not be tested. + */ + setLegacyMode(legacyMode = true) { + this.legacyMode = legacyMode; + return this; + } + /** + * Perform analysis and retrieve results. *Does not chain.* + * @return Promise + */ + async analyze() { + const context = normalizeContext(this.includes, this.excludes); + const { page } = this; + await page.evaluate(this.script()); + const runPartialDefined = await page.evaluate( + 'typeof window.axe.runPartial === "function"' + ); + let results; + if (!runPartialDefined || this.legacyMode) { + results = await this.runLegacy(context); + return results; + } + const partialResults = await this.runPartialRecursive( + page.mainFrame(), + context + ); + const partials = await partialResults.getPartials(); + try { + return await this.finishRun(partials); + } catch (error) { + throw new Error( + `${error.message} + Please check out ${this.errorUrl}` + ); + } + } + /** + * Injects `axe-core` into all frames. + * @param Page - playwright page object + * @returns Promise + */ + async inject(frames, shouldThrow) { + for (const iframe of frames) { + const race = new Promise((_, reject) => { + setTimeout(() => { + reject(new Error("Script Timeout")); + }, 1e3); + }); + const evaluate = iframe.evaluate(this.script()); + try { + await Promise.race([evaluate, race]); + await iframe.evaluate(await this.axeConfigure()); + } catch (err) { + if (shouldThrow) { + throw err; + } + } + } + } + /** + * Get axe-core source and configurations + * @returns String + */ + script() { + return this.axeSource || source; + } + async runLegacy(context) { + const frames = this.page.frames(); + await this.inject(frames); + const axeResults = await this.page.evaluate(analyzePage, { + context, + options: this.option + }); + if (axeResults.error) { + throw new Error(axeResults.error); + } + return axeResults.results; + } + /** + * Inject `axe-core` into each frame and run `axe.runPartial`. + * Because we need to inject axe into all frames all at once + * (to avoid any potential problems with the DOM becoming out-of-sync) + * but also need to not process results for any child frames if the parent + * frame throws an error (requirements of the data structure for `axe.finishRun`), + * we have to return a deeply nested array of Promises and then flatten + * the array once all Promises have finished, throwing out any nested Promises + * if the parent Promise is not fulfilled. + * @param frame - playwright frame object + * @param context - axe-core context object + * @returns Promise + */ + async runPartialRecursive(frame, context) { + const frameContexts = await frame.evaluate(axeGetFrameContexts, { + context + }); + const partialPromise = frame.evaluate(axeRunPartial, { + context, + options: this.option + }); + const initiator = frame === this.page.mainFrame(); + const axePartialRunner = new AxePartialRunner(partialPromise, initiator); + for (const { frameSelector, frameContext } of frameContexts) { + let childResults = null; + try { + const iframeHandle = await frame.evaluateHandle(axeShadowSelect, { + frameSelector + }); + const iframeElement = iframeHandle.asElement(); + const childFrame = await iframeElement.contentFrame(); + if (childFrame) { + await this.inject([childFrame], true); + childResults = await this.runPartialRecursive( + childFrame, + frameContext + ); + } + } catch { + } + axePartialRunner.addChildResults(childResults); + } + return axePartialRunner; + } + async finishRun(partialResults) { + const { page, option: options } = this; + const context = page.context(); + const blankPage = await context.newPage(); + (0, import_assert.default)( + blankPage, + "Please make sure that you have popup blockers disabled." + ); + await blankPage.evaluate(this.script()); + await blankPage.evaluate(await this.axeConfigure()); + const sizeLimit = 6e7; + const partialString = JSON.stringify(partialResults); + async function chunkResults(result) { + const chunk = result.substring(0, sizeLimit); + await blankPage.evaluate(chunkResultString, chunk); + if (result.length > sizeLimit) { + return await chunkResults(result.substr(sizeLimit)); + } + return; + } + await chunkResults(partialString); + return await blankPage.evaluate(axeFinishRun, { + options + }).finally(async () => { + await blankPage.close(); + }); + } + async axeConfigure() { + const hasRunPartial = await this.page.evaluate( + 'typeof window.axe?.runPartial === "function"' + ); + return ` + ;axe.configure({ + ${!this.legacyMode && !hasRunPartial ? 'allowedOrigins: [""],' : 'allowedOrigins: [""],'} + branding: { application: 'playwright' } + }) + `; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AxeBuilder +}); + +if (module.exports.default) { + var ___default_export = module.exports.default; + var ___export_entries = Object.entries(module.exports); + module.exports = ___default_export; + ___export_entries.forEach(([key, value]) => { + if (module.exports[key]) { + throw new Error(`Export "${key}" already exists on default export`); + } + + module.exports[key] = value; + }); +} diff --git a/node_modules/@axe-core/playwright/dist/index.mjs b/node_modules/@axe-core/playwright/dist/index.mjs new file mode 100644 index 000000000..3b9f81dd0 --- /dev/null +++ b/node_modules/@axe-core/playwright/dist/index.mjs @@ -0,0 +1,352 @@ +// src/index.ts +import assert from "assert"; +import axe from "axe-core"; + +// src/utils.ts +var normalizeContext = (includes, excludes) => { + const base = { + exclude: [], + include: [] + }; + if (excludes.length && Array.isArray(base.exclude)) { + base.exclude.push(...excludes); + } + if (includes.length) { + base.include = includes; + } + return base; +}; +var analyzePage = ({ + context, + options +}) => { + const axeCore = window.axe; + return axeCore.run(context || document, options || {}).then((results) => { + return { error: null, results }; + }).catch((err) => { + return { error: err.message, results: null }; + }); +}; + +// src/browser.ts +var axeGetFrameContexts = ({ + context +}) => { + return window.axe.utils.getFrameContexts(context); +}; +var axeShadowSelect = ({ + frameSelector +}) => { + return window.axe.utils.shadowSelect(frameSelector); +}; +var axeRunPartial = ({ + context, + options +}) => { + return window.axe.runPartial(context, options); +}; +var axeFinishRun = ({ + options +}) => { + return window.axe.finishRun(JSON.parse(window.partialResults), options); +}; +function chunkResultString(chunk) { + if (!window.partialResults) { + window.partialResults = ""; + } + window.partialResults += chunk; +} + +// src/AxePartialRunner.ts +var AxePartialRunner = class { + constructor(partialPromise, initiator = false) { + this.initiator = initiator; + this.partialPromise = caught(partialPromise); + } + partialPromise; + childRunners = []; + addChildResults(childResultRunner) { + this.childRunners.push(childResultRunner); + } + async getPartials() { + try { + const parentPartial = await this.partialPromise; + const childPromises = this.childRunners.map((childRunner) => { + return childRunner ? caught(childRunner.getPartials()) : [null]; + }); + const childPartials = (await Promise.all(childPromises)).flat(1); + return [parentPartial, ...childPartials]; + } catch (e) { + if (this.initiator) { + throw e; + } + return [null]; + } + } +}; +var caught = /* @__PURE__ */ ((f) => { + return (p) => (p.catch(f), p); +})(() => { +}); + +// src/index.ts +var { source } = axe; +var AxeBuilder = class { + page; + includes; + excludes; + option; + axeSource; + legacyMode = false; + errorUrl; + constructor({ page, axeSource }) { + this.page = page; + this.includes = []; + this.excludes = []; + this.option = {}; + this.axeSource = axeSource; + this.errorUrl = "https://github.com/dequelabs/axe-core-npm/blob/develop/packages/playwright/error-handling.md"; + } + /** + * Selector to include in analysis. + * This may be called any number of times. + * @param String selector + * @returns this + */ + include(selector) { + this.includes.push(selector); + return this; + } + /** + * Selector to exclude in analysis. + * This may be called any number of times. + * @param String selector + * @returns this + */ + exclude(selector) { + this.excludes.push(selector); + return this; + } + /** + * Set options to be passed into axe-core + * @param RunOptions options + * @returns AxeBuilder + */ + options(options) { + this.option = options; + return this; + } + /** + * Limit analysis to only the specified rules. + * Cannot be used with `AxeBuilder#withTags` + * @param String|Array rules + * @returns this + */ + withRules(rules) { + rules = Array.isArray(rules) ? rules : [rules]; + this.option = this.option || {}; + this.option.runOnly = { + type: "rule", + values: rules + }; + return this; + } + /** + * Limit analysis to only specified tags. + * Cannot be used with `AxeBuilder#withRules` + * @param String|Array tags + * @returns this + */ + withTags(tags) { + tags = Array.isArray(tags) ? tags : [tags]; + this.option = this.option || {}; + this.option.runOnly = { + type: "tag", + values: tags + }; + return this; + } + /** + * Set the list of rules to skip when running an analysis. + * @param String|Array rules + * @returns this + */ + disableRules(rules) { + rules = Array.isArray(rules) ? rules : [rules]; + this.option = this.option || {}; + this.option.rules = {}; + for (const rule of rules) { + this.option.rules[rule] = { enabled: false }; + } + return this; + } + /** + * Use frameMessenger with + * + * This disables use of axe.runPartial() which is called in each frame, and + * axe.finishRun() which is called in a blank page. This uses axe.run() instead, + * but with the restriction that cross-origin frames will not be tested. + */ + setLegacyMode(legacyMode = true) { + this.legacyMode = legacyMode; + return this; + } + /** + * Perform analysis and retrieve results. *Does not chain.* + * @return Promise + */ + async analyze() { + const context = normalizeContext(this.includes, this.excludes); + const { page } = this; + await page.evaluate(this.script()); + const runPartialDefined = await page.evaluate( + 'typeof window.axe.runPartial === "function"' + ); + let results; + if (!runPartialDefined || this.legacyMode) { + results = await this.runLegacy(context); + return results; + } + const partialResults = await this.runPartialRecursive( + page.mainFrame(), + context + ); + const partials = await partialResults.getPartials(); + try { + return await this.finishRun(partials); + } catch (error) { + throw new Error( + `${error.message} + Please check out ${this.errorUrl}` + ); + } + } + /** + * Injects `axe-core` into all frames. + * @param Page - playwright page object + * @returns Promise + */ + async inject(frames, shouldThrow) { + for (const iframe of frames) { + const race = new Promise((_, reject) => { + setTimeout(() => { + reject(new Error("Script Timeout")); + }, 1e3); + }); + const evaluate = iframe.evaluate(this.script()); + try { + await Promise.race([evaluate, race]); + await iframe.evaluate(await this.axeConfigure()); + } catch (err) { + if (shouldThrow) { + throw err; + } + } + } + } + /** + * Get axe-core source and configurations + * @returns String + */ + script() { + return this.axeSource || source; + } + async runLegacy(context) { + const frames = this.page.frames(); + await this.inject(frames); + const axeResults = await this.page.evaluate(analyzePage, { + context, + options: this.option + }); + if (axeResults.error) { + throw new Error(axeResults.error); + } + return axeResults.results; + } + /** + * Inject `axe-core` into each frame and run `axe.runPartial`. + * Because we need to inject axe into all frames all at once + * (to avoid any potential problems with the DOM becoming out-of-sync) + * but also need to not process results for any child frames if the parent + * frame throws an error (requirements of the data structure for `axe.finishRun`), + * we have to return a deeply nested array of Promises and then flatten + * the array once all Promises have finished, throwing out any nested Promises + * if the parent Promise is not fulfilled. + * @param frame - playwright frame object + * @param context - axe-core context object + * @returns Promise + */ + async runPartialRecursive(frame, context) { + const frameContexts = await frame.evaluate(axeGetFrameContexts, { + context + }); + const partialPromise = frame.evaluate(axeRunPartial, { + context, + options: this.option + }); + const initiator = frame === this.page.mainFrame(); + const axePartialRunner = new AxePartialRunner(partialPromise, initiator); + for (const { frameSelector, frameContext } of frameContexts) { + let childResults = null; + try { + const iframeHandle = await frame.evaluateHandle(axeShadowSelect, { + frameSelector + }); + const iframeElement = iframeHandle.asElement(); + const childFrame = await iframeElement.contentFrame(); + if (childFrame) { + await this.inject([childFrame], true); + childResults = await this.runPartialRecursive( + childFrame, + frameContext + ); + } + } catch { + } + axePartialRunner.addChildResults(childResults); + } + return axePartialRunner; + } + async finishRun(partialResults) { + const { page, option: options } = this; + const context = page.context(); + const blankPage = await context.newPage(); + assert( + blankPage, + "Please make sure that you have popup blockers disabled." + ); + await blankPage.evaluate(this.script()); + await blankPage.evaluate(await this.axeConfigure()); + const sizeLimit = 6e7; + const partialString = JSON.stringify(partialResults); + async function chunkResults(result) { + const chunk = result.substring(0, sizeLimit); + await blankPage.evaluate(chunkResultString, chunk); + if (result.length > sizeLimit) { + return await chunkResults(result.substr(sizeLimit)); + } + return; + } + await chunkResults(partialString); + return await blankPage.evaluate(axeFinishRun, { + options + }).finally(async () => { + await blankPage.close(); + }); + } + async axeConfigure() { + const hasRunPartial = await this.page.evaluate( + 'typeof window.axe?.runPartial === "function"' + ); + return ` + ;axe.configure({ + ${!this.legacyMode && !hasRunPartial ? 'allowedOrigins: [""],' : 'allowedOrigins: [""],'} + branding: { application: 'playwright' } + }) + `; + } +}; +export { + AxeBuilder, + AxeBuilder as default +}; diff --git a/node_modules/@axe-core/playwright/package.json b/node_modules/@axe-core/playwright/package.json new file mode 100644 index 000000000..eb75bd9b5 --- /dev/null +++ b/node_modules/@axe-core/playwright/package.json @@ -0,0 +1,93 @@ +{ + "name": "@axe-core/playwright", + "version": "4.11.3", + "description": "Provides a method to inject and analyze web pages using axe", + "contributors": [ + { + "name": "Michael Siek (me@michaelsiek.com)" + } + ], + "files": [ + "/dist" + ], + "keywords": [ + "a11y", + "unit", + "testing", + "tdd", + "bdd", + "accessibility", + "axe", + "playwright", + "axe-core" + ], + "repository": { + "type": "git", + "url": "https://github.com/dequelabs/axe-core-npm.git" + }, + "license": "MPL-2.0", + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "prebuild": "rimraf dist", + "build": "tsup src/index.ts --dts --format esm,cjs", + "test": "mocha --timeout 60000 -r ts-node/register 'test/**.spec.ts'", + "test:export": "npm run test:esm && npm run test:commonjs && npm run test:ts", + "test:esm": "node test/esmTest.mjs", + "test:commonjs": "node test/commonjsTest.js", + "test:ts": "tsc test/tsTest.ts --noEmit --skipLibCheck --esModuleInterop", + "coverage": "nyc npm run test", + "prepare": "npx playwright install && npm run build" + }, + "dependencies": { + "axe-core": "~4.11.4" + }, + "devDependencies": { + "@playwright/test": "^1.44.0", + "@types/chai": "^4.3.3", + "@types/express": "^5.0.3", + "@types/mocha": "^10.0.0", + "async-listen": "^3.0.1", + "axe-test-fixtures": "github:dequelabs/axe-test-fixtures#v1", + "chai": "^4.3.6", + "express": "^5.1.0", + "mocha": "^11.7.1", + "nyc": "^17.1.0", + "rimraf": "^6.0.1", + "tsup": "^8.0.1" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" + }, + "nyc": { + "include": [ + "src/index.ts" + ], + "extension": [ + ".ts" + ], + "reporter": [ + "text-summary", + "html" + ], + "sourceMap": true, + "instrument": true, + "checkCoverage": true, + "statements": 95, + "branches": 90, + "functions": 100, + "lines": 95 + }, + "gitHead": "25fbfd2a7b4d38fcdca487d393192e811592f1ec" +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 000000000..1f6ce94c1 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 000000000..b3e0708bf --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 000000000..532bab39f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,423 @@ +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var 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; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +export { + decode, + decodeGeneratedRanges, + decodeOriginalScopes, + encode, + encodeGeneratedRanges, + encodeOriginalScopes +}; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 000000000..c276844b2 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts", "../src/sourcemap-codec.ts"], + "mappings": ";AAEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAAsB,UAA0B;AAC5E,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,KAAG;AACD,UAAM,IAAI,OAAO,KAAK;AACtB,cAAU,UAAU,CAAC;AACrB,cAAU,UAAU,OAAO;AAC3B,aAAS;AAAA,EACX,SAAS,UAAU;AAEnB,QAAM,eAAe,QAAQ;AAC7B,aAAW;AAEX,MAAI,cAAc;AAChB,YAAQ,cAAc,CAAC;AAAA,EACzB;AAEA,SAAO,WAAW;AACpB;AAEO,SAAS,cAAc,SAAuB,KAAa,UAA0B;AAC1F,MAAI,QAAQ,MAAM;AAElB,UAAQ,QAAQ,IAAK,CAAC,SAAS,IAAK,IAAI,SAAS;AACjD,KAAG;AACD,QAAI,UAAU,QAAQ;AACtB,eAAW;AACX,QAAI,QAAQ,EAAG,YAAW;AAC1B,YAAQ,MAAM,UAAU,OAAO,CAAC;AAAA,EAClC,SAAS,QAAQ;AAEjB,SAAO;AACT;AAEO,SAAS,WAAW,QAAsB,KAAa;AAC5D,MAAI,OAAO,OAAO,IAAK,QAAO;AAC9B,SAAO,OAAO,KAAK,MAAM;AAC3B;;;ACtDA,IAAM,YAAY,OAAO;AAGzB,IAAM,KACJ,OAAO,gBAAgB,cACH,oBAAI,YAAY,IAChC,OAAO,WAAW,cAChB;AAAA,EACE,OAAO,KAAyB;AAC9B,UAAM,MAAM,OAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,IAAI,UAAU;AAClE,WAAO,IAAI,SAAS;AAAA,EACtB;AACF,IACA;AAAA,EACE,OAAO,KAAyB;AAC9B,QAAI,MAAM;AACV,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,aAAO,OAAO,aAAa,IAAI,CAAC,CAAC;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;AAED,IAAM,eAAN,MAAmB;AAAA,EAAnB;AACL,eAAM;AACN,SAAQ,MAAM;AACd,SAAQ,SAAS,IAAI,WAAW,SAAS;AAAA;AAAA,EAEzC,MAAM,GAAiB;AACrB,UAAM,EAAE,OAAO,IAAI;AACnB,WAAO,KAAK,KAAK,IAAI;AACrB,QAAI,KAAK,QAAQ,WAAW;AAC1B,WAAK,OAAO,GAAG,OAAO,MAAM;AAC5B,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AAAA,EAEA,QAAgB;AACd,UAAM,EAAE,QAAQ,KAAK,IAAI,IAAI;AAC7B,WAAO,MAAM,IAAI,MAAM,GAAG,OAAO,OAAO,SAAS,GAAG,GAAG,CAAC,IAAI;AAAA,EAC9D;AACF;AAEO,IAAM,eAAN,MAAmB;AAAA,EAIxB,YAAY,QAAgB;AAH5B,eAAM;AAIJ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AAAA,EAC1C;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,GAAG;AAAA,EACxC;AAAA,EAEA,QAAQ,MAAsB;AAC5B,UAAM,EAAE,QAAQ,IAAI,IAAI;AACxB,UAAM,MAAM,OAAO,QAAQ,MAAM,GAAG;AACpC,WAAO,QAAQ,KAAK,OAAO,SAAS;AAAA,EACtC;AACF;;;AC7DA,IAAM,QAAe,CAAC;AA+Bf,SAAS,qBAAqB,OAAgC;AACnE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA0B,CAAC;AACjC,QAAM,QAAyB,CAAC;AAChC,MAAI,OAAO;AAEX,SAAO,OAAO,MAAM,QAAQ,OAAO,OAAO;AACxC,WAAO,cAAc,QAAQ,IAAI;AACjC,UAAM,SAAS,cAAc,QAAQ,CAAC;AAEtC,QAAI,CAAC,WAAW,QAAQ,MAAM,GAAG;AAC/B,YAAM,OAAO,MAAM,IAAI;AACvB,WAAK,CAAC,IAAI;AACV,WAAK,CAAC,IAAI;AACV;AAAA,IACF;AAEA,UAAM,OAAO,cAAc,QAAQ,CAAC;AACpC,UAAM,SAAS,cAAc,QAAQ,CAAC;AACtC,UAAM,UAAU,SAAS;AAEzB,UAAM,QACJ,UAAU,CAAC,MAAM,QAAQ,GAAG,GAAG,MAAM,cAAc,QAAQ,CAAC,CAAC,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,IAAI;AAG5F,QAAI,OAAc;AAClB,QAAI,WAAW,QAAQ,MAAM,GAAG;AAC9B,aAAO,CAAC;AACR,SAAG;AACD,cAAM,YAAY,cAAc,QAAQ,CAAC;AACzC,aAAK,KAAK,SAAS;AAAA,MACrB,SAAS,WAAW,QAAQ,MAAM;AAAA,IACpC;AACA,UAAM,OAAO;AAEb,WAAO,KAAK,KAAK;AACjB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,QAAiC;AACpE,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,sBAAsB,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC;AAAA,EAClD;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,sBACP,QACA,OACA,QACA,OAGQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,EAAE,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,MAAM,KAAK,IAAI;AAElF,MAAI,QAAQ,EAAG,QAAO,MAAM,KAAK;AAEjC,QAAM,CAAC,IAAI,cAAc,QAAQ,WAAW,MAAM,CAAC,CAAC;AACpD,gBAAc,QAAQ,aAAa,CAAC;AACpC,gBAAc,QAAQ,MAAM,CAAC;AAE7B,QAAM,SAAS,MAAM,WAAW,IAAI,IAAS;AAC7C,gBAAc,QAAQ,QAAQ,CAAC;AAC/B,MAAI,MAAM,WAAW,EAAG,eAAc,QAAQ,MAAM,CAAC,GAAG,CAAC;AAEzD,aAAW,KAAK,MAAM;AACpB,kBAAc,QAAQ,GAAG,CAAC;AAAA,EAC5B;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,sBAAsB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC5D;AAEA,SAAO,MAAM,KAAK;AAClB,QAAM,CAAC,IAAI,cAAc,QAAQ,SAAS,MAAM,CAAC,CAAC;AAClD,gBAAc,QAAQ,WAAW,CAAC;AAElC,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAiC;AACrE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA2B,CAAC;AAClC,QAAM,QAA0B,CAAC;AAEjC,MAAI,UAAU;AACd,MAAI,yBAAyB;AAC7B,MAAI,uBAAuB;AAC3B,MAAI,uBAAuB;AAC3B,MAAI,eAAe;AACnB,MAAI,iBAAiB;AACrB,MAAI,cAAc;AAClB,MAAI,gBAAgB;AAEpB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,QAAI,YAAY;AAEhB,WAAO,OAAO,MAAM,MAAM,OAAO,OAAO;AACtC,kBAAY,cAAc,QAAQ,SAAS;AAE3C,UAAI,CAAC,WAAW,QAAQ,IAAI,GAAG;AAC7B,cAAM,OAAO,MAAM,IAAI;AACvB,aAAK,CAAC,IAAI;AACV,aAAK,CAAC,IAAI;AACV;AAAA,MACF;AAEA,YAAM,SAAS,cAAc,QAAQ,CAAC;AACtC,YAAM,gBAAgB,SAAS;AAC/B,YAAM,cAAc,SAAS;AAC7B,YAAM,WAAW,SAAS;AAE1B,UAAI,WAA4B;AAChC,UAAI,WAAsB;AAC1B,UAAI;AACJ,UAAI,eAAe;AACjB,cAAM,kBAAkB,cAAc,QAAQ,sBAAsB;AACpE,+BAAuB;AAAA,UACrB;AAAA,UACA,2BAA2B,kBAAkB,uBAAuB;AAAA,QACtE;AAEA,iCAAyB;AACzB,gBAAQ,CAAC,SAAS,WAAW,GAAG,GAAG,iBAAiB,oBAAoB;AAAA,MAC1E,OAAO;AACL,gBAAQ,CAAC,SAAS,WAAW,GAAG,CAAC;AAAA,MACnC;AAEA,YAAM,UAAU,CAAC,CAAC;AAElB,UAAI,aAAa;AACf,cAAM,UAAU;AAChB,cAAM,WAAW;AACjB,+BAAuB,cAAc,QAAQ,oBAAoB;AACjE,cAAM,aAAa,YAAY;AAC/B,uBAAe,cAAc,QAAQ,aAAa,eAAe,CAAC;AAClE,yBAAiB;AAAA,UACf;AAAA,UACA,cAAc,aAAa,eAAe,iBAAiB;AAAA,QAC7D;AAEA,mBAAW,CAAC,sBAAsB,cAAc,cAAc;AAAA,MAChE;AACA,YAAM,WAAW;AAEjB,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,mBAAW,CAAC;AACZ,WAAG;AACD,wBAAc;AACd,0BAAgB;AAChB,gBAAM,mBAAmB,cAAc,QAAQ,CAAC;AAChD,cAAI;AACJ,cAAI,mBAAmB,IAAI;AACzB,+BAAmB,CAAC,CAAC,cAAc,QAAQ,CAAC,CAAC,CAAC;AAC9C,qBAAS,IAAI,IAAI,IAAI,kBAAkB,KAAK;AAC1C,oBAAM,SAAS;AACf,4BAAc,cAAc,QAAQ,WAAW;AAC/C,8BAAgB,cAAc,QAAQ,gBAAgB,SAAS,gBAAgB,CAAC;AAChF,oBAAM,aAAa,cAAc,QAAQ,CAAC;AAC1C,+BAAiB,KAAK,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,YAChE;AAAA,UACF,OAAO;AACL,+BAAmB,CAAC,CAAC,gBAAgB,CAAC;AAAA,UACxC;AACA,mBAAS,KAAK,gBAAgB;AAAA,QAChC,SAAS,WAAW,QAAQ,IAAI;AAAA,MAClC;AACA,YAAM,WAAW;AAEjB,aAAO,KAAK,KAAK;AACjB,YAAM,KAAK,KAAK;AAAA,IAClB;AAEA;AACA,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,MAAM;AAEtB,SAAO;AACT;AAEO,SAAS,sBAAsB,QAAkC;AACtE,MAAI,OAAO,WAAW,EAAG,QAAO;AAEhC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,uBAAuB,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAAA,EACrE;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,uBACP,QACA,OACA,QACA,OASQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM;AAAA,IACJ,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,MAAM,CAAC,IAAI,WAAW;AACxB,gBAAY,QAAQ,MAAM,CAAC,GAAG,SAAS;AACvC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,WAAW,QAAQ,GAAG;AACpB,WAAO,MAAM,KAAK;AAAA,EACpB;AAEA,QAAM,CAAC,IAAI,cAAc,QAAQ,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC;AAEnD,QAAM,UACH,MAAM,WAAW,IAAI,IAAS,MAAM,WAAW,IAAS,MAAM,UAAU,IAAS;AACpF,gBAAc,QAAQ,QAAQ,CAAC;AAE/B,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,EAAE,GAAG,cAAc,GAAG,YAAY,IAAI;AAC5C,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AAAA,IACb;AACA,UAAM,CAAC,IAAI,cAAc,QAAQ,cAAc,MAAM,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI,cAAc,QAAQ,aAAa,MAAM,CAAC,CAAC;AAAA,EACxD;AAEA,MAAI,UAAU;AACZ,UAAM,EAAE,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,IAAI,MAAM;AAC9D,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AACX,YAAM,CAAC,IAAI;AAAA,IACb,WAAW,aAAa,MAAM,CAAC,GAAG;AAChC,YAAM,CAAC,IAAI;AAAA,IACb;AACA,UAAM,CAAC,IAAI,cAAc,QAAQ,cAAc,MAAM,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI,cAAc,QAAQ,UAAU,MAAM,CAAC,CAAC;AACnD,UAAM,CAAC,IAAI,cAAc,QAAQ,YAAY,MAAM,CAAC,CAAC;AAAA,EACvD;AAEA,MAAI,UAAU;AACZ,eAAW,WAAW,UAAU;AAC9B,UAAI,QAAQ,SAAS,EAAG,eAAc,QAAQ,CAAC,QAAQ,QAAQ,CAAC;AAChE,YAAM,aAAa,QAAQ,CAAC,EAAE,CAAC;AAC/B,oBAAc,QAAQ,YAAY,CAAC;AACnC,UAAI,mBAAmB;AACvB,UAAI,qBAAqB;AACzB,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,cAAM,WAAW,QAAQ,CAAC;AAC1B,2BAAmB,cAAc,QAAQ,SAAS,CAAC,GAAI,gBAAgB;AACvE,6BAAqB,cAAc,QAAQ,SAAS,CAAC,GAAI,kBAAkB;AAC3E,sBAAc,QAAQ,SAAS,CAAC,GAAI,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,uBAAuB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC7D;AAEA,MAAI,MAAM,CAAC,IAAI,SAAS;AACtB,gBAAY,QAAQ,MAAM,CAAC,GAAG,OAAO;AACrC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,OAAO;AACL,WAAO,MAAM,KAAK;AAAA,EACpB;AACA,QAAM,CAAC,IAAI,cAAc,QAAQ,WAAW,MAAM,CAAC,CAAC;AAEpD,SAAO;AACT;AAEA,SAAS,YAAY,QAAsB,UAAkB,MAAc;AACzE,KAAG;AACD,WAAO,MAAM,SAAS;AAAA,EACxB,SAAS,EAAE,WAAW;AACxB;;;ACtUO,SAAS,OAAO,UAAqC;AAC1D,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,QAAQ;AACxC,QAAM,UAA6B,CAAC;AACpC,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,OAAsB,CAAC;AAC7B,QAAI,SAAS;AACb,QAAI,UAAU;AACd,gBAAY;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,UAAI;AAEJ,kBAAY,cAAc,QAAQ,SAAS;AAC3C,UAAI,YAAY,QAAS,UAAS;AAClC,gBAAU;AAEV,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,uBAAe,cAAc,QAAQ,YAAY;AACjD,qBAAa,cAAc,QAAQ,UAAU;AAC7C,uBAAe,cAAc,QAAQ,YAAY;AAEjD,YAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,uBAAa,cAAc,QAAQ,UAAU;AAC7C,gBAAM,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU;AAAA,QACtE,OAAO;AACL,gBAAM,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,QAC1D;AAAA,MACF,OAAO;AACL,cAAM,CAAC,SAAS;AAAA,MAClB;AAEA,WAAK,KAAK,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,OAAQ,MAAK,IAAI;AACtB,YAAQ,KAAK,IAAI;AACjB,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,kBAAY,cAAc,QAAQ,QAAQ,CAAC,GAAG,SAAS;AAEvD,UAAI,QAAQ,WAAW,EAAG;AAC1B,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 000000000..2d8e459f3 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,464 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.sourcemapCodec = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module) { +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/sourcemap-codec.ts +var sourcemap_codec_exports = {}; +__export(sourcemap_codec_exports, { + decode: () => decode, + decodeGeneratedRanges: () => decodeGeneratedRanges, + decodeOriginalScopes: () => decodeOriginalScopes, + encode: () => encode, + encodeGeneratedRanges: () => encodeGeneratedRanges, + encodeOriginalScopes: () => encodeOriginalScopes +}); +module.exports = __toCommonJS(sourcemap_codec_exports); + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function encodeInteger(builder, num, relative) { + let delta = num - relative; + delta = delta < 0 ? -delta << 1 | 1 : delta << 1; + do { + let clamped = delta & 31; + delta >>>= 5; + if (delta > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (delta > 0); + return num; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var 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; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + for (const v of vars) { + encodeInteger(writer, v, 0); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0 + ); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0 + ); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + state[1] = encodeInteger(writer, range[1], state[1]); + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, fields, 0); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn); + encodeInteger(writer, expRange[0], 0); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + genColumn = encodeInteger(writer, segment[0], genColumn); + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + return writer.flush(); +} +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 000000000..abc18d286 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/sourcemap-codec.ts", "../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAAsB,UAA0B;AAC5E,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,KAAG;AACD,UAAM,IAAI,OAAO,KAAK;AACtB,cAAU,UAAU,CAAC;AACrB,cAAU,UAAU,OAAO;AAC3B,aAAS;AAAA,EACX,SAAS,UAAU;AAEnB,QAAM,eAAe,QAAQ;AAC7B,aAAW;AAEX,MAAI,cAAc;AAChB,YAAQ,cAAc,CAAC;AAAA,EACzB;AAEA,SAAO,WAAW;AACpB;AAEO,SAAS,cAAc,SAAuB,KAAa,UAA0B;AAC1F,MAAI,QAAQ,MAAM;AAElB,UAAQ,QAAQ,IAAK,CAAC,SAAS,IAAK,IAAI,SAAS;AACjD,KAAG;AACD,QAAI,UAAU,QAAQ;AACtB,eAAW;AACX,QAAI,QAAQ,EAAG,YAAW;AAC1B,YAAQ,MAAM,UAAU,OAAO,CAAC;AAAA,EAClC,SAAS,QAAQ;AAEjB,SAAO;AACT;AAEO,SAAS,WAAW,QAAsB,KAAa;AAC5D,MAAI,OAAO,OAAO,IAAK,QAAO;AAC9B,SAAO,OAAO,KAAK,MAAM;AAC3B;;;ACtDA,IAAM,YAAY,OAAO;AAGzB,IAAM,KACJ,OAAO,gBAAgB,cACH,oBAAI,YAAY,IAChC,OAAO,WAAW,cAChB;AAAA,EACE,OAAO,KAAyB;AAC9B,UAAM,MAAM,OAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,IAAI,UAAU;AAClE,WAAO,IAAI,SAAS;AAAA,EACtB;AACF,IACA;AAAA,EACE,OAAO,KAAyB;AAC9B,QAAI,MAAM;AACV,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,aAAO,OAAO,aAAa,IAAI,CAAC,CAAC;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;AAED,IAAM,eAAN,MAAmB;AAAA,EAAnB;AACL,eAAM;AACN,SAAQ,MAAM;AACd,SAAQ,SAAS,IAAI,WAAW,SAAS;AAAA;AAAA,EAEzC,MAAM,GAAiB;AACrB,UAAM,EAAE,OAAO,IAAI;AACnB,WAAO,KAAK,KAAK,IAAI;AACrB,QAAI,KAAK,QAAQ,WAAW;AAC1B,WAAK,OAAO,GAAG,OAAO,MAAM;AAC5B,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AAAA,EAEA,QAAgB;AACd,UAAM,EAAE,QAAQ,KAAK,IAAI,IAAI;AAC7B,WAAO,MAAM,IAAI,MAAM,GAAG,OAAO,OAAO,SAAS,GAAG,GAAG,CAAC,IAAI;AAAA,EAC9D;AACF;AAEO,IAAM,eAAN,MAAmB;AAAA,EAIxB,YAAY,QAAgB;AAH5B,eAAM;AAIJ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AAAA,EAC1C;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,GAAG;AAAA,EACxC;AAAA,EAEA,QAAQ,MAAsB;AAC5B,UAAM,EAAE,QAAQ,IAAI,IAAI;AACxB,UAAM,MAAM,OAAO,QAAQ,MAAM,GAAG;AACpC,WAAO,QAAQ,KAAK,OAAO,SAAS;AAAA,EACtC;AACF;;;AC7DA,IAAM,QAAe,CAAC;AA+Bf,SAAS,qBAAqB,OAAgC;AACnE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA0B,CAAC;AACjC,QAAM,QAAyB,CAAC;AAChC,MAAI,OAAO;AAEX,SAAO,OAAO,MAAM,QAAQ,OAAO,OAAO;AACxC,WAAO,cAAc,QAAQ,IAAI;AACjC,UAAM,SAAS,cAAc,QAAQ,CAAC;AAEtC,QAAI,CAAC,WAAW,QAAQ,MAAM,GAAG;AAC/B,YAAM,OAAO,MAAM,IAAI;AACvB,WAAK,CAAC,IAAI;AACV,WAAK,CAAC,IAAI;AACV;AAAA,IACF;AAEA,UAAM,OAAO,cAAc,QAAQ,CAAC;AACpC,UAAM,SAAS,cAAc,QAAQ,CAAC;AACtC,UAAM,UAAU,SAAS;AAEzB,UAAM,QACJ,UAAU,CAAC,MAAM,QAAQ,GAAG,GAAG,MAAM,cAAc,QAAQ,CAAC,CAAC,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,IAAI;AAG5F,QAAI,OAAc;AAClB,QAAI,WAAW,QAAQ,MAAM,GAAG;AAC9B,aAAO,CAAC;AACR,SAAG;AACD,cAAM,YAAY,cAAc,QAAQ,CAAC;AACzC,aAAK,KAAK,SAAS;AAAA,MACrB,SAAS,WAAW,QAAQ,MAAM;AAAA,IACpC;AACA,UAAM,OAAO;AAEb,WAAO,KAAK,KAAK;AACjB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,QAAiC;AACpE,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,sBAAsB,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC;AAAA,EAClD;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,sBACP,QACA,OACA,QACA,OAGQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,EAAE,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,MAAM,KAAK,IAAI;AAElF,MAAI,QAAQ,EAAG,QAAO,MAAM,KAAK;AAEjC,QAAM,CAAC,IAAI,cAAc,QAAQ,WAAW,MAAM,CAAC,CAAC;AACpD,gBAAc,QAAQ,aAAa,CAAC;AACpC,gBAAc,QAAQ,MAAM,CAAC;AAE7B,QAAM,SAAS,MAAM,WAAW,IAAI,IAAS;AAC7C,gBAAc,QAAQ,QAAQ,CAAC;AAC/B,MAAI,MAAM,WAAW,EAAG,eAAc,QAAQ,MAAM,CAAC,GAAG,CAAC;AAEzD,aAAW,KAAK,MAAM;AACpB,kBAAc,QAAQ,GAAG,CAAC;AAAA,EAC5B;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,sBAAsB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC5D;AAEA,SAAO,MAAM,KAAK;AAClB,QAAM,CAAC,IAAI,cAAc,QAAQ,SAAS,MAAM,CAAC,CAAC;AAClD,gBAAc,QAAQ,WAAW,CAAC;AAElC,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAiC;AACrE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA2B,CAAC;AAClC,QAAM,QAA0B,CAAC;AAEjC,MAAI,UAAU;AACd,MAAI,yBAAyB;AAC7B,MAAI,uBAAuB;AAC3B,MAAI,uBAAuB;AAC3B,MAAI,eAAe;AACnB,MAAI,iBAAiB;AACrB,MAAI,cAAc;AAClB,MAAI,gBAAgB;AAEpB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,QAAI,YAAY;AAEhB,WAAO,OAAO,MAAM,MAAM,OAAO,OAAO;AACtC,kBAAY,cAAc,QAAQ,SAAS;AAE3C,UAAI,CAAC,WAAW,QAAQ,IAAI,GAAG;AAC7B,cAAM,OAAO,MAAM,IAAI;AACvB,aAAK,CAAC,IAAI;AACV,aAAK,CAAC,IAAI;AACV;AAAA,MACF;AAEA,YAAM,SAAS,cAAc,QAAQ,CAAC;AACtC,YAAM,gBAAgB,SAAS;AAC/B,YAAM,cAAc,SAAS;AAC7B,YAAM,WAAW,SAAS;AAE1B,UAAI,WAA4B;AAChC,UAAI,WAAsB;AAC1B,UAAI;AACJ,UAAI,eAAe;AACjB,cAAM,kBAAkB,cAAc,QAAQ,sBAAsB;AACpE,+BAAuB;AAAA,UACrB;AAAA,UACA,2BAA2B,kBAAkB,uBAAuB;AAAA,QACtE;AAEA,iCAAyB;AACzB,gBAAQ,CAAC,SAAS,WAAW,GAAG,GAAG,iBAAiB,oBAAoB;AAAA,MAC1E,OAAO;AACL,gBAAQ,CAAC,SAAS,WAAW,GAAG,CAAC;AAAA,MACnC;AAEA,YAAM,UAAU,CAAC,CAAC;AAElB,UAAI,aAAa;AACf,cAAM,UAAU;AAChB,cAAM,WAAW;AACjB,+BAAuB,cAAc,QAAQ,oBAAoB;AACjE,cAAM,aAAa,YAAY;AAC/B,uBAAe,cAAc,QAAQ,aAAa,eAAe,CAAC;AAClE,yBAAiB;AAAA,UACf;AAAA,UACA,cAAc,aAAa,eAAe,iBAAiB;AAAA,QAC7D;AAEA,mBAAW,CAAC,sBAAsB,cAAc,cAAc;AAAA,MAChE;AACA,YAAM,WAAW;AAEjB,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,mBAAW,CAAC;AACZ,WAAG;AACD,wBAAc;AACd,0BAAgB;AAChB,gBAAM,mBAAmB,cAAc,QAAQ,CAAC;AAChD,cAAI;AACJ,cAAI,mBAAmB,IAAI;AACzB,+BAAmB,CAAC,CAAC,cAAc,QAAQ,CAAC,CAAC,CAAC;AAC9C,qBAAS,IAAI,IAAI,IAAI,kBAAkB,KAAK;AAC1C,oBAAM,SAAS;AACf,4BAAc,cAAc,QAAQ,WAAW;AAC/C,8BAAgB,cAAc,QAAQ,gBAAgB,SAAS,gBAAgB,CAAC;AAChF,oBAAM,aAAa,cAAc,QAAQ,CAAC;AAC1C,+BAAiB,KAAK,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,YAChE;AAAA,UACF,OAAO;AACL,+BAAmB,CAAC,CAAC,gBAAgB,CAAC;AAAA,UACxC;AACA,mBAAS,KAAK,gBAAgB;AAAA,QAChC,SAAS,WAAW,QAAQ,IAAI;AAAA,MAClC;AACA,YAAM,WAAW;AAEjB,aAAO,KAAK,KAAK;AACjB,YAAM,KAAK,KAAK;AAAA,IAClB;AAEA;AACA,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,MAAM;AAEtB,SAAO;AACT;AAEO,SAAS,sBAAsB,QAAkC;AACtE,MAAI,OAAO,WAAW,EAAG,QAAO;AAEhC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,uBAAuB,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAAA,EACrE;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,uBACP,QACA,OACA,QACA,OASQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM;AAAA,IACJ,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,MAAM,CAAC,IAAI,WAAW;AACxB,gBAAY,QAAQ,MAAM,CAAC,GAAG,SAAS;AACvC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,WAAW,QAAQ,GAAG;AACpB,WAAO,MAAM,KAAK;AAAA,EACpB;AAEA,QAAM,CAAC,IAAI,cAAc,QAAQ,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC;AAEnD,QAAM,UACH,MAAM,WAAW,IAAI,IAAS,MAAM,WAAW,IAAS,MAAM,UAAU,IAAS;AACpF,gBAAc,QAAQ,QAAQ,CAAC;AAE/B,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,EAAE,GAAG,cAAc,GAAG,YAAY,IAAI;AAC5C,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AAAA,IACb;AACA,UAAM,CAAC,IAAI,cAAc,QAAQ,cAAc,MAAM,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI,cAAc,QAAQ,aAAa,MAAM,CAAC,CAAC;AAAA,EACxD;AAEA,MAAI,UAAU;AACZ,UAAM,EAAE,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,IAAI,MAAM;AAC9D,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AACX,YAAM,CAAC,IAAI;AAAA,IACb,WAAW,aAAa,MAAM,CAAC,GAAG;AAChC,YAAM,CAAC,IAAI;AAAA,IACb;AACA,UAAM,CAAC,IAAI,cAAc,QAAQ,cAAc,MAAM,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI,cAAc,QAAQ,UAAU,MAAM,CAAC,CAAC;AACnD,UAAM,CAAC,IAAI,cAAc,QAAQ,YAAY,MAAM,CAAC,CAAC;AAAA,EACvD;AAEA,MAAI,UAAU;AACZ,eAAW,WAAW,UAAU;AAC9B,UAAI,QAAQ,SAAS,EAAG,eAAc,QAAQ,CAAC,QAAQ,QAAQ,CAAC;AAChE,YAAM,aAAa,QAAQ,CAAC,EAAE,CAAC;AAC/B,oBAAc,QAAQ,YAAY,CAAC;AACnC,UAAI,mBAAmB;AACvB,UAAI,qBAAqB;AACzB,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,cAAM,WAAW,QAAQ,CAAC;AAC1B,2BAAmB,cAAc,QAAQ,SAAS,CAAC,GAAI,gBAAgB;AACvE,6BAAqB,cAAc,QAAQ,SAAS,CAAC,GAAI,kBAAkB;AAC3E,sBAAc,QAAQ,SAAS,CAAC,GAAI,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,uBAAuB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC7D;AAEA,MAAI,MAAM,CAAC,IAAI,SAAS;AACtB,gBAAY,QAAQ,MAAM,CAAC,GAAG,OAAO;AACrC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,OAAO;AACL,WAAO,MAAM,KAAK;AAAA,EACpB;AACA,QAAM,CAAC,IAAI,cAAc,QAAQ,WAAW,MAAM,CAAC,CAAC;AAEpD,SAAO;AACT;AAEA,SAAS,YAAY,QAAsB,UAAkB,MAAc;AACzE,KAAG;AACD,WAAO,MAAM,SAAS;AAAA,EACxB,SAAS,EAAE,WAAW;AACxB;;;AHtUO,SAAS,OAAO,UAAqC;AAC1D,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,QAAQ;AACxC,QAAM,UAA6B,CAAC;AACpC,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,OAAsB,CAAC;AAC7B,QAAI,SAAS;AACb,QAAI,UAAU;AACd,gBAAY;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,UAAI;AAEJ,kBAAY,cAAc,QAAQ,SAAS;AAC3C,UAAI,YAAY,QAAS,UAAS;AAClC,gBAAU;AAEV,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,uBAAe,cAAc,QAAQ,YAAY;AACjD,qBAAa,cAAc,QAAQ,UAAU;AAC7C,uBAAe,cAAc,QAAQ,YAAY;AAEjD,YAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,uBAAa,cAAc,QAAQ,UAAU;AAC7C,gBAAM,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU;AAAA,QACtE,OAAO;AACL,gBAAM,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,QAC1D;AAAA,MACF,OAAO;AACL,cAAM,CAAC,SAAS;AAAA,MAClB;AAEA,WAAK,KAAK,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,OAAQ,MAAK,IAAI;AACtB,YAAQ,KAAK,IAAI;AACjB,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,kBAAY,cAAc,QAAQ,QAAQ,CAAC,GAAG,SAAS;AAEvD,UAAI,QAAQ,WAAW,EAAG;AAC1B,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAC7D,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AACzD,qBAAe,cAAc,QAAQ,QAAQ,CAAC,GAAG,YAAY;AAE7D,UAAI,QAAQ,WAAW,EAAG;AAC1B,mBAAa,cAAc,QAAQ,QAAQ,CAAC,GAAG,UAAU;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 000000000..da5513764 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,63 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.5", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "types/sourcemap-codec.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/sourcemap-codec.d.mts", + "default": "./dist/sourcemap-codec.mjs" + }, + "default": { + "types": "./types/sourcemap-codec.d.cts", + "default": "./dist/sourcemap-codec.umd.js" + } + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs sourcemap-codec.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/sourcemap-codec" + }, + "author": "Justin Ridgewell ", + "license": "MIT" +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts new file mode 100644 index 000000000..d194c2f0a --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts @@ -0,0 +1,345 @@ +import { StringReader, StringWriter } from './strings'; +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; + +const EMPTY: any[] = []; + +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; + +type Mix = (A & O) | (B & O); + +export type OriginalScope = Mix< + [Line, Column, Line, Column, Kind], + [Line, Column, Line, Column, Kind, Name], + { vars: Var[] } +>; + +export type GeneratedRange = Mix< + [Line, Column, Line, Column], + [Line, Column, Line, Column, SourcesIndex, ScopesIndex], + { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; + } +>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; + +export function decodeOriginalScopes(input: string): OriginalScope[] { + const { length } = input; + const reader = new StringReader(input); + const scopes: OriginalScope[] = []; + const stack: OriginalScope[] = []; + let line = 0; + + for (; reader.pos < length; reader.pos++) { + line = decodeInteger(reader, line); + const column = decodeInteger(reader, 0); + + if (!hasMoreVlq(reader, length)) { + const last = stack.pop()!; + last[2] = line; + last[3] = column; + continue; + } + + const kind = decodeInteger(reader, 0); + const fields = decodeInteger(reader, 0); + const hasName = fields & 0b0001; + + const scope: OriginalScope = ( + hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind] + ) as OriginalScope; + + let vars: Var[] = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeInteger(reader, 0); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + + scopes.push(scope); + stack.push(scope); + } + + return scopes; +} + +export function encodeOriginalScopes(scopes: OriginalScope[]): string { + const writer = new StringWriter(); + + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + + return writer.flush(); +} + +function _encodeOriginalScopes( + scopes: OriginalScope[], + index: number, + writer: StringWriter, + state: [ + number, // GenColumn + ], +): number { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + + if (index > 0) writer.write(comma); + + state[0] = encodeInteger(writer, startLine, state[0]); + encodeInteger(writer, startColumn, 0); + encodeInteger(writer, kind, 0); + + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, fields, 0); + if (scope.length === 6) encodeInteger(writer, scope[5], 0); + + for (const v of vars) { + encodeInteger(writer, v, 0); + } + + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + + writer.write(comma); + state[0] = encodeInteger(writer, endLine, state[0]); + encodeInteger(writer, endColumn, 0); + + return index; +} + +export function decodeGeneratedRanges(input: string): GeneratedRange[] { + const { length } = input; + const reader = new StringReader(input); + const ranges: GeneratedRange[] = []; + const stack: GeneratedRange[] = []; + + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + + for (; reader.pos < semi; reader.pos++) { + genColumn = decodeInteger(reader, genColumn); + + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop()!; + last[2] = genLine; + last[3] = genColumn; + continue; + } + + const fields = decodeInteger(reader, 0); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + + let callsite: CallSite | null = null; + let bindings: Binding[] = EMPTY; + let range: GeneratedRange; + if (hasDefinition) { + const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex); + definitionScopeIndex = decodeInteger( + reader, + definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0, + ); + + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange; + } else { + range = [genLine, genColumn, 0, 0] as GeneratedRange; + } + + range.isScope = !!hasScope; + + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0); + callsiteColumn = decodeInteger( + reader, + sameSource && prevLine === callsiteLine ? callsiteColumn : 0, + ); + + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeInteger(reader, 0); + let expressionRanges: BindingExpressionRange[]; + if (expressionsCount < -1) { + expressionRanges = [[decodeInteger(reader, 0)]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine = decodeInteger(reader, bindingLine); + bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0); + const expression = decodeInteger(reader, 0); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + + ranges.push(range); + stack.push(range); + } + + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + + return ranges; +} + +export function encodeGeneratedRanges(ranges: GeneratedRange[]): string { + if (ranges.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + + return writer.flush(); +} + +function _encodeGeneratedRanges( + ranges: GeneratedRange[], + index: number, + writer: StringWriter, + state: [ + number, // GenLine + number, // GenColumn + number, // DefSourcesIndex + number, // DefScopesIndex + number, // CallSourcesIndex + number, // CallLine + number, // CallColumn + ], +): number { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings, + } = range; + + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + + state[1] = encodeInteger(writer, range[1], state[1]); + + const fields = + (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, fields, 0); + + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + state[2] = encodeInteger(writer, sourcesIndex, state[2]); + state[3] = encodeInteger(writer, scopesIndex, state[3]); + } + + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + state[4] = encodeInteger(writer, sourcesIndex, state[4]); + state[5] = encodeInteger(writer, callLine, state[5]); + state[6] = encodeInteger(writer, callColumn, state[6]); + } + + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, -binding.length, 0); + const expression = binding[0][0]; + encodeInteger(writer, expression, 0); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine); + bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn); + encodeInteger(writer, expRange[0]!, 0); + } + } + } + + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + state[1] = encodeInteger(writer, endColumn, state[1]); + + return index; +} + +function catchupLine(writer: StringWriter, lastLine: number, line: number) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 000000000..a81f894dc --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,111 @@ +import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq'; +import { StringWriter, StringReader } from './strings'; + +export { + decodeOriginalScopes, + encodeOriginalScopes, + decodeGeneratedRanges, + encodeGeneratedRanges, +} from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +export function decode(mappings: string): SourceMapMappings { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded: SourceMapMappings = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + do { + const semi = reader.indexOf(';'); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + + while (reader.pos < semi) { + let seg: SourceMapSegment; + + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + + line.push(seg); + reader.pos++; + } + + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return decoded; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + + let genColumn = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + + genColumn = encodeInteger(writer, segment[0], genColumn); + + if (segment.length === 1) continue; + sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex); + sourceLine = encodeInteger(writer, segment[2], sourceLine); + sourceColumn = encodeInteger(writer, segment[3], sourceColumn); + + if (segment.length === 4) continue; + namesIndex = encodeInteger(writer, segment[4], namesIndex); + } + } + + return writer.flush(); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/strings.ts b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts new file mode 100644 index 000000000..d1619650e --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/strings.ts @@ -0,0 +1,65 @@ +const bufLength = 1024 * 16; + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array): string { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array): string { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export class StringWriter { + pos = 0; + private out = ''; + private buffer = new Uint8Array(bufLength); + + write(v: number): void { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + + flush(): string { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} + +export class StringReader { + pos = 0; + declare private buffer: string; + + constructor(buffer: string) { + this.buffer = buffer; + } + + next(): number { + return this.buffer.charCodeAt(this.pos++); + } + + peek(): number { + return this.buffer.charCodeAt(this.pos); + } + + indexOf(char: string): number { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts new file mode 100644 index 000000000..a42c68151 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts @@ -0,0 +1,55 @@ +import type { StringReader, StringWriter } from './strings'; + +export const comma = ','.charCodeAt(0); +export 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; +} + +export function decodeInteger(reader: StringReader, relative: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + return relative + value; +} + +export function encodeInteger(builder: StringWriter, num: number, relative: number): number { + let delta = num - relative; + + delta = delta < 0 ? (-delta << 1) | 1 : delta << 1; + do { + let clamped = delta & 0b011111; + delta >>>= 5; + if (delta > 0) clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (delta > 0); + + return num; +} + +export function hasMoreVlq(reader: StringReader, max: number) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts new file mode 100644 index 000000000..c583c7560 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map new file mode 100644 index 000000000..630e6477b --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts new file mode 100644 index 000000000..c583c7560 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map new file mode 100644 index 000000000..630e6477b --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts new file mode 100644 index 000000000..5f35e22fb --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map new file mode 100644 index 000000000..7123d5208 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts new file mode 100644 index 000000000..199fb9f53 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts @@ -0,0 +1,9 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map new file mode 100644 index 000000000..7123d5208 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts new file mode 100644 index 000000000..62faceb3d --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map new file mode 100644 index 000000000..d3602da42 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 000000000..62faceb3d --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 000000000..d3602da42 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 000000000..dbd6602d1 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 000000000..6fdc35697 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 000000000..2c739bc9f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,7 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader, relative: number): number; +export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 000000000..6fdc35697 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/node_modules/@oxc-project/types/LICENSE b/node_modules/@oxc-project/types/LICENSE new file mode 100644 index 000000000..444bffc00 --- /dev/null +++ b/node_modules/@oxc-project/types/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024-present VoidZero Inc. & Contributors +Copyright (c) 2023 Boshen + +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/@oxc-project/types/README.md b/node_modules/@oxc-project/types/README.md new file mode 100644 index 000000000..d5b248ac3 --- /dev/null +++ b/node_modules/@oxc-project/types/README.md @@ -0,0 +1,3 @@ +# Oxc Types + +Typescript definitions for Oxc AST nodes. diff --git a/node_modules/@oxc-project/types/package.json b/node_modules/@oxc-project/types/package.json new file mode 100644 index 000000000..f18122650 --- /dev/null +++ b/node_modules/@oxc-project/types/package.json @@ -0,0 +1,26 @@ +{ + "name": "@oxc-project/types", + "version": "0.127.0", + "description": "Types for Oxc AST nodes", + "keywords": [ + "AST", + "Parser" + ], + "homepage": "https://oxc.rs", + "bugs": "https://github.com/oxc-project/oxc/issues", + "license": "MIT", + "author": "Boshen and oxc contributors", + "repository": { + "type": "git", + "url": "git+https://github.com/oxc-project/oxc.git", + "directory": "npm/oxc-types" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "files": [ + "types.d.ts" + ], + "type": "module", + "types": "types.d.ts" +} \ No newline at end of file diff --git a/node_modules/@oxc-project/types/types.d.ts b/node_modules/@oxc-project/types/types.d.ts new file mode 100644 index 000000000..c94c1159e --- /dev/null +++ b/node_modules/@oxc-project/types/types.d.ts @@ -0,0 +1,1912 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/typescript.rs`. + +export interface Program extends Span { + type: "Program"; + body: Array; + sourceType: ModuleKind; + hashbang: Hashbang | null; + parent?: null; +} + +export type Expression = + | BooleanLiteral + | NullLiteral + | NumericLiteral + | BigIntLiteral + | RegExpLiteral + | StringLiteral + | TemplateLiteral + | IdentifierReference + | MetaProperty + | Super + | ArrayExpression + | ArrowFunctionExpression + | AssignmentExpression + | AwaitExpression + | BinaryExpression + | CallExpression + | ChainExpression + | Class + | ConditionalExpression + | Function + | ImportExpression + | LogicalExpression + | NewExpression + | ObjectExpression + | ParenthesizedExpression + | SequenceExpression + | TaggedTemplateExpression + | ThisExpression + | UnaryExpression + | UpdateExpression + | YieldExpression + | PrivateInExpression + | JSXElement + | JSXFragment + | TSAsExpression + | TSSatisfiesExpression + | TSTypeAssertion + | TSNonNullExpression + | TSInstantiationExpression + | V8IntrinsicExpression + | MemberExpression; + +export interface IdentifierName extends Span { + type: "Identifier"; + decorators?: []; + name: string; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface IdentifierReference extends Span { + type: "Identifier"; + decorators?: []; + name: string; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface BindingIdentifier extends Span { + type: "Identifier"; + decorators?: []; + name: string; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface LabelIdentifier extends Span { + type: "Identifier"; + decorators?: []; + name: string; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface ThisExpression extends Span { + type: "ThisExpression"; + parent?: Node; +} + +export interface ArrayExpression extends Span { + type: "ArrayExpression"; + elements: Array; + parent?: Node; +} + +export type ArrayExpressionElement = SpreadElement | null | Expression; + +export interface ObjectExpression extends Span { + type: "ObjectExpression"; + properties: Array; + parent?: Node; +} + +export type ObjectPropertyKind = ObjectProperty | SpreadElement; + +export interface ObjectProperty extends Span { + type: "Property"; + kind: PropertyKind; + key: PropertyKey; + value: Expression; + method: boolean; + shorthand: boolean; + computed: boolean; + optional?: false; + parent?: Node; +} + +export type PropertyKey = IdentifierName | PrivateIdentifier | Expression; + +export type PropertyKind = "init" | "get" | "set"; + +export interface TemplateLiteral extends Span { + type: "TemplateLiteral"; + quasis: Array; + expressions: Array; + parent?: Node; +} + +export interface TaggedTemplateExpression extends Span { + type: "TaggedTemplateExpression"; + tag: Expression; + typeArguments?: TSTypeParameterInstantiation | null; + quasi: TemplateLiteral; + parent?: Node; +} + +export interface TemplateElement extends Span { + type: "TemplateElement"; + value: TemplateElementValue; + tail: boolean; + parent?: Node; +} + +export interface TemplateElementValue { + raw: string; + cooked: string | null; +} + +export type MemberExpression = + | ComputedMemberExpression + | StaticMemberExpression + | PrivateFieldExpression; + +export interface ComputedMemberExpression extends Span { + type: "MemberExpression"; + object: Expression; + property: Expression; + optional: boolean; + computed: true; + parent?: Node; +} + +export interface StaticMemberExpression extends Span { + type: "MemberExpression"; + object: Expression; + property: IdentifierName; + optional: boolean; + computed: false; + parent?: Node; +} + +export interface PrivateFieldExpression extends Span { + type: "MemberExpression"; + object: Expression; + property: PrivateIdentifier; + optional: boolean; + computed: false; + parent?: Node; +} + +export interface CallExpression extends Span { + type: "CallExpression"; + callee: Expression; + typeArguments?: TSTypeParameterInstantiation | null; + arguments: Array; + optional: boolean; + parent?: Node; +} + +export interface NewExpression extends Span { + type: "NewExpression"; + callee: Expression; + typeArguments?: TSTypeParameterInstantiation | null; + arguments: Array; + parent?: Node; +} + +export interface MetaProperty extends Span { + type: "MetaProperty"; + meta: IdentifierName; + property: IdentifierName; + parent?: Node; +} + +export interface SpreadElement extends Span { + type: "SpreadElement"; + argument: Expression; + parent?: Node; +} + +export type Argument = SpreadElement | Expression; + +export interface UpdateExpression extends Span { + type: "UpdateExpression"; + operator: UpdateOperator; + prefix: boolean; + argument: SimpleAssignmentTarget; + parent?: Node; +} + +export interface UnaryExpression extends Span { + type: "UnaryExpression"; + operator: UnaryOperator; + argument: Expression; + prefix: true; + parent?: Node; +} + +export interface BinaryExpression extends Span { + type: "BinaryExpression"; + left: Expression; + operator: BinaryOperator; + right: Expression; + parent?: Node; +} + +export interface PrivateInExpression extends Span { + type: "BinaryExpression"; + left: PrivateIdentifier; + operator: "in"; + right: Expression; + parent?: Node; +} + +export interface LogicalExpression extends Span { + type: "LogicalExpression"; + left: Expression; + operator: LogicalOperator; + right: Expression; + parent?: Node; +} + +export interface ConditionalExpression extends Span { + type: "ConditionalExpression"; + test: Expression; + consequent: Expression; + alternate: Expression; + parent?: Node; +} + +export interface AssignmentExpression extends Span { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: AssignmentTarget; + right: Expression; + parent?: Node; +} + +export type AssignmentTarget = SimpleAssignmentTarget | AssignmentTargetPattern; + +export type SimpleAssignmentTarget = + | IdentifierReference + | TSAsExpression + | TSSatisfiesExpression + | TSNonNullExpression + | TSTypeAssertion + | MemberExpression; + +export type AssignmentTargetPattern = ArrayAssignmentTarget | ObjectAssignmentTarget; + +export interface ArrayAssignmentTarget extends Span { + type: "ArrayPattern"; + decorators?: []; + elements: Array; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface ObjectAssignmentTarget extends Span { + type: "ObjectPattern"; + decorators?: []; + properties: Array; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface AssignmentTargetRest extends Span { + type: "RestElement"; + decorators?: []; + argument: AssignmentTarget; + optional?: false; + typeAnnotation?: null; + value?: null; + parent?: Node; +} + +export type AssignmentTargetMaybeDefault = AssignmentTargetWithDefault | AssignmentTarget; + +export interface AssignmentTargetWithDefault extends Span { + type: "AssignmentPattern"; + decorators?: []; + left: AssignmentTarget; + right: Expression; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export type AssignmentTargetProperty = + | AssignmentTargetPropertyIdentifier + | AssignmentTargetPropertyProperty; + +export interface AssignmentTargetPropertyIdentifier extends Span { + type: "Property"; + kind: "init"; + key: IdentifierReference; + value: IdentifierReference | AssignmentTargetWithDefault; + method: false; + shorthand: true; + computed: false; + optional?: false; + parent?: Node; +} + +export interface AssignmentTargetPropertyProperty extends Span { + type: "Property"; + kind: "init"; + key: PropertyKey; + value: AssignmentTargetMaybeDefault; + method: false; + shorthand: false; + computed: boolean; + optional?: false; + parent?: Node; +} + +export interface SequenceExpression extends Span { + type: "SequenceExpression"; + expressions: Array; + parent?: Node; +} + +export interface Super extends Span { + type: "Super"; + parent?: Node; +} + +export interface AwaitExpression extends Span { + type: "AwaitExpression"; + argument: Expression; + parent?: Node; +} + +export interface ChainExpression extends Span { + type: "ChainExpression"; + expression: ChainElement; + parent?: Node; +} + +export type ChainElement = CallExpression | TSNonNullExpression | MemberExpression; + +export interface ParenthesizedExpression extends Span { + type: "ParenthesizedExpression"; + expression: Expression; + parent?: Node; +} + +export type Statement = + | BlockStatement + | BreakStatement + | ContinueStatement + | DebuggerStatement + | DoWhileStatement + | EmptyStatement + | ExpressionStatement + | ForInStatement + | ForOfStatement + | ForStatement + | IfStatement + | LabeledStatement + | ReturnStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | WithStatement + | Declaration + | ModuleDeclaration; + +export interface Directive extends Span { + type: "ExpressionStatement"; + expression: StringLiteral; + directive: string; + parent?: Node; +} + +export interface Hashbang extends Span { + type: "Hashbang"; + value: string; + parent?: Node; +} + +export interface BlockStatement extends Span { + type: "BlockStatement"; + body: Array; + parent?: Node; +} + +export type Declaration = + | VariableDeclaration + | Function + | Class + | TSTypeAliasDeclaration + | TSInterfaceDeclaration + | TSEnumDeclaration + | TSModuleDeclaration + | TSGlobalDeclaration + | TSImportEqualsDeclaration; + +export interface VariableDeclaration extends Span { + type: "VariableDeclaration"; + kind: VariableDeclarationKind; + declarations: Array; + declare?: boolean; + parent?: Node; +} + +export type VariableDeclarationKind = "var" | "let" | "const" | "using" | "await using"; + +export interface VariableDeclarator extends Span { + type: "VariableDeclarator"; + id: BindingPattern; + init: Expression | null; + definite?: boolean; + parent?: Node; +} + +export interface EmptyStatement extends Span { + type: "EmptyStatement"; + parent?: Node; +} + +export interface ExpressionStatement extends Span { + type: "ExpressionStatement"; + expression: Expression; + directive?: string | null; + parent?: Node; +} + +export interface IfStatement extends Span { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate: Statement | null; + parent?: Node; +} + +export interface DoWhileStatement extends Span { + type: "DoWhileStatement"; + body: Statement; + test: Expression; + parent?: Node; +} + +export interface WhileStatement extends Span { + type: "WhileStatement"; + test: Expression; + body: Statement; + parent?: Node; +} + +export interface ForStatement extends Span { + type: "ForStatement"; + init: ForStatementInit | null; + test: Expression | null; + update: Expression | null; + body: Statement; + parent?: Node; +} + +export type ForStatementInit = VariableDeclaration | Expression; + +export interface ForInStatement extends Span { + type: "ForInStatement"; + left: ForStatementLeft; + right: Expression; + body: Statement; + parent?: Node; +} + +export type ForStatementLeft = VariableDeclaration | AssignmentTarget; + +export interface ForOfStatement extends Span { + type: "ForOfStatement"; + await: boolean; + left: ForStatementLeft; + right: Expression; + body: Statement; + parent?: Node; +} + +export interface ContinueStatement extends Span { + type: "ContinueStatement"; + label: LabelIdentifier | null; + parent?: Node; +} + +export interface BreakStatement extends Span { + type: "BreakStatement"; + label: LabelIdentifier | null; + parent?: Node; +} + +export interface ReturnStatement extends Span { + type: "ReturnStatement"; + argument: Expression | null; + parent?: Node; +} + +export interface WithStatement extends Span { + type: "WithStatement"; + object: Expression; + body: Statement; + parent?: Node; +} + +export interface SwitchStatement extends Span { + type: "SwitchStatement"; + discriminant: Expression; + cases: Array; + parent?: Node; +} + +export interface SwitchCase extends Span { + type: "SwitchCase"; + test: Expression | null; + consequent: Array; + parent?: Node; +} + +export interface LabeledStatement extends Span { + type: "LabeledStatement"; + label: LabelIdentifier; + body: Statement; + parent?: Node; +} + +export interface ThrowStatement extends Span { + type: "ThrowStatement"; + argument: Expression; + parent?: Node; +} + +export interface TryStatement extends Span { + type: "TryStatement"; + block: BlockStatement; + handler: CatchClause | null; + finalizer: BlockStatement | null; + parent?: Node; +} + +export interface CatchClause extends Span { + type: "CatchClause"; + param: BindingPattern | null; + body: BlockStatement; + parent?: Node; +} + +export interface DebuggerStatement extends Span { + type: "DebuggerStatement"; + parent?: Node; +} + +export type BindingPattern = BindingIdentifier | ObjectPattern | ArrayPattern | AssignmentPattern; + +export interface AssignmentPattern extends Span { + type: "AssignmentPattern"; + decorators?: []; + left: BindingPattern; + right: Expression; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface ObjectPattern extends Span { + type: "ObjectPattern"; + decorators?: []; + properties: Array; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface BindingProperty extends Span { + type: "Property"; + kind: "init"; + key: PropertyKey; + value: BindingPattern; + method: false; + shorthand: boolean; + computed: boolean; + optional?: false; + parent?: Node; +} + +export interface ArrayPattern extends Span { + type: "ArrayPattern"; + decorators?: []; + elements: Array; + optional?: false; + typeAnnotation?: null; + parent?: Node; +} + +export interface BindingRestElement extends Span { + type: "RestElement"; + decorators?: []; + argument: BindingPattern; + optional?: false; + typeAnnotation?: null; + value?: null; + parent?: Node; +} + +export interface Function extends Span { + type: FunctionType; + id: BindingIdentifier | null; + generator: boolean; + async: boolean; + declare?: boolean; + typeParameters?: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType?: TSTypeAnnotation | null; + body: FunctionBody | null; + expression: false; + parent?: Node; +} + +export type ParamPattern = FormalParameter | TSParameterProperty | FormalParameterRest; + +export type FunctionType = + | "FunctionDeclaration" + | "FunctionExpression" + | "TSDeclareFunction" + | "TSEmptyBodyFunctionExpression"; + +export interface FormalParameterRest extends Span { + type: "RestElement"; + argument: BindingPattern; + decorators?: []; + optional?: boolean; + typeAnnotation?: TSTypeAnnotation | null; + value?: null; + parent?: Node; +} + +export type FormalParameter = { + decorators?: Array; +} & BindingPattern; + +export interface TSParameterProperty extends Span { + type: "TSParameterProperty"; + accessibility: TSAccessibility | null; + decorators: Array; + override: boolean; + parameter: FormalParameter; + readonly: boolean; + static: boolean; + parent?: Node; +} + +export interface FunctionBody extends Span { + type: "BlockStatement"; + body: Array; + parent?: Node; +} + +export interface ArrowFunctionExpression extends Span { + type: "ArrowFunctionExpression"; + expression: boolean; + async: boolean; + typeParameters?: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType?: TSTypeAnnotation | null; + body: FunctionBody | Expression; + id: null; + generator: false; + parent?: Node; +} + +export interface YieldExpression extends Span { + type: "YieldExpression"; + delegate: boolean; + argument: Expression | null; + parent?: Node; +} + +export interface Class extends Span { + type: ClassType; + decorators: Array; + id: BindingIdentifier | null; + typeParameters?: TSTypeParameterDeclaration | null; + superClass: Expression | null; + superTypeArguments?: TSTypeParameterInstantiation | null; + implements?: Array; + body: ClassBody; + abstract?: boolean; + declare?: boolean; + parent?: Node; +} + +export type ClassType = "ClassDeclaration" | "ClassExpression"; + +export interface ClassBody extends Span { + type: "ClassBody"; + body: Array; + parent?: Node; +} + +export type ClassElement = + | StaticBlock + | MethodDefinition + | PropertyDefinition + | AccessorProperty + | TSIndexSignature; + +export interface MethodDefinition extends Span { + type: MethodDefinitionType; + decorators: Array; + key: PropertyKey; + value: Function; + kind: MethodDefinitionKind; + computed: boolean; + static: boolean; + override?: boolean; + optional?: boolean; + accessibility?: TSAccessibility | null; + parent?: Node; +} + +export type MethodDefinitionType = "MethodDefinition" | "TSAbstractMethodDefinition"; + +export interface PropertyDefinition extends Span { + type: PropertyDefinitionType; + decorators: Array; + key: PropertyKey; + typeAnnotation?: TSTypeAnnotation | null; + value: Expression | null; + computed: boolean; + static: boolean; + declare?: boolean; + override?: boolean; + optional?: boolean; + definite?: boolean; + readonly?: boolean; + accessibility?: TSAccessibility | null; + parent?: Node; +} + +export type PropertyDefinitionType = "PropertyDefinition" | "TSAbstractPropertyDefinition"; + +export type MethodDefinitionKind = "constructor" | "method" | "get" | "set"; + +export interface PrivateIdentifier extends Span { + type: "PrivateIdentifier"; + name: string; + parent?: Node; +} + +export interface StaticBlock extends Span { + type: "StaticBlock"; + body: Array; + parent?: Node; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportAllDeclaration + | ExportDefaultDeclaration + | ExportNamedDeclaration + | TSExportAssignment + | TSNamespaceExportDeclaration; + +export type AccessorPropertyType = "AccessorProperty" | "TSAbstractAccessorProperty"; + +export interface AccessorProperty extends Span { + type: AccessorPropertyType; + decorators: Array; + key: PropertyKey; + typeAnnotation?: TSTypeAnnotation | null; + value: Expression | null; + computed: boolean; + static: boolean; + override?: boolean; + definite?: boolean; + accessibility?: TSAccessibility | null; + declare?: false; + optional?: false; + readonly?: false; + parent?: Node; +} + +export interface ImportExpression extends Span { + type: "ImportExpression"; + source: Expression; + options: Expression | null; + phase: ImportPhase | null; + parent?: Node; +} + +export interface ImportDeclaration extends Span { + type: "ImportDeclaration"; + specifiers: Array; + source: StringLiteral; + phase: ImportPhase | null; + attributes: Array; + importKind?: ImportOrExportKind; + parent?: Node; +} + +export type ImportPhase = "source" | "defer"; + +export type ImportDeclarationSpecifier = + | ImportSpecifier + | ImportDefaultSpecifier + | ImportNamespaceSpecifier; + +export interface ImportSpecifier extends Span { + type: "ImportSpecifier"; + imported: ModuleExportName; + local: BindingIdentifier; + importKind?: ImportOrExportKind; + parent?: Node; +} + +export interface ImportDefaultSpecifier extends Span { + type: "ImportDefaultSpecifier"; + local: BindingIdentifier; + parent?: Node; +} + +export interface ImportNamespaceSpecifier extends Span { + type: "ImportNamespaceSpecifier"; + local: BindingIdentifier; + parent?: Node; +} + +export interface ImportAttribute extends Span { + type: "ImportAttribute"; + key: ImportAttributeKey; + value: StringLiteral; + parent?: Node; +} + +export type ImportAttributeKey = IdentifierName | StringLiteral; + +export interface ExportNamedDeclaration extends Span { + type: "ExportNamedDeclaration"; + declaration: Declaration | null; + specifiers: Array; + source: StringLiteral | null; + exportKind?: ImportOrExportKind; + attributes: Array; + parent?: Node; +} + +export interface ExportDefaultDeclaration extends Span { + type: "ExportDefaultDeclaration"; + declaration: ExportDefaultDeclarationKind; + exportKind?: "value"; + parent?: Node; +} + +export interface ExportAllDeclaration extends Span { + type: "ExportAllDeclaration"; + exported: ModuleExportName | null; + source: StringLiteral; + attributes: Array; + exportKind?: ImportOrExportKind; + parent?: Node; +} + +export interface ExportSpecifier extends Span { + type: "ExportSpecifier"; + local: ModuleExportName; + exported: ModuleExportName; + exportKind?: ImportOrExportKind; + parent?: Node; +} + +export type ExportDefaultDeclarationKind = Function | Class | TSInterfaceDeclaration | Expression; + +export type ModuleExportName = IdentifierName | IdentifierReference | StringLiteral; + +export interface V8IntrinsicExpression extends Span { + type: "V8IntrinsicExpression"; + name: IdentifierName; + arguments: Array; + parent?: Node; +} + +export interface BooleanLiteral extends Span { + type: "Literal"; + value: boolean; + raw: string | null; + parent?: Node; +} + +export interface NullLiteral extends Span { + type: "Literal"; + value: null; + raw: "null" | null; + parent?: Node; +} + +export interface NumericLiteral extends Span { + type: "Literal"; + value: number; + raw: string | null; + parent?: Node; +} + +export interface StringLiteral extends Span { + type: "Literal"; + value: string; + raw: string | null; + parent?: Node; +} + +export interface BigIntLiteral extends Span { + type: "Literal"; + value: bigint; + raw: string | null; + bigint: string; + parent?: Node; +} + +export interface RegExpLiteral extends Span { + type: "Literal"; + value: RegExp | null; + raw: string | null; + regex: { pattern: string; flags: string }; + parent?: Node; +} + +export interface JSXElement extends Span { + type: "JSXElement"; + openingElement: JSXOpeningElement; + children: Array; + closingElement: JSXClosingElement | null; + parent?: Node; +} + +export interface JSXOpeningElement extends Span { + type: "JSXOpeningElement"; + name: JSXElementName; + typeArguments?: TSTypeParameterInstantiation | null; + attributes: Array; + selfClosing: boolean; + parent?: Node; +} + +export interface JSXClosingElement extends Span { + type: "JSXClosingElement"; + name: JSXElementName; + parent?: Node; +} + +export interface JSXFragment extends Span { + type: "JSXFragment"; + openingFragment: JSXOpeningFragment; + children: Array; + closingFragment: JSXClosingFragment; + parent?: Node; +} + +export interface JSXOpeningFragment extends Span { + type: "JSXOpeningFragment"; + attributes?: []; + selfClosing?: false; + parent?: Node; +} + +export interface JSXClosingFragment extends Span { + type: "JSXClosingFragment"; + parent?: Node; +} + +export type JSXElementName = JSXIdentifier | JSXNamespacedName | JSXMemberExpression; + +export interface JSXNamespacedName extends Span { + type: "JSXNamespacedName"; + namespace: JSXIdentifier; + name: JSXIdentifier; + parent?: Node; +} + +export interface JSXMemberExpression extends Span { + type: "JSXMemberExpression"; + object: JSXMemberExpressionObject; + property: JSXIdentifier; + parent?: Node; +} + +export type JSXMemberExpressionObject = JSXIdentifier | JSXMemberExpression; + +export interface JSXExpressionContainer extends Span { + type: "JSXExpressionContainer"; + expression: JSXExpression; + parent?: Node; +} + +export type JSXExpression = JSXEmptyExpression | Expression; + +export interface JSXEmptyExpression extends Span { + type: "JSXEmptyExpression"; + parent?: Node; +} + +export type JSXAttributeItem = JSXAttribute | JSXSpreadAttribute; + +export interface JSXAttribute extends Span { + type: "JSXAttribute"; + name: JSXAttributeName; + value: JSXAttributeValue | null; + parent?: Node; +} + +export interface JSXSpreadAttribute extends Span { + type: "JSXSpreadAttribute"; + argument: Expression; + parent?: Node; +} + +export type JSXAttributeName = JSXIdentifier | JSXNamespacedName; + +export type JSXAttributeValue = StringLiteral | JSXExpressionContainer | JSXElement | JSXFragment; + +export interface JSXIdentifier extends Span { + type: "JSXIdentifier"; + name: string; + parent?: Node; +} + +export type JSXChild = JSXText | JSXElement | JSXFragment | JSXExpressionContainer | JSXSpreadChild; + +export interface JSXSpreadChild extends Span { + type: "JSXSpreadChild"; + expression: Expression; + parent?: Node; +} + +export interface JSXText extends Span { + type: "JSXText"; + value: string; + raw: string | null; + parent?: Node; +} + +export interface TSThisParameter extends Span { + type: "Identifier"; + decorators: []; + name: "this"; + optional: false; + typeAnnotation: TSTypeAnnotation | null; + parent?: Node; +} + +export interface TSEnumDeclaration extends Span { + type: "TSEnumDeclaration"; + id: BindingIdentifier; + body: TSEnumBody; + const: boolean; + declare: boolean; + parent?: Node; +} + +export interface TSEnumBody extends Span { + type: "TSEnumBody"; + members: Array; + parent?: Node; +} + +export interface TSEnumMember extends Span { + type: "TSEnumMember"; + id: TSEnumMemberName; + initializer: Expression | null; + computed: boolean; + parent?: Node; +} + +export type TSEnumMemberName = IdentifierName | StringLiteral | TemplateLiteral; + +export interface TSTypeAnnotation extends Span { + type: "TSTypeAnnotation"; + typeAnnotation: TSType; + parent?: Node; +} + +export interface TSLiteralType extends Span { + type: "TSLiteralType"; + literal: TSLiteral; + parent?: Node; +} + +export type TSLiteral = + | BooleanLiteral + | NumericLiteral + | BigIntLiteral + | StringLiteral + | TemplateLiteral + | UnaryExpression; + +export type TSType = + | TSAnyKeyword + | TSBigIntKeyword + | TSBooleanKeyword + | TSIntrinsicKeyword + | TSNeverKeyword + | TSNullKeyword + | TSNumberKeyword + | TSObjectKeyword + | TSStringKeyword + | TSSymbolKeyword + | TSUndefinedKeyword + | TSUnknownKeyword + | TSVoidKeyword + | TSArrayType + | TSConditionalType + | TSConstructorType + | TSFunctionType + | TSImportType + | TSIndexedAccessType + | TSInferType + | TSIntersectionType + | TSLiteralType + | TSMappedType + | TSNamedTupleMember + | TSTemplateLiteralType + | TSThisType + | TSTupleType + | TSTypeLiteral + | TSTypeOperator + | TSTypePredicate + | TSTypeQuery + | TSTypeReference + | TSUnionType + | TSParenthesizedType + | JSDocNullableType + | JSDocNonNullableType + | JSDocUnknownType; + +export interface TSConditionalType extends Span { + type: "TSConditionalType"; + checkType: TSType; + extendsType: TSType; + trueType: TSType; + falseType: TSType; + parent?: Node; +} + +export interface TSUnionType extends Span { + type: "TSUnionType"; + types: Array; + parent?: Node; +} + +export interface TSIntersectionType extends Span { + type: "TSIntersectionType"; + types: Array; + parent?: Node; +} + +export interface TSParenthesizedType extends Span { + type: "TSParenthesizedType"; + typeAnnotation: TSType; + parent?: Node; +} + +export interface TSTypeOperator extends Span { + type: "TSTypeOperator"; + operator: TSTypeOperatorOperator; + typeAnnotation: TSType; + parent?: Node; +} + +export type TSTypeOperatorOperator = "keyof" | "unique" | "readonly"; + +export interface TSArrayType extends Span { + type: "TSArrayType"; + elementType: TSType; + parent?: Node; +} + +export interface TSIndexedAccessType extends Span { + type: "TSIndexedAccessType"; + objectType: TSType; + indexType: TSType; + parent?: Node; +} + +export interface TSTupleType extends Span { + type: "TSTupleType"; + elementTypes: Array; + parent?: Node; +} + +export interface TSNamedTupleMember extends Span { + type: "TSNamedTupleMember"; + label: IdentifierName; + elementType: TSTupleElement; + optional: boolean; + parent?: Node; +} + +export interface TSOptionalType extends Span { + type: "TSOptionalType"; + typeAnnotation: TSType; + parent?: Node; +} + +export interface TSRestType extends Span { + type: "TSRestType"; + typeAnnotation: TSType; + parent?: Node; +} + +export type TSTupleElement = TSOptionalType | TSRestType | TSType; + +export interface TSAnyKeyword extends Span { + type: "TSAnyKeyword"; + parent?: Node; +} + +export interface TSStringKeyword extends Span { + type: "TSStringKeyword"; + parent?: Node; +} + +export interface TSBooleanKeyword extends Span { + type: "TSBooleanKeyword"; + parent?: Node; +} + +export interface TSNumberKeyword extends Span { + type: "TSNumberKeyword"; + parent?: Node; +} + +export interface TSNeverKeyword extends Span { + type: "TSNeverKeyword"; + parent?: Node; +} + +export interface TSIntrinsicKeyword extends Span { + type: "TSIntrinsicKeyword"; + parent?: Node; +} + +export interface TSUnknownKeyword extends Span { + type: "TSUnknownKeyword"; + parent?: Node; +} + +export interface TSNullKeyword extends Span { + type: "TSNullKeyword"; + parent?: Node; +} + +export interface TSUndefinedKeyword extends Span { + type: "TSUndefinedKeyword"; + parent?: Node; +} + +export interface TSVoidKeyword extends Span { + type: "TSVoidKeyword"; + parent?: Node; +} + +export interface TSSymbolKeyword extends Span { + type: "TSSymbolKeyword"; + parent?: Node; +} + +export interface TSThisType extends Span { + type: "TSThisType"; + parent?: Node; +} + +export interface TSObjectKeyword extends Span { + type: "TSObjectKeyword"; + parent?: Node; +} + +export interface TSBigIntKeyword extends Span { + type: "TSBigIntKeyword"; + parent?: Node; +} + +export interface TSTypeReference extends Span { + type: "TSTypeReference"; + typeName: TSTypeName; + typeArguments: TSTypeParameterInstantiation | null; + parent?: Node; +} + +export type TSTypeName = IdentifierReference | TSQualifiedName | ThisExpression; + +export interface TSQualifiedName extends Span { + type: "TSQualifiedName"; + left: TSTypeName; + right: IdentifierName; + parent?: Node; +} + +export interface TSTypeParameterInstantiation extends Span { + type: "TSTypeParameterInstantiation"; + params: Array; + parent?: Node; +} + +export interface TSTypeParameter extends Span { + type: "TSTypeParameter"; + name: BindingIdentifier; + constraint: TSType | null; + default: TSType | null; + in: boolean; + out: boolean; + const: boolean; + parent?: Node; +} + +export interface TSTypeParameterDeclaration extends Span { + type: "TSTypeParameterDeclaration"; + params: Array; + parent?: Node; +} + +export interface TSTypeAliasDeclaration extends Span { + type: "TSTypeAliasDeclaration"; + id: BindingIdentifier; + typeParameters: TSTypeParameterDeclaration | null; + typeAnnotation: TSType; + declare: boolean; + parent?: Node; +} + +export type TSAccessibility = "private" | "protected" | "public"; + +export interface TSClassImplements extends Span { + type: "TSClassImplements"; + expression: IdentifierReference | ThisExpression | MemberExpression; + typeArguments: TSTypeParameterInstantiation | null; + parent?: Node; +} + +export interface TSInterfaceDeclaration extends Span { + type: "TSInterfaceDeclaration"; + id: BindingIdentifier; + typeParameters: TSTypeParameterDeclaration | null; + extends: Array; + body: TSInterfaceBody; + declare: boolean; + parent?: Node; +} + +export interface TSInterfaceBody extends Span { + type: "TSInterfaceBody"; + body: Array; + parent?: Node; +} + +export interface TSPropertySignature extends Span { + type: "TSPropertySignature"; + computed: boolean; + optional: boolean; + readonly: boolean; + key: PropertyKey; + typeAnnotation: TSTypeAnnotation | null; + accessibility: null; + static: false; + parent?: Node; +} + +export type TSSignature = + | TSIndexSignature + | TSPropertySignature + | TSCallSignatureDeclaration + | TSConstructSignatureDeclaration + | TSMethodSignature; + +export interface TSIndexSignature extends Span { + type: "TSIndexSignature"; + parameters: Array; + typeAnnotation: TSTypeAnnotation; + readonly: boolean; + static: boolean; + accessibility: null; + parent?: Node; +} + +export interface TSCallSignatureDeclaration extends Span { + type: "TSCallSignatureDeclaration"; + typeParameters: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType: TSTypeAnnotation | null; + parent?: Node; +} + +export type TSMethodSignatureKind = "method" | "get" | "set"; + +export interface TSMethodSignature extends Span { + type: "TSMethodSignature"; + key: PropertyKey; + computed: boolean; + optional: boolean; + kind: TSMethodSignatureKind; + typeParameters: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType: TSTypeAnnotation | null; + accessibility: null; + readonly: false; + static: false; + parent?: Node; +} + +export interface TSConstructSignatureDeclaration extends Span { + type: "TSConstructSignatureDeclaration"; + typeParameters: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType: TSTypeAnnotation | null; + parent?: Node; +} + +export interface TSIndexSignatureName extends Span { + type: "Identifier"; + decorators: []; + name: string; + optional: false; + typeAnnotation: TSTypeAnnotation; + parent?: Node; +} + +export interface TSInterfaceHeritage extends Span { + type: "TSInterfaceHeritage"; + expression: Expression; + typeArguments: TSTypeParameterInstantiation | null; + parent?: Node; +} + +export interface TSTypePredicate extends Span { + type: "TSTypePredicate"; + parameterName: TSTypePredicateName; + asserts: boolean; + typeAnnotation: TSTypeAnnotation | null; + parent?: Node; +} + +export type TSTypePredicateName = IdentifierName | TSThisType; + +export interface TSModuleDeclaration extends Span { + type: "TSModuleDeclaration"; + id: BindingIdentifier | StringLiteral | TSQualifiedName; + body: TSModuleBlock | null; + kind: TSModuleDeclarationKind; + declare: boolean; + global: false; + parent?: Node; +} + +export type TSModuleDeclarationKind = "module" | "namespace"; + +export interface TSGlobalDeclaration extends Span { + type: "TSModuleDeclaration"; + id: IdentifierName; + body: TSModuleBlock; + kind: "global"; + declare: boolean; + global: true; + parent?: Node; +} + +export interface TSModuleBlock extends Span { + type: "TSModuleBlock"; + body: Array; + parent?: Node; +} + +export interface TSTypeLiteral extends Span { + type: "TSTypeLiteral"; + members: Array; + parent?: Node; +} + +export interface TSInferType extends Span { + type: "TSInferType"; + typeParameter: TSTypeParameter; + parent?: Node; +} + +export interface TSTypeQuery extends Span { + type: "TSTypeQuery"; + exprName: TSTypeQueryExprName; + typeArguments: TSTypeParameterInstantiation | null; + parent?: Node; +} + +export type TSTypeQueryExprName = TSImportType | TSTypeName; + +export interface TSImportType extends Span { + type: "TSImportType"; + source: StringLiteral; + options: ObjectExpression | null; + qualifier: TSImportTypeQualifier | null; + typeArguments: TSTypeParameterInstantiation | null; + parent?: Node; +} + +export type TSImportTypeQualifier = IdentifierName | TSImportTypeQualifiedName; + +export interface TSImportTypeQualifiedName extends Span { + type: "TSQualifiedName"; + left: TSImportTypeQualifier; + right: IdentifierName; + parent?: Node; +} + +export interface TSFunctionType extends Span { + type: "TSFunctionType"; + typeParameters: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType: TSTypeAnnotation; + parent?: Node; +} + +export interface TSConstructorType extends Span { + type: "TSConstructorType"; + abstract: boolean; + typeParameters: TSTypeParameterDeclaration | null; + params: ParamPattern[]; + returnType: TSTypeAnnotation; + parent?: Node; +} + +export interface TSMappedType extends Span { + type: "TSMappedType"; + key: BindingIdentifier; + constraint: TSType; + nameType: TSType | null; + typeAnnotation: TSType | null; + optional: TSMappedTypeModifierOperator | false; + readonly: TSMappedTypeModifierOperator | null; + parent?: Node; +} + +export type TSMappedTypeModifierOperator = true | "+" | "-"; + +export interface TSTemplateLiteralType extends Span { + type: "TSTemplateLiteralType"; + quasis: Array; + types: Array; + parent?: Node; +} + +export interface TSAsExpression extends Span { + type: "TSAsExpression"; + expression: Expression; + typeAnnotation: TSType; + parent?: Node; +} + +export interface TSSatisfiesExpression extends Span { + type: "TSSatisfiesExpression"; + expression: Expression; + typeAnnotation: TSType; + parent?: Node; +} + +export interface TSTypeAssertion extends Span { + type: "TSTypeAssertion"; + typeAnnotation: TSType; + expression: Expression; + parent?: Node; +} + +export interface TSImportEqualsDeclaration extends Span { + type: "TSImportEqualsDeclaration"; + id: BindingIdentifier; + moduleReference: TSModuleReference; + importKind: ImportOrExportKind; + parent?: Node; +} + +export type TSModuleReference = TSExternalModuleReference | IdentifierReference | TSQualifiedName; + +export interface TSExternalModuleReference extends Span { + type: "TSExternalModuleReference"; + expression: StringLiteral; + parent?: Node; +} + +export interface TSNonNullExpression extends Span { + type: "TSNonNullExpression"; + expression: Expression; + parent?: Node; +} + +export interface Decorator extends Span { + type: "Decorator"; + expression: Expression; + parent?: Node; +} + +export interface TSExportAssignment extends Span { + type: "TSExportAssignment"; + expression: Expression; + parent?: Node; +} + +export interface TSNamespaceExportDeclaration extends Span { + type: "TSNamespaceExportDeclaration"; + id: IdentifierName; + parent?: Node; +} + +export interface TSInstantiationExpression extends Span { + type: "TSInstantiationExpression"; + expression: Expression; + typeArguments: TSTypeParameterInstantiation; + parent?: Node; +} + +export type ImportOrExportKind = "value" | "type"; + +export interface JSDocNullableType extends Span { + type: "TSJSDocNullableType"; + typeAnnotation: TSType; + postfix: boolean; + parent?: Node; +} + +export interface JSDocNonNullableType extends Span { + type: "TSJSDocNonNullableType"; + typeAnnotation: TSType; + postfix: boolean; + parent?: Node; +} + +export interface JSDocUnknownType extends Span { + type: "TSJSDocUnknownType"; + parent?: Node; +} + +export type ModuleKind = "script" | "module" | "commonjs"; + +export interface Span { + start: number; + end: number; + range?: [number, number]; +} + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "<<" + | ">>" + | ">>>" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type UnaryOperator = "+" | "-" | "!" | "~" | "typeof" | "void" | "delete"; + +export type UpdateOperator = "++" | "--"; + +export type Node = + | Program + | IdentifierName + | IdentifierReference + | BindingIdentifier + | LabelIdentifier + | ThisExpression + | ArrayExpression + | ObjectExpression + | ObjectProperty + | TemplateLiteral + | TaggedTemplateExpression + | TemplateElement + | ComputedMemberExpression + | StaticMemberExpression + | PrivateFieldExpression + | CallExpression + | NewExpression + | MetaProperty + | SpreadElement + | UpdateExpression + | UnaryExpression + | BinaryExpression + | PrivateInExpression + | LogicalExpression + | ConditionalExpression + | AssignmentExpression + | ArrayAssignmentTarget + | ObjectAssignmentTarget + | AssignmentTargetRest + | AssignmentTargetWithDefault + | AssignmentTargetPropertyIdentifier + | AssignmentTargetPropertyProperty + | SequenceExpression + | Super + | AwaitExpression + | ChainExpression + | ParenthesizedExpression + | Directive + | Hashbang + | BlockStatement + | VariableDeclaration + | VariableDeclarator + | EmptyStatement + | ExpressionStatement + | IfStatement + | DoWhileStatement + | WhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | ContinueStatement + | BreakStatement + | ReturnStatement + | WithStatement + | SwitchStatement + | SwitchCase + | LabeledStatement + | ThrowStatement + | TryStatement + | CatchClause + | DebuggerStatement + | AssignmentPattern + | ObjectPattern + | BindingProperty + | ArrayPattern + | BindingRestElement + | Function + | FunctionBody + | ArrowFunctionExpression + | YieldExpression + | Class + | ClassBody + | MethodDefinition + | PropertyDefinition + | PrivateIdentifier + | StaticBlock + | AccessorProperty + | ImportExpression + | ImportDeclaration + | ImportSpecifier + | ImportDefaultSpecifier + | ImportNamespaceSpecifier + | ImportAttribute + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration + | ExportSpecifier + | V8IntrinsicExpression + | BooleanLiteral + | NullLiteral + | NumericLiteral + | StringLiteral + | BigIntLiteral + | RegExpLiteral + | JSXElement + | JSXOpeningElement + | JSXClosingElement + | JSXFragment + | JSXOpeningFragment + | JSXClosingFragment + | JSXNamespacedName + | JSXMemberExpression + | JSXExpressionContainer + | JSXEmptyExpression + | JSXAttribute + | JSXSpreadAttribute + | JSXIdentifier + | JSXSpreadChild + | JSXText + | TSThisParameter + | TSEnumDeclaration + | TSEnumBody + | TSEnumMember + | TSTypeAnnotation + | TSLiteralType + | TSConditionalType + | TSUnionType + | TSIntersectionType + | TSParenthesizedType + | TSTypeOperator + | TSArrayType + | TSIndexedAccessType + | TSTupleType + | TSNamedTupleMember + | TSOptionalType + | TSRestType + | TSAnyKeyword + | TSStringKeyword + | TSBooleanKeyword + | TSNumberKeyword + | TSNeverKeyword + | TSIntrinsicKeyword + | TSUnknownKeyword + | TSNullKeyword + | TSUndefinedKeyword + | TSVoidKeyword + | TSSymbolKeyword + | TSThisType + | TSObjectKeyword + | TSBigIntKeyword + | TSTypeReference + | TSQualifiedName + | TSTypeParameterInstantiation + | TSTypeParameter + | TSTypeParameterDeclaration + | TSTypeAliasDeclaration + | TSClassImplements + | TSInterfaceDeclaration + | TSInterfaceBody + | TSPropertySignature + | TSIndexSignature + | TSCallSignatureDeclaration + | TSMethodSignature + | TSConstructSignatureDeclaration + | TSIndexSignatureName + | TSInterfaceHeritage + | TSTypePredicate + | TSModuleDeclaration + | TSGlobalDeclaration + | TSModuleBlock + | TSTypeLiteral + | TSInferType + | TSTypeQuery + | TSImportType + | TSImportTypeQualifiedName + | TSFunctionType + | TSConstructorType + | TSMappedType + | TSTemplateLiteralType + | TSAsExpression + | TSSatisfiesExpression + | TSTypeAssertion + | TSImportEqualsDeclaration + | TSExternalModuleReference + | TSNonNullExpression + | Decorator + | TSExportAssignment + | TSNamespaceExportDeclaration + | TSInstantiationExpression + | JSDocNullableType + | JSDocNonNullableType + | JSDocUnknownType + | ParamPattern; diff --git a/node_modules/@playwright/test/LICENSE b/node_modules/@playwright/test/LICENSE new file mode 100644 index 000000000..df112373e --- /dev/null +++ b/node_modules/@playwright/test/LICENSE @@ -0,0 +1,202 @@ + 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. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@playwright/test/NOTICE b/node_modules/@playwright/test/NOTICE new file mode 100644 index 000000000..814ec1696 --- /dev/null +++ b/node_modules/@playwright/test/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/node_modules/@playwright/test/README.md b/node_modules/@playwright/test/README.md new file mode 100644 index 000000000..4a44d1f0c --- /dev/null +++ b/node_modules/@playwright/test/README.md @@ -0,0 +1,170 @@ +# 🎭 Playwright + +[![npm version](https://img.shields.io/npm/v/playwright.svg)](https://www.npmjs.com/package/playwright) [![Chromium version](https://img.shields.io/badge/chromium-147.0.7727.15-blue.svg?logo=google-chrome)](https://www.chromium.org/Home) [![Firefox version](https://img.shields.io/badge/firefox-148.0.2-blue.svg?logo=firefoxbrowser)](https://www.mozilla.org/en-US/firefox/new/) [![WebKit version](https://img.shields.io/badge/webkit-26.4-blue.svg?logo=safari)](https://webkit.org/) [![Join Discord](https://img.shields.io/badge/join-discord-informational)](https://aka.ms/playwright/discord) + +## [Documentation](https://playwright.dev) | [API reference](https://playwright.dev/docs/api/class-playwright) + +Playwright is a framework for Web Testing and Automation. It allows testing [Chromium](https://www.chromium.org/Home)1, [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable**, and **fast**. + +| | Linux | macOS | Windows | +| :--- | :---: | :---: | :---: | +| Chromium1 147.0.7727.15 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| WebKit 26.4 | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Firefox 148.0.2 | :white_check_mark: | :white_check_mark: | :white_check_mark: | + +Headless execution is supported for all browsers on all platforms. Check out [system requirements](https://playwright.dev/docs/intro#system-requirements) for details. + +Looking for Playwright for [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)? + +1 Playwright uses [Chrome for Testing](https://developer.chrome.com/blog/chrome-for-testing) by default. + +## Installation + +Playwright has its own test runner for end-to-end tests, we call it Playwright Test. + +### Using init command + +The easiest way to get started with Playwright Test is to run the init command. + +```Shell +# Run from your project's root directory +npm init playwright@latest +# Or create a new project +npm init playwright@latest new-project +``` + +This will create a configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts. You can now jump directly to writing assertions section. + +### Manually + +Add dependency and install browsers. + +```Shell +npm i -D @playwright/test +# install supported browsers +npx playwright install +``` + +You can optionally install only selected browsers, see [install browsers](https://playwright.dev/docs/cli#install-browsers) for more details. Or you can install no browsers at all and use existing [browser channels](https://playwright.dev/docs/browsers). + +* [Getting started](https://playwright.dev/docs/intro) +* [API reference](https://playwright.dev/docs/api/class-playwright) + +## Capabilities + +### Resilient • No flaky tests + +**Auto-wait**. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts - a primary cause of flaky tests. + +**Web-first assertions**. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met. + +**Tracing**. Configure test retry strategy, capture execution trace, videos and screenshots to eliminate flakes. + +### No trade-offs • No limits + +Browsers run web content belonging to different origins in different processes. Playwright is aligned with the architecture of the modern browsers and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations. + +**Multiple everything**. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test. + +**Trusted events**. Hover elements, interact with dynamic controls and produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user. + +Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly. + +### Full isolation • Fast execution + +**Browser contexts**. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds. + +**Log in once**. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests. + +### Powerful Tooling + +**[Codegen](https://playwright.dev/docs/codegen)**. Generate tests by recording your actions. Save them into any language. + +**[Playwright inspector](https://playwright.dev/docs/inspector)**. Inspect page, generate selectors, step through the test execution, see click points and explore execution logs. + +**[Trace Viewer](https://playwright.dev/docs/trace-viewer)**. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source and many more. + +Looking for Playwright for [TypeScript](https://playwright.dev/docs/intro), [JavaScript](https://playwright.dev/docs/intro), [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)? + +## Examples + +To learn how to run these Playwright Test examples, check out our [getting started docs](https://playwright.dev/docs/intro). + +#### Page screenshot + +This code snippet navigates to Playwright homepage and saves a screenshot. + +```TypeScript +import { test } from '@playwright/test'; + +test('Page Screenshot', async ({ page }) => { + await page.goto('https://playwright.dev/'); + await page.screenshot({ path: `example.png` }); +}); +``` + +#### Mobile and geolocation + +This snippet emulates Mobile Safari on a device at given geolocation, navigates to maps.google.com, performs the action and takes a screenshot. + +```TypeScript +import { test, devices } from '@playwright/test'; + +test.use({ + ...devices['iPhone 13 Pro'], + locale: 'en-US', + geolocation: { longitude: 12.492507, latitude: 41.889938 }, + permissions: ['geolocation'], +}) + +test('Mobile and geolocation', async ({ page }) => { + await page.goto('https://maps.google.com'); + await page.getByText('Your location').click(); + await page.waitForRequest(/.*preview\/pwa/); + await page.screenshot({ path: 'colosseum-iphone.png' }); +}); +``` + +#### Evaluate in browser context + +This code snippet navigates to example.com, and executes a script in the page context. + +```TypeScript +import { test } from '@playwright/test'; + +test('Evaluate in browser context', async ({ page }) => { + await page.goto('https://www.example.com/'); + const dimensions = await page.evaluate(() => { + return { + width: document.documentElement.clientWidth, + height: document.documentElement.clientHeight, + deviceScaleFactor: window.devicePixelRatio + } + }); + console.log(dimensions); +}); +``` + +#### Intercept network requests + +This code snippet sets up request routing for a page to log all network requests. + +```TypeScript +import { test } from '@playwright/test'; + +test('Intercept network requests', async ({ page }) => { + // Log and continue all network requests + await page.route('**', route => { + console.log(route.request().url()); + route.continue(); + }); + await page.goto('http://todomvc.com'); +}); +``` + +## Resources + +* [Documentation](https://playwright.dev) +* [API reference](https://playwright.dev/docs/api/class-playwright/) +* [Contribution guide](CONTRIBUTING.md) +* [Changelog](https://github.com/microsoft/playwright/releases) diff --git a/node_modules/@playwright/test/cli.js b/node_modules/@playwright/test/cli.js new file mode 100644 index 000000000..e42facb07 --- /dev/null +++ b/node_modules/@playwright/test/cli.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +const { program } = require('playwright/lib/program'); +program.parse(process.argv); diff --git a/node_modules/@playwright/test/index.d.ts b/node_modules/@playwright/test/index.d.ts new file mode 100644 index 000000000..8d99c9150 --- /dev/null +++ b/node_modules/@playwright/test/index.d.ts @@ -0,0 +1,18 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +export * from 'playwright/test'; +export { default } from 'playwright/test'; diff --git a/node_modules/@playwright/test/index.js b/node_modules/@playwright/test/index.js new file mode 100644 index 000000000..8536f0639 --- /dev/null +++ b/node_modules/@playwright/test/index.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +module.exports = require('playwright/test'); diff --git a/node_modules/@playwright/test/index.mjs b/node_modules/@playwright/test/index.mjs new file mode 100644 index 000000000..8d99c9150 --- /dev/null +++ b/node_modules/@playwright/test/index.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +export * from 'playwright/test'; +export { default } from 'playwright/test'; diff --git a/node_modules/@playwright/test/package.json b/node_modules/@playwright/test/package.json new file mode 100644 index 000000000..fedc3f4e2 --- /dev/null +++ b/node_modules/@playwright/test/package.json @@ -0,0 +1,35 @@ +{ + "name": "@playwright/test", + "version": "1.59.1", + "description": "A high-level API to automate web browsers", + "repository": { + "type": "git", + "url": "git+https://github.com/microsoft/playwright.git" + }, + "homepage": "https://playwright.dev", + "engines": { + "node": ">=18" + }, + "author": { + "name": "Microsoft Corporation" + }, + "license": "Apache-2.0", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "require": "./index.js", + "default": "./index.js" + }, + "./cli": "./cli.js", + "./package.json": "./package.json", + "./reporter": "./reporter.js" + }, + "bin": { + "playwright": "cli.js" + }, + "scripts": {}, + "dependencies": { + "playwright": "1.59.1" + } +} diff --git a/node_modules/@playwright/test/reporter.d.ts b/node_modules/@playwright/test/reporter.d.ts new file mode 100644 index 000000000..806d13fb0 --- /dev/null +++ b/node_modules/@playwright/test/reporter.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +export * from 'playwright/types/testReporter'; diff --git a/node_modules/@playwright/test/reporter.js b/node_modules/@playwright/test/reporter.js new file mode 100644 index 000000000..485e880a6 --- /dev/null +++ b/node_modules/@playwright/test/reporter.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +// We only export types in reporter.d.ts. diff --git a/node_modules/@playwright/test/reporter.mjs b/node_modules/@playwright/test/reporter.mjs new file mode 100644 index 000000000..485e880a6 --- /dev/null +++ b/node_modules/@playwright/test/reporter.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * 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. + */ + +// We only export types in reporter.d.ts. diff --git a/node_modules/@rolldown/binding-linux-x64-gnu/README.md b/node_modules/@rolldown/binding-linux-x64-gnu/README.md new file mode 100644 index 000000000..deea4245f --- /dev/null +++ b/node_modules/@rolldown/binding-linux-x64-gnu/README.md @@ -0,0 +1,3 @@ +# `@rolldown/binding-linux-x64-gnu` + +This is the **x86_64-unknown-linux-gnu** binary for `@rolldown/binding` diff --git a/node_modules/@rolldown/binding-linux-x64-gnu/package.json b/node_modules/@rolldown/binding-linux-x64-gnu/package.json new file mode 100644 index 000000000..2fc03dc99 --- /dev/null +++ b/node_modules/@rolldown/binding-linux-x64-gnu/package.json @@ -0,0 +1,40 @@ +{ + "name": "@rolldown/binding-linux-x64-gnu", + "version": "1.0.0-rc.17", + "cpu": [ + "x64" + ], + "main": "rolldown-binding.linux-x64-gnu.node", + "files": [ + "rolldown-binding.linux-x64-gnu.node" + ], + "description": "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.", + "keywords": [ + "bundler", + "esbuild", + "parcel", + "rolldown", + "rollup", + "webpack" + ], + "homepage": "https://rolldown.rs/", + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/rolldown/rolldown.git", + "directory": "packages/rolldown" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "os": [ + "linux" + ], + "libc": [ + "glibc" + ] +} \ No newline at end of file diff --git a/node_modules/@rolldown/binding-linux-x64-gnu/rolldown-binding.linux-x64-gnu.node b/node_modules/@rolldown/binding-linux-x64-gnu/rolldown-binding.linux-x64-gnu.node new file mode 100644 index 000000000..ca23bc15c Binary files /dev/null and b/node_modules/@rolldown/binding-linux-x64-gnu/rolldown-binding.linux-x64-gnu.node differ diff --git a/node_modules/@rolldown/binding-linux-x64-musl/README.md b/node_modules/@rolldown/binding-linux-x64-musl/README.md new file mode 100644 index 000000000..bd8447710 --- /dev/null +++ b/node_modules/@rolldown/binding-linux-x64-musl/README.md @@ -0,0 +1,3 @@ +# `@rolldown/binding-linux-x64-musl` + +This is the **x86_64-unknown-linux-musl** binary for `@rolldown/binding` diff --git a/node_modules/@rolldown/binding-linux-x64-musl/package.json b/node_modules/@rolldown/binding-linux-x64-musl/package.json new file mode 100644 index 000000000..a1d49c60a --- /dev/null +++ b/node_modules/@rolldown/binding-linux-x64-musl/package.json @@ -0,0 +1,40 @@ +{ + "name": "@rolldown/binding-linux-x64-musl", + "version": "1.0.0-rc.17", + "cpu": [ + "x64" + ], + "main": "rolldown-binding.linux-x64-musl.node", + "files": [ + "rolldown-binding.linux-x64-musl.node" + ], + "description": "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.", + "keywords": [ + "bundler", + "esbuild", + "parcel", + "rolldown", + "rollup", + "webpack" + ], + "homepage": "https://rolldown.rs/", + "license": "MIT", + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/rolldown/rolldown.git", + "directory": "packages/rolldown" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "os": [ + "linux" + ], + "libc": [ + "musl" + ] +} \ No newline at end of file diff --git a/node_modules/@rolldown/binding-linux-x64-musl/rolldown-binding.linux-x64-musl.node b/node_modules/@rolldown/binding-linux-x64-musl/rolldown-binding.linux-x64-musl.node new file mode 100644 index 000000000..645c23a61 Binary files /dev/null and b/node_modules/@rolldown/binding-linux-x64-musl/rolldown-binding.linux-x64-musl.node differ diff --git a/node_modules/@rolldown/pluginutils/LICENSE b/node_modules/@rolldown/pluginutils/LICENSE new file mode 100644 index 000000000..afc0cdbab --- /dev/null +++ b/node_modules/@rolldown/pluginutils/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) 2024-present VoidZero Inc. & 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. + +end of terms and conditions + +The licenses of externally maintained libraries from which parts of the Software is derived are listed [here](https://github.com/rolldown/rolldown/blob/main/THIRD-PARTY-LICENSE). diff --git a/node_modules/@rolldown/pluginutils/README.md b/node_modules/@rolldown/pluginutils/README.md new file mode 100644 index 000000000..6d29a9010 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/README.md @@ -0,0 +1,83 @@ +# @rolldown/pluginutils + +A utility library for building flexible, composable filter expressions that can be used in plugin hook filters of Rolldown/Vite/Rollup/Unplugin plugins. + +## Installation + +```sh +pnpm add @rolldown/pluginutils +``` + +## Usage + +### Simple Filters + +```ts +import { exactRegex, makeIdFiltersToMatchWithQuery, prefixRegex } from '@rolldown/pluginutils'; + +// Match exactly 'foo.js' +const filter = exactRegex('foo.js'); + +// Match any id starting with 'lib/' +const prefix = prefixRegex('lib/'); + +// Match ids with query params (e.g. 'foo.js?bar') +const idFilters = makeIdFiltersToMatchWithQuery(['**/*.js', /\.ts$/]); + +// Usage in a plugin to define a hook filter +const myPlugin = { + resolveId: { + filter: { + id: [exactRegex('MY_ID_TO_CHECK'), /some-other-regex/], + }, + handler(id) { + // Your code here + }, + }, +}; +``` + +### Composable Filters + +> [!WARNING] +> Composable filters are not yet supported in Vite or unplugin. They can be used in Rolldown plugins only. + +```ts +import { and, id, include, moduleType, query } from '@rolldown/pluginutils'; + +// Build a filter expression +const filterExpr = and(id(/\.ts$/), moduleType('ts'), query('foo', true)); + +// Usage in a plugin to define a hook filter +const myPlugin = { + transform: { + filter: [include(filterExpr)], + handler(code, id, options) { + // Your code here + }, + }, +}; +``` + +## API Reference + +### Simple Filters + +- `exactRegex(str: string, flags?: string): RegExp` — Matches the exact string. +- `prefixRegex(str: string, flags?: string): RegExp` — Matches values with the given prefix. +- `makeIdFiltersToMatchWithQuery(input: string | RegExp | (string | RegExp)[]): string | RegExp | (string | RegExp)[]` — Adapts filters to match ids with query params. + +### Composable Filters + +- `and(...exprs)` / `or(...exprs)` / `not(expr)` — Logical composition of filter expressions. +- `id(pattern, params?)` — Filter by id. A `string` pattern is matched by exact equality (not glob); a `RegExp` is tested against the id. +- `importerId(pattern, params?)` — Filter by importer id. A `string` pattern is matched by exact equality; a `RegExp` is tested against the importer id. Only usable with the `resolveId` hook. +- `moduleType(type)` — Filter by module type (e.g. 'js', 'tsx', or 'json'). +- `code(pattern)` — Filter by code content. +- `query(key, pattern)` — Filter by query parameter. +- `include(expr)` / `exclude(expr)` — Top-level include/exclude wrappers. +- `queries(obj)` — Compose multiple query filters. + +### Utilities + +- `filterVitePlugins(plugins)` — Filters out Vite plugins with `apply: 'serve'`. diff --git a/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.d.ts b/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.d.ts new file mode 100644 index 000000000..9e622a11e --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.d.ts @@ -0,0 +1,90 @@ +type StringOrRegExp = string | RegExp; +type PluginModuleType = 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'text' | 'base64' | 'dataurl' | 'binary' | 'empty' | (string & {}); +export type FilterExpressionKind = FilterExpression['kind']; +export type FilterExpression = And | Or | Not | Id | ImporterId | ModuleType | Code | Query; +export type TopLevelFilterExpression = Include | Exclude; +declare class And { + kind: 'and'; + args: FilterExpression[]; + constructor(...args: FilterExpression[]); +} +declare class Or { + kind: 'or'; + args: FilterExpression[]; + constructor(...args: FilterExpression[]); +} +declare class Not { + kind: 'not'; + expr: FilterExpression; + constructor(expr: FilterExpression); +} +export interface QueryFilterObject { + [key: string]: StringOrRegExp | boolean; +} +interface IdParams { + cleanUrl?: boolean; +} +declare class Id { + kind: 'id'; + pattern: StringOrRegExp; + params: IdParams; + constructor(pattern: StringOrRegExp, params?: IdParams); +} +declare class ImporterId { + kind: 'importerId'; + pattern: StringOrRegExp; + params: IdParams; + constructor(pattern: StringOrRegExp, params?: IdParams); +} +declare class ModuleType { + kind: 'moduleType'; + pattern: PluginModuleType; + constructor(pattern: PluginModuleType); +} +declare class Code { + kind: 'code'; + pattern: StringOrRegExp; + constructor(expr: StringOrRegExp); +} +declare class Query { + kind: 'query'; + key: string; + pattern: StringOrRegExp | boolean; + constructor(key: string, pattern: StringOrRegExp | boolean); +} +declare class Include { + kind: 'include'; + expr: FilterExpression; + constructor(expr: FilterExpression); +} +declare class Exclude { + kind: 'exclude'; + expr: FilterExpression; + constructor(expr: FilterExpression); +} +export declare function and(...args: FilterExpression[]): And; +export declare function or(...args: FilterExpression[]): Or; +export declare function not(expr: FilterExpression): Not; +export declare function id(pattern: StringOrRegExp, params?: IdParams): Id; +export declare function importerId(pattern: StringOrRegExp, params?: IdParams): ImporterId; +export declare function moduleType(pattern: PluginModuleType): ModuleType; +export declare function code(pattern: StringOrRegExp): Code; +export declare function query(key: string, pattern: StringOrRegExp | boolean): Query; +export declare function include(expr: FilterExpression): Include; +export declare function exclude(expr: FilterExpression): Exclude; +/** + * convert a queryObject to FilterExpression like + * ```js + * and(query(k1, v1), query(k2, v2)) + * ``` + * @param queryFilterObject The query filter object needs to be matched. + * @returns a `And` FilterExpression + */ +export declare function queries(queryFilter: QueryFilterObject): And; +export declare function interpreter(exprs: TopLevelFilterExpression | TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string): boolean; +interface InterpreterCtx { + urlSearchParamsCache?: URLSearchParams; +} +export declare function interpreterImpl(expr: TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean; +export declare function exprInterpreter(expr: FilterExpression, code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean; +export {}; diff --git a/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.js b/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.js new file mode 100644 index 000000000..186356267 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/composable-filters.js @@ -0,0 +1,256 @@ +import { cleanUrl, extractQueryWithoutFragment } from "../utils.js"; +class And { + kind; + args; + constructor(...args) { + if (args.length === 0) { + throw new Error('`And` expects at least one operand'); + } + this.args = args; + this.kind = 'and'; + } +} +class Or { + kind; + args; + constructor(...args) { + if (args.length === 0) { + throw new Error('`Or` expects at least one operand'); + } + this.args = args; + this.kind = 'or'; + } +} +class Not { + kind; + expr; + constructor(expr) { + this.expr = expr; + this.kind = 'not'; + } +} +class Id { + kind; + pattern; + params; + constructor(pattern, params) { + this.pattern = pattern; + this.kind = 'id'; + this.params = params ?? { + cleanUrl: false, + }; + } +} +class ImporterId { + kind; + pattern; + params; + constructor(pattern, params) { + this.pattern = pattern; + this.kind = 'importerId'; + this.params = params ?? { + cleanUrl: false, + }; + } +} +class ModuleType { + kind; + pattern; + constructor(pattern) { + this.pattern = pattern; + this.kind = 'moduleType'; + } +} +class Code { + kind; + pattern; + constructor(expr) { + this.pattern = expr; + this.kind = 'code'; + } +} +class Query { + kind; + key; + pattern; + constructor(key, pattern) { + this.pattern = pattern; + this.key = key; + this.kind = 'query'; + } +} +class Include { + kind; + expr; + constructor(expr) { + this.expr = expr; + this.kind = 'include'; + } +} +class Exclude { + kind; + expr; + constructor(expr) { + this.expr = expr; + this.kind = 'exclude'; + } +} +export function and(...args) { + return new And(...args); +} +export function or(...args) { + return new Or(...args); +} +export function not(expr) { + return new Not(expr); +} +export function id(pattern, params) { + return new Id(pattern, params); +} +export function importerId(pattern, params) { + return new ImporterId(pattern, params); +} +export function moduleType(pattern) { + return new ModuleType(pattern); +} +export function code(pattern) { + return new Code(pattern); +} +/* + * There are three kinds of conditions are supported: + * 1. `boolean`: if the value is `true`, the key must exist and be truthy. if the value is `false`, the key must not exist or be falsy. + * 2. `string`: the key must exist and be equal to the value. + * 3. `RegExp`: the key must exist and match the value. + */ +export function query(key, pattern) { + return new Query(key, pattern); +} +export function include(expr) { + return new Include(expr); +} +export function exclude(expr) { + return new Exclude(expr); +} +/** + * convert a queryObject to FilterExpression like + * ```js + * and(query(k1, v1), query(k2, v2)) + * ``` + * @param queryFilterObject The query filter object needs to be matched. + * @returns a `And` FilterExpression + */ +export function queries(queryFilter) { + let arr = Object.entries(queryFilter).map(([key, value]) => { + return new Query(key, value); + }); + return and(...arr); +} +export function interpreter(exprs, code, id, moduleType, importerId) { + let arr = []; + if (Array.isArray(exprs)) { + arr = exprs; + } + else { + arr = [exprs]; + } + return interpreterImpl(arr, code, id, moduleType, importerId); +} +export function interpreterImpl(expr, code, id, moduleType, importerId, ctx = {}) { + let hasInclude = false; + for (const e of expr) { + switch (e.kind) { + case 'include': { + hasInclude = true; + if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) { + return true; + } + break; + } + case 'exclude': { + if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) { + return false; + } + break; + } + } + } + return !hasInclude; +} +export function exprInterpreter(expr, code, id, moduleType, importerId, ctx = {}) { + switch (expr.kind) { + case 'and': { + return expr.args.every((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx)); + } + case 'or': { + return expr.args.some((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx)); + } + case 'not': { + return !exprInterpreter(expr.expr, code, id, moduleType, importerId, ctx); + } + case 'id': { + if (id === undefined) { + throw new Error('`id` is required for `id` expression'); + } + let idToMatch = id; + if (expr.params.cleanUrl) { + idToMatch = cleanUrl(idToMatch); + } + return typeof expr.pattern === 'string' + ? idToMatch === expr.pattern + : expr.pattern.test(idToMatch); + } + case 'importerId': { + if (importerId === undefined) { + return false; // Entry files have no importer, so no match + } + let importerIdToMatch = importerId; + if (expr.params.cleanUrl) { + importerIdToMatch = cleanUrl(importerIdToMatch); + } + return typeof expr.pattern === 'string' + ? importerIdToMatch === expr.pattern + : expr.pattern.test(importerIdToMatch); + } + case 'moduleType': { + if (moduleType === undefined) { + throw new Error('`moduleType` is required for `moduleType` expression'); + } + return moduleType === expr.pattern; + } + case 'code': { + if (code === undefined) { + throw new Error('`code` is required for `code` expression'); + } + return typeof expr.pattern === 'string' + ? code.includes(expr.pattern) + : expr.pattern.test(code); + } + case 'query': { + if (id === undefined) { + throw new Error('`id` is required for `Query` expression'); + } + if (!ctx.urlSearchParamsCache) { + let queryString = extractQueryWithoutFragment(id); + ctx.urlSearchParamsCache = new URLSearchParams(queryString); + } + let urlParams = ctx.urlSearchParamsCache; + if (typeof expr.pattern === 'boolean') { + if (expr.pattern) { + return urlParams.has(expr.key); + } + else { + return !urlParams.has(expr.key); + } + } + else if (typeof expr.pattern === 'string') { + return urlParams.get(expr.key) === expr.pattern; + } + else { + return expr.pattern.test(urlParams.get(expr.key) ?? ''); + } + } + default: { + throw new Error(`Expression ${JSON.stringify(expr)} is not expected.`); + } + } +} diff --git a/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.d.ts b/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.d.ts new file mode 100644 index 000000000..256d8fce4 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.d.ts @@ -0,0 +1,28 @@ +/** + * Filters out Vite plugins that have `apply: 'serve'` set. + * + * Since Rolldown operates in build mode, plugins marked with `apply: 'serve'` + * are intended only for Vite's dev server and should be excluded from the build process. + * + * @param plugins - Array of plugins (can include nested arrays) + * @returns Filtered array with serve-only plugins removed + * + * @example + * ```ts + * import { defineConfig } from 'rolldown'; + * import { filterVitePlugins } from '@rolldown/pluginutils'; + * import viteReact from '@vitejs/plugin-react'; + * + * export default defineConfig({ + * plugins: filterVitePlugins([ + * viteReact(), + * { + * name: 'dev-only', + * apply: 'serve', // This will be filtered out + * // ... + * } + * ]) + * }); + * ``` + */ +export declare function filterVitePlugins(plugins: T | T[] | null | undefined | false): T[]; diff --git a/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.js b/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.js new file mode 100644 index 000000000..dea79ca97 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/filter-vite-plugins.js @@ -0,0 +1,75 @@ +/** + * Filters out Vite plugins that have `apply: 'serve'` set. + * + * Since Rolldown operates in build mode, plugins marked with `apply: 'serve'` + * are intended only for Vite's dev server and should be excluded from the build process. + * + * @param plugins - Array of plugins (can include nested arrays) + * @returns Filtered array with serve-only plugins removed + * + * @example + * ```ts + * import { defineConfig } from 'rolldown'; + * import { filterVitePlugins } from '@rolldown/pluginutils'; + * import viteReact from '@vitejs/plugin-react'; + * + * export default defineConfig({ + * plugins: filterVitePlugins([ + * viteReact(), + * { + * name: 'dev-only', + * apply: 'serve', // This will be filtered out + * // ... + * } + * ]) + * }); + * ``` + */ +export function filterVitePlugins(plugins) { + if (!plugins) { + return []; + } + const pluginArray = Array.isArray(plugins) ? plugins : [plugins]; + const result = []; + for (const plugin of pluginArray) { + // Skip falsy values + if (!plugin) { + continue; + } + // Handle nested arrays recursively + if (Array.isArray(plugin)) { + result.push(...filterVitePlugins(plugin)); + continue; + } + // Check if plugin has apply property + const pluginWithApply = plugin; + if ('apply' in pluginWithApply) { + const applyValue = pluginWithApply.apply; + // If apply is a function, call it with build mode + if (typeof applyValue === 'function') { + try { + const shouldApply = applyValue({}, // config object + { command: 'build', mode: 'production' }); + if (shouldApply) { + result.push(plugin); + } + } + catch { + // If function throws, include the plugin to be safe + result.push(plugin); + } + } // If apply is 'serve', skip this plugin + else if (applyValue === 'serve') { + continue; + } // If apply is 'build' or anything else, include it + else { + result.push(plugin); + } + } + else { + // No apply property, include the plugin + result.push(plugin); + } + } + return result; +} diff --git a/node_modules/@rolldown/pluginutils/dist/filter/index.d.ts b/node_modules/@rolldown/pluginutils/dist/filter/index.d.ts new file mode 100644 index 000000000..a7a1ea237 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/index.d.ts @@ -0,0 +1,3 @@ +export * from './composable-filters.ts'; +export * from './filter-vite-plugins.ts'; +export * from './simple-filters.ts'; diff --git a/node_modules/@rolldown/pluginutils/dist/filter/index.js b/node_modules/@rolldown/pluginutils/dist/filter/index.js new file mode 100644 index 000000000..6f5bb4fa8 --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/index.js @@ -0,0 +1,3 @@ +export * from "./composable-filters.js"; +export * from "./filter-vite-plugins.js"; +export * from "./simple-filters.js"; diff --git a/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.d.ts b/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.d.ts new file mode 100644 index 000000000..1f033615c --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.d.ts @@ -0,0 +1,71 @@ +/** + * Constructs a RegExp that matches the exact string specified. + * + * This is useful for plugin hook filters. + * + * @param str the string to match. + * @param flags flags for the RegExp. + * + * @example + * ```ts + * import { exactRegex } from '@rolldown/pluginutils'; + * const plugin = { + * name: 'plugin', + * resolveId: { + * filter: { id: exactRegex('foo') }, + * handler(id) {} // will only be called for `foo` + * } + * } + * ``` + */ +export declare function exactRegex(str: string, flags?: string): RegExp; +/** + * Constructs a RegExp that matches a value that has the specified prefix. + * + * This is useful for plugin hook filters. + * + * @param str the string to match. + * @param flags flags for the RegExp. + * + * @example + * ```ts + * import { prefixRegex } from '@rolldown/pluginutils'; + * const plugin = { + * name: 'plugin', + * resolveId: { + * filter: { id: prefixRegex('foo') }, + * handler(id) {} // will only be called for IDs starting with `foo` + * } + * } + * ``` + */ +export declare function prefixRegex(str: string, flags?: string): RegExp; +type WidenString = T extends string ? string : T; +/** + * Converts a id filter to match with an id with a query. + * + * @param input the id filters to convert. + * + * @example + * ```ts + * import { makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils'; + * const plugin = { + * name: 'plugin', + * transform: { + * filter: { id: makeIdFiltersToMatchWithQuery(['**' + '/*.js', /\.ts$/]) }, + * // The handler will be called for IDs like: + * // - foo.js + * // - foo.js?foo + * // - foo.txt?foo.js + * // - foo.ts + * // - foo.ts?foo + * // - foo.txt?foo.ts + * handler(code, id) {} + * } + * } + * ``` + */ +export declare function makeIdFiltersToMatchWithQuery(input: T): WidenString; +export declare function makeIdFiltersToMatchWithQuery(input: readonly T[]): WidenString[]; +export declare function makeIdFiltersToMatchWithQuery(input: string | RegExp | readonly (string | RegExp)[]): string | RegExp | (string | RegExp)[]; +export {}; diff --git a/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.js b/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.js new file mode 100644 index 000000000..241380c8d --- /dev/null +++ b/node_modules/@rolldown/pluginutils/dist/filter/simple-filters.js @@ -0,0 +1,70 @@ +/** + * Constructs a RegExp that matches the exact string specified. + * + * This is useful for plugin hook filters. + * + * @param str the string to match. + * @param flags flags for the RegExp. + * + * @example + * ```ts + * import { exactRegex } from '@rolldown/pluginutils'; + * const plugin = { + * name: 'plugin', + * resolveId: { + * filter: { id: exactRegex('foo') }, + * handler(id) {} // will only be called for `foo` + * } + * } + * ``` + */ +export function exactRegex(str, flags) { + return new RegExp(`^${escapeRegex(str)}$`, flags); +} +/** + * Constructs a RegExp that matches a value that has the specified prefix. + * + * This is useful for plugin hook filters. + * + * @param str the string to match. + * @param flags flags for the RegExp. + * + * @example + * ```ts + * import { prefixRegex } from '@rolldown/pluginutils'; + * const plugin = { + * name: 'plugin', + * resolveId: { + * filter: { id: prefixRegex('foo') }, + * handler(id) {} // will only be called for IDs starting with `foo` + * } + * } + * ``` + */ +export function prefixRegex(str, flags) { + return new RegExp(`^${escapeRegex(str)}`, flags); +} +const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; +function escapeRegex(str) { + return str.replace(escapeRegexRE, '\\$&'); +} +export function makeIdFiltersToMatchWithQuery(input) { + if (!Array.isArray(input)) { + return makeIdFilterToMatchWithQuery( + // Array.isArray cannot narrow the type + // https://github.com/microsoft/TypeScript/issues/17002 + input); + } + return input.map((i) => makeIdFilterToMatchWithQuery(i)); +} +function makeIdFilterToMatchWithQuery(input) { + if (typeof input === 'string') { + return `${input}{?*,}`; + } + return makeRegexIdFilterToMatchWithQuery(input); +} +function makeRegexIdFilterToMatchWithQuery(input) { + return new RegExp( + // replace `$` with `(?:\?.*)?$` (ignore `\$`) + input.source.replace(/(? + Standard Schema fire logo +
+ Standard Schema +

+ A family of specs for interoperable TypeScript +
+ standardschema.dev +

+
+ + + +The Standard Schema project is a set of interfaces that standardize the provision and consumption of shared functionality in the TypeScript ecosystem. + +Its goal is to allow tools to accept a single input that includes all the types and capabilities they need— no library-specific adapters, no extra dependencies. The result is an ecosystem that's fair for implementers, friendly for consumers, and open for end users. + +## The specifications + +The specifications can be found below in their entirety. Libraries wishing to implement a spec can copy/paste the code block below into their codebase. They're also available at `@standard-schema/spec` on [npm](https://www.npmjs.com/package/@standard-schema/spec) and [JSR](https://jsr.io/@standard-schema/spec). + +```ts +// ######################### +// ### Standard Typed ### +// ######################### + +/** The Standard Typed interface. This is a base type extended by other specs. */ +export interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} + +export declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + export interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + + /** The Standard Typed types interface. */ + export interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + + /** Infers the input type of a Standard Typed. */ + export type InferInput = NonNullable< + Schema["~standard"]["types"] + >["input"]; + + /** Infers the output type of a Standard Typed. */ + export type InferOutput = NonNullable< + Schema["~standard"]["types"] + >["output"]; +} + +// ########################## +// ### Standard Schema ### +// ########################## + +/** The Standard Schema interface. */ +export interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} + +export declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: ( + value: unknown, + options?: StandardSchemaV1.Options | undefined + ) => Result | Promise>; + } + + /** The result interface of the validate function. */ + export type Result = SuccessResult | FailureResult; + + /** The result interface if validation succeeds. */ + export interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + + export interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The result interface if validation fails. */ + export interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + + /** The issue interface of the failure output. */ + export interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + + /** The path segment interface of the issue. */ + export interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} + +// ############################### +// ### Standard JSON Schema ### +// ############################### + +/** The Standard JSON Schema interface. */ +export interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} + +export declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + export interface Props + extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + + /** The Standard JSON Schema converter interface. */ + export interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: ( + options: StandardJSONSchemaV1.Options + ) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: ( + options: StandardJSONSchemaV1.Options + ) => Record; + } + + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + export type Target = + | "draft-2020-12" + | "draft-07" + | "openapi-3.0" + // Accepts any string for future targets while preserving autocomplete + | ({} & string); + + /** The options for the input/output methods. */ + export interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The Standard types interface. */ + export interface Types + extends StandardTypedV1.Types {} + + /** Infers the input type of a Standard. */ + export type InferInput = + StandardTypedV1.InferInput; + + /** Infers the output type of a Standard. */ + export type InferOutput = + StandardTypedV1.InferOutput; +} +``` diff --git a/node_modules/@standard-schema/spec/dist/index.cjs b/node_modules/@standard-schema/spec/dist/index.cjs new file mode 100644 index 000000000..321666eb3 --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.cjs @@ -0,0 +1,18 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); diff --git a/node_modules/@standard-schema/spec/dist/index.d.cts b/node_modules/@standard-schema/spec/dist/index.d.cts new file mode 100644 index 000000000..5e4acaad2 --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.d.cts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/node_modules/@standard-schema/spec/dist/index.d.ts b/node_modules/@standard-schema/spec/dist/index.d.ts new file mode 100644 index 000000000..5e4acaad2 --- /dev/null +++ b/node_modules/@standard-schema/spec/dist/index.d.ts @@ -0,0 +1,119 @@ +/** The Standard Typed interface. This is a base type extended by other specs. */ +interface StandardTypedV1 { + /** The Standard properties. */ + readonly "~standard": StandardTypedV1.Props; +} +declare namespace StandardTypedV1 { + /** The Standard Typed properties interface. */ + interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + /** The Standard Typed types interface. */ + interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + /** Infers the input type of a Standard Typed. */ + type InferInput = NonNullable["input"]; + /** Infers the output type of a Standard Typed. */ + type InferOutput = NonNullable["output"]; +} +/** The Standard Schema interface. */ +interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly "~standard": StandardSchemaV1.Props; +} +declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Validates unknown input values. */ + readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; + } + /** The result interface of the validate function. */ + type Result = SuccessResult | FailureResult; + /** The result interface if validation succeeds. */ + interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The result interface if validation fails. */ + interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + /** The issue interface of the failure output. */ + interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + /** The path segment interface of the issue. */ + interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} +/** The Standard JSON Schema interface. */ +interface StandardJSONSchemaV1 { + /** The Standard JSON Schema properties. */ + readonly "~standard": StandardJSONSchemaV1.Props; +} +declare namespace StandardJSONSchemaV1 { + /** The Standard JSON Schema properties interface. */ + interface Props extends StandardTypedV1.Props { + /** Methods for generating the input/output JSON Schema. */ + readonly jsonSchema: StandardJSONSchemaV1.Converter; + } + /** The Standard JSON Schema converter interface. */ + interface Converter { + /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ + readonly input: (options: StandardJSONSchemaV1.Options) => Record; + /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ + readonly output: (options: StandardJSONSchemaV1.Options) => Record; + } + /** + * The target version of the generated JSON Schema. + * + * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. + * + * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. + */ + type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); + /** The options for the input/output methods. */ + interface Options { + /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ + readonly target: Target; + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + /** The Standard types interface. */ + interface Types extends StandardTypedV1.Types { + } + /** Infers the input type of a Standard. */ + type InferInput = StandardTypedV1.InferInput; + /** Infers the output type of a Standard. */ + type InferOutput = StandardTypedV1.InferOutput; +} + +export { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 }; diff --git a/node_modules/@standard-schema/spec/dist/index.js b/node_modules/@standard-schema/spec/dist/index.js new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/@standard-schema/spec/package.json b/node_modules/@standard-schema/spec/package.json new file mode 100644 index 000000000..62bb55187 --- /dev/null +++ b/node_modules/@standard-schema/spec/package.json @@ -0,0 +1,52 @@ +{ + "name": "@standard-schema/spec", + "description": "A family of specs for interoperable TypeScript", + "version": "1.1.0", + "license": "MIT", + "author": "Colin McDonnell", + "homepage": "https://standardschema.dev", + "repository": { + "type": "git", + "url": "https://github.com/standard-schema/standard-schema" + }, + "keywords": [ + "typescript", + "schema", + "validation", + "standard", + "interface" + ], + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "standard-schema-spec": "./src/index.ts", + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "tsup": "^8.3.0", + "typescript": "^5.6.2" + }, + "scripts": { + "lint": "pnpm biome lint ./src", + "format": "pnpm biome format --write ./src", + "check": "pnpm biome check ./src", + "build": "tsup" + } +} \ No newline at end of file diff --git a/node_modules/@types/chai/LICENSE b/node_modules/@types/chai/LICENSE new file mode 100644 index 000000000..9e841e7a2 --- /dev/null +++ b/node_modules/@types/chai/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/chai/README.md b/node_modules/@types/chai/README.md new file mode 100644 index 000000000..27c135678 --- /dev/null +++ b/node_modules/@types/chai/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/chai` + +# Summary +This package contains type definitions for chai (http://chaijs.com/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai. + +### Additional Details + * Last updated: Mon, 20 Oct 2025 23:32:35 GMT + * Dependencies: [@types/deep-eql](https://npmjs.com/package/@types/deep-eql), [assertion-error](https://npmjs.com/package/assertion-error) + +# Credits +These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), [Andrew Brown](https://github.com/AGBrown), [Olivier Chevet](https://github.com/olivr70), [Matt Wistrand](https://github.com/mwistrand), [Shaun Luttin](https://github.com/shaunluttin), [Satana Charuwichitratana](https://github.com/micksatana), [Erik Schierboom](https://github.com/ErikSchierboom), [Bogdan Paranytsia](https://github.com/bparan), [CXuesong](https://github.com/CXuesong), and [Joey Kilpatrick](https://github.com/joeykilpatrick). diff --git a/node_modules/@types/chai/index.d.ts b/node_modules/@types/chai/index.d.ts new file mode 100644 index 000000000..4fed6b906 --- /dev/null +++ b/node_modules/@types/chai/index.d.ts @@ -0,0 +1,2145 @@ +import deepEqual = require("deep-eql"); +import { AssertionError as ImportedAssertionError } from "assertion-error"; + +declare global { + namespace Chai { + export type Message = string | (() => string); + export type ObjectProperty = string | symbol | number; + + export interface PathInfo { + parent: object; + name: string; + value?: any; + exists: boolean; + } + + export interface Constructor { + new(...args: any[]): T; + } + + export interface ErrorConstructor { + new(...args: any[]): Error; + } + + export interface ChaiUtils { + addChainableMethod( + // object to define the method on, e.g. chai.Assertion.prototype + ctx: object, + // method name + name: string, + // method itself; any arguments + method: (...args: any[]) => void, + // called when property is accessed + chainingBehavior?: () => void, + ): void; + overwriteChainableMethod( + ctx: object, + name: string, + method: (...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + addLengthGuard( + fn: Function, + assertionName: string, + isChainable: boolean, + ): void; + addMethod(ctx: object, name: string, method: Function): void; + addProperty(ctx: object, name: string, getter: () => any): void; + overwriteMethod(ctx: object, name: string, method: Function): void; + overwriteProperty(ctx: object, name: string, getter: (this: AssertionStatic, _super: any) => any): void; + compareByInspect(a: object, b: object): -1 | 1; + expectTypes(obj: object, types: string[]): void; + flag(obj: object, key: string, value?: any): any; + getActual(obj: object, args: AssertionArgs): any; + getProperties(obj: object): string[]; + getEnumerableProperties(obj: object): string[]; + getOwnEnumerablePropertySymbols(obj: object): symbol[]; + getOwnEnumerableProperties(obj: object): Array; + getMessage(errorLike: Error | string): string; + getMessage(obj: any, args: AssertionArgs): string; + inspect(obj: any, showHidden?: boolean, depth?: number, colors?: boolean): string; + isProxyEnabled(): boolean; + objDisplay(obj: object): void; + proxify(obj: object, nonChainableMethodName: string): object; + test(obj: object, args: AssertionArgs): boolean; + transferFlags(assertion: Assertion, obj: object, includeAll?: boolean): void; + compatibleInstance(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleConstructor(thrown: Error, errorLike: Error | ErrorConstructor): boolean; + compatibleMessage(thrown: Error, errMatcher: string | RegExp): boolean; + getConstructorName(constructorFn: Function): string; + getFuncName(constructorFn: Function): string | null; + + // Reexports from pathval: + hasProperty(obj: object | undefined | null, name: ObjectProperty): boolean; + getPathInfo(obj: object, path: string): PathInfo; + getPathValue(obj: object, path: string): object | undefined; + + eql: typeof deepEqual; + } + + export type ChaiPlugin = (chai: ChaiStatic, utils: ChaiUtils) => void; + + export interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: ChaiPlugin): ChaiStatic; + util: ChaiUtils; + assert: AssertStatic; + config: Config; + Assertion: AssertionStatic; + AssertionError: typeof AssertionError; + version: string; + } + + export interface ExpectStatic { + (val: any, message?: string): Assertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface AssertStatic extends Assert { + } + + // chai.Assertion.prototype.assert arguments + export type AssertionArgs = [ + any, // expression to be tested + Message, // message or function that returns message to display if expression fails + Message, // negatedMessage or function that returns negatedMessage to display if expression fails + any?, // expected value + any?, // actual value + boolean?, // showDiff, when set to `true`, assert will display a diff in addition to the message if expression fails + ]; + + export interface AssertionPrototype { + assert(...args: AssertionArgs): void; + _obj: any; + } + + export interface AssertionStatic extends AssertionPrototype { + prototype: AssertionPrototype; + + new(target: any, message?: string, ssfi?: Function, lockSsfi?: boolean): Assertion; + + // Deprecated properties: + includeStack: boolean; + showDiff: boolean; + + // Partials of functions on ChaiUtils: + addProperty(name: string, getter: (this: AssertionStatic) => any): void; + addMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + addChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + overwriteProperty(name: string, getter: (this: AssertionStatic, _super: any) => any): void; + overwriteMethod(name: string, method: (this: AssertionStatic, ...args: any[]) => any): void; + overwriteChainableMethod( + name: string, + method: (this: AssertionStatic, ...args: any[]) => void, + chainingBehavior?: () => void, + ): void; + } + + export type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; + + export type OperatorComparable = boolean | null | number | string | undefined | Date; + + export interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + export interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(message?: string): never; + fail(actual: any, expected: any, message?: string, operator?: Operator): never; + } + + export interface ShouldThrow { + (actual: Function, expected?: string | RegExp, message?: string): void; + (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; + } + + export interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + ordered: Ordered; + nested: Nested; + own: Own; + any: KeyFilter; + all: KeyFilter; + a: Assertion; + an: Assertion; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + finite: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + containSubset: ContainSubset; + property: Property; + ownProperty: Property; + haveOwnProperty: Property; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf: OneOf; + } + + export interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + but: Assertion; + does: Assertion; + } + + export interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + greaterThanOrEqual: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + lessThanOrEqual: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + within(start: Date, finish: Date, message?: string): Assertion; + } + + export interface NumberComparer { + (value: number | Date, message?: string): Assertion; + } + + export interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + export interface InstanceOf { + (constructor: any, message?: string): Assertion; + } + + export interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + export interface Nested { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + members: Members; + } + + export interface Own { + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + } + + export interface Deep extends KeyFilter { + be: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + include: Include; + includes: Include; + contain: Include; + contains: Include; + property: Property; + ordered: Ordered; + nested: Nested; + oneOf: OneOf; + own: Own; + } + + export interface Ordered { + members: Members; + } + + export interface KeyFilter { + keys: Keys; + members: Members; + } + + export interface Equal { + (value: any, message?: string): Assertion; + } + + export interface ContainSubset { + (expected: any): Assertion; + } + + export interface Property { + (name: string | symbol, value: any, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface OwnPropertyDescriptor { + (name: string | symbol, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string | symbol, message?: string): Assertion; + } + + export interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + export interface Include { + (value: any, message?: string): Assertion; + keys: Keys; + deep: Deep; + ordered: Ordered; + members: Members; + any: KeyFilter; + all: KeyFilter; + oneOf: OneOf; + } + + export interface OneOf { + (list: readonly unknown[], message?: string): Assertion; + } + + export interface Match { + (regexp: RegExp, message?: string): Assertion; + } + + export interface Keys { + (...keys: string[]): Assertion; + (keys: readonly any[] | Object): Assertion; + } + + export interface Throw { + (expected?: string | RegExp, message?: string): Assertion; + (constructor: Error | Function, expected?: string | RegExp, message?: string): Assertion; + } + + export interface RespondTo { + (method: string, message?: string): Assertion; + } + + export interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + export interface Members { + (set: readonly any[], message?: string): Assertion; + } + + export interface PropertyChange { + (object: Object, property?: string, message?: string): DeltaAssertion; + } + + export interface DeltaAssertion extends Assertion { + by(delta: number, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): asserts expression; + + /** + * Throws a failure. + * + * @param message Message to display on error. + * @remarks Node.js assert module-compatible. + */ + fail(message?: string): never; + + /** + * Throws a failure. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + * @param operator Comparison operator, if not strict equality. + * @remarks Node.js assert module-compatible. + */ + fail(actual: T, expected: T, message?: string, operator?: Operator): never; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + isOk(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is truthy. + * + * @param object Object to test. + * @param message Message to display on error. + */ + ok(value: unknown, message?: string): asserts value; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotOk(value: T, message?: string): void; + + /** + * Asserts that object is falsy. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + notOk(value: T, message?: string): void; + + /** + * Asserts non-strict equality (==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + equal(actual: T, expected: T, message?: string): void; + + /** + * Asserts non-strict inequality (!=) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict equality (===) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + strictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts strict inequality (!==) of actual and expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepEqual(actual: T, expected: T, message?: string): void; + + /** + * Asserts that actual is not deeply equal to expected. + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + notDeepEqual(actual: T, expected: T, message?: string): void; + + /** + * Alias to deepEqual + * + * T Type of the objects. + * @param actual Actual value. + * @param expected Potential expected value. + * @param message Message to display on error. + */ + deepStrictEqual(actual: T, expected: T, message?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containSubset(val: any, exp: any, msg?: string): void; + + /** + * Partially matches actual and expected. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + containsSubset(val: any, exp: any, msg?: string): void; + + /** + * No partial match between actual and expected exists. + * + * @param actual Actual value. + * @param expected Potential subset of the value. + * @param message Message to display on error. + */ + doesNotContainSubset(val: any, exp: any, msg?: string): void; + + /** + * Asserts valueToCheck is strictly greater than (>) valueToBeAbove. + * + * @param valueToCheck Actual value. + * @param valueToBeAbove Minimum Potential expected value. + * @param message Message to display on error. + */ + isAbove(valueToCheck: number, valueToBeAbove: number, message?: string): void; + + /** + * Asserts valueToCheck is greater than or equal to (>=) valueToBeAtLeast. + * + * @param valueToCheck Actual value. + * @param valueToBeAtLeast Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtLeast(valueToCheck: number, valueToBeAtLeast: number, message?: string): void; + + /** + * Asserts valueToCheck is strictly less than (<) valueToBeBelow. + * + * @param valueToCheck Actual value. + * @param valueToBeBelow Minimum Potential expected value. + * @param message Message to display on error. + */ + isBelow(valueToCheck: number, valueToBeBelow: number, message?: string): void; + + /** + * Asserts valueToCheck is less than or equal to (<=) valueToBeAtMost. + * + * @param valueToCheck Actual value. + * @param valueToBeAtMost Minimum Potential expected value. + * @param message Message to display on error. + */ + isAtMost(valueToCheck: number, valueToBeAtMost: number, message?: string): void; + + /** + * Asserts that value is true. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isTrue(value: unknown, message?: string): asserts value is true; + + /** + * Asserts that value is false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isFalse(value: unknown, message?: string): asserts value is false; + + /** + * Asserts that value is not true. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotTrue(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is not false. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFalse(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is null. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isNull(value: unknown, message?: string): asserts value is null; + + /** + * Asserts that value is not null. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNull(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNaN(value: T, message?: string): void; + + /** + * Asserts that value is not NaN. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNaN(value: T, message?: string): void; + + /** + * Asserts that the target is neither null nor undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): asserts value is NonNullable; + + /** + * Asserts that the target is either null or undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: unknown, message?: string): asserts value is + | null + | undefined; + + /** + * Asserts that value is undefined. + * + * @param value Actual value. + * @param message Message to display on error. + */ + isUndefined(value: unknown, message?: string): asserts value is undefined; + + /** + * Asserts that value is not undefined. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isDefined(value: T, message?: string): asserts value is Exclude; + + /** + * Asserts that value is a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isFunction(value: T, message?: string): void; + + /** + * Asserts that value is not a function. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotFunction(value: T, message?: string): void; + + /** + * Asserts that value is an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + * @remarks The assertion does not match subclassed objects. + */ + isObject(value: T, message?: string): void; + + /** + * Asserts that value is not an object of type 'Object' + * (as revealed by Object.prototype.toString). + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotObject(value: T, message?: string): void; + + /** + * Asserts that value is an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isArray(value: T, message?: string): void; + + /** + * Asserts that value is not an array. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotArray(value: T, message?: string): void; + + /** + * Asserts that value is a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isString(value: T, message?: string): void; + + /** + * Asserts that value is not a string. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotString(value: T, message?: string): void; + + /** + * Asserts that value is a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNumber(value: T, message?: string): void; + + /** + * Asserts that value is not a number. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotNumber(value: T, message?: string): void; + + /** + * Asserts that value is a finite number. + * Unlike `.isNumber`, this will fail for `NaN` and `Infinity`. + * + * T Type of value + * @param value Actual value + * @param message Message to display on error. + */ + isFinite(value: T, message?: string): void; + + /** + * Asserts that value is a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isBoolean(value: T, message?: string): void; + + /** + * Asserts that value is not a boolean. + * + * T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + isNotBoolean(value: T, message?: string): void; + + /** + * Asserts that value's type is name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + typeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value's type is not name, as determined by Object.prototype.toString. + * + * T Type of value. + * @param value Actual value. + * @param name Potential expected type name of value. + * @param message Message to display on error. + */ + notTypeOf(value: T, name: string, message?: string): void; + + /** + * Asserts that value is an instance of constructor. + * + * T Expected type of value. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + instanceOf( + value: unknown, + constructor: Constructor, + message?: string, + ): asserts value is T; + + /** + * Asserts that value is not an instance of constructor. + * + * T Type of value. + * U Type that value shouldn't be an instance of. + * @param value Actual value. + * @param constructor Potential expected contructor of value. + * @param message Message to display on error. + */ + notInstanceOf(value: T, type: Constructor, message?: string): asserts value is Exclude; + + /** + * Asserts that haystack includes needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + include(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + include(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack includes needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + include(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + */ + notInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of values in haystack. + * @param haystack WeakSet container. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notInclude(haystack: WeakSet, needle: T, message?: string): void; + + /** + * Asserts that haystack does not include needle. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notInclude(haystack: T, needle: Partial, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#include} instead. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + deepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack includes needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + deepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential substring of haystack. + * @param message Message to display on error. + * + * @deprecated Does not have any effect on string. Use {@link Assert#notInclude} instead. + */ + notDeepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of values in haystack. + * @param haystack Container array, set or map. + * @param needle Potential value contained in haystack. + * @param message Message to display on error. + */ + notDeepInclude( + haystack: readonly T[] | ReadonlySet | ReadonlyMap, + needle: T, + message?: string, + ): void; + + /** + * Asserts that haystack does not include needle. Deep equality is used. + * + * T Type of haystack. + * @param haystack Object. + * @param needle Potential subset of the haystack's properties. + * @param message Message to display on error. + */ + notDeepInclude(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that value matches the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + match(value: string, regexp: RegExp, message?: string): void; + + /** + * Asserts that value does not match the regular expression regexp. + * + * @param value Actual value. + * @param regexp Potential match of value. + * @param message Message to display on error. + */ + notMatch(expected: any, regexp: RegExp, message?: string): void; + + /** + * Asserts that object has a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + property(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object does not have a property named by property. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notProperty(object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + deepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * @param object Container object. + * @param property Potential contained property of object. + * @param message Message to display on error. + */ + notDeepProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + propertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notPropertyVal(object: T, property: string, /* keyof T */ value: V, message?: string): void; + + /** + * Asserts that object has a property named by property, which can be a string + * using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + deepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object does not have a property named by property, which can be a + * string using dot- and bracket-notation for deep reference. + * + * T Type of object. + * V Type of value. + * @param object Container object. + * @param property Potential contained property of object. + * @param value Potential expected property value. + * @param message Message to display on error. + */ + notDeepPropertyVal(object: T, property: string, value: V, message?: string): void; + + /** + * Asserts that object has a length property with the expected value. + * + * T Type of object. + * @param object Container object. + * @param length Potential expected length of object. + * @param message Message to display on error. + */ + lengthOf( + object: T, + length: number, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + throws(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + throws( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + Throw(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + Throw( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errMsgMatcher Expected error message matcher. + * @param ignored Ignored parameter. + * @param message Message to display on error. + */ + doesNotThrow(fn: () => void, errMsgMatcher?: RegExp | string, ignored?: any, message?: string): void; + + /** + * Asserts that fn will not throw an error. + * + * @param fn Function that may throw. + * @param errorLike Expected error constructor or error instance. + * @param errMsgMatcher Expected error message matcher. + * @param message Message to display on error. + */ + doesNotThrow( + fn: () => void, + errorLike?: ErrorConstructor | Error | null, + errMsgMatcher?: RegExp | string | null, + message?: string, + ): void; + + /** + * Compares two values using operator. + * + * @param val1 Left value during comparison. + * @param operator Comparison operator. + * @param val2 Right value during comparison. + * @param message Message to display on error. + */ + operator(val1: OperatorComparable, operator: Operator, val2: OperatorComparable, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + + /** + * Asserts that the target is equal to expected, to within a +/- delta range. + * + * @param actual Actual value + * @param expected Potential expected value. + * @param delta Maximum differenced between values. + * @param message Message to display on error. + */ + approximately(act: number, exp: number, delta: number, message?: string): void; + + /** + * Asserts that set1 and set2 have the same members. Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that `set1` and `set2` don't have the same members in any order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 + * @param set2 + * @param message + */ + notSameDeepMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + sameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that set1 and set2 don’t have the same members in the same order. + * Uses a deep equality check. + * + * T Type of set values. + * @param set1 Actual set of values. + * @param set2 Potential expected set of values. + * @param message Message to display on error. + */ + notSameDeepOrderedMembers(set1: T[], set2: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a strict equality check (===). + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in the same order beginning with the first element in superset. + * Uses a deep equality check. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepOrderedMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset. Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset isn’t included in superset in any order. + * Uses a strict equality check (===). Duplicates are ignored. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential not contained set of values. + * @param message Message to display on error. + */ + notIncludeMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that subset is included in superset using deep equality checking. + * Order is not take into account. + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + includeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that `subset` isn't included in `superset` in any order. Uses a + * deep equality check. Duplicates are ignored. + * + * assert.notIncludeDeepMembers([ { a: 1 }, { b: 2 }, { c: 3 } ], [ { b: 2 }, { f: 5 } ], 'not include deep members'); + * + * T Type of set values. + * @param superset Actual set of values. + * @param subset Potential contained set of values. + * @param message Message to display on error. + */ + notIncludeDeepMembers(superset: T[], subset: T[], message?: string): void; + + /** + * Asserts that non-object, non-array value inList appears in the flat array list. + * + * T Type of list values. + * @param inList Value expected to be in the list. + * @param list List of values. + * @param message Message to display on error. + */ + oneOf(inList: T, list: T[], message?: string): void; + + /** + * Asserts that a function changes the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be modified. + * @param message Message to display on error. + */ + changes(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function changes the value of a property by an amount (delta). + * + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + changesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + changesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not change the value of a property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be modified. + * @param message Message to display on error. + */ + doesNotChange(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be increased. + * @param message Message to display on error. + */ + increases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function increases a numeric object property or a function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + increasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not increase an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be increased. + * @param message Message to display on error. + */ + doesNotIncrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not increase a numeric object property or function's return value by an amount (delta). + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + increasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + increasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function decreases an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected to be decreased. + * @param message Message to display on error. + */ + decreases(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decrease an object property. + * + * T Type of object. + * @param modifier Function to run. + * @param object Container object. + * @param property Property of object expected not to be decreased. + * @param message Message to display on error. + */ + doesNotDecrease(modifier: Function, object: T, property: string, /* keyof T */ message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + doesNotDecreaseBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + doesNotDecreaseBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts that a function does not decreases a numeric object property or a function's return value by an amount (delta) + * + * T Type of object or function. + * @param modifier function + * @param object or getter function + * @param property name _optional_ + * @param change amount (delta) + * @param message _optional_ + */ + + decreasesButNotBy( + modifier: Function, + object: T, + property: string, + /* keyof T */ change: number, + message?: string, + ): void; + decreasesButNotBy(modifier: Function, object: T, change: number, message?: string): void; + + /** + * Asserts if value is not a false value, and throws if it is a true value. + * + * T Type of object. + * @param object Actual value. + * @param message Message to display on error. + * @remarks This is added to allow for chai to be a drop-in replacement for + * Node’s assert class. + */ + ifError(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isExtensible(object: T, message?: string): void; + + /** + * Asserts that object is extensible (can have new properties added to it). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + extensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotExtensible(object: T, message?: string): void; + + /** + * Asserts that object is not extensible. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notExtensible(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isSealed(object: T, message?: string): void; + + /** + * Asserts that object is sealed (can have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + sealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotSealed(object: T, message?: string): void; + + /** + * Asserts that object is not sealed. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notSealed(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isFrozen(object: T, message?: string): void; + + /** + * Asserts that object is frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + frozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isNotFrozen(object: T, message?: string): void; + + /** + * Asserts that object is not frozen (cannot have new properties added to it + * and its existing properties cannot be removed). + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target does not contain any values. For arrays and + * strings, it checks the length property. For Map and Set instances, it + * checks the size property. For non-function objects, it gets the count + * of own enumerable string keys. + * + * T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isEmpty(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys( + object: T, + keys: Array | { [key: string]: any }, + message?: string, + ): void; + + /** + * Asserts that object has a direct or inherited property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + nestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object does not have a property named by property, + * which can be a string using dot- and bracket-notation for nested reference. + * The property cannot exist on the object nor anywhere in its prototype chain. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param message Message to display on error. + */ + notNestedProperty(object: T, property: string, message?: string): void; + + /** + * Asserts that object has a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + nestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a strict equality check (===). + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object has a property named by property with a value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + deepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + + /** + * Asserts that object does not have a property named by property with value given by value. + * property can use dot- and bracket-notation for nested reference. Uses a deep equality check. + * + * T Type of object. + * @param object Object to test. + * @param property Property to test. + * @param value Value to test. + * @param message Message to display on error. + */ + notDeepNestedPropertyVal(object: T, property: string, value: any, message?: string): void; + } + + export interface Config { + /** + * Default: false + */ + includeStack: boolean; + + /** + * Default: true + */ + showDiff: boolean; + + /** + * Default: 40 + */ + truncateThreshold: number; + + /** + * Default: true + */ + useProxy: boolean; + + /** + * Default: ['then', 'catch', 'inspect', 'toJSON'] + */ + proxyExcludedKeys: string[]; + + deepEqual: (expected: L, actual: R) => void; + } + + export type { ImportedAssertionError as AssertionError }; + } +} + +export function use(fn: Chai.ChaiPlugin): Chai.ChaiStatic; + +export const util: Chai.ChaiUtils; +export const config: Chai.Config; +export const Assertion: Chai.AssertionStatic; +export const AssertionError: typeof ImportedAssertionError; +export function should(): Chai.Should; +export function Should(): Chai.Should; +export const assert: Chai.AssertStatic; +export const expect: Chai.ExpectStatic; diff --git a/node_modules/@types/chai/package.json b/node_modules/@types/chai/package.json new file mode 100644 index 000000000..7aec8d1c6 --- /dev/null +++ b/node_modules/@types/chai/package.json @@ -0,0 +1,75 @@ +{ + "name": "@types/chai", + "version": "5.2.3", + "description": "TypeScript definitions for chai", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai", + "license": "MIT", + "contributors": [ + { + "name": "Bart van der Schoor", + "githubUsername": "Bartvds", + "url": "https://github.com/Bartvds" + }, + { + "name": "Andrew Brown", + "githubUsername": "AGBrown", + "url": "https://github.com/AGBrown" + }, + { + "name": "Olivier Chevet", + "githubUsername": "olivr70", + "url": "https://github.com/olivr70" + }, + { + "name": "Matt Wistrand", + "githubUsername": "mwistrand", + "url": "https://github.com/mwistrand" + }, + { + "name": "Shaun Luttin", + "githubUsername": "shaunluttin", + "url": "https://github.com/shaunluttin" + }, + { + "name": "Satana Charuwichitratana", + "githubUsername": "micksatana", + "url": "https://github.com/micksatana" + }, + { + "name": "Erik Schierboom", + "githubUsername": "ErikSchierboom", + "url": "https://github.com/ErikSchierboom" + }, + { + "name": "Bogdan Paranytsia", + "githubUsername": "bparan", + "url": "https://github.com/bparan" + }, + { + "name": "CXuesong", + "githubUsername": "CXuesong", + "url": "https://github.com/CXuesong" + }, + { + "name": "Joey Kilpatrick", + "githubUsername": "joeykilpatrick", + "url": "https://github.com/joeykilpatrick" + } + ], + "type": "module", + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/chai" + }, + "scripts": {}, + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d9d83f1594f42010e624e46e4c8cfeee284bdd04cb05eb0730aec14140f2a833", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/node_modules/@types/chai/register-should.d.ts b/node_modules/@types/chai/register-should.d.ts new file mode 100644 index 000000000..1e14f93b3 --- /dev/null +++ b/node_modules/@types/chai/register-should.d.ts @@ -0,0 +1,7 @@ +declare global { + interface Object { + should: Chai.Assertion; + } +} + +export {}; diff --git a/node_modules/@types/deep-eql/LICENSE b/node_modules/@types/deep-eql/LICENSE new file mode 100644 index 000000000..9e841e7a2 --- /dev/null +++ b/node_modules/@types/deep-eql/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/deep-eql/README.md b/node_modules/@types/deep-eql/README.md new file mode 100644 index 000000000..48d96fc64 --- /dev/null +++ b/node_modules/@types/deep-eql/README.md @@ -0,0 +1,57 @@ +# Installation +> `npm install --save @types/deep-eql` + +# Summary +This package contains type definitions for deep-eql (https://github.com/chaijs/deep-eql). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql. +## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql/index.d.ts) +````ts +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; + +```` + +### Additional Details + * Last updated: Mon, 06 Nov 2023 22:41:05 GMT + * Dependencies: none + +# Credits +These definitions were written by [Rodrigo Pietnechuk](https://github.com/ghnoob). diff --git a/node_modules/@types/deep-eql/index.d.ts b/node_modules/@types/deep-eql/index.d.ts new file mode 100644 index 000000000..0cdbefe93 --- /dev/null +++ b/node_modules/@types/deep-eql/index.d.ts @@ -0,0 +1,38 @@ +declare namespace deepEqual { + /** + * Memoization class used to speed up comparison. + */ + class MemoizeMap extends WeakMap {} + + interface DeepEqualOptions { + /** + * Override default algorithm, determining custom equality. + */ + comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null; + + /** + * Provide a custom memoization object which will cache the results of + * complex objects for a speed boost. + * + * By passing `false` you can disable memoization, but this will cause circular + * references to blow the stack. + */ + memoize?: MemoizeMap | false; + } +} + +/** + * Assert deeply nested sameValue equality between two objects of any type. + * + * @param leftHandOperand + * @param rightHandOperand + * @param [options] Additional options + * @return equal match + */ +declare function deepEqual( + leftHandOperand: T1, + rightHandOperand: T2, + options?: deepEqual.DeepEqualOptions, +): boolean; + +export = deepEqual; diff --git a/node_modules/@types/deep-eql/package.json b/node_modules/@types/deep-eql/package.json new file mode 100644 index 000000000..876158157 --- /dev/null +++ b/node_modules/@types/deep-eql/package.json @@ -0,0 +1,25 @@ +{ + "name": "@types/deep-eql", + "version": "4.0.2", + "description": "TypeScript definitions for deep-eql", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/deep-eql", + "license": "MIT", + "contributors": [ + { + "name": "Rodrigo Pietnechuk", + "githubUsername": "ghnoob", + "url": "https://github.com/ghnoob" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/deep-eql" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "3b8981ce557947fc00ca08cbd93b4206bfc0943360956867381a0a3f6b1eabf5", + "typeScriptVersion": "4.5" +} \ No newline at end of file diff --git a/node_modules/@types/estree/LICENSE b/node_modules/@types/estree/LICENSE new file mode 100644 index 000000000..9e841e7a2 --- /dev/null +++ b/node_modules/@types/estree/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/estree/README.md b/node_modules/@types/estree/README.md new file mode 100644 index 000000000..2af760b2b --- /dev/null +++ b/node_modules/@types/estree/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/estree` + +# Summary +This package contains type definitions for estree (https://github.com/estree/estree). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. + +### Additional Details + * Last updated: Fri, 06 Jun 2025 00:04:33 GMT + * Dependencies: none + +# Credits +These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/node_modules/@types/estree/flow.d.ts b/node_modules/@types/estree/flow.d.ts new file mode 100644 index 000000000..9d001a92b --- /dev/null +++ b/node_modules/@types/estree/flow.d.ts @@ -0,0 +1,167 @@ +declare namespace ESTree { + interface FlowTypeAnnotation extends Node {} + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface ClassProperty { + key: Expression; + value?: Expression | null; + typeAnnotation?: TypeAnnotation | null; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + body: ObjectTypeAnnotation; + extends: InterfaceExtends[]; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: FunctionTypeParam[]; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam | null; + typeParameters?: TypeParameterDeclaration | null; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation | null; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration | null; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Identifier[]; + } + + interface TypeParameterInstantiation extends Node { + params: FlowTypeAnnotation[]; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: FlowTypeAnnotation[]; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} diff --git a/node_modules/@types/estree/index.d.ts b/node_modules/@types/estree/index.d.ts new file mode 100644 index 000000000..2bc66fb6c --- /dev/null +++ b/node_modules/@types/estree/index.d.ts @@ -0,0 +1,694 @@ +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +export interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +export interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +export interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +export type Node = NodeMap[keyof NodeMap]; + +export interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +export interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +export interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +export interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +export interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +export interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +export type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +export interface BaseStatement extends BaseNode {} + +export interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +export interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +export interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +export interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +export interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +export interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +export interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +export interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +export interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +export interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +export interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +export interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +export interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +export interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +export interface BaseDeclaration extends BaseStatement {} + +export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +export interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +export interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +export interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +export type Expression = ExpressionMap[keyof ExpressionMap]; + +export interface BaseExpression extends BaseNode {} + +export type ChainElement = SimpleCallExpression | MemberExpression; + +export interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +export interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +export interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +export interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +export interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +export interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +export interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +export interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +export interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +export interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +export interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +export interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +export interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +export interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +export interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +export type CallExpression = SimpleCallExpression | NewExpression; + +export interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +export interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +export interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +export interface BasePattern extends BaseNode {} + +export interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +export interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +export interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +export interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +export interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +export interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +export type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +export type LogicalOperator = "||" | "&&" | "??"; + +export type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +export type UpdateOperator = "++" | "--"; + +export interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +export interface Super extends BaseNode { + type: "Super"; +} + +export interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +export interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +export interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +export interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +export interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +export interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +export interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +export interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export type Class = ClassDeclaration | ClassExpression; +export interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +export interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +export interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +export interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +export interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +export interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +export interface BaseModuleDeclaration extends BaseNode {} + +export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +export interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +export interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +export interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +export interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +export interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +export interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +export interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +export interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +export interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} diff --git a/node_modules/@types/estree/package.json b/node_modules/@types/estree/package.json new file mode 100644 index 000000000..68c0782c7 --- /dev/null +++ b/node_modules/@types/estree/package.json @@ -0,0 +1,27 @@ +{ + "name": "@types/estree", + "version": "1.0.8", + "description": "TypeScript definitions for estree", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", + "license": "MIT", + "contributors": [ + { + "name": "RReverser", + "githubUsername": "RReverser", + "url": "https://github.com/RReverser" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/estree" + }, + "scripts": {}, + "dependencies": {}, + "peerDependencies": {}, + "typesPublisherContentHash": "7a167b6e4a4d9f6e9a2cb9fd3fc45c885f89cbdeb44b3e5961bb057a45c082fd", + "typeScriptVersion": "5.1", + "nonNpm": true +} \ No newline at end of file diff --git a/node_modules/@vitest/expect/LICENSE b/node_modules/@vitest/expect/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/expect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/expect/README.md b/node_modules/@vitest/expect/README.md new file mode 100644 index 000000000..d3c72567d --- /dev/null +++ b/node_modules/@vitest/expect/README.md @@ -0,0 +1,25 @@ +# @vitest/expect + +[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner) + +Jest's expect matchers as a Chai plugin. + +## Usage + +```js +import { + JestAsymmetricMatchers, + JestChaiExpect, + JestExtend, +} from '@vitest/expect' +import * as chai from 'chai' + +// allows using expect.extend instead of chai.use to extend plugins +chai.use(JestExtend) +// adds all jest matchers to expect +chai.use(JestChaiExpect) +// adds asymmetric matchers like stringContaining, objectContaining +chai.use(JestAsymmetricMatchers) +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/expect) | [Documentation](https://vitest.dev/api/expect) diff --git a/node_modules/@vitest/expect/dist/index.d.ts b/node_modules/@vitest/expect/dist/index.d.ts new file mode 100644 index 000000000..ede7017e8 --- /dev/null +++ b/node_modules/@vitest/expect/dist/index.d.ts @@ -0,0 +1,930 @@ +import { MockInstance } from '@vitest/spy'; +import { Formatter } from 'tinyrainbow'; +import { StandardSchemaV1 } from '@standard-schema/spec'; +import { diff, printDiffOrStringify } from '@vitest/utils/diff'; +export { DiffOptions } from '@vitest/utils/diff'; +import { stringify } from '@vitest/utils/display'; +import * as chai from 'chai'; +export { chai }; + +interface AsymmetricMatcherInterface { + asymmetricMatch: (other: unknown, customTesters?: Array) => boolean; + toString: () => string; + getExpectedType?: () => string; + toAsymmetricMatcher?: () => string; +} +declare abstract class AsymmetricMatcher< + T, + State extends MatcherState = MatcherState +> implements AsymmetricMatcherInterface { + protected sample: T; + protected inverse: boolean; + $$typeof: symbol; + constructor(sample: T, inverse?: boolean); + protected getMatcherContext(expect?: Chai.ExpectStatic): State; + abstract asymmetricMatch(other: unknown, customTesters?: Array): boolean; + abstract toString(): string; + getExpectedType?(): string; + toAsymmetricMatcher?(): string; +} +declare class StringContaining extends AsymmetricMatcher { + constructor(sample: string, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Anything extends AsymmetricMatcher { + asymmetricMatch(other: unknown): boolean; + toString(): string; + toAsymmetricMatcher(): string; +} +declare class ObjectContaining extends AsymmetricMatcher> { + constructor(sample: Record, inverse?: boolean); + getPrototype(obj: object): any; + hasProperty(obj: object | null, property: string | symbol): boolean; + getProperties(obj: object): (string | symbol)[]; + asymmetricMatch(other: any, customTesters?: Array): boolean; + toString(): string; + getExpectedType(): string; +} +declare class ArrayContaining extends AsymmetricMatcher> { + constructor(sample: Array, inverse?: boolean); + asymmetricMatch(other: Array, customTesters?: Array): boolean; + toString(): string; + getExpectedType(): string; +} +declare class Any extends AsymmetricMatcher { + constructor(sample: unknown); + fnNameFor(func: Function): string; + asymmetricMatch(other: unknown): boolean; + toString(): string; + getExpectedType(): string; + toAsymmetricMatcher(): string; +} +declare class StringMatching extends AsymmetricMatcher { + constructor(sample: string | RegExp, inverse?: boolean); + asymmetricMatch(other: string): boolean; + toString(): string; + getExpectedType(): string; +} +declare class SchemaMatching extends AsymmetricMatcher> { + private result; + constructor(sample: StandardSchemaV1, inverse?: boolean); + asymmetricMatch(other: unknown): boolean; + toString(): string; + getExpectedType(): string; + toAsymmetricMatcher(): string; +} +declare const JestAsymmetricMatchers: ChaiPlugin; + +declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string; +declare function printReceived(object: unknown): string; +declare function printExpected(value: unknown): string; +declare function getMatcherUtils(): { + EXPECTED_COLOR: Formatter; + RECEIVED_COLOR: Formatter; + INVERTED_COLOR: Formatter; + BOLD_WEIGHT: Formatter; + DIM_COLOR: Formatter; + diff: typeof diff; + matcherHint: typeof matcherHint; + printReceived: typeof printReceived; + printExpected: typeof printExpected; + printDiffOrStringify: typeof printDiffOrStringify; + printWithType: typeof printWithType; +}; +declare function printWithType(name: string, value: T, print: (value: T) => string): string; +declare function addCustomEqualityTesters(newTesters: Array): void; + +/** +* 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. +* +*/ + +type ChaiPlugin = Chai.ChaiPlugin; +type Tester = (this: TesterContext, a: any, b: any, customTesters: Array) => boolean | undefined; +interface TesterContext { + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; +} + +interface MatcherHintOptions { + comment?: string; + expectedColor?: Formatter; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: Formatter; + secondArgument?: string; + secondArgumentColor?: Formatter; +} +interface MatcherState { + customTesters: Array; + assertionCalls: number; + currentTestName?: string; + /** + * @deprecated exists only in types + */ + dontThrow?: () => void; + /** + * @deprecated exists only in types + */ + error?: Error; + equals: (a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean) => boolean; + /** + * @deprecated exists only in types + */ + expand?: boolean; + expectedAssertionsNumber?: number | null; + expectedAssertionsNumberErrorGen?: (() => Error) | null; + isExpectingAssertions?: boolean; + isExpectingAssertionsError?: Error | null; + isNot: boolean; + promise: string; + /** + * @deprecated exists only in types + */ + suppressedErrors: Array; + testPath?: string; + utils: ReturnType & { + diff: typeof diff; + stringify: typeof stringify; + iterableEquality: Tester; + subsetEquality: Tester; + }; + soft?: boolean; + poll?: boolean; + /** + * The same assertion instance that chai plugins receive. + * @experimental + * @see {@link https://www.chaijs.com/guide/plugins/} Core Plugin Concepts + */ + readonly assertion: Assertion; +} +interface SyncExpectationResult { + pass: boolean; + message: () => string; + actual?: any; + expected?: any; + meta?: object; +} +type AsyncExpectationResult = Promise; +type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; +interface RawMatcherFn< + T extends MatcherState = MatcherState, + E extends Array = Array +> { + (this: T, received: any, ...expected: E): ExpectationResult; +} +interface Matchers {} +type MatchersObject = Record> & ThisType & { [K in keyof Matchers]? : RawMatcherFn[K]>> }; +interface ExpectStatic extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining { + (actual: T, message?: string): Assertion; + extend: (expects: MatchersObject) => void; + anything: () => any; + any: (constructor: unknown) => any; + getState: () => MatcherState; + setState: (state: Partial) => void; + not: AsymmetricMatchersContaining; +} +interface CustomMatcher { + /** + * Checks that a value satisfies a custom matcher function. + * + * @param matcher - A function returning a boolean based on the custom condition + * @param message - Optional custom error message on failure + * + * @example + * expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18'); + * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18')); + */ + toSatisfy: (matcher: (value: any) => boolean, message?: string) => any; + /** + * Matches if the received value is one of the values in the expected array or set. + * + * @example + * expect(1).toBeOneOf([1, 2, 3]) + * expect('foo').toBeOneOf([expect.any(String)]) + * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) }) + */ + toBeOneOf: (sample: Array | Set) => any; +} +interface AsymmetricMatchersContaining extends CustomMatcher { + /** + * Matches if the received string contains the expected substring. + * + * @example + * expect('I have an apple').toEqual(expect.stringContaining('apple')); + * expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') }); + */ + stringContaining: (expected: string) => any; + /** + * Matches if the received object contains all properties of the expected object. + * + * @example + * expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' })) + */ + objectContaining: (expected: DeeplyAllowMatchers) => any; + /** + * Matches if the received array contains all elements in the expected array. + * + * @example + * expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a'])); + */ + arrayContaining: (expected: Array>) => any; + /** + * Matches if the received string or regex matches the expected pattern. + * + * @example + * expect('hello world').toEqual(expect.stringMatching(/^hello/)); + * expect('hello world').toEqual(expect.stringMatching('hello')); + */ + stringMatching: (expected: string | RegExp) => any; + /** + * Matches if the received number is within a certain precision of the expected number. + * + * @example + * expect(10.45).toEqual(expect.closeTo(10.5, 1)); + * expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision + */ + closeTo: (expected: number, precision?: number) => any; + /** + * Matches if the received value validates against a Standard Schema. + * + * @param schema - A Standard Schema V1 compatible schema object + * + * @example + * expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() }))) + * expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())]) + */ + schemaMatching: (schema: unknown) => any; +} +type WithAsymmetricMatcher = T | AsymmetricMatcher; +type DeeplyAllowMatchers = T extends Array ? WithAsymmetricMatcher | DeeplyAllowMatchers[] : T extends object ? WithAsymmetricMatcher | { [K in keyof T] : DeeplyAllowMatchers } : WithAsymmetricMatcher; +interface JestAssertion extends jest.Matchers, CustomMatcher { + /** + * Used when you want to check that two objects have the same value. + * This matcher recursively checks the equality of all fields, rather than checking for object identity. + * + * @example + * expect(user).toEqual({ name: 'Alice', age: 30 }); + */ + toEqual: (expected: E) => void; + /** + * Use to test that objects have the same types as well as structure. + * + * @example + * expect(user).toStrictEqual({ name: 'Alice', age: 30 }); + */ + toStrictEqual: (expected: E) => void; + /** + * Checks that a value is what you expect. It calls `Object.is` to compare values. + * Don't use `toBe` with floating-point numbers. + * + * @example + * expect(result).toBe(42); + * expect(status).toBe(true); + */ + toBe: (expected: E) => void; + /** + * Check that a string matches a regular expression. + * + * @example + * expect(message).toMatch(/hello/); + * expect(greeting).toMatch('world'); + */ + toMatch: (expected: string | RegExp) => void; + /** + * Used to check that a JavaScript object matches a subset of the properties of an object + * + * @example + * expect(user).toMatchObject({ + * name: 'Alice', + * address: { city: 'Wonderland' } + * }); + */ + toMatchObject: (expected: E) => void; + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this uses `===`, a strict equality check. + * + * @example + * expect(items).toContain('apple'); + * expect(numbers).toContain(5); + */ + toContain: (item: E) => void; + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this matcher recursively checks the + * equality of all fields, rather than checking for object identity. + * + * @example + * expect(items).toContainEqual({ name: 'apple', quantity: 1 }); + */ + toContainEqual: (item: E) => void; + /** + * Use when you don't care what a value is, you just want to ensure a value + * is true in a boolean context. In JavaScript, there are six falsy values: + * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. + * + * @example + * expect(user.isActive).toBeTruthy(); + */ + toBeTruthy: () => void; + /** + * When you don't care what a value is, you just want to + * ensure a value is false in a boolean context. + * + * @example + * expect(user.isActive).toBeFalsy(); + */ + toBeFalsy: () => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeGreaterThan(10); + */ + toBeGreaterThan: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeGreaterThanOrEqual(10); + */ + toBeGreaterThanOrEqual: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeLessThan(10); + */ + toBeLessThan: (num: number | bigint) => void; + /** + * For comparing floating point numbers. + * + * @example + * expect(score).toBeLessThanOrEqual(10); + */ + toBeLessThanOrEqual: (num: number | bigint) => void; + /** + * Used to check that a variable is NaN. + * + * @example + * expect(value).toBeNaN(); + */ + toBeNaN: () => void; + /** + * Used to check that a variable is undefined. + * + * @example + * expect(value).toBeUndefined(); + */ + toBeUndefined: () => void; + /** + * This is the same as `.toBe(null)` but the error messages are a bit nicer. + * So use `.toBeNull()` when you want to check that something is null. + * + * @example + * expect(value).toBeNull(); + */ + toBeNull: () => void; + /** + * Used to check that a variable is nullable (null or undefined). + * + * @example + * expect(value).toBeNullable(); + */ + toBeNullable: () => void; + /** + * Ensure that a variable is not undefined. + * + * @example + * expect(value).toBeDefined(); + */ + toBeDefined: () => void; + /** + * Ensure that an object is an instance of a class. + * This matcher uses `instanceof` underneath. + * + * @example + * expect(new Date()).toBeInstanceOf(Date); + */ + toBeInstanceOf: (expected: E) => void; + /** + * Used to check that an object has a `.length` property + * and it is set to a certain numeric value. + * + * @example + * expect([1, 2, 3]).toHaveLength(3); + * expect('hello').toHaveLength(5); + */ + toHaveLength: (length: number) => void; + /** + * Use to check if a property at the specified path exists on an object. + * For checking deeply nested properties, you may use dot notation or an array containing + * the path segments for deep references. + * + * Optionally, you can provide a value to check if it matches the value present at the path + * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks + * the equality of all fields. + * + * @example + * expect(user).toHaveProperty('address.city', 'New York'); + * expect(config).toHaveProperty(['settings', 'theme'], 'dark'); + */ + toHaveProperty: (property: string | (string | number)[], value?: E) => void; + /** + * Using exact equality with floating point numbers is a bad idea. + * Rounding means that intuitive things fail. + * The default for `numDigits` is 2. + * + * @example + * expect(price).toBeCloseTo(9.99, 2); + */ + toBeCloseTo: (number: number, numDigits?: number) => void; + /** + * Ensures that a mock function is called an exact number of times. + * + * Also under the alias `expect.toBeCalledTimes`. + * + * @example + * expect(mockFunc).toHaveBeenCalledTimes(2); + */ + toHaveBeenCalledTimes: (times: number) => void; + /** + * Ensures that a mock function is called an exact number of times. + * + * Alias for `expect.toHaveBeenCalledTimes`. + * + * @example + * expect(mockFunc).toBeCalledTimes(2); + * @deprecated Use `toHaveBeenCalledTimes` instead + */ + toBeCalledTimes: (times: number) => void; + /** + * Ensures that a mock function is called. + * + * Also under the alias `expect.toBeCalled`. + * + * @example + * expect(mockFunc).toHaveBeenCalled(); + */ + toHaveBeenCalled: () => void; + /** + * Ensures that a mock function is called. + * + * Alias for `expect.toHaveBeenCalled`. + * + * @example + * expect(mockFunc).toBeCalled(); + * @deprecated Use `toHaveBeenCalled` instead + */ + toBeCalled: () => void; + /** + * Ensure that a mock function is called with specific arguments. + * + * Also under the alias `expect.toBeCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenCalledWith('arg1', 42); + */ + toHaveBeenCalledWith: (...args: E) => void; + /** + * Ensure that a mock function is called with specific arguments. + * + * Alias for `expect.toHaveBeenCalledWith`. + * + * @example + * expect(mockFunc).toBeCalledWith('arg1', 42); + * @deprecated Use `toHaveBeenCalledWith` instead + */ + toBeCalledWith: (...args: E) => void; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + * + * Also under the alias `expect.nthCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg'); + */ + toHaveBeenNthCalledWith: (n: number, ...args: E) => void; + /** + * If you have a mock function, you can use `.toHaveBeenLastCalledWith` + * to test what arguments it was last called with. + * + * Also under the alias `expect.lastCalledWith`. + * + * @example + * expect(mockFunc).toHaveBeenLastCalledWith('lastArg'); + */ + toHaveBeenLastCalledWith: (...args: E) => void; + /** + * Used to test that a function throws when it is called. + * + * Also under the alias `expect.toThrowError`. + * + * @example + * expect(() => functionWithError()).toThrow('Error message'); + * expect(() => parseJSON('invalid')).toThrow(SyntaxError); + * expect(() => { throw 42 }).toThrow(42); + */ + toThrow: (expected?: any) => void; + /** + * Used to test that a function throws when it is called. + * + * Alias for `expect.toThrow`. + * + * @example + * expect(() => functionWithError()).toThrowError('Error message'); + * expect(() => parseJSON('invalid')).toThrowError(SyntaxError); + * expect(() => { throw 42 }).toThrowError(42); + * @deprecated Use `toThrow` instead + */ + toThrowError: (expected?: any) => void; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + * + * Alias for `expect.toHaveReturned`. + * + * @example + * expect(mockFunc).toReturn(); + * @deprecated Use `toHaveReturned` instead + */ + toReturn: () => void; + /** + * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time + * + * Also under the alias `expect.toReturn`. + * + * @example + * expect(mockFunc).toHaveReturned(); + */ + toHaveReturned: () => void; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + * + * Alias for `expect.toHaveReturnedTimes`. + * + * @example + * expect(mockFunc).toReturnTimes(3); + * @deprecated Use `toHaveReturnedTimes` instead + */ + toReturnTimes: (times: number) => void; + /** + * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. + * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. + * + * Also under the alias `expect.toReturnTimes`. + * + * @example + * expect(mockFunc).toHaveReturnedTimes(3); + */ + toHaveReturnedTimes: (times: number) => void; + /** + * Use to ensure that a mock function returned a specific value. + * + * Alias for `expect.toHaveReturnedWith`. + * + * @example + * expect(mockFunc).toReturnWith('returnValue'); + * @deprecated Use `toHaveReturnedWith` instead + */ + toReturnWith: (value: E) => void; + /** + * Use to ensure that a mock function returned a specific value. + * + * Also under the alias `expect.toReturnWith`. + * + * @example + * expect(mockFunc).toHaveReturnedWith('returnValue'); + */ + toHaveReturnedWith: (value: E) => void; + /** + * Use to test the specific value that a mock function last returned. + * If the last call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Also under the alias `expect.lastReturnedWith`. + * + * @example + * expect(mockFunc).toHaveLastReturnedWith('lastValue'); + */ + toHaveLastReturnedWith: (value: E) => void; + /** + * Use to test the specific value that a mock function returned for the nth call. + * If the nth call to the mock function threw an error, then this matcher will fail + * no matter what value you provided as the expected return value. + * + * Also under the alias `expect.nthReturnedWith`. + * + * @example + * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue'); + */ + toHaveNthReturnedWith: (nthCall: number, value: E) => void; +} +type VitestAssertion< + A, + T +> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion } & ((type: string, message?: string) => Assertion); +type Promisify = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify & ((...args: A) => Promise) : O[K] }; +type PromisifyAssertion = Promisify>; +interface Assertion extends VitestAssertion, JestAssertion, ChaiMockAssertion, Matchers { + /** + * Ensures a value is of a specific type. + * + * @example + * expect(value).toBeTypeOf('string'); + * expect(number).toBeTypeOf('number'); + */ + toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => void; + /** + * Asserts that a mock function was called exactly once. + * + * @example + * expect(mockFunc).toHaveBeenCalledOnce(); + */ + toHaveBeenCalledOnce: () => void; + /** + * Ensure that a mock function is called with specific arguments and called + * exactly once. + * + * @example + * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42); + */ + toHaveBeenCalledExactlyOnceWith: (...args: E) => void; + /** + * This assertion checks if a `Mock` was called before another `Mock`. + * @param mock - A mock function created by `vi.spyOn` or `vi.fn` + * @param failIfNoFirstInvocation - Fail if the first mock was never called + * @example + * const mock1 = vi.fn() + * const mock2 = vi.fn() + * + * mock1() + * mock2() + * mock1() + * + * expect(mock1).toHaveBeenCalledBefore(mock2) + */ + toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * This assertion checks if a `Mock` was called after another `Mock`. + * @param mock - A mock function created by `vi.spyOn` or `vi.fn` + * @param failIfNoFirstInvocation - Fail if the first mock was never called + * @example + * const mock1 = vi.fn() + * const mock2 = vi.fn() + * + * mock2() + * mock1() + * mock2() + * + * expect(mock1).toHaveBeenCalledAfter(mock2) + */ + toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * Checks that a promise resolves successfully at least once. + * + * @example + * await expect(promise).toHaveResolved(); + */ + toHaveResolved: () => void; + /** + * Checks that a promise resolves to a specific value. + * + * @example + * await expect(promise).toHaveResolvedWith('success'); + */ + toHaveResolvedWith: (value: E) => void; + /** + * Ensures a promise resolves a specific number of times. + * + * @example + * expect(mockAsyncFunc).toHaveResolvedTimes(3); + */ + toHaveResolvedTimes: (times: number) => void; + /** + * Asserts that the last resolved value of a promise matches an expected value. + * + * @example + * await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult'); + */ + toHaveLastResolvedWith: (value: E) => void; + /** + * Ensures a specific value was returned by a promise on the nth resolution. + * + * @example + * await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult'); + */ + toHaveNthResolvedWith: (nthCall: number, value: E) => void; + /** + * Verifies that a promise resolves. + * + * @example + * await expect(someAsyncFunc).resolves.toBe(42); + */ + resolves: PromisifyAssertion; + /** + * Verifies that a promise rejects. + * + * @example + * await expect(someAsyncFunc).rejects.toThrow('error'); + */ + rejects: PromisifyAssertion; +} +/** +* Chai-style assertions for spy/mock testing. +* These provide sinon-chai compatible assertion names that delegate to Jest-style implementations. +*/ +interface ChaiMockAssertion { + /** + * Checks that a spy was called at least once. + * Chai-style equivalent of `toHaveBeenCalled`. + * + * @example + * expect(spy).to.have.been.called + */ + readonly called: Assertion; + /** + * Checks that a spy was called a specific number of times. + * Chai-style equivalent of `toHaveBeenCalledTimes`. + * + * @example + * expect(spy).to.have.callCount(3) + */ + callCount: (count: number) => void; + /** + * Checks that a spy was called with specific arguments at least once. + * Chai-style equivalent of `toHaveBeenCalledWith`. + * + * @example + * expect(spy).to.have.been.calledWith('arg1', 'arg2') + */ + calledWith: (...args: E) => void; + /** + * Checks that a spy was called exactly once. + * Chai-style equivalent of `toHaveBeenCalledOnce`. + * + * @example + * expect(spy).to.have.been.calledOnce + */ + readonly calledOnce: Assertion; + /** + * Checks that a spy was called exactly once with specific arguments. + * Chai-style equivalent of `toHaveBeenCalledExactlyOnceWith`. + * + * @example + * expect(spy).to.have.been.calledOnceWith('arg1', 'arg2') + */ + calledOnceWith: (...args: E) => void; + /** + * Checks that the last call to a spy was made with specific arguments. + * Chai-style equivalent of `toHaveBeenLastCalledWith`. + * + * @example + * expect(spy).to.have.been.lastCalledWith('arg1', 'arg2') + */ + lastCalledWith: (...args: E) => void; + /** + * Checks that the nth call to a spy was made with specific arguments. + * Chai-style equivalent of `toHaveBeenNthCalledWith`. + * + * @example + * expect(spy).to.have.been.nthCalledWith(2, 'arg1', 'arg2') + */ + nthCalledWith: (n: number, ...args: E) => void; + /** + * Checks that a spy returned a specific value at least once. + * Chai-style equivalent of `toHaveReturnedWith`. + * + * @example + * expect(spy).to.have.returned('value') + */ + returned: (value: E) => void; + /** + * Checks that a spy returned a specific value at least once. + * Chai-style equivalent of `toHaveReturnedWith`. + * + * @example + * expect(spy).to.have.returnedWith('value') + */ + returnedWith: (value: E) => void; + /** + * Checks that a spy returned successfully a specific number of times. + * Chai-style equivalent of `toHaveReturnedTimes`. + * + * @example + * expect(spy).to.have.returnedTimes(3) + */ + returnedTimes: (count: number) => void; + /** + * Checks that the last return value of a spy matches the expected value. + * Chai-style equivalent of `toHaveLastReturnedWith`. + * + * @example + * expect(spy).to.have.lastReturnedWith('value') + */ + lastReturnedWith: (value: E) => void; + /** + * Checks that the nth return value of a spy matches the expected value. + * Chai-style equivalent of `toHaveNthReturnedWith`. + * + * @example + * expect(spy).to.have.nthReturnedWith(2, 'value') + */ + nthReturnedWith: (n: number, value: E) => void; + /** + * Checks that a spy was called before another spy. + * Chai-style equivalent of `toHaveBeenCalledBefore`. + * + * @example + * expect(spy1).to.have.been.calledBefore(spy2) + */ + calledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * Checks that a spy was called after another spy. + * Chai-style equivalent of `toHaveBeenCalledAfter`. + * + * @example + * expect(spy1).to.have.been.calledAfter(spy2) + */ + calledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; + /** + * Checks that a spy was called exactly twice. + * Chai-style equivalent of `toHaveBeenCalledTimes(2)`. + * + * @example + * expect(spy).to.have.been.calledTwice + */ + readonly calledTwice: Assertion; + /** + * Checks that a spy was called exactly three times. + * Chai-style equivalent of `toHaveBeenCalledTimes(3)`. + * + * @example + * expect(spy).to.have.been.calledThrice + */ + readonly calledThrice: Assertion; +} +declare global { + namespace jest { + interface Matchers< + R, + T = {} + > {} + } +} + +declare const ChaiStyleAssertions: ChaiPlugin; + +declare const MATCHERS_OBJECT: unique symbol; +declare const JEST_MATCHERS_OBJECT: unique symbol; +declare const GLOBAL_EXPECT: unique symbol; +declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol; + +declare const customMatchers: MatchersObject; + +declare const JestChaiExpect: ChaiPlugin; + +declare const JestExtend: ChaiPlugin; + +declare function equals(a: unknown, b: unknown, customTesters?: Array, strictCheck?: boolean): boolean; +declare function isAsymmetric(obj: any): obj is AsymmetricMatcher; +declare function hasAsymmetric(obj: any, seen?: Set): boolean; +declare function isError(value: unknown): value is Error; +declare function isA(typeName: string, value: unknown): boolean; +declare function fnNameFor(func: Function): string; +declare function hasProperty(obj: object | null, property: string): boolean; +declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean; +declare function isImmutableUnorderedSet(maybeSet: any): boolean; +declare function iterableEquality(a: any, b: any, customTesters?: Array, aStack?: Array, bStack?: Array): boolean | undefined; +declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array): boolean | undefined; +declare function typeEquality(a: any, b: any): boolean | undefined; +declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined; +declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array): boolean | undefined; +declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string; +declare function pluralize(word: string, count: number): string; +declare function getObjectKeys(object: object): Array; +declare function getObjectSubset(object: any, subset: any, customTesters: Array): { + subset: any; + stripped: number; +}; +/** +* Detects if an object is a Standard Schema V1 compatible schema +*/ +declare function isStandardSchema(obj: any): obj is StandardSchemaV1; + +declare function getState(expect: ExpectStatic): State; +declare function setState(state: Partial, expect: ExpectStatic): void; + +declare function createAssertionMessage(util: Chai.ChaiUtils, assertion: Chai.Assertion, hasArgs: boolean): string; +declare function recordAsyncExpect(_test: any, promise: Promise, assertion: string, error: Error, isSoft?: boolean): Promise; +/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */ +declare function wrapAssertion(utils: Chai.ChaiUtils, name: string, fn: (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike): (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion }; +export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiMockAssertion, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext }; diff --git a/node_modules/@vitest/expect/dist/index.js b/node_modules/@vitest/expect/dist/index.js new file mode 100644 index 000000000..82366c6b2 --- /dev/null +++ b/node_modules/@vitest/expect/dist/index.js @@ -0,0 +1,1952 @@ +import { printDiffOrStringify, diff } from '@vitest/utils/diff'; +import { stringify } from '@vitest/utils/display'; +import { getType, isObject, noop, assertTypes, ordinal } from '@vitest/utils/helpers'; +import c from 'tinyrainbow'; +import { isMockFunction } from '@vitest/spy'; +import { processError } from '@vitest/utils/error'; +import { use, util } from 'chai'; +import * as chai from 'chai'; +export { chai }; + +const ChaiStyleAssertions = (chai, utils) => { + function defProperty(name, delegateTo) { + utils.addProperty(chai.Assertion.prototype, name, function() { + const jestMethod = chai.Assertion.prototype[delegateTo]; + if (!jestMethod) { + throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`); + } + return jestMethod.call(this); + }); + } + function defPropertyWithArgs(name, delegateTo, ...args) { + utils.addProperty(chai.Assertion.prototype, name, function() { + const jestMethod = chai.Assertion.prototype[delegateTo]; + if (!jestMethod) { + throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`); + } + return jestMethod.call(this, ...args); + }); + } + function defMethod(name, delegateTo) { + utils.addMethod(chai.Assertion.prototype, name, function(...args) { + const jestMethod = chai.Assertion.prototype[delegateTo]; + if (!jestMethod) { + throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`); + } + return jestMethod.call(this, ...args); + }); + } + // API to (somewhat) mirror sinon-chai + // https://github.com/chaijs/sinon-chai + defProperty("called", "toHaveBeenCalled"); + defProperty("calledOnce", "toHaveBeenCalledOnce"); + defPropertyWithArgs("calledTwice", "toHaveBeenCalledTimes", 2); + defPropertyWithArgs("calledThrice", "toHaveBeenCalledTimes", 3); + defMethod("callCount", "toHaveBeenCalledTimes"); + defMethod("calledWith", "toHaveBeenCalledWith"); + defMethod("calledOnceWith", "toHaveBeenCalledExactlyOnceWith"); + defMethod("lastCalledWith", "toHaveBeenLastCalledWith"); + defMethod("nthCalledWith", "toHaveBeenNthCalledWith"); + defMethod("returned", "toHaveReturned"); + defMethod("returnedWith", "toHaveReturnedWith"); + defMethod("returnedTimes", "toHaveReturnedTimes"); + defMethod("lastReturnedWith", "toHaveLastReturnedWith"); + defMethod("nthReturnedWith", "toHaveNthReturnedWith"); + defMethod("calledBefore", "toHaveBeenCalledBefore"); + defMethod("calledAfter", "toHaveBeenCalledAfter"); + // TODO: implement + // defMethod('thrown', 'toHaveThrown') +}; + +const MATCHERS_OBJECT = Symbol.for("matchers-object"); +const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object"); +const GLOBAL_EXPECT = Symbol.for("expect-global"); +const ASYMMETRIC_MATCHERS_OBJECT = Symbol.for("asymmetric-matchers-object"); + +// selectively ported from https://github.com/jest-community/jest-extended +const customMatchers = { + toSatisfy(actual, expected, message) { + const { printReceived, printExpected, matcherHint } = this.utils; + const pass = expected(actual); + return { + pass, + message: () => pass ? `\ +${matcherHint(".not.toSatisfy", "received", "")} + +Expected value to not satisfy: +${message || printExpected(expected)} +Received: +${printReceived(actual)}` : `\ +${matcherHint(".toSatisfy", "received", "")} + +Expected value to satisfy: +${message || printExpected(expected)} + +Received: +${printReceived(actual)}` + }; + }, + toBeOneOf(actual, expected) { + const { equals, customTesters } = this; + const { printReceived, printExpected, matcherHint } = this.utils; + let pass; + if (Array.isArray(expected)) { + pass = expected.length === 0 || expected.some((item) => equals(item, actual, customTesters)); + } else if (expected instanceof Set) { + pass = expected.size === 0 || expected.has(actual) || [...expected].some((item) => equals(item, actual, customTesters)); + } else { + throw new TypeError(`You must provide an array or set to ${matcherHint(".toBeOneOf")}, not '${typeof expected}'.`); + } + return { + pass, + message: () => pass ? `\ +${matcherHint(".not.toBeOneOf", "received", "")} + +Expected value to not be one of: +${printExpected(expected)} +Received: +${printReceived(actual)}` : `\ +${matcherHint(".toBeOneOf", "received", "")} + +Expected value to be one of: +${printExpected(expected)} + +Received: +${printReceived(actual)}` + }; + } +}; + +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(".")) { + // Old format: for backward compatibility, + // especially without promise or isNot options + dimString += matcherName; + } else { + // New format: omit period from matcherName arg + 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 = "·"; +// Instead of inverse highlight which now implies a change, +// replace common spaces with middle dot at the end of any line. +function replaceTrailingSpaces(text) { + return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); +} +function printReceived(object) { + return RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); +} +function printExpected(value) { + return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); +} +function getMatcherUtils() { + return { + EXPECTED_COLOR, + RECEIVED_COLOR, + INVERTED_COLOR, + BOLD_WEIGHT, + DIM_COLOR, + diff, + matcherHint, + printReceived, + printExpected, + printDiffOrStringify, + printWithType + }; +} +function printWithType(name, value, print) { + const type = getType(value); + const hasType = type !== "null" && type !== "undefined" ? `${name} has type: ${type}\n` : ""; + const hasValue = `${name} has value: ${print(value)}`; + return hasType + hasValue; +} +function addCustomEqualityTesters(newTesters) { + if (!Array.isArray(newTesters)) { + throw new TypeError(`expect.customEqualityTesters: Must be set to an array of Testers. Was given "${getType(newTesters)}"`); + } + globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push(...newTesters); +} +function getCustomEqualityTesters() { + return globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters; +} + +// Extracted out of jasmine 2.5.2 +function equals(a, b, customTesters, strictCheck) { + customTesters = customTesters || []; + return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey); +} +const functionToString = Function.prototype.toString; +function isAsymmetric(obj) { + return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch); +} +function hasAsymmetric(obj, seen = new Set()) { + if (seen.has(obj)) { + return false; + } + seen.add(obj); + if (isAsymmetric(obj)) { + return true; + } + if (Array.isArray(obj)) { + return obj.some((i) => hasAsymmetric(i, seen)); + } + if (obj instanceof Set) { + return Array.from(obj).some((i) => hasAsymmetric(i, seen)); + } + if (isObject(obj)) { + return Object.values(obj).some((v) => hasAsymmetric(v, seen)); + } + return false; +} +function asymmetricMatch(a, b, customTesters) { + const asymmetricA = isAsymmetric(a); + const asymmetricB = isAsymmetric(b); + if (asymmetricA && asymmetricB) { + return undefined; + } + if (asymmetricA) { + return a.asymmetricMatch(b, customTesters); + } + if (asymmetricB) { + return b.asymmetricMatch(a, customTesters); + } +} +// https://github.com/jestjs/jest/blob/905bcbced3d40cdf7aadc4cdf6fb731c4bb3dbe3/packages/expect-utils/src/utils.ts#L509 +function isError(value) { + if (typeof Error.isError === "function") { + return Error.isError(value); + } + switch (Object.prototype.toString.call(value)) { + case "[object Error]": + case "[object Exception]": + case "[object DOMException]": return true; + default: return value instanceof Error; + } +} +// Equality function lovingly adapted from isEqual in +// [Underscore](http://underscorejs.org) +function eq(a, b, aStack, bStack, customTesters, hasKey) { + let result = true; + const asymmetricResult = asymmetricMatch(a, b, customTesters); + if (asymmetricResult !== undefined) { + return asymmetricResult; + } + const testerContext = { equals }; + for (let i = 0; i < customTesters.length; i++) { + const customTesterResult = customTesters[i].call(testerContext, a, b, customTesters); + if (customTesterResult !== undefined) { + return customTesterResult; + } + } + if (typeof URL === "function" && a instanceof URL && b instanceof URL) { + return a.href === b.href; + } + if (Object.is(a, b)) { + return true; + } + // A strict comparison is necessary because `null == undefined`. + 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) { + // One is a primitive, one a `new Primitive()` + return false; + } else if (typeof a !== "object" && typeof b !== "object") { + // both are proper primitives + return Object.is(a, b); + } else { + // both are `new Primitive()`s + return Object.is(a.valueOf(), b.valueOf()); + } + case "[object Date]": { + const numA = +a; + const numB = +b; + // Coerce dates to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are equivalent. + return numA === numB || Number.isNaN(numA) && Number.isNaN(numB); + } + case "[object RegExp]": return a.source === b.source && a.flags === b.flags; + case "[object Temporal.Instant]": + case "[object Temporal.ZonedDateTime]": + case "[object Temporal.PlainDateTime]": + case "[object Temporal.PlainDate]": + case "[object Temporal.PlainTime]": + case "[object Temporal.PlainYearMonth]": + case "[object Temporal.PlainMonthDay]": return a.equals(b); + case "[object Temporal.Duration]": return a.toString() === b.toString(); + } + if (typeof a !== "object" || typeof b !== "object") { + return false; + } + // Use DOM3 method isEqualNode (IE>=9) + if (isDomNode(a) && isDomNode(b)) { + return a.isEqualNode(b); + } + // Used to detect circular references. + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } else if (bStack[length] === b) { + return false; + } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (className === "[object Array]" && a.length !== b.length) { + return false; + } + if (isError(a) && isError(b)) { + try { + return isErrorEqual(a, b, aStack, bStack, customTesters, hasKey); + } finally { + aStack.pop(); + bStack.pop(); + } + } + // Deep compare objects. + const aKeys = keys(a, hasKey); + let key; + let size = aKeys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (keys(b, hasKey).length !== size) { + return false; + } + while (size--) { + key = aKeys[size]; + // Deep compare each member + result = hasKey(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey); + if (!result) { + return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; +} +function isErrorEqual(a, b, aStack, bStack, customTesters, hasKey) { + // https://nodejs.org/docs/latest-v22.x/api/assert.html#comparison-details + // - [[Prototype]] of objects are compared using the === operator. + // - Only enumerable "own" properties are considered. + // - Error names, messages, causes, and errors are always compared, even if these are not enumerable properties. errors is also compared. + let result = Object.prototype.toString.call(a) === Object.prototype.toString.call(b) && a.name === b.name && a.message === b.message; + // check Error.cause asymmetrically + if (typeof b.cause !== "undefined") { + result &&= eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey); + } + // AggregateError.errors + if (a instanceof AggregateError && b instanceof AggregateError) { + result &&= eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey); + } + // spread to compare enumerable properties + result &&= eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey); + return result; +} +function keys(obj, hasKey) { + const keys = []; + for (const key in obj) { + if (hasKey(obj, key)) { + keys.push(key); + } + } + return keys.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable)); +} +function hasDefinedKey(obj, key) { + return hasKey(obj, key) && obj[key] !== undefined; +} +function hasKey(obj, key) { + return Object.hasOwn(obj, key); +} +function isA(typeName, value) { + return Object.prototype.toString.apply(value) === `[object ${typeName}]`; +} +function isDomNode(obj) { + return obj !== null && typeof obj === "object" && "nodeType" in obj && typeof obj.nodeType === "number" && "nodeName" in obj && typeof obj.nodeName === "string" && "isEqualNode" in obj && typeof obj.isEqualNode === "function"; +} +function fnNameFor(func) { + if (func.name) { + return func.name; + } + const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/); + return matches ? matches[1] : ""; +} +function getPrototype(obj) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(obj); + } + if (obj.constructor.prototype === obj) { + return null; + } + return obj.constructor.prototype; +} +function hasProperty(obj, property) { + if (!obj) { + return false; + } + if (Object.hasOwn(obj, property)) { + return true; + } + return hasProperty(getPrototype(obj), property); +} +// SENTINEL constants are from https://github.com/facebook/immutable-js +const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; +const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; +const IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; +const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +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]); +} +function isObjectLiteral(source) { + return source != null && typeof source === "object" && !Array.isArray(source); +} +function isImmutableList(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_LIST_SENTINEL]); +} +function isImmutableOrderedKeyed(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_KEYED_SENTINEL] && source[IS_ORDERED_SENTINEL]); +} +function isImmutableOrderedSet(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_SET_SENTINEL] && source[IS_ORDERED_SENTINEL]); +} +function isImmutableRecord(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_RECORD_SYMBOL]); +} +/** +* 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 IteratorSymbol = Symbol.iterator; +function hasIterator(object) { + return !!(object != null && object[IteratorSymbol]); +} +function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) { + if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) { + return undefined; + } + if (a.constructor !== b.constructor) { + return false; + } + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } + } + aStack.push(a); + bStack.push(b); + const filteredCustomTesters = [...customTesters.filter((t) => t !== iterableEquality), iterableEqualityWithStack]; + function iterableEqualityWithStack(a, b) { + return iterableEquality(a, b, [...customTesters], [...aStack], [...bStack]); + } + if (a.size !== undefined) { + 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, filteredCustomTesters); + if (isEqual === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + 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]), filteredCustomTesters)) { + let has = false; + for (const bEntry of b) { + const matchedKey = equals(aEntry[0], bEntry[0], filteredCustomTesters); + let matchedValue = false; + if (matchedKey === true) { + matchedValue = equals(aEntry[1], bEntry[1], filteredCustomTesters); + } + if (matchedValue === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + 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, filteredCustomTesters)) { + return false; + } + } + if (!bIterator.next().done) { + return false; + } + if (!isImmutableList(a) && !isImmutableOrderedKeyed(a) && !isImmutableOrderedSet(a) && !isImmutableRecord(a)) { + const aEntries = Object.entries(a); + const bEntries = Object.entries(b); + if (!equals(aEntries, bEntries, filteredCustomTesters)) { + return false; + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return true; +} +/** +* Checks if `hasOwnProperty(object, key)` up the prototype chain, stopping at `Object.prototype`. +*/ +function hasPropertyInObject(object, key) { + const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; + if (shouldTerminate) { + return false; + } + return Object.hasOwn(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key); +} +function isObjectWithKeys(a) { + return isObject(a) && !isError(a) && !Array.isArray(a) && !(a instanceof Date) && !(a instanceof Set) && !(a instanceof Map); +} +function subsetEquality(object, subset, customTesters = []) { + const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality); + // subsetEquality needs to keep track of the references + // it has already visited to avoid infinite loops in case + // there are circular references in the subset passed to it. + const subsetEqualityWithContext = (seenReferences = new WeakMap()) => (object, subset) => { + if (!isObjectWithKeys(subset)) { + return undefined; + } + return Object.keys(subset).every((key) => { + if (subset[key] != null && typeof subset[key] === "object") { + if (seenReferences.has(subset[key])) { + return equals(object[key], subset[key], filteredCustomTesters); + } + seenReferences.set(subset[key], true); + } + const result = object != null && hasPropertyInObject(object, key) && equals(object[key], subset[key], [...filteredCustomTesters, subsetEqualityWithContext(seenReferences)]); + // The main goal of using seenReference is to avoid circular node on tree. + // It will only happen within a parent and its child, not a node and nodes next to it (same level) + // We should keep the reference for a parent and its child only + // Thus we should delete the reference immediately so that it doesn't interfere + // other nodes within the same level on tree. + seenReferences.delete(subset[key]); + return result; + }); + }; + return subsetEqualityWithContext()(object, subset); +} +function typeEquality(a, b) { + if (a == null || b == null || a.constructor === b.constructor) { + return undefined; + } + return false; +} +function arrayBufferEquality(a, b) { + let dataViewA = a; + let dataViewB = b; + if (!(a instanceof DataView && b instanceof DataView)) { + if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) { + return undefined; + } + try { + dataViewA = new DataView(a); + dataViewB = new DataView(b); + } catch { + return undefined; + } + } + // Buffers are not equal when they do not have the same byte length + if (dataViewA.byteLength !== dataViewB.byteLength) { + return false; + } + // Check if every byte value is equal to each other + for (let i = 0; i < dataViewA.byteLength; i++) { + if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) { + return false; + } + } + return true; +} +function sparseArrayEquality(a, b, customTesters = []) { + if (!Array.isArray(a) || !Array.isArray(b)) { + return undefined; + } + // A sparse array [, , 1] will have keys ["2"] whereas [undefined, undefined, 1] will have keys ["0", "1", "2"] + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const filteredCustomTesters = customTesters.filter((t) => t !== sparseArrayEquality); + return equals(a, b, filteredCustomTesters, true) && equals(aKeys, bKeys); +} +function generateToBeMessage(deepEqualityName, expected = "#{this}", actual = "#{exp}") { + const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`; + if (["toStrictEqual", "toEqual"].includes(deepEqualityName)) { + return `${toBeMessage}\n\nIf it should pass with deep equality, replace "toBe" with "${deepEqualityName}"\n\nExpected: ${expected}\nReceived: serializes to the same string\n`; + } + return toBeMessage; +} +function pluralize(word, count) { + return `${count} ${word}${count === 1 ? "" : "s"}`; +} +function getObjectKeys(object) { + return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => Object.getOwnPropertyDescriptor(object, s)?.enumerable)]; +} +function getObjectSubset(object, subset, customTesters) { + let stripped = 0; + const getObjectSubsetWithContext = (seenReferences = new WeakMap()) => (object, subset) => { + if (Array.isArray(object)) { + if (Array.isArray(subset) && subset.length === object.length) { + // The map method returns correct subclass of subset. + return subset.map((sub, i) => getObjectSubsetWithContext(seenReferences)(object[i], sub)); + } + } else if (object instanceof Date) { + return object; + } else if (isObject(object) && isObject(subset)) { + if (equals(object, subset, [ + ...customTesters, + iterableEquality, + subsetEquality + ])) { + // return "expected" subset to avoid showing irrelevant toMatchObject diff + return subset; + } + const trimmed = {}; + seenReferences.set(object, trimmed); + // preserve constructor for toMatchObject diff + if (typeof object.constructor === "function" && typeof object.constructor.name === "string") { + Object.defineProperty(trimmed, "constructor", { + enumerable: false, + value: object.constructor + }); + } + for (const key of getObjectKeys(object)) { + if (hasPropertyInObject(subset, key)) { + trimmed[key] = seenReferences.has(object[key]) ? seenReferences.get(object[key]) : getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); + } else { + if (!seenReferences.has(object[key])) { + stripped += 1; + if (isObject(object[key])) { + stripped += getObjectKeys(object[key]).length; + } + getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); + } + } + } + if (getObjectKeys(trimmed).length > 0) { + return trimmed; + } + } + return object; + }; + return { + subset: getObjectSubsetWithContext()(object, subset), + stripped + }; +} +/** +* Detects if an object is a Standard Schema V1 compatible schema +*/ +function isStandardSchema(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && obj["~standard"] && typeof obj["~standard"].validate === "function"; +} + +if (!Object.hasOwn(globalThis, MATCHERS_OBJECT)) { + const globalState = new WeakMap(); + const matchers = Object.create(null); + const customEqualityTesters = []; + const asymmetricMatchers = 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, + customEqualityTesters + }) + }); + Object.defineProperty(globalThis, ASYMMETRIC_MATCHERS_OBJECT, { get: () => asymmetricMatchers }); +} +function getState(expect) { + return globalThis[MATCHERS_OBJECT].get(expect); +} +function setState(state, expect) { + const map = globalThis[MATCHERS_OBJECT]; + const current = map.get(expect) || {}; + // so it keeps getters from `testPath` + const results = Object.defineProperties(current, { + ...Object.getOwnPropertyDescriptors(current), + ...Object.getOwnPropertyDescriptors(state) + }); + map.set(expect, results); +} + +class AsymmetricMatcher { + // should have "jest" to be compatible with its ecosystem + $$typeof = Symbol.for("jest.asymmetricMatcher"); + constructor(sample, inverse = false) { + this.sample = sample; + this.inverse = inverse; + } + getMatcherContext(expect) { + return { + ...getState(expect || globalThis[GLOBAL_EXPECT]), + equals, + isNot: this.inverse, + customTesters: getCustomEqualityTesters(), + utils: { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + } + }; + } +} +// implement custom chai/loupe inspect for better AssertionError.message formatting +// https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 +// @ts-expect-error computed properties is not supported when isolatedDeclarations is enabled +// FIXME: https://github.com/microsoft/TypeScript/issues/61068 +AsymmetricMatcher.prototype[Symbol.for("chai/inspect")] = function(options) { + // minimal pretty-format with simple manual truncation + const result = stringify(this, options.depth, { min: true }); + if (result.length <= options.truncate) { + return result; + } + return `${this.toString()}{…}`; +}; +class StringContaining extends AsymmetricMatcher { + 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 { + asymmetricMatch(other) { + return other != null; + } + toString() { + return "Anything"; + } + toAsymmetricMatcher() { + return "Anything"; + } +} +class ObjectContaining extends AsymmetricMatcher { + 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.hasOwn(obj, property)) { + return true; + } + return this.hasProperty(this.getPrototype(obj), property); + } + getProperties(obj) { + return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => Object.getOwnPropertyDescriptor(obj, s)?.enumerable)]; + } + asymmetricMatch(other, customTesters) { + if (typeof this.sample !== "object") { + throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`); + } + let result = true; + const properties = this.getProperties(this.sample); + for (const property of properties) { + if (!this.hasProperty(other, property)) { + result = false; + break; + } + const value = this.sample[property]; + const otherValue = other[property]; + if (!equals(value, otherValue, customTesters)) { + result = false; + break; + } + } + return this.inverse ? !result : result; + } + toString() { + return `Object${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "object"; + } +} +class ArrayContaining extends AsymmetricMatcher { + constructor(sample, inverse = false) { + super(sample, inverse); + } + asymmetricMatch(other, customTesters) { + 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, customTesters))); + return this.inverse ? !result : result; + } + toString() { + return `Array${this.inverse ? "Not" : ""}Containing`; + } + getExpectedType() { + return "array"; + } +} +class Any extends AsymmetricMatcher { + 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 functionToString = Function.prototype.toString; + const matches = functionToString.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" || typeof other === "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 { + 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"; + } +} +class CloseTo extends AsymmetricMatcher { + precision; + constructor(sample, precision = 2, inverse = false) { + if (!isA("Number", sample)) { + throw new Error("Expected is not a Number"); + } + if (!isA("Number", precision)) { + throw new Error("Precision is not a Number"); + } + super(sample); + this.inverse = inverse; + this.precision = precision; + } + asymmetricMatch(other) { + if (!isA("Number", other)) { + return false; + } + let result = false; + if (other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY) { + result = true; + } else if (other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY) { + result = true; + } else { + result = Math.abs(this.sample - other) < 10 ** -this.precision / 2; + } + return this.inverse ? !result : result; + } + toString() { + return `Number${this.inverse ? "Not" : ""}CloseTo`; + } + getExpectedType() { + return "number"; + } + toAsymmetricMatcher() { + return [ + this.toString(), + this.sample, + `(${pluralize("digit", this.precision)})` + ].join(" "); + } +} +class SchemaMatching extends AsymmetricMatcher { + result; + constructor(sample, inverse = false) { + if (!isStandardSchema(sample)) { + throw new TypeError("SchemaMatching expected to receive a Standard Schema."); + } + super(sample, inverse); + } + asymmetricMatch(other) { + const result = this.sample["~standard"].validate(other); + // Check if the result is a Promise (async validation) + if (result instanceof Promise) { + throw new TypeError("Async schema validation is not supported in asymmetric matchers."); + } + this.result = result; + const pass = !this.result.issues || this.result.issues.length === 0; + return this.inverse ? !pass : pass; + } + toString() { + return `Schema${this.inverse ? "Not" : ""}Matching`; + } + getExpectedType() { + return "object"; + } + toAsymmetricMatcher() { + const { utils } = this.getMatcherContext(); + const issues = this.result?.issues || []; + if (issues.length > 0) { + return `${this.toString()} ${utils.stringify(this.result, undefined, { printBasicPrototype: false })}`; + } + return this.toString(); + } +} +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)); + utils.addMethod(chai.expect, "closeTo", (expected, precision) => new CloseTo(expected, precision)); + utils.addMethod(chai.expect, "schemaMatching", (expected) => new SchemaMatching(expected)); + // defineProperty does not work + 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), + closeTo: (expected, precision) => new CloseTo(expected, precision, true), + schemaMatching: (expected) => new SchemaMatching(expected, true) + }; +}; + +function createAssertionMessage(util, assertion, hasArgs) { + const soft = util.flag(assertion, "soft") ? ".soft" : ""; + const not = util.flag(assertion, "negate") ? "not." : ""; + const name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`; + const promiseName = util.flag(assertion, "promise"); + const promise = promiseName ? `.${promiseName}` : ""; + return `expect${soft}(actual)${promise}.${not}${name}`; +} +function recordAsyncExpect(_test, promise, assertion, error, isSoft) { + const test = _test; + // record promise for test, that resolves before test ends + if (test && promise instanceof Promise) { + // if promise is explicitly awaited, remove it from the list + promise = promise.finally(() => { + if (!test.promises) { + return; + } + const index = test.promises.indexOf(promise); + if (index !== -1) { + test.promises.splice(index, 1); + } + }); + // record promise + if (!test.promises) { + test.promises = []; + } + // setup `expect.soft` handler here instead of `wrapAssertion` + // to avoid double error tracking while keeping non-await promise detection. + if (isSoft) { + promise = promise.then(noop, (err) => { + handleTestError(test, err); + }); + } + test.promises.push(promise); + let resolved = false; + test.onFinished ??= []; + test.onFinished.push(() => { + if (!resolved) { + const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""); + const stack = processor(error.stack); + console.warn([ + `Promise returned by \`${assertion}\` was not awaited. `, + "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in the next Vitest major. ", + "Please remember to await the assertion.\n", + stack + ].join("")); + } + }); + return { + then(onFulfilled, onRejected) { + resolved = true; + return promise.then(onFulfilled, onRejected); + }, + catch(onRejected) { + resolved = true; + return promise.catch(onRejected); + }, + finally(onFinally) { + resolved = true; + return promise.finally(onFinally); + }, + [Symbol.toStringTag]: "Promise" + }; + } + return promise; +} +function handleTestError(test, err) { + test.result ||= { state: "fail" }; + test.result.state = "fail"; + test.result.errors ||= []; + test.result.errors.push(processError(err)); +} +/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */ +function wrapAssertion(utils, name, fn) { + return function(...args) { + // private + if (name !== "withTest") { + utils.flag(this, "_name", name); + } + if (!utils.flag(this, "soft")) { + // avoid WebKit's proper tail call to preserve stacktrace offset for inline snapshot + // https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit + try { + return fn.apply(this, args); + } finally {} + } + const test = utils.flag(this, "vitest-test"); + if (!test) { + throw new Error("expect.soft() can only be used inside a test"); + } + try { + const result = fn.apply(this, args); + if (result && typeof result === "object" && typeof result.then === "function") { + return result.then(noop, (err) => { + handleTestError(test, err); + }); + } + return result; + } catch (err) { + handleTestError(test, err); + } + }; +} + +// Jest Expect Compact +const JestChaiExpect = (chai, utils) => { + const { AssertionError } = chai; + const customTesters = getCustomEqualityTesters(); + function def(name, fn) { + const addMethod = (n) => { + const softWrapper = wrapAssertion(utils, n, fn); + utils.addMethod(chai.Assertion.prototype, n, softWrapper); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, softWrapper); + }; + 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); + }; + }); + }); + // @ts-expect-error @internal + 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, [...customTesters, 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, [ + ...customTesters, + 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, [ + ...customTesters, + iterableEquality, + typeEquality, + sparseArrayEquality, + arrayBufferEquality + ], true); + if (toStrictEqualPass) { + deepEqualityName = "toStrictEqual"; + } else { + const toEqualPass = equals(actual, expected, [...customTesters, 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; + const pass = equals(actual, expected, [ + ...customTesters, + iterableEquality, + subsetEquality + ]); + const isNot = utils.flag(this, "negate"); + const { subset: actualSubset, stripped } = getObjectSubset(actual, expected, customTesters); + if (pass && isNot || !pass && !isNot) { + const msg = utils.getMessage(this, [ + pass, + "expected #{this} to match object #{exp}", + "expected #{this} to not match object #{exp}", + expected, + actualSubset, + false + ]); + const message = stripped === 0 ? msg : `${msg}\n(${stripped} matching ${stripped === 1 ? "property" : "properties"} omitted from actual)`; + throw new AssertionError(message, { + showDiff: true, + expected, + actual: actualSubset + }); + } + }); + def("toMatch", function(expected) { + const actual = this._obj; + if (typeof actual !== "string") { + throw new TypeError(`.toMatch() expects to receive a string, but got ${typeof actual}`); + } + return this.assert(typeof expected === "string" ? actual.includes(expected) : actual.match(expected), `expected #{this} to match #{exp}`, `expected #{this} not to match #{exp}`, expected, actual); + }); + def("toContain", function(item) { + const actual = this._obj; + if (typeof Node !== "undefined" && actual instanceof Node) { + if (!(item instanceof Node)) { + throw new TypeError(`toContain() expected a DOM node as the argument, but got ${typeof item}`); + } + return this.assert(actual.contains(item), "expected #{this} to contain element #{exp}", "expected #{this} not to contain element #{exp}", item, actual); + } + if (typeof DOMTokenList !== "undefined" && actual instanceof DOMTokenList) { + assertTypes(item, "class name", ["string"]); + const isNot = utils.flag(this, "negate"); + const expectedClassList = isNot ? actual.value.replace(item, "").trim() : `${actual.value} ${item}`; + return this.assert(actual.contains(item), `expected "${actual.value}" to contain "${item}"`, `expected "${actual.value}" not to contain "${item}"`, expectedClassList, actual.value); + } + // handle simple case on our own using `this.assert` to include diff in error message + if (typeof actual === "string" && typeof item === "string") { + return this.assert(actual.includes(item), `expected #{this} to contain #{exp}`, `expected #{this} not to contain #{exp}`, item, actual); + } + // make "actual" indexable to have compatibility with jest + if (actual != null && typeof actual !== "string") { + utils.flag(this, "object", Array.from(actual)); + } + 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, customTesters); + }); + 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", true, obj); + }); + def("toBeFalsy", function() { + const obj = utils.flag(this, "object"); + this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", false, 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}`, expected, actual, false); + }); + 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}`, expected, actual, false); + }); + 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}`, expected, actual, false); + }); + 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}`, expected, actual, false); + }); + def("toBeNaN", function() { + const obj = utils.flag(this, "object"); + this.assert(Number.isNaN(obj), "expected #{this} to be NaN", "expected #{this} not to be NaN", Number.NaN, obj); + }); + def("toBeUndefined", function() { + const obj = utils.flag(this, "object"); + this.assert(undefined === obj, "expected #{this} to be undefined", "expected #{this} not to be undefined", undefined, obj); + }); + def("toBeNull", function() { + const obj = utils.flag(this, "object"); + this.assert(obj === null, "expected #{this} to be null", "expected #{this} not to be null", null, obj); + }); + def("toBeNullable", function() { + const obj = utils.flag(this, "object"); + this.assert(obj == null, "expected #{this} to be nullish", "expected #{this} not to be nullish", null, obj); + }); + def("toBeDefined", function() { + const obj = utils.flag(this, "object"); + this.assert(typeof obj !== "undefined", "expected #{this} to be defined", "expected #{this} to be undefined", obj); + }); + 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); + }); + // destructuring, because it checks `arguments` inside, and value is passing as `undefined` + def("toHaveProperty", function(...args) { + if (Array.isArray(args[0])) { + args[0] = args[0].map((key) => String(key).replace(/([.[\]])/g, "\\$1")).join("."); + } + const actual = this._obj; + const [propertyName, expected] = args; + const getValue = () => { + const hasOwn = Object.hasOwn(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, customTesters)); + 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}`, expected, exists ? value : undefined); + }); + def("toBeCloseTo", function(received, precision = 2) { + const expected = this._obj; + let pass = false; + let expectedDiff = 0; + let receivedDiff = 0; + if (received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY) { + pass = true; + } else if (received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_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, false); + }); + function assertIsMock(assertion) { + if (!isMockFunction(assertion._obj)) { + throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`); + } + } + function getSpy(assertion) { + assertIsMock(assertion); + return assertion._obj; + } + 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, but got ${callCount} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount, false); + }); + 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, but got ${callCount} times`, `expected "${spyName}" to not be called once`, 1, callCount, false); + }); + def(["toHaveBeenCalled", "toBeCalled"], function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + const called = callCount > 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, but actually been called ${callCount} times`, + true, + called + ]); + if (called && isNot) { + msg = formatCalls(spy, msg); + } + if (called && isNot || !called && !isNot) { + throw new AssertionError(msg); + } + }); + // manually compare array elements since `jestEquals` cannot + // apply asymmetric matcher to `undefined` array element. + function equalsArgumentArray(a, b) { + return a.length === b.length && a.every((aItem, i) => equals(aItem, b[i], [...customTesters, iterableEquality])); + } + def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); + const isNot = utils.flag(this, "negate"); + const 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) { + throw new AssertionError(formatCalls(spy, msg, args)); + } + }); + def("toHaveBeenCalledExactlyOnceWith", function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const callCount = spy.mock.calls.length; + const hasCallWithArgs = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); + const pass = hasCallWithArgs && callCount === 1; + const isNot = utils.flag(this, "negate"); + const msg = utils.getMessage(this, [ + pass, + `expected "${spyName}" to be called once with arguments: #{exp}`, + `expected "${spyName}" to not be called once with arguments: #{exp}`, + args + ]); + if (pass && isNot || !pass && !isNot) { + throw new AssertionError(formatCalls(spy, msg, args)); + } + }); + def("toHaveBeenNthCalledWith", function(times, ...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const nthCall = spy.mock.calls[times - 1]; + const callCount = spy.mock.calls.length; + const isCalled = times <= callCount; + this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinal(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinal(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled); + }); + def("toHaveBeenLastCalledWith", function(...args) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const lastCall = spy.mock.calls.at(-1); + this.assert(lastCall && equalsArgumentArray(lastCall, args), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall); + }); + /** + * Used for `toHaveBeenCalledBefore` and `toHaveBeenCalledAfter` to determine if the expected spy was called before the result spy. + */ + function isSpyCalledBeforeAnotherSpy(beforeSpy, afterSpy, failIfNoFirstInvocation) { + const beforeInvocationCallOrder = beforeSpy.mock.invocationCallOrder; + const afterInvocationCallOrder = afterSpy.mock.invocationCallOrder; + if (beforeInvocationCallOrder.length === 0) { + return !failIfNoFirstInvocation; + } + if (afterInvocationCallOrder.length === 0) { + return false; + } + return beforeInvocationCallOrder[0] < afterInvocationCallOrder[0]; + } + def(["toHaveBeenCalledBefore"], function(resultSpy, failIfNoFirstInvocation = true) { + const expectSpy = getSpy(this); + if (!isMockFunction(resultSpy)) { + throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); + } + this.assert(isSpyCalledBeforeAnotherSpy(expectSpy, resultSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called before "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called before "${resultSpy.getMockName()}"`, resultSpy, expectSpy); + }); + def(["toHaveBeenCalledAfter"], function(resultSpy, failIfNoFirstInvocation = true) { + const expectSpy = getSpy(this); + if (!isMockFunction(resultSpy)) { + throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); + } + this.assert(isSpyCalledBeforeAnotherSpy(resultSpy, expectSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called after "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called after "${resultSpy.getMockName()}"`, resultSpy, expectSpy); + }); + def(["toThrow", "toThrowError"], function(expected) { + if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp) { + // Fixes the issue related to `chai` + return this.throws(expected === "" ? /^$/ : 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 { + let isThrow = false; + try { + obj(); + } catch (err) { + isThrow = true; + thrown = err; + } + if (!isThrow && !isNot) { + const message = utils.flag(this, "message") || "expected function to throw an error, but it didn't"; + const error = { showDiff: false }; + throw new AssertionError(message, error, utils.flag(this, "ssfi")); + } + } + 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 (isError(expected)) { + const equal = equals(thrown, expected, [...customTesters, iterableEquality]); + return this.assert(equal, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown); + } + 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, thrown); + } + const equal = equals(thrown, expected, [...customTesters, iterableEquality]); + return this.assert(equal, "expected a thrown value to equal #{exp}", "expected a thrown value not to equal #{exp}", expected, thrown); + }); + [{ + name: "toHaveResolved", + condition: (spy) => spy.mock.settledResults.length > 0 && spy.mock.settledResults.some(({ type }) => type === "fulfilled"), + action: "resolved" + }, { + name: ["toHaveReturned", "toReturn"], + condition: (spy) => spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== "throw"), + action: "called" + }].forEach(({ name, condition, action }) => { + def(name, function() { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = condition(spy); + this.assert(pass, `expected "${spyName}" to be successfully ${action} at least once`, `expected "${spyName}" to not be successfully ${action}`, pass, !pass, false); + }); + }); + [{ + name: "toHaveResolvedTimes", + condition: (spy, times) => spy.mock.settledResults.reduce((s, { type }) => type === "fulfilled" ? ++s : s, 0) === times, + action: "resolved" + }, { + name: ["toHaveReturnedTimes", "toReturnTimes"], + condition: (spy, times) => spy.mock.results.reduce((s, { type }) => type === "throw" ? s : ++s, 0) === times, + action: "called" + }].forEach(({ name, condition, action }) => { + def(name, function(times) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const pass = condition(spy, times); + this.assert(pass, `expected "${spyName}" to be successfully ${action} ${times} times`, `expected "${spyName}" to not be successfully ${action} ${times} times`, `expected resolved times: ${times}`, `received resolved times: ${pass}`, false); + }); + }); + [{ + name: "toHaveResolvedWith", + condition: (spy, value) => spy.mock.settledResults.some(({ type, value: result }) => type === "fulfilled" && equals(value, result)), + action: "resolve" + }, { + name: ["toHaveReturnedWith", "toReturnWith"], + condition: (spy, value) => spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result)), + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(value) { + const spy = getSpy(this); + const pass = condition(spy, value); + const isNot = utils.flag(this, "negate"); + if (pass && isNot || !pass && !isNot) { + const spyName = spy.getMockName(); + const msg = utils.getMessage(this, [ + pass, + `expected "${spyName}" to ${action} with: #{exp} at least once`, + `expected "${spyName}" to not ${action} with: #{exp}`, + value + ]); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + throw new AssertionError(formatReturns(spy, results, msg, value)); + } + }); + }); + [{ + name: "toHaveLastResolvedWith", + condition: (spy, value) => { + const result = spy.mock.settledResults.at(-1); + return Boolean(result && result.type === "fulfilled" && equals(result.value, value)); + }, + action: "resolve" + }, { + name: "toHaveLastReturnedWith", + condition: (spy, value) => { + const result = spy.mock.results.at(-1); + return Boolean(result && result.type === "return" && equals(result.value, value)); + }, + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(value) { + const spy = getSpy(this); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + const result = results.at(-1); + const spyName = spy.getMockName(); + this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result?.value); + }); + }); + [{ + name: "toHaveNthResolvedWith", + condition: (spy, index, value) => { + const result = spy.mock.settledResults[index - 1]; + return result && result.type === "fulfilled" && equals(result.value, value); + }, + action: "resolve" + }, { + name: "toHaveNthReturnedWith", + condition: (spy, index, value) => { + const result = spy.mock.results[index - 1]; + return result && result.type === "return" && equals(result.value, value); + }, + action: "return" + }].forEach(({ name, condition, action }) => { + def(name, function(nthCall, value) { + const spy = getSpy(this); + const spyName = spy.getMockName(); + const results = action === "return" ? spy.mock.results : spy.mock.settledResults; + const result = results[nthCall - 1]; + const ordinalCall = `${ordinal(nthCall)} call`; + this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result?.value); + }); + }); + // @ts-expect-error @internal + def("withContext", function(context) { + for (const key in context) { + utils.flag(this, key, context[key]); + } + return this; + }); + utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() { + const error = new Error("resolves"); + utils.flag(this, "promise", "resolves"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + if (utils.flag(this, "poll")) { + throw new SyntaxError(`expect.poll() is not supported in combination with .resolves`); + } + if (typeof 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 (...args) => { + utils.flag(this, "_name", key); + const promise = Promise.resolve(obj).then((value) => { + utils.flag(this, "object", value); + return result.call(this, ...args); + }, (err) => { + const _error = new AssertionError(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: false }); + _error.cause = err; + throw _error; + }).catch((err) => { + if (isError(err) && error.stack) { + err.stack = error.stack.replace(error.message, err.message); + } + throw err; + }); + return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft")); + }; + } }); + return proxy; + }); + utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() { + const error = new Error("rejects"); + utils.flag(this, "promise", "rejects"); + utils.flag(this, "error", error); + const test = utils.flag(this, "vitest-test"); + const obj = utils.flag(this, "object"); + const wrapper = typeof obj === "function" ? obj() : obj; + if (utils.flag(this, "poll")) { + throw new SyntaxError(`expect.poll() is not supported in combination with .rejects`); + } + if (typeof 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 (...args) => { + utils.flag(this, "_name", key); + const promise = Promise.resolve(wrapper).then((value) => { + const _error = new AssertionError(`promise resolved "${utils.inspect(value)}" instead of rejecting`, { + showDiff: true, + expected: new Error("rejected promise"), + actual: value + }); + throw _error; + }, (err) => { + utils.flag(this, "object", err); + return result.call(this, ...args); + }).catch((err) => { + if (isError(err) && error.stack) { + err.stack = error.stack.replace(error.message, err.message); + } + throw err; + }); + return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft")); + }; + } }); + return proxy; + }); +}; +function formatCalls(spy, msg, showActualCall) { + if (spy.mock.calls.length) { + msg += c.gray(`\n\nReceived:\n\n${spy.mock.calls.map((callArg, i) => { + let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call:\n\n`); + if (showActualCall) { + methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true }); + } else { + methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n"); + } + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + } + msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); + return msg; +} +function formatReturns(spy, results, msg, showActualReturn) { + if (results.length) { + msg += c.gray(`\n\nReceived:\n\n${results.map((callReturn, i) => { + let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call return:\n\n`); + if (showActualReturn) { + methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true }); + } else { + methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n"); + } + methodCall += "\n"; + return methodCall; + }).join("\n")}`); + } + msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); + return msg; +} + +function getMatcherState(assertion, expect) { + const obj = assertion._obj; + const isNot = util.flag(assertion, "negate"); + const promise = util.flag(assertion, "promise") || ""; + const customMessage = util.flag(assertion, "message"); + const jestUtils = { + ...getMatcherUtils(), + diff, + stringify, + iterableEquality, + subsetEquality + }; + let task = util.flag(assertion, "vitest-test"); + const currentTestName = task?.fullTestName ?? ""; + if (task?.type !== "test") { + task = undefined; + } + const matcherState = { + ...getState(expect), + currentTestName, + customTesters: getCustomEqualityTesters(), + isNot, + utils: jestUtils, + promise, + equals, + suppressedErrors: [], + soft: util.flag(assertion, "soft"), + poll: util.flag(assertion, "poll"), + assertion + }; + Object.assign(matcherState, { task }); + return { + state: matcherState, + isNot, + obj, + customMessage + }; +} +class JestExtendError extends Error { + constructor(message, actual, expected, __vitest_error_context__) { + super(message); + this.actual = actual; + this.expected = expected; + this.__vitest_error_context__ = __vitest_error_context__; + } +} +function JestExtendPlugin(c, expect, matchers) { + return (_, utils) => { + Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => { + function __VITEST_EXTEND_ASSERTION__(...args) { + const { state, isNot, obj, customMessage } = getMatcherState(this, expect); + const result = expectAssertion.call(state, obj, ...args); + if (result && typeof result === "object" && typeof result.then === "function") { + const thenable = result; + return thenable.then(({ pass, message, actual, expected, meta }) => { + if (pass && isNot || !pass && !isNot) { + const errorMessage = (customMessage ? `${customMessage}: ` : "") + message(); + throw new JestExtendError(errorMessage, actual, expected, { + assertionName: expectAssertionName, + meta + }); + } + }); + } + const { pass, message, actual, expected, meta } = result; + if (pass && isNot || !pass && !isNot) { + const errorMessage = (customMessage ? `${customMessage}: ` : "") + message(); + throw new JestExtendError(errorMessage, actual, expected, { + assertionName: expectAssertionName, + meta + }); + } + } + const softWrapper = wrapAssertion(utils, expectAssertionName, __VITEST_EXTEND_ASSERTION__); + utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper); + utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper); + // `expect.poll()` inspects the installed Chai assertion method, + // so copy the internal marker from the original matcher function. + // this is only for domain snapshot matchers for now. + if (expectAssertion.__vitest_poll_takeover__) { + const addedMethod = c.Assertion.prototype[expectAssertionName]; + Object.defineProperty(addedMethod, "__vitest_poll_takeover__", { value: true }); + } + class CustomMatcher extends AsymmetricMatcher { + 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((item) => stringify(item)).join(", ")}>`; + } + } + const customMatcher = (...sample) => new CustomMatcher(false, ...sample); + Object.defineProperty(expect, expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + Object.defineProperty(expect.not, expectAssertionName, { + configurable: true, + enumerable: true, + value: (...sample) => new CustomMatcher(true, ...sample), + writable: true + }); + // keep track of asymmetric matchers on global so that it can be copied over to local context's `expect`. + // note that the negated variant is automatically shared since it's assigned on the single `expect.not` object. + Object.defineProperty(globalThis[ASYMMETRIC_MATCHERS_OBJECT], expectAssertionName, { + configurable: true, + enumerable: true, + value: customMatcher, + writable: true + }); + }); + }; +} +const JestExtend = (chai, utils) => { + utils.addMethod(chai.expect, "extend", (expect, expects) => { + use(JestExtendPlugin(chai, expect, expects)); + }); +}; + +export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion }; diff --git a/node_modules/@vitest/expect/package.json b/node_modules/@vitest/expect/package.json new file mode 100644 index 000000000..a8fdad322 --- /dev/null +++ b/node_modules/@vitest/expect/package.json @@ -0,0 +1,52 @@ +{ + "name": "@vitest/expect", + "type": "module", + "version": "4.1.5", + "description": "Jest's expect matchers as a Chai plugin", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/expect", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/expect" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "chai", + "assertion" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0", + "@vitest/spy": "4.1.5", + "@vitest/utils": "4.1.5" + }, + "devDependencies": { + "@vitest/runner": "4.1.5" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/mocker/LICENSE b/node_modules/@vitest/mocker/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/mocker/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/mocker/README.md b/node_modules/@vitest/mocker/README.md new file mode 100644 index 000000000..dae8292f6 --- /dev/null +++ b/node_modules/@vitest/mocker/README.md @@ -0,0 +1,7 @@ +# @vitest/mocker + +[![NPM version](https://img.shields.io/npm/v/@vitest/mocker?color=a1b858&label=)](https://npmx.dev/package/@vitest/mocker) + +Vitest's module mocker implementation. + +[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md) diff --git a/node_modules/@vitest/mocker/dist/auto-register.d.ts b/node_modules/@vitest/mocker/dist/auto-register.d.ts new file mode 100644 index 000000000..04fa25ee3 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/auto-register.d.ts @@ -0,0 +1,2 @@ + +export { }; diff --git a/node_modules/@vitest/mocker/dist/auto-register.js b/node_modules/@vitest/mocker/dist/auto-register.js new file mode 100644 index 000000000..5e80823e3 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/auto-register.js @@ -0,0 +1,10 @@ +import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; +import { registerModuleMocker } from './register.js'; +import './chunk-mocker.js'; +import './chunk-helpers.js'; +import './index.js'; +import './chunk-registry.js'; +import './chunk-pathe.M-eThtNZ.js'; +import '@vitest/spy'; + +registerModuleMocker(() => new ModuleMockerServerInterceptor()); diff --git a/node_modules/@vitest/mocker/dist/automock.d.ts b/node_modules/@vitest/mocker/dist/automock.d.ts new file mode 100644 index 000000000..23daf27b7 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/automock.d.ts @@ -0,0 +1,13 @@ +import MagicString from 'magic-string'; + +interface AutomockOptions { + /** + * @default "__vitest_mocker__" + */ + globalThisAccessor?: string; + id?: string; +} +declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString; + +export { automockModule }; +export type { AutomockOptions }; diff --git a/node_modules/@vitest/mocker/dist/automock.js b/node_modules/@vitest/mocker/dist/automock.js new file mode 100644 index 000000000..d8d1fbf77 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/automock.js @@ -0,0 +1,8 @@ +import 'node:fs'; +import 'node:url'; +import 'magic-string'; +export { a as automockModule } from './chunk-automock.js'; +import 'estree-walker'; +import 'node:module'; +import 'node:path'; +import './chunk-helpers.js'; diff --git a/node_modules/@vitest/mocker/dist/browser.d.ts b/node_modules/@vitest/mocker/dist/browser.d.ts new file mode 100644 index 000000000..edbf53bc1 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/browser.d.ts @@ -0,0 +1,53 @@ +import { M as ModuleMockerInterceptor } from './mocker.d-QEntlm6J.js'; +export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, c as ModuleMockerConfig, d as ModuleMockerRPC, R as ResolveIdResult, e as ResolveMockResult, f as createCompilerHints } from './mocker.d-QEntlm6J.js'; +import { StartOptions, SetupWorker } from 'msw/browser'; +import { M as MockerRegistry, a as MockedModule } from './types.d-BjI5eAwu.js'; +import '@vitest/spy'; +import './index.d-B41z0AuW.js'; + +interface ModuleMockerMSWInterceptorOptions { + /** + * The identifier to access the globalThis object in the worker. + * This will be injected into the script as is, so make sure it's a valid JS expression. + * @example + * ```js + * // globalThisAccessor: '__my_variable__' produces: + * globalThis[__my_variable__] + * // globalThisAccessor: 'Symbol.for('secret:mocks')' produces: + * globalThis[Symbol.for('secret:mocks')] + * // globalThisAccessor: '"__vitest_mocker__"' (notice quotes) produces: + * globalThis["__vitest_mocker__"] + * ``` + * @default `"__vitest_mocker__"` + */ + globalThisAccessor?: string; + /** + * Options passed down to `msw.setupWorker().start(options)` + */ + mswOptions?: StartOptions; + /** + * A pre-configured `msw.setupWorker` instance. + */ + mswWorker?: SetupWorker; +} +declare class ModuleMockerMSWInterceptor implements ModuleMockerInterceptor { + private readonly options; + protected readonly mocks: MockerRegistry; + private startPromise; + private worker; + constructor(options?: ModuleMockerMSWInterceptorOptions); + register(module: MockedModule): Promise; + delete(url: string): Promise; + invalidate(): Promise; + private resolveManualMock; + protected init(): Promise; +} + +declare class ModuleMockerServerInterceptor implements ModuleMockerInterceptor { + register(module: MockedModule): Promise; + delete(id: string): Promise; + invalidate(): Promise; +} + +export { ModuleMockerInterceptor, ModuleMockerMSWInterceptor, ModuleMockerServerInterceptor }; +export type { ModuleMockerMSWInterceptorOptions }; diff --git a/node_modules/@vitest/mocker/dist/browser.js b/node_modules/@vitest/mocker/dist/browser.js new file mode 100644 index 000000000..0c29c0624 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/browser.js @@ -0,0 +1,92 @@ +export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js'; +import { M as MockerRegistry } from './chunk-registry.js'; +import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js'; +export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; +import './chunk-helpers.js'; +import './index.js'; +import './chunk-pathe.M-eThtNZ.js'; + +class ModuleMockerMSWInterceptor { + mocks = new MockerRegistry(); + startPromise; + worker; + constructor(options = {}) { + this.options = options; + if (!options.globalThisAccessor) { + options.globalThisAccessor = "\"__vitest_mocker__\""; + } + } + async register(module) { + await this.init(); + this.mocks.add(module); + } + async delete(url) { + await this.init(); + this.mocks.delete(url); + } + async invalidate() { + this.mocks.clear(); + } + async resolveManualMock(mock) { + const exports$1 = Object.keys(await mock.resolve()); + const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor); + return new Response(text, { headers: { "Content-Type": "application/javascript" } }); + } + async init() { + if (this.worker) { + return this.worker; + } + if (this.startPromise) { + return this.startPromise; + } + const worker = this.options.mswWorker; + this.startPromise = Promise.all([worker ? { setupWorker(handler) { + worker.use(handler); + return worker; + } } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => { + const worker = setupWorker(http.get(/.+/, async ({ request }) => { + const path = cleanQuery(request.url.slice(location.origin.length)); + if (!this.mocks.has(path)) { + return passthrough(); + } + const mock = this.mocks.get(path); + switch (mock.type) { + case "manual": return this.resolveManualMock(mock); + case "automock": + case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`)); + case "redirect": return Response.redirect(mock.redirect); + default: throw new Error(`Unknown mock type: ${mock.type}`); + } + })); + return worker.start(this.options.mswOptions).then(() => worker); + }).finally(() => { + this.worker = worker; + this.startPromise = undefined; + }); + return await this.startPromise; + } +} +const trailingSeparatorRE = /[?&]$/; +const timestampRE = /\bt=\d{13}&?\b/; +const versionRE = /\bv=\w{8}&?\b/; +function cleanQuery(url) { + return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, ""); +} +function passthrough() { + return new Response(null, { + status: 302, + statusText: "Passthrough", + headers: { "x-msw-intention": "passthrough" } + }); +} +const replacePercentageRE = /%/g; +function injectQuery(url, queryToInject) { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href); + const { search, hash } = resolvedUrl; + const pathname = cleanUrl(url); + return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`; +} + +export { ModuleMockerMSWInterceptor }; diff --git a/node_modules/@vitest/mocker/dist/chunk-automock.js b/node_modules/@vitest/mocker/dist/chunk-automock.js new file mode 100644 index 000000000..1639d2880 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-automock.js @@ -0,0 +1,526 @@ +import { readFileSync } from 'node:fs'; +import { pathToFileURL, fileURLToPath } from 'node:url'; +import MagicString from 'magic-string'; +import { walk } from 'estree-walker'; +import module$1, { isBuiltin, createRequire } from 'node:module'; +import { extname } from 'node:path'; +import { f as filterOutComments } from './chunk-helpers.js'; + +const isNodeInPatternWeakSet = new WeakSet(); +function setIsNodeInPattern(node) { + return isNodeInPatternWeakSet.add(node); +} +function isNodeInPattern(node) { + return isNodeInPatternWeakSet.has(node); +} +/** +* Same logic from \@vue/compiler-core & \@vue/compiler-sfc +* Except this is using acorn AST +*/ +function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) { + const parentStack = []; + const varKindStack = []; + const scopeMap = new WeakMap(); + const identifiers = []; + const setScope = (node, name) => { + let scopeIds = scopeMap.get(node); + if (scopeIds && scopeIds.has(name)) { + return; + } + if (!scopeIds) { + scopeIds = new Set(); + scopeMap.set(node, scopeIds); + } + scopeIds.add(name); + }; + function isInScope(name, parents) { + return parents.some((node) => node && scopeMap.get(node)?.has(name)); + } + function handlePattern(p, parentScope) { + if (p.type === "Identifier") { + setScope(parentScope, p.name); + } else if (p.type === "RestElement") { + handlePattern(p.argument, parentScope); + } else if (p.type === "ObjectPattern") { + p.properties.forEach((property) => { + if (property.type === "RestElement") { + setScope(parentScope, property.argument.name); + } else { + handlePattern(property.value, parentScope); + } + }); + } else if (p.type === "ArrayPattern") { + p.elements.forEach((element) => { + if (element) { + handlePattern(element, parentScope); + } + }); + } else if (p.type === "AssignmentPattern") { + handlePattern(p.left, parentScope); + } else { + setScope(parentScope, p.name); + } + } + walk(root, { + enter(node, parent) { + if (node.type === "ImportDeclaration") { + return this.skip(); + } + // track parent stack, skip for "else-if"/"else" branches as acorn nests + // the ast within "if" nodes instead of flattening them + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { + parentStack.unshift(parent); + } + // track variable declaration kind stack used by VariableDeclarator + if (node.type === "VariableDeclaration") { + varKindStack.unshift(node.kind); + } + if (node.type === "CallExpression") { + onCallExpression?.(node); + } + if (node.type === "MetaProperty" && node.meta.name === "import") { + onImportMeta?.(node); + } else if (node.type === "ImportExpression") { + onDynamicImport?.(node); + } + if (node.type === "Identifier") { + if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) { + // record the identifier, for DFS -> BFS + identifiers.push([node, parentStack.slice(0)]); + } + } else if (node.type === "ClassDeclaration" && node.id) { + // A class declaration name could shadow an import, so add its name to the parent scope + const parentScope = findParentScope(parentStack); + if (parentScope) { + setScope(parentScope, node.id.name); + } + } else if (node.type === "ClassExpression" && node.id) { + // A class expression name could shadow an import, so add its name to the scope + setScope(node, node.id.name); + } else if (isFunctionNode(node)) { + // If it is a function declaration, it could be shadowing an import + // Add its name to the scope so it won't get replaced + if (node.type === "FunctionDeclaration") { + const parentScope = findParentScope(parentStack); + if (parentScope) { + setScope(parentScope, node.id.name); + } + } + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + node.params.forEach((p) => { + if (p.type === "ObjectPattern" || p.type === "ArrayPattern") { + handlePattern(p, node); + return; + } + walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) { + // skip params default value of destructure + if (parent?.type === "AssignmentPattern" && parent?.right === child) { + return this.skip(); + } + if (child.type !== "Identifier") { + return; + } + // do not record as scope variable if is a destructuring keyword + if (isStaticPropertyKey(child, parent)) { + return; + } + // do not record if this is a default value + // assignment of a destructuring variable + if (parent?.type === "TemplateLiteral" && parent?.expressions.includes(child) || parent?.type === "CallExpression" && parent?.callee === child) { + return; + } + setScope(node, child.name); + } }); + }); + } else if (node.type === "Property" && parent.type === "ObjectPattern") { + // mark property in destructuring pattern + setIsNodeInPattern(node); + } else if (node.type === "VariableDeclarator") { + const parentFunction = findParentScope(parentStack, varKindStack[0] === "var"); + if (parentFunction) { + handlePattern(node.id, parentFunction); + } + } else if (node.type === "CatchClause" && node.param) { + handlePattern(node.param, node); + } + }, + leave(node, parent) { + // untrack parent stack from above + if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { + parentStack.shift(); + } + if (node.type === "VariableDeclaration") { + varKindStack.shift(); + } + } + }); + // emit the identifier events in BFS so the hoisted declarations + // can be captured correctly + identifiers.forEach(([node, stack]) => { + if (!isInScope(node.name, stack)) { + const parent = stack[0]; + const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)); + const classDeclaration = parent.type === "ClassDeclaration" && node === parent.superClass; + const classExpression = parent.type === "ClassExpression" && node === parent.id; + onIdentifier?.(node, { + hasBindingShortcut, + classDeclaration, + classExpression + }, stack); + } + }); +} +function isRefIdentifier(id, parent, parentStack) { + // declaration id + if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) { + return false; + } + if (isFunctionNode(parent)) { + // function declaration/expression id + if (parent.id === id) { + return false; + } + // params list + if (parent.params.includes(id)) { + return false; + } + } + // class method name + if (parent.type === "MethodDefinition" && !parent.computed) { + return false; + } + // class property + if (parent.type === "PropertyDefinition" && !parent.computed) { + // Default values can still reference identifiers + return id === parent.value; + } + // property key + if (isStaticPropertyKey(id, parent)) { + return false; + } + // object destructuring pattern + if (isNodeInPattern(parent) && parent.value === id) { + return false; + } + // non-assignment array destructuring pattern + if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) { + return false; + } + // member expression property + if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) { + return false; + } + if (parent.type === "ExportSpecifier") { + return false; + } + // is a special keyword but parsed as identifier + if (id.name === "arguments") { + return false; + } + return true; +} +function isStaticProperty(node) { + return node && node.type === "Property" && !node.computed; +} +function isStaticPropertyKey(node, parent) { + return isStaticProperty(parent) && parent.key === node; +} +const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; +function isFunctionNode(node) { + return functionNodeTypeRE.test(node.type); +} +const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; +function isBlock(node) { + return blockNodeTypeRE.test(node.type); +} +function findParentScope(parentStack, isVar = false) { + return parentStack.find(isVar ? isFunctionNode : isBlock); +} +function isInDestructuringAssignment(parent, parentStack) { + if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) { + return parentStack.some((i) => i.type === "AssignmentExpression"); + } + return false; +} +function getArbitraryModuleIdentifier(node) { + return node.type === "Identifier" ? node.name : node.raw; +} + +/* cjs-module-lexer 2.2.0 */ +let A$1;const B$1=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$1(E,g="@"){if(!A$1)throw new Error("Not initialized");const w=E.length+1,D=(A$1.__heap_base.value||A$1.__heap_base)+4*w-A$1.memory.buffer.byteLength;D>0&&A$1.memory.grow(Math.ceil(D/65536));const G=A$1.sa(w);(B$1?C$1:I)(E,new Uint16Array(A$1.memory.buffer,G,w));const S=A$1.parseCJS(G,E.length,0,0,0);if(S){const B=new Error(`Parse error ${g}${A$1.e()}:${E.slice(0,A$1.e()).split("\n").length}:${A$1.e()-E.lastIndexOf("\n",A$1.e()-1)}`);throw Object.assign(B,{idx:A$1.e()}),5!==S&&6!==S&&7!==S||Object.assign(B,{code:"ERR_LEXER_ESM_SYNTAX"}),B}let o=new Set,R=new Set,y=new Set;for(;A$1.rre();){const B=Q$1(E.slice(A$1.res(),A$1.ree()));B&&R.add(B);}for(;A$1.ru();)y.add(Q$1(E.slice(A$1.us(),A$1.ue())));for(;A$1.re();){let B=Q$1(E.slice(A$1.es(),A$1.ee()));void 0===B||y.has(B)||o.add(B);}return {exports:[...o],reexports:[...R]}}function Q$1(A){if('"'!==A[0]&&"'"!==A[0])return A;try{const B=function(A){const B=A[0];if('"'===B)try{return JSON.parse(A)}catch{}else if("'"===B&&A.length>1&&"'"===A[A.length-1]&&-1===A.indexOf('"'))try{return JSON.parse('"'+A.slice(1,-1)+'"')}catch{}let Q="",g={v:1};for(;g.v1114111)throw new SyntaxError;++B.v;}while("}"!==A[B.v]);++B.v;}else for(let E=0;E<4;++E)Q=16*Q+g(A[B.v]),++B.v;return String.fromCodePoint(Q)}(A,B);case "0":case "1":case "2":case "3":case "4":case "5":case "6":case "7":return function(A,B,Q){let E=A<="3"?2:1,g=+A;do{if((A=B[Q.v])<"0"||A>"7")break;g=8*g+ +A,++Q.v,--E;}while(E>0);return String.fromCodePoint(g)}(Q,A,B);default:return Q}}function g(A){if(A>="0"&&A<="9")return +A;if(A>="a"&&A<="f")return A.charCodeAt(0)-87;if(A>="A"&&A<="F")return A.charCodeAt(0)-55;throw new SyntaxError}function I(A,B){const Q=A.length;let E=0;for(;E>>8;}}function C$1(A,B){const Q=A.length;let E=0;for(;EA.charCodeAt(0))}let D;function init$1(){return D||(D=(async()=>{const B=await WebAssembly.compile(w()),{exports:Q}=await WebAssembly.instantiate(B);A$1=Q;})())} + +/* es-module-lexer 2.0.0 */ +var ImportType;!function(A){A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase",A[A.StaticDeferPhase=6]="StaticDeferPhase",A[A.DynamicDeferPhase=7]="DynamicDeferPhase";}(ImportType||(ImportType={}));const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse(E,g="@"){if(!C)return init.then((()=>parse(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const D=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,D,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const w=[],K=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.it(),g=C.ai(),I=C.id(),o=C.ss(),D=C.se();let K;C.ip()&&(K=k(E.slice(-1===I?A-1:A,-1===I?Q+1:Q)));const N=[];for(C.rsa();C.ra();){const A=C.aks(),Q=C.ake(),B=C.avs(),g=C.ave();N.push([J(E.slice(A,Q)),J(E.slice(B,g))]);}w.push({n:K,t:B,s:A,e:Q,ss:o,se:D,d:I,a:g,at:N.length>0?N:null});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=J(E.slice(A,Q)),o=B<0?void 0:J(E.slice(B,g));K.push({s:A,e:Q,ls:B,le:g,n:I,ln:o});}function k(A){try{return (0,eval)(A)}catch(A){}}function J(A){if(!A)return A;const Q=A[0];return ('"'===Q||"'"===Q)&&k(A)||A}return [w,K,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C{return A="AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADNzYAAQECAgICAgICAgICAgICAgICAgICAgICAwIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwedARsGbWVtb3J5AgACc2EAAAFlAAMCaXMABAJpZQAFAnNzAAYCc2UABwJpdAAIAmFpAAkCaWQACgJpcAALAmVzAAwCZWUADQNlbHMADgNlbGUADwJyaQAQAnJlABEBZgASAm1zABMCcmEAFANha3MAFQNha2UAFgNhdnMAFwNhdmUAGANyc2EAGQVwYXJzZQAaC19faGVhcF9iYXNlAwEKkkY2aAEBf0EAIAA2AvQJQQAoAtAJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgL4CUEAIAA2AvwJQQBBADYC1AlBAEEANgLkCUEAQQA2AtwJQQBBADYC2AlBAEEANgLsCUEAQQA2AuAJIAEL0wEBA39BACgC5AkhBEEAQQAoAvwJIgU2AuQJQQAgBDYC6AlBACAFQShqNgL8CSAEQSRqQdQJIAQbIAU2AgBBACgCyAkhBEEAKALECSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUIANwIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALECSADRiICOgAYAkACQCACDQBBACgCyAkgA0cNAQtBAEEBOgCACgsLXgEBf0EAKALsCSIEQRBqQdgJIAQbQQAoAvwJIgQ2AgBBACAENgLsCUEAIARBFGo2AvwJQQBBAToAgAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKECgsVAEEAKALcCSgCAEEAKALQCWtBAXULHgEBf0EAKALcCSgCBCIAQQAoAtAJa0EBdUF/IAAbCxUAQQAoAtwJKAIIQQAoAtAJa0EBdQseAQF/QQAoAtwJKAIMIgBBACgC0AlrQQF1QX8gABsLCwBBACgC3AkoAhwLHgEBf0EAKALcCSgCECIAQQAoAtAJa0EBdUF/IAAbCzsBAX8CQEEAKALcCSgCFCIAQQAoAsQJRw0AQX8PCwJAIABBACgCyAlHDQBBfg8LIABBACgC0AlrQQF1CwsAQQAoAtwJLQAYCxUAQQAoAuAJKAIAQQAoAtAJa0EBdQsVAEEAKALgCSgCBEEAKALQCWtBAXULHgEBf0EAKALgCSgCCCIAQQAoAtAJa0EBdUF/IAAbCx4BAX9BACgC4AkoAgwiAEEAKALQCWtBAXVBfyAAGwslAQF/QQBBACgC3AkiAEEkakHUCSAAGygCACIANgLcCSAAQQBHCyUBAX9BAEEAKALgCSIAQRBqQdgJIAAbKAIAIgA2AuAJIABBAEcLCABBAC0AiAoLCABBAC0AgAoLKwEBf0EAQQAoAowKIgBBEGpBACgC3AlBIGogABsoAgAiADYCjAogAEEARwsVAEEAKAKMCigCAEEAKALQCWtBAXULFQBBACgCjAooAgRBACgC0AlrQQF1CxUAQQAoAowKKAIIQQAoAtAJa0EBdQsVAEEAKAKMCigCDEEAKALQCWtBAXULCgBBAEEANgKMCgvdDQEFfyMAQYDQAGsiACQAQQBBAToAiApBAEEAKALMCTYClApBAEEAKALQCUF+aiIBNgKoCkEAIAFBACgC9AlBAXRqIgI2AqwKQQBBADoAgApBAEEAOwGQCkEAQQA7AZIKQQBBADoAmApBAEEANgKECkEAQQA6APAJQQAgAEGAEGo2ApwKQQAgADYCoApBAEEAOgCkCgJAAkACQAJAA0BBACABQQJqIgM2AqgKIAEgAk8NAQJAIAMvAQAiAkF3akEFSQ0AAkACQAJAAkACQCACQZt/ag4FAQgICAIACyACQSBGDQQgAkEvRg0DIAJBO0YNAgwHC0EALwGSCg0BIAMQG0UNASABQQRqQYIIQQoQNQ0BEBxBAC0AiAoNAUEAQQAoAqgKIgE2ApQKDAcLIAMQG0UNACABQQRqQYwIQQoQNQ0AEB0LQQBBACgCqAo2ApQKDAELAkAgAS8BBCIDQSpGDQAgA0EvRw0EEB4MAQtBARAfC0EAKAKsCiECQQAoAqgKIQEMAAsLQQAhAiADIQFBAC0A8AkNAgwBC0EAIAE2AqgKQQBBADoAiAoLA0BBACABQQJqIgM2AqgKAkACQAJAAkACQAJAAkAgAUEAKAKsCk8NACADLwEAIgJBd2pBBUkNBgJAAkACQAJAAkACQAJAAkACQAJAIAJBYGoOChAPBg8PDw8FAQIACwJAAkACQAJAIAJBoH9qDgoLEhIDEgESEhICAAsgAkGFf2oOAwURBgkLQQAvAZIKDRAgAxAbRQ0QIAFBBGpBgghBChA1DRAQHAwQCyADEBtFDQ8gAUEEakGMCEEKEDUNDxAdDA8LIAMQG0UNDiABKQAEQuyAhIOwjsA5Ug0OIAEvAQwiA0F3aiIBQRdLDQxBASABdEGfgIAEcUUNDAwNC0EAQQAvAZIKIgFBAWo7AZIKQQAoApwKIAFBA3RqIgFBATYCACABQQAoApQKNgIEDA0LQQAvAZIKIgNFDQlBACADQX9qIgM7AZIKQQAvAZAKIgJFDQxBACgCnAogA0H//wNxQQN0aigCAEEFRw0MAkAgAkECdEEAKAKgCmpBfGooAgAiAygCBA0AIANBACgClApBAmo2AgQLQQAgAkF/ajsBkAogAyABQQRqNgIMDAwLAkBBACgClAoiAS8BAEEpRw0AQQAoAuQJIgNFDQAgAygCBCABRw0AQQBBACgC6AkiAzYC5AkCQCADRQ0AIANBADYCJAwBC0EAQQA2AtQJC0EAQQAvAZIKIgNBAWo7AZIKQQAoApwKIANBA3RqIgNBBkECQQAtAKQKGzYCACADIAE2AgRBAEEAOgCkCgwLC0EALwGSCiIBRQ0HQQAgAUF/aiIBOwGSCkEAKAKcCiABQf//A3FBA3RqKAIAQQRGDQQMCgtBJxAgDAkLQSIQIAwICyACQS9HDQcCQAJAIAEvAQQiAUEqRg0AIAFBL0cNARAeDAoLQQEQHwwJCwJAAkACQAJAQQAoApQKIgEvAQAiAxAhRQ0AAkACQCADQVVqDgQACQEDCQsgAUF+ai8BAEErRg0DDAgLIAFBfmovAQBBLUYNAgwHCyADQSlHDQFBACgCnApBAC8BkgoiAkEDdGooAgQQIkUNAgwGCyABQX5qLwEAQVBqQf//A3FBCk8NBQtBAC8BkgohAgsCQAJAIAJB//8DcSICRQ0AIANB5gBHDQBBACgCnAogAkF/akEDdGoiBCgCAEEBRw0AIAFBfmovAQBB7wBHDQEgBCgCBEGWCEEDECNFDQEMBQsgA0H9AEcNAEEAKAKcCiACQQN0aiICKAIEECQNBCACKAIAQQZGDQQLIAEQJQ0DIANFDQMgA0EvRkEALQCYCkEAR3ENAwJAQQAoAuwJIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBAsgAUF+aiEBQQAoAtAJIQICQANAIAFBAmoiBCACTQ0BQQAgATYClAogAS8BACEDIAFBfmoiBCEBIAMQJkUNAAsgBEECaiEECwJAIANB//8DcRAnRQ0AIARBfmohAQJAA0AgAUECaiIDIAJNDQFBACABNgKUCiABLwEAIQMgAUF+aiIEIQEgAxAnDQALIARBAmohAwsgAxAoDQQLQQBBAToAmAoMBwtBACgCnApBAC8BkgoiAUEDdCIDakEAKAKUCjYCBEEAIAFBAWo7AZIKQQAoApwKIANqQQM2AgALECkMBQtBAC0A8AlBAC8BkApBAC8BkgpyckUhAgwHCxAqQQBBADoAmAoMAwsQK0EAIQIMBQsgA0GgAUcNAQtBAEEBOgCkCgtBAEEAKAKoCjYClAoLQQAoAqgKIQEMAAsLIABBgNAAaiQAIAILGgACQEEAKALQCSAARw0AQQEPCyAAQX5qECwL/goBBn9BAEEAKAKoCiIAQQxqIgE2AqgKQQAoAuwJIQJBARAvIQMCQAJAAkACQAJAAkACQAJAAkBBACgCqAoiBCABRw0AIAMQLkUNAQsCQAJAAkACQAJAAkACQCADQSpGDQAgA0H7AEcNAUEAIARBAmo2AqgKQQEQLyEDQQAoAqgKIQQDQAJAAkAgA0H//wNxIgNBIkYNACADQSdGDQAgAxAyGkEAKAKoCiEDDAELIAMQIEEAQQAoAqgKQQJqIgM2AqgKC0EBEC8aAkAgBCADEDMiA0EsRw0AQQBBACgCqApBAmo2AqgKQQEQLyEDCyADQf0ARg0DQQAoAqgKIgUgBEYNDyAFIQQgBUEAKAKsCk0NAAwPCwtBACAEQQJqNgKoCkEBEC8aQQAoAqgKIgMgAxAzGgwCC0EAQQA6AIgKAkACQAJAAkACQAJAIANBn39qDgwCCwQBCwMLCwsLCwUACyADQfYARg0EDAoLQQAgBEEOaiIDNgKoCgJAAkACQEEBEC9Bn39qDgYAEgISEgESC0EAKAKoCiIFKQACQvOA5IPgjcAxUg0RIAUvAQoQJ0UNEUEAIAVBCmo2AqgKQQAQLxoLQQAoAqgKIgVBAmpBsghBDhA1DRAgBS8BECICQXdqIgFBF0sNDUEBIAF0QZ+AgARxRQ0NDA4LQQAoAqgKIgUpAAJC7ICEg7COwDlSDQ8gBS8BCiICQXdqIgFBF00NBgwKC0EAIARBCmo2AqgKQQAQLxpBACgCqAohBAtBACAEQRBqNgKoCgJAQQEQLyIEQSpHDQBBAEEAKAKoCkECajYCqApBARAvIQQLQQAoAqgKIQMgBBAyGiADQQAoAqgKIgQgAyAEEAJBAEEAKAKoCkF+ajYCqAoPCwJAIAQpAAJC7ICEg7COwDlSDQAgBC8BChAmRQ0AQQAgBEEKajYCqApBARAvIQRBACgCqAohAyAEEDIaIANBACgCqAoiBCADIAQQAkEAQQAoAqgKQX5qNgKoCg8LQQAgBEEEaiIENgKoCgtBACAEQQZqNgKoCkEAQQA6AIgKQQEQLyEEQQAoAqgKIQMgBBAyIQRBACgCqAohAiAEQd//A3EiAUHbAEcNA0EAIAJBAmo2AqgKQQEQLyEFQQAoAqgKIQNBACEEDAQLQQBBAToAgApBAEEAKAKoCkECajYCqAoLQQEQLyEEQQAoAqgKIQMCQCAEQeYARw0AIANBAmpBrAhBBhA1DQBBACADQQhqNgKoCiAAQQEQL0EAEDEgAkEQakHYCSACGyEDA0AgAygCACIDRQ0FIANCADcCCCADQRBqIQMMAAsLQQAgA0F+ajYCqAoMAwtBASABdEGfgIAEcUUNAwwEC0EBIQQLA0ACQAJAIAQOAgABAQsgBUH//wNxEDIaQQEhBAwBCwJAAkBBACgCqAoiBCADRg0AIAMgBCADIAQQAkEBEC8hBAJAIAFB2wBHDQAgBEEgckH9AEYNBAtBACgCqAohAwJAIARBLEcNAEEAIANBAmo2AqgKQQEQLyEFQQAoAqgKIQMgBUEgckH7AEcNAgtBACADQX5qNgKoCgsgAUHbAEcNAkEAIAJBfmo2AqgKDwtBACEEDAALCw8LIAJBoAFGDQAgAkH7AEcNBAtBACAFQQpqNgKoCkEBEC8iBUH7AEYNAwwCCwJAIAJBWGoOAwEDAQALIAJBoAFHDQILQQAgBUEQajYCqAoCQEEBEC8iBUEqRw0AQQBBACgCqApBAmo2AqgKQQEQLyEFCyAFQShGDQELQQAoAqgKIQEgBRAyGkEAKAKoCiIFIAFNDQAgBCADIAEgBRACQQBBACgCqApBfmo2AqgKDwsgBCADQQBBABACQQAgBEEMajYCqAoPCxArC4UMAQp/QQBBACgCqAoiAEEMaiIBNgKoCkEBEC8hAkEAKAKoCiEDAkACQAJAAkACQAJAAkACQCACQS5HDQBBACADQQJqNgKoCgJAQQEQLyICQeQARg0AAkAgAkHzAEYNACACQe0ARw0HQQAoAqgKIgJBAmpBnAhBBhA1DQcCQEEAKAKUCiIDEDANACADLwEAQS5GDQgLIAAgACACQQhqQQAoAsgJEAEPC0EAKAKoCiICQQJqQaIIQQoQNQ0GAkBBACgClAoiAxAwDQAgAy8BAEEuRg0HC0EAIQRBACACQQxqNgKoCkEBIQVBBSEGQQEQLyECQQAhB0EBIQgMAgtBACgCqAoiAikAAkLlgJiD0IyAOVINBQJAQQAoApQKIgMQMA0AIAMvAQBBLkYNBgtBACEEQQAgAkEKajYCqApBAiEIQQchBkEBIQdBARAvIQJBASEFDAELAkACQAJAAkAgAkHzAEcNACADIAFNDQAgA0ECakGiCEEKEDUNAAJAIAMvAQwiBEF3aiIHQRdLDQBBASAHdEGfgIAEcQ0CCyAEQaABRg0BC0EAIQdBByEGQQEhBCACQeQARg0BDAILQQAhBEEAIANBDGoiAjYCqApBASEFQQEQLyEJAkBBACgCqAoiBiACRg0AQeYAIQICQCAJQeYARg0AQQUhBkEAIQdBASEIIAkhAgwEC0EAIQdBASEIIAZBAmpBrAhBBhA1DQQgBi8BCBAmRQ0EC0EAIQdBACADNgKoCkEHIQZBASEEQQAhBUEAIQggCSECDAILIAMgAEEKak0NAEEAIQhB5AAhAgJAIAMpAAJC5YCYg9CMgDlSDQACQAJAIAMvAQoiBEF3aiIHQRdLDQBBASAHdEGfgIAEcQ0BC0EAIQggBEGgAUcNAQtBACEFQQAgA0EKajYCqApBKiECQQEhB0ECIQhBARAvIglBKkYNBEEAIAM2AqgKQQEhBEEAIQdBACEIIAkhAgwCCyADIQZBACEHDAILQQAhBUEAIQgLAkAgAkEoRw0AQQAoApwKQQAvAZIKIgJBA3RqIgNBACgCqAo2AgRBACACQQFqOwGSCiADQQU2AgBBACgClAovAQBBLkYNBEEAQQAoAqgKIgNBAmo2AqgKQQEQLyECIABBACgCqApBACADEAECQAJAIAUNAEEAKALkCSEBDAELQQAoAuQJIgEgBjYCHAtBAEEALwGQCiIDQQFqOwGQCkEAKAKgCiADQQJ0aiABNgIAAkAgAkEiRg0AIAJBJ0YNAEEAQQAoAqgKQX5qNgKoCg8LIAIQIEEAQQAoAqgKQQJqIgI2AqgKAkACQAJAQQEQL0FXag4EAQICAAILQQBBACgCqApBAmo2AqgKQQEQLxpBACgC5AkiAyACNgIEIANBAToAGCADQQAoAqgKIgI2AhBBACACQX5qNgKoCg8LQQAoAuQJIgMgAjYCBCADQQE6ABhBAEEALwGSCkF/ajsBkgogA0EAKAKoCkECajYCDEEAQQAvAZAKQX9qOwGQCg8LQQBBACgCqApBfmo2AqgKDwsCQCAEQQFzIAJB+wBHcg0AQQAoAqgKIQJBAC8BkgoNBQNAAkACQAJAIAJBACgCrApPDQBBARAvIgJBIkYNASACQSdGDQEgAkH9AEcNAkEAQQAoAqgKQQJqNgKoCgtBARAvIQNBACgCqAohAgJAIANB5gBHDQAgAkECakGsCEEGEDUNBwtBACACQQhqNgKoCgJAQQEQLyICQSJGDQAgAkEnRw0HCyAAIAJBABAxDwsgAhAgC0EAQQAoAqgKQQJqIgI2AqgKDAALCwJAAkAgAkFZag4EAwEBAwALIAJBIkYNAgtBACgCqAohBgsgBiABRw0AQQAgAEEKajYCqAoPCyACQSpHIAdxDQNBAC8BkgpB//8DcQ0DQQAoAqgKIQJBACgCrAohAQNAIAIgAU8NAQJAAkAgAi8BACIDQSdGDQAgA0EiRw0BCyAAIAMgCBAxDwtBACACQQJqIgI2AqgKDAALCxArCw8LQQAgAkF+ajYCqAoPC0EAQQAoAqgKQX5qNgKoCgtHAQN/QQAoAqgKQQJqIQBBACgCrAohAQJAA0AgACICQX5qIAFPDQEgAkECaiEAIAIvAQBBdmoOBAEAAAEACwtBACACNgKoCguYAQEDf0EAQQAoAqgKIgFBAmo2AqgKIAFBBmohAUEAKAKsCiECA0ACQAJAAkAgAUF8aiACTw0AIAFBfmovAQAhAwJAAkAgAA0AIANBKkYNASADQXZqDgQCBAQCBAsgA0EqRw0DCyABLwEAQS9HDQJBACABQX5qNgKoCgwBCyABQX5qIQELQQAgATYCqAoPCyABQQJqIQEMAAsLiAEBBH9BACgCqAohAUEAKAKsCiECAkACQANAIAEiA0ECaiEBIAMgAk8NASABLwEAIgQgAEYNAgJAIARB3ABGDQAgBEF2ag4EAgEBAgELIANBBGohASADLwEEQQ1HDQAgA0EGaiABIAMvAQZBCkYbIQEMAAsLQQAgATYCqAoQKw8LQQAgATYCqAoLbAEBfwJAAkAgAEFfaiIBQQVLDQBBASABdEExcQ0BCyAAQUZqQf//A3FBBkkNACAAQSlHIABBWGpB//8DcUEHSXENAAJAIABBpX9qDgQBAAABAAsgAEH9AEcgAEGFf2pB//8DcUEESXEPC0EBCy4BAX9BASEBAkAgAEGcCUEFECMNACAAQZYIQQMQIw0AIABBpglBAhAjIQELIAELRgEDf0EAIQMCQCAAIAJBAXQiAmsiBEECaiIAQQAoAtAJIgVJDQAgACABIAIQNQ0AAkAgACAFRw0AQQEPCyAEECwhAwsgAwuDAQECf0EBIQECQAJAAkACQAJAAkAgAC8BACICQUVqDgQFBAQBAAsCQCACQZt/ag4EAwQEAgALIAJBKUYNBCACQfkARw0DIABBfmpBsglBBhAjDwsgAEF+ai8BAEE9Rg8LIABBfmpBqglBBBAjDwsgAEF+akG+CUEDECMPC0EAIQELIAELtAMBAn9BACEBAkACQAJAAkACQAJAAkACQAJAAkAgAC8BAEGcf2oOFAABAgkJCQkDCQkEBQkJBgkHCQkICQsCQAJAIABBfmovAQBBl39qDgQACgoBCgsgAEF8akHACEECECMPCyAAQXxqQcQIQQMQIw8LAkACQAJAIABBfmovAQBBjX9qDgMAAQIKCwJAIABBfGovAQAiAkHhAEYNACACQewARw0KIABBempB5QAQLQ8LIABBempB4wAQLQ8LIABBfGpByghBBBAjDwsgAEF8akHSCEEGECMPCyAAQX5qLwEAQe8ARw0GIABBfGovAQBB5QBHDQYCQCAAQXpqLwEAIgJB8ABGDQAgAkHjAEcNByAAQXhqQd4IQQYQIw8LIABBeGpB6ghBAhAjDwsgAEF+akHuCEEEECMPC0EBIQEgAEF+aiIAQekAEC0NBCAAQfYIQQUQIw8LIABBfmpB5AAQLQ8LIABBfmpBgAlBBxAjDwsgAEF+akGOCUEEECMPCwJAIABBfmovAQAiAkHvAEYNACACQeUARw0BIABBfGpB7gAQLQ8LIABBfGpBlglBAxAjIQELIAELNAEBf0EBIQECQCAAQXdqQf//A3FBBUkNACAAQYABckGgAUYNACAAQS5HIAAQLnEhAQsgAQswAQF/AkACQCAAQXdqIgFBF0sNAEEBIAF0QY2AgARxDQELIABBoAFGDQBBAA8LQQELTgECf0EAIQECQAJAIAAvAQAiAkHlAEYNACACQesARw0BIABBfmpB7ghBBBAjDwsgAEF+ai8BAEH1AEcNACAAQXxqQdIIQQYQIyEBCyABC94BAQR/QQAoAqgKIQBBACgCrAohAQJAAkACQANAIAAiAkECaiEAIAIgAU8NAQJAAkACQCAALwEAIgNBpH9qDgUCAwMDAQALIANBJEcNAiACLwEEQfsARw0CQQAgAkEEaiIANgKoCkEAQQAvAZIKIgJBAWo7AZIKQQAoApwKIAJBA3RqIgJBBDYCACACIAA2AgQPC0EAIAA2AqgKQQBBAC8BkgpBf2oiADsBkgpBACgCnAogAEH//wNxQQN0aigCAEEDRw0DDAQLIAJBBGohAAwACwtBACAANgKoCgsQKwsLcAECfwJAAkADQEEAQQAoAqgKIgBBAmoiATYCqAogAEEAKAKsCk8NAQJAAkACQCABLwEAIgFBpX9qDgIBAgALAkAgAUF2ag4EBAMDBAALIAFBL0cNAgwECxA0GgwBC0EAIABBBGo2AqgKDAALCxArCws1AQF/QQBBAToA8AlBACgCqAohAEEAQQAoAqwKQQJqNgKoCkEAIABBACgC0AlrQQF1NgKECgtDAQJ/QQEhAQJAIAAvAQAiAkF3akH//wNxQQVJDQAgAkGAAXJBoAFGDQBBACEBIAIQLkUNACACQS5HIAAQMHIPCyABCz0BAn9BACECAkBBACgC0AkiAyAASw0AIAAvAQAgAUcNAAJAIAMgAEcNAEEBDwsgAEF+ai8BABAmIQILIAILaAECf0EBIQECQAJAIABBX2oiAkEFSw0AQQEgAnRBMXENAQsgAEH4/wNxQShGDQAgAEFGakH//wNxQQZJDQACQCAAQaV/aiICQQNLDQAgAkEBRw0BCyAAQYV/akH//wNxQQRJIQELIAELnAEBA39BACgCqAohAQJAA0ACQAJAIAEvAQAiAkEvRw0AAkAgAS8BAiIBQSpGDQAgAUEvRw0EEB4MAgsgABAfDAELAkACQCAARQ0AIAJBd2oiAUEXSw0BQQEgAXRBn4CABHFFDQEMAgsgAhAnRQ0DDAELIAJBoAFHDQILQQBBACgCqAoiA0ECaiIBNgKoCiADQQAoAqwKSQ0ACwsgAgsxAQF/QQAhAQJAIAAvAQBBLkcNACAAQX5qLwEAQS5HDQAgAEF8ai8BAEEuRiEBCyABC9sEAQV/AkAgAUEiRg0AIAFBJ0YNABArDwtBACgCqAohAyABECAgACADQQJqQQAoAqgKQQAoAsQJEAECQCACQQFIDQBBACgC5AlBBEEGIAJBAUYbNgIcC0EAQQAoAqgKQQJqNgKoCkEAEC8hAkEAKAKoCiEBAkACQCACQfcARw0AIAEvAQJB6QBHDQAgAS8BBEH0AEcNACABLwEGQegARg0BC0EAIAFBfmo2AqgKDwtBACABQQhqNgKoCgJAQQEQL0H7AEYNAEEAIAE2AqgKDwtBACgCqAoiBCEDQQAhAANAQQAgA0ECajYCqAoCQAJAAkACQEEBEC8iAkEnRw0AQQAoAqgKIQVBJxAgQQAoAqgKQQJqIQMMAQtBACgCqAohBSACQSJHDQFBIhAgQQAoAqgKQQJqIQMLQQAgAzYCqApBARAvIQIMAQsgAhAyIQJBACgCqAohAwsCQCACQTpGDQBBACABNgKoCg8LQQBBACgCqApBAmo2AqgKAkBBARAvIgJBIkYNACACQSdGDQBBACABNgKoCg8LQQAoAqgKIQYgAhAgQQBBACgC/AkiAkEUajYC/AlBACgCqAohByACIAU2AgAgAkEANgIQIAIgBjYCCCACIAM2AgQgAiAHQQJqNgIMQQBBACgCqApBAmo2AqgKIABBEGpBACgC5AlBIGogABsgAjYCAAJAAkBBARAvIgBBLEYNACAAQf0ARg0BQQAgATYCqAoPC0EAQQAoAqgKQQJqIgM2AqgKIAIhAAwBCwtBACgC5AkiASAENgIQIAFBACgCqApBAmo2AgwLbQECfwJAAkADQAJAIABB//8DcSIBQXdqIgJBF0sNAEEBIAJ0QZ+AgARxDQILIAFBoAFGDQEgACECIAEQLg0CQQAhAkEAQQAoAqgKIgBBAmo2AqgKIAAvAQIiAA0ADAILCyAAIQILIAJB//8DcQurAQEEfwJAAkBBACgCqAoiAi8BACIDQeEARg0AIAEhBCAAIQUMAQtBACACQQRqNgKoCkEBEC8hAkEAKAKoCiEFAkACQCACQSJGDQAgAkEnRg0AIAIQMhpBACgCqAohBAwBCyACECBBAEEAKAKoCkECaiIENgKoCgtBARAvIQNBACgCqAohAgsCQCACIAVGDQAgBSAEQQAgACAAIAFGIgIbQQAgASACGxACCyADC3IBBH9BACgCqAohAEEAKAKsCiEBAkACQANAIABBAmohAiAAIAFPDQECQAJAIAIvAQAiA0Gkf2oOAgEEAAsgAiEAIANBdmoOBAIBAQIBCyAAQQRqIQAMAAsLQQAgAjYCqAoQK0EADwtBACACNgKoCkHdAAtJAQN/QQAhAwJAIAJFDQACQANAIAAtAAAiBCABLQAAIgVHDQEgAUEBaiEBIABBAWohACACQX9qIgINAAwCCwsgBCAFayEDCyADCwviAQIAQYAIC8QBAAB4AHAAbwByAHQAbQBwAG8AcgB0AGYAbwByAGUAdABhAG8AdQByAGMAZQByAG8AbQB1AG4AYwB0AGkAbwBuAHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABBxAkLEAEAAAACAAAAAAQAADA5AAA=","undefined"!=typeof Buffer?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(A=>A.charCodeAt(0)));var A;};const init=WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;})); + +async function initSyntaxLexers() { + await Promise.all([init$1(), init]); +} +const isTransform = process.execArgv.includes("--experimental-transform-types") || process.env.NODE_OPTIONS?.includes("--experimental-transform-types"); +function transformCode(code, filename) { + const ext = extname(filename.split("?")[0]); + const isTs = ext === ".ts" || ext === ".cts" || ext === ".mts"; + if (!isTs) { + return code; + } + if (!module$1.stripTypeScriptTypes) { + throw new Error(`Cannot parse '${filename}' because "module.stripTypeScriptTypes" is not supported. Module mocking requires Node.js 22.15 or higher. This is NOT a bug of Vitest.`); + } + return module$1.stripTypeScriptTypes(code, { mode: isTransform ? "transform" : "strip" }); +} +const cachedFileExports = new Map(); +function collectModuleExports(filename, code, format, exports$1 = []) { + if (format === "module") { + const [imports_, exports_] = parse(code, filename); + const fileExports = [...exports_.map((p) => p.n)]; + imports_.forEach(({ ss: start, se: end, n: name }) => { + const substring = code.substring(start, end).replace(/ +/g, " "); + if (name && substring.startsWith("export *") && !substring.startsWith("export * as")) { + fileExports.push(...tryParseModule(name)); + } + }); + cachedFileExports.set(filename, fileExports); + exports$1.push(...fileExports); + } else { + const { exports: exports_, reexports } = parse$1(code, filename); + const fileExports = [...exports_]; + reexports.forEach((name) => { + fileExports.push(...tryParseModule(name)); + }); + cachedFileExports.set(filename, fileExports); + exports$1.push(...fileExports); + } + function tryParseModule(name) { + try { + return parseModule(name); + } catch (error) { + console.warn(`[module mocking] Failed to parse '${name}' imported from ${filename}:`, error); + return []; + } + } + let __require; + function getModuleRequire() { + return __require ??= createRequire(filename); + } + function parseModule(name) { + if (isBuiltin(name)) { + if (cachedFileExports.has(name)) { + const cachedExports = cachedFileExports.get(name); + return cachedExports; + } + const builtinModule = getBuiltinModule(name); + const builtinExports = Object.keys(builtinModule); + cachedFileExports.set(name, builtinExports); + return builtinExports; + } + const resolvedModuleUrl = format === "module" ? import.meta.resolve(name, pathToFileURL(filename).toString()) : getModuleRequire().resolve(name); + const resolvedModulePath = format === "commonjs" ? resolvedModuleUrl : fileURLToPath(resolvedModuleUrl); + if (cachedFileExports.has(resolvedModulePath)) { + return cachedFileExports.get(resolvedModulePath); + } + const fileContent = readFileSync(resolvedModulePath, "utf-8"); + const ext = extname(resolvedModulePath); + const code = transformCode(fileContent, resolvedModulePath); + if (code == null) { + cachedFileExports.set(resolvedModulePath, []); + return []; + } + const resolvedModuleFormat = resolveModuleFormat(resolvedModulePath, code); + if (ext === ".json") { + return ["default"]; + } else { + // can't do wasm, for example + console.warn(`Cannot process '${resolvedModuleFormat}' imported from ${filename} because of unknown file extension: ${ext}.`); + } + if (resolvedModuleFormat) { + return collectModuleExports(resolvedModulePath, code, resolvedModuleFormat, exports$1); + } + return []; + } + return Array.from(new Set(exports$1)); +} +function resolveModuleFormat(url, code) { + const ext = extname(url); + if (ext === ".cjs" || ext === ".cts") { + return "commonjs"; + } else if (ext === ".mjs" || ext === ".mts") { + return "module"; + } else if (ext === ".js" || ext === ".ts" || ext === "") { + if (!module$1.findPackageJSON) { + throw new Error(`Cannot parse the module format of '${url}' because "module.findPackageJSON" is not available. Upgrade to Node 22.14 to use this feature. This is NOT a bug of Vitest.`); + } + const pkgJsonPath = module$1.findPackageJSON(url); + const pkgJson = pkgJsonPath ? JSON.parse(readFileSync(pkgJsonPath, "utf-8")) : {}; + if (pkgJson?.type === "module") { + return "module"; + } else if (pkgJson?.type === "commonjs") { + return "commonjs"; + } else { + // Ambiguous input! Check if it has ESM syntax. Node.js is much smarter here, + // but we don't need to run the code, so we can be more relaxed + if (hasESM(filterOutComments(code))) { + return "module"; + } else { + return "commonjs"; + } + } + } + return undefined; +} +let __globalRequire; +function getBuiltinModule(moduleId) { + __globalRequire ??= module$1.createRequire(import.meta.url); + return __globalRequire(moduleId); +} +const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; +function hasESM(code) { + return ESM_RE.test(code); +} + +// TODO: better source map replacement +function automockModule(code, mockType, parse, options = {}) { + const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + let ast; + try { + ast = parse(code); + } catch (cause) { + if (options.id) { + throw new Error(`failed to parse ${options.id}`, { cause }); + } + throw cause; + } + const m = new MagicString(code); + const allSpecifiers = []; + const replacers = []; + let importIndex = 0; + for (const _node of ast.body) { + if (_node.type === "ExportAllDeclaration") { + const node = _node; + // TODO: pass it down in the browser mode + if (!options.id) { + throw new Error(`automocking files with \`export *\` is not supported because it cannot be easily statically analysed`); + } + const source = node.source.value; + if (typeof source !== "string") { + throw new TypeError(`unknown source type while automocking: ${source}`); + } + const moduleUrl = import.meta.resolve(source, pathToFileURL(options.id).toString()); + const modulePath = fileURLToPath(moduleUrl); + const moduleContent = readFileSync(modulePath, "utf-8"); + const transformedCode = transformCode(moduleContent, moduleUrl); + const moduleFormat = resolveModuleFormat(moduleUrl, transformedCode); + const moduleExports = collectModuleExports(modulePath, transformedCode, moduleFormat || "module"); + replacers.push(() => { + const importNames = []; + moduleExports.forEach((exportName) => { + const isReexported = allSpecifiers.some(({ name, alias }) => name === exportName || alias === exportName); + if (!isReexported) { + importNames.push(exportName); + allSpecifiers.push({ name: exportName }); + } + }); + const importString = `import { ${importNames.join(", ")} } from '${source}';`; + m.overwrite(node.start, node.end, importString); + }); + } + if (_node.type === "ExportNamedDeclaration") { + const node = _node; + const declaration = node.declaration; + function traversePattern(expression) { + // export const test = '1' + if (expression.type === "Identifier") { + allSpecifiers.push({ name: expression.name }); + } else if (expression.type === "ArrayPattern") { + expression.elements.forEach((element) => { + if (!element) { + return; + } + traversePattern(element); + }); + } else if (expression.type === "ObjectPattern") { + expression.properties.forEach((property) => { + // export const { ...rest } = {} + if (property.type === "RestElement") { + traversePattern(property); + } else if (property.type === "Property") { + traversePattern(property.value); + } else ; + }); + } else if (expression.type === "RestElement") { + traversePattern(expression.argument); + } else if (expression.type === "AssignmentPattern") { + throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`); + } else if (expression.type === "MemberExpression") { + throw new Error(`MemberExpression is not supported. Please open a new bug report.`); + } else ; + } + if (declaration) { + if (declaration.type === "FunctionDeclaration") { + allSpecifiers.push({ name: declaration.id.name }); + } else if (declaration.type === "VariableDeclaration") { + declaration.declarations.forEach((declaration) => { + traversePattern(declaration.id); + }); + } else if (declaration.type === "ClassDeclaration") { + allSpecifiers.push({ name: declaration.id.name }); + } else ; + m.remove(node.start, declaration.start); + } + const specifiers = node.specifiers || []; + const source = node.source; + if (!source && specifiers.length) { + specifiers.forEach((specifier) => { + allSpecifiers.push({ + alias: getArbitraryModuleIdentifier(specifier.exported), + name: getArbitraryModuleIdentifier(specifier.local) + }); + }); + m.remove(node.start, node.end); + } else if (source && specifiers.length) { + const importNames = []; + specifiers.forEach((specifier) => { + const importedName = `__vitest_imported_${importIndex++}__`; + importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]); + allSpecifiers.push({ + name: importedName, + alias: getArbitraryModuleIdentifier(specifier.exported) + }); + }); + const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`; + m.overwrite(node.start, node.end, importString); + } + } + if (_node.type === "ExportDefaultDeclaration") { + const node = _node; + const declaration = node.declaration; + allSpecifiers.push({ + name: "__vitest_default", + alias: "default" + }); + m.overwrite(node.start, declaration.start, `const __vitest_default = `); + } + } + replacers.forEach((cb) => cb()); + const moduleObject = ` +const __vitest_current_es_module__ = { + __esModule: true, + ${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")} +} +const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}") +`; + const assigning = allSpecifiers.map(({ name }, index) => { + return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`; + }).join("\n"); + const redeclarations = allSpecifiers.map(({ name, alias }, index) => { + return ` __vitest_mocked_${index}__ as ${alias || name},`; + }).join("\n"); + const specifiersExports = ` +export { +${redeclarations} +} +`; + m.append(moduleObject + assigning + specifiersExports); + return m; +} + +export { automockModule as a, collectModuleExports as c, esmWalker as e, initSyntaxLexers as i }; diff --git a/node_modules/@vitest/mocker/dist/chunk-helpers.js b/node_modules/@vitest/mocker/dist/chunk-helpers.js new file mode 100644 index 000000000..eff497d19 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-helpers.js @@ -0,0 +1,44 @@ +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +function createSimpleStackTrace(options) { + const { message = "$$stack trace 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; +} +function filterOutComments(s) { + const result = []; + let commentState = "none"; + for (let i = 0; i < s.length; ++i) { + if (commentState === "singleline") { + if (s[i] === "\n") { + commentState = "none"; + } + } else if (commentState === "multiline") { + if (s[i - 1] === "*" && s[i] === "/") { + commentState = "none"; + } + } else if (commentState === "none") { + if (s[i] === "/" && s[i + 1] === "/") { + commentState = "singleline"; + } else if (s[i] === "/" && s[i + 1] === "*") { + commentState = "multiline"; + i += 2; + } else { + result.push(s[i]); + } + } + } + return result.join(""); +} + +export { createSimpleStackTrace as c, filterOutComments as f }; diff --git a/node_modules/@vitest/mocker/dist/chunk-hoistMocks.js b/node_modules/@vitest/mocker/dist/chunk-hoistMocks.js new file mode 100644 index 000000000..15cdee208 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-hoistMocks.js @@ -0,0 +1,659 @@ +import MagicString from 'magic-string'; +import { e as esmWalker } from './chunk-automock.js'; + +// AST walker module for ESTree compatible trees + + +function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } +} + +var Found = function Found(node, state) { this.node = node; this.state = state; }; + +// Find the innermost node of a given type that contains the given +// position. Interface similar to findNodeAt. +function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + visitNode(baseVisitor, type, node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +function skipThrough(node, st, c) { c(node, st); } +function ignore(_node, _st, _c) {} + +function visitNode(baseVisitor, type, node, st, c) { + if (baseVisitor[type] == null) { throw new Error(("No walker function defined for node type " + type)) } + baseVisitor[type](node, st, c); +} + +// Node walkers. + +var base = {}; + +base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; +base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } +}; +base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i = 0, list = node.cases; i < list.length; i += 1) { + var cs = list[i]; + + c(cs, st); + } +}; +base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } +}; +base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; +base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } +}; +base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); +}; +base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); +}; +base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } +}; +base.DebuggerStatement = ignore; + +base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; +base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } +}; +base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } +}; + +base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); +}; + +base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } +}; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; +base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } +}; +base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } +}; + +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } +}; +base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } +}; +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } +}; +base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } +}; +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); +}; +base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); +}; +base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); +}; +base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } +}; +base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } +}; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } + if (node.attributes) + { for (var i = 0, list = node.attributes; i < list.length; i += 1) + { + var attr = list[i]; + + c(attr, st); + } } +}; +base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); + if (node.attributes) + { for (var i = 0, list = node.attributes; i < list.length; i += 1) + { + var attr = list[i]; + + c(attr, st); + } } +}; +base.ImportAttribute = function (node, st, c) { + c(node.value, st, "Expression"); +}; +base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); + if (node.attributes) + { for (var i$1 = 0, list$1 = node.attributes; i$1 < list$1.length; i$1 += 1) + { + var attr = list$1[i$1]; + + c(attr, st); + } } +}; +base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); + if (node.options) { c(node.options, st, "Expression"); } +}; +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + +base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); +}; +base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; +base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); +}; +base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } +}; +base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } +}; + +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' option`; +function API_NOT_FOUND_CHECK(names) { + return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`; +} +function isIdentifier(node) { + return node.type === "Identifier"; +} +function getNodeTail(code, node) { + let end = node.end; + if (code[node.end] === ";") { + end += 1; + } + if (code[node.end] === "\n") { + return end + 1; + } + if (code[node.end + 1] === "\n") { + end += 1; + } + return end; +} +const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/; +const hashbangRE = /^#!.*\n/; +// this is a fork of Vite SSR transform +function hoistMocks(code, id, parse, options = {}) { + const needHoisting = (options.regexpHoistable || regexpHoistable).test(code); + if (!needHoisting) { + return; + } + const s = options.magicString?.() || new MagicString(code); + let ast; + try { + ast = parse(code); + } catch (err) { + console.error(`Cannot parse ${id}:\n${err.message}.`); + return; + } + const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ + "mock", + "unmock", + "doMock", + "doUnmock" + ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options; + // hoist at the start of the file, after the hashbang + const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0; + let hoistIndex = hashbangEnd; + let hoistedModuleImported = false; + let uid = 0; + const idToImportMap = new Map(); + const imports = []; + // this will transform import statements into dynamic ones, if there are imports + // it will keep the import as is, if we don't need to mock anything + // in browser environment it will wrap the module value with "vitest_wrap_module" function + // that returns a proxy to the module so that named exports can be mocked + function defineImport(importNode) { + const source = importNode.source.value; + // always hoist vitest import to top of the file, so + // "vi" helpers can access it + if (hoistedModule === source) { + hoistedModuleImported = true; + return; + } + const importId = `__vi_import_${uid++}__`; + imports.push({ + id: importId, + node: importNode + }); + return importId; + } + // 1. check all import statements and record id -> importName map + for (const node of ast.body) { + // import foo from 'foo' --> foo -> __import_foo__.default + // import { baz } from 'foo' --> baz -> __import_foo__.baz + // import * as ok from 'foo' --> ok -> __import_foo__ + if (node.type === "ImportDeclaration") { + const importId = defineImport(node); + if (!importId) { + continue; + } + for (const spec of node.specifiers) { + if (spec.type === "ImportSpecifier") { + if (spec.imported.type === "Identifier") { + idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); + } else { + idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`); + } + } else if (spec.type === "ImportDefaultSpecifier") { + idToImportMap.set(spec.local.name, `${importId}.default`); + } else { + // namespace specifier + idToImportMap.set(spec.local.name, importId); + } + } + } + } + const declaredConst = new Set(); + const hoistedNodes = new Set(); + function createSyntaxError(node, message) { + const _error = new SyntaxError(message); + Error.captureStackTrace(_error, createSyntaxError); + const serializedError = { + name: "SyntaxError", + message: _error.message, + stack: _error.stack + }; + if (options.codeFrameGenerator) { + serializedError.frame = options.codeFrameGenerator(node, id, code); + } + return serializedError; + } + function assertNotDefaultExport(node, error) { + const defaultExport = findNodeAround(ast, node.start, "ExportDefaultDeclaration")?.node; + if (defaultExport?.declaration === node || defaultExport?.declaration.type === "AwaitExpression" && defaultExport.declaration.argument === node) { + throw createSyntaxError(defaultExport, error); + } + } + function assertNotNamedExport(node, error) { + const nodeExported = findNodeAround(ast, node.start, "ExportNamedDeclaration")?.node; + if (nodeExported?.declaration === node) { + throw createSyntaxError(nodeExported, error); + } + } + function getVariableDeclaration(node) { + const declarationNode = findNodeAround(ast, node.start, "VariableDeclaration")?.node; + const init = declarationNode?.declarations[0]?.init; + if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) { + return declarationNode; + } + } + const usedUtilityExports = new Set(); + let hasImportMetaVitest = false; + esmWalker(ast, { + onImportMeta(node) { + const property = code.slice(node.end, node.end + 7); + if (property === ".vitest") { + hasImportMetaVitest = true; + } + }, + onIdentifier(id, info, parentStack) { + const binding = idToImportMap.get(id.name); + if (!binding) { + return; + } + if (info.hasBindingShortcut) { + s.appendLeft(id.end, `: ${binding}`); + } else if (info.classDeclaration) { + if (!declaredConst.has(id.name)) { + declaredConst.add(id.name); + // locate the top-most node containing the class declaration + const topNode = parentStack[parentStack.length - 2]; + s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); + } + } else if (!info.classExpression) { + s.update(id.start, id.end, binding); + } + }, + onDynamicImport(_node) { + // TODO: vi.mock(import) breaks it, and vi.mock('', () => import) also does, + // only move imports that are outside of vi.mock + // backwards compat, don't do if not passed + // if (!options.globalThisAccessor) { + // return + // } + // const globalThisAccessor = options.globalThisAccessor + // const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(` + // const importSubstring = code.substring(node.start, node.end) + // const hasIgnore = importSubstring.includes('/* @vite-ignore */') + // s.overwrite( + // node.start, + // (node.source as Positioned).start, + // replaceString + (hasIgnore ? '/* @vite-ignore */ ' : ''), + // ) + // s.overwrite(node.end - 1, node.end, '))') + }, + onCallExpression(node) { + if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) { + const methodName = node.callee.property.name; + usedUtilityExports.add(node.callee.object.name); + if (hoistableMockMethodNames.includes(methodName)) { + const method = `${node.callee.object.name}.${methodName}`; + assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); + const declarationNode = getVariableDeclaration(node); + if (declarationNode) { + assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); + } + // rewrite vi.mock(import('..')) into vi.mock('..') + if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) { + const moduleInfo = node.arguments[0]; + // vi.mock(import('./path')) -> vi.mock('./path') + if (moduleInfo.type === "ImportExpression") { + const source = moduleInfo.source; + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + // vi.mock(await import('./path')) -> vi.mock('./path') + if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { + const source = moduleInfo.argument.source; + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + } + hoistedNodes.add(node); + } else if (dynamicImportMockMethodNames.includes(methodName)) { + const moduleInfo = node.arguments[0]; + let source = null; + if (moduleInfo.type === "ImportExpression") { + source = moduleInfo.source; + } + if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { + source = moduleInfo.argument.source; + } + if (source) { + s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); + } + } + if (hoistedMethodNames.includes(methodName)) { + assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); + const declarationNode = getVariableDeclaration(node); + if (declarationNode) { + assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); + // hoist "const variable = vi.hoisted(() => {})" + hoistedNodes.add(declarationNode); + } else { + const awaitedExpression = findNodeAround(ast, node.start, "AwaitExpression")?.node; + // hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})" + const moveNode = awaitedExpression?.argument === node ? awaitedExpression : node; + hoistedNodes.add(moveNode); + } + } + } + } + }); + function getNodeName(node) { + const callee = node.callee || {}; + if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) { + const argument = node.arguments[0]; + const argStr = argument.type === "Literal" || argument.type === "ImportExpression" ? code.slice(argument.start, argument.end) : ""; + return `${callee.object.name}.${callee.property.name}(${argStr})`; + } + return "\"hoisted method\""; + } + function getNodeCall(node) { + if (node.type === "CallExpression") { + return node; + } + if (node.type === "VariableDeclaration") { + const { declarations } = node; + const init = declarations[0].init; + if (init) { + return getNodeCall(init); + } + } + if (node.type === "AwaitExpression") { + const { argument } = node; + if (argument.type === "CallExpression") { + return getNodeCall(argument); + } + } + return node; + } + function createError(outsideNode, insideNode) { + const outsideCall = getNodeCall(outsideNode); + const insideCall = getNodeCall(insideNode); + throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`); + } + // validate hoistedNodes doesn't have nodes inside other nodes + const arrayNodes = Array.from(hoistedNodes); + for (let i = 0; i < arrayNodes.length; i++) { + const node = arrayNodes[i]; + for (let j = i + 1; j < arrayNodes.length; j++) { + const otherNode = arrayNodes[j]; + if (node.start >= otherNode.start && node.end <= otherNode.end) { + throw createError(otherNode, node); + } + if (otherNode.start >= node.start && otherNode.end <= node.end) { + throw createError(node, otherNode); + } + } + } + // validate that hoisted nodes are defined on the top level + // ignore `import.meta.vitest` because it needs to be inside an IfStatement + // and it can be used anywhere in the code (inside methods too) + if (!hasImportMetaVitest) { + for (const node of ast.body) { + hoistedNodes.delete(node); + if (node.type === "ExpressionStatement") { + hoistedNodes.delete(node.expression); + } + } + for (const invalidNode of hoistedNodes) { + console.warn(`Warning: A ${getNodeName(getNodeCall(invalidNode))} call in "${id}" is not at the top level of the module. ` + `Although it appears nested, it will be hoisted and executed before any tests run. ` + `Move it to the top level to reflect its actual execution order. This will become an error in a future version.\n` + `See: https://vitest.dev/guide/mocking/modules#how-it-works`); + } + } + // hoist vi.mock/vi.hoisted + for (const node of arrayNodes) { + const end = getNodeTail(code, node); + // don't hoist into itself if it's already at the top + if (hoistIndex === end || hoistIndex === node.start) { + hoistIndex = end; + } else { + s.move(node.start, end, hoistIndex); + } + } + // hoist actual dynamic imports last so they are inserted after all hoisted mocks + for (const { node: importNode, id: importId } of imports) { + const source = importNode.source.value; + const sourceString = JSON.stringify(source); + let importLine = `const ${importId} = await `; + if (options.globalThisAccessor) { + importLine += `globalThis[${options.globalThisAccessor}].wrapDynamicImport(() => import(${sourceString}));\n`; + } else { + importLine += `import(${sourceString});\n`; + } + s.update(importNode.start, importNode.end, importLine); + if (importNode.start === hoistIndex) { + // no need to hoist, but update hoistIndex to keep the order + hoistIndex = importNode.end; + } else { + // There will be an error if the module is called before it is imported, + // so the module import statement is hoisted to the top + s.move(importNode.start, importNode.end, hoistIndex); + } + } + if (!hoistedModuleImported && arrayNodes.length > 0) { + const utilityImports = [...usedUtilityExports]; + // "vi" or "vitest" is imported from a module other than "vitest" + if (utilityImports.some((name) => idToImportMap.has(name))) { + s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports)); + } else if (utilityImports.length) { + s.appendLeft(hashbangEnd, `import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`); + } + } + return s; +} + +export { hoistMocks as h }; diff --git a/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js b/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js new file mode 100644 index 000000000..4b472ccf2 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js @@ -0,0 +1,15 @@ +import { r as rpc } from './chunk-mocker.js'; + +class ModuleMockerServerInterceptor { + async register(module) { + await rpc("vitest:interceptor:register", module.toJSON()); + } + async delete(id) { + await rpc("vitest:interceptor:delete", id); + } + async invalidate() { + await rpc("vitest:interceptor:invalidate"); + } +} + +export { ModuleMockerServerInterceptor as M }; diff --git a/node_modules/@vitest/mocker/dist/chunk-mocker.js b/node_modules/@vitest/mocker/dist/chunk-mocker.js new file mode 100644 index 000000000..a1a06029c --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-mocker.js @@ -0,0 +1,532 @@ +import { c as createSimpleStackTrace } from './chunk-helpers.js'; +import { mockObject } from './index.js'; +import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js'; +import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js'; + +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 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 = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; + +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; +const NOW_LENGTH = Date.now().toString().length; +const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`); +function extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (!urlLike.includes(":")) { + return [urlLike]; + } + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) { + return [urlLike]; + } + let url = parts[1]; + if (url.startsWith("async ")) { + url = url.slice(6); + } + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + urlObj.searchParams.delete("import"); + urlObj.searchParams.delete("browserv"); + url = urlObj.pathname + urlObj.hash + urlObj.search; + } + if (url.startsWith("/@fs/")) { + const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); + url = url.slice(isWindows ? 5 : 4); + } + if (url.includes("vitest=")) { + url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, ""); + } + return [ + url, + parts[2] || undefined, + parts[3] || undefined + ]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { + return null; + } + if (line.includes(" > eval")) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + } + // Early return for lines that don't look like Firefox/Safari stack traces + // Firefox/Safari stack traces must contain '@' and should have location info after it + if (!line.includes("@")) { + return null; + } + // Find the correct @ that separates function name from location + // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' + // we need to find the first @ that precedes a valid location (containing :) + let atIndex = -1; + let locationPart = ""; + let functionName; + // Try each @ from left to right to find the one that gives us a valid location + for (let i = 0; i < line.length; i++) { + if (line[i] === "@") { + const candidateLocation = line.slice(i + 1); + // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") + if (candidateLocation.includes(":") && candidateLocation.length >= 3) { + atIndex = i; + locationPart = candidateLocation; + functionName = i > 0 ? line.slice(0, i) : undefined; + break; + } + } + } + // Validate we found a valid location with minimum length (filename:line format) + if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { + return null; + } + const [url, lineNumber, columnNumber] = extractLocation(locationPart); + if (!url || !lineNumber || !columnNumber) { + return null; + } + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleStack(raw) { + const line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return parseSingleFFOrSafariStack(line); + } + return parseSingleV8Stack(line); +} +// Based on https://github.com/stacktracejs/error-stack-parser +// Credit to stacktracejs +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return null; + } + 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+/, ""); + // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + const location = sanitizedLine.match(/ (\(.+\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine + // because this line doesn't have function name + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? undefined : url; + if (!file || !lineNumber || !columnNumber) { + return null; + } + if (method.startsWith("async ")) { + method = method.slice(6); + } + if (file.startsWith("file://")) { + file = file.slice(7); + } + // normalize Windows path (\ -> /) + file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); + if (method) { + method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); + } + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} + +function createCompilerHints(options) { + const globalThisAccessor = options?.globalThisKey || "__vitest_mocker__"; + function _mocker() { + // @ts-expect-error injected by the plugin + return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) { + throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`); + } }); + } + return { + hoisted(factory) { + if (typeof factory !== "function") { + throw new TypeError(`vi.hoisted() expects a function, but received a ${typeof factory}`); + } + return factory(); + }, + mock(path, factory) { + if (typeof path !== "string") { + throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`); + } + const importer = getImporter("mock"); + _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); + }, + unmock(path) { + if (typeof path !== "string") { + throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`); + } + _mocker().queueUnmock(path, getImporter("unmock")); + }, + doMock(path, factory) { + if (typeof path !== "string") { + throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`); + } + const importer = getImporter("doMock"); + _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); + }, + doUnmock(path) { + if (typeof path !== "string") { + throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`); + } + _mocker().queueUnmock(path, getImporter("doUnmock")); + }, + async importActual(path) { + return _mocker().importActual(path, getImporter("importActual")); + }, + async importMock(path) { + return _mocker().importMock(path, getImporter("importMock")); + } + }; +} +function getImporter(name) { + const stackTrace = /* @__PURE__ */ createSimpleStackTrace({ stackTraceLimit: 5 }); + const stackArray = stackTrace.split("\n"); + // if there is no message in a stack trace, use the item - 1 + const importerStackIndex = stackArray.findIndex((stack) => { + return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`); + }); + const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]); + return stack?.file || ""; +} + +const hot = import.meta.hot || { + on: warn, + off: warn, + send: warn +}; +function warn() { + console.warn("Vitest mocker cannot work if Vite didn't establish WS connection."); +} +function rpc(event, data) { + hot.send(event, data); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error(`Failed to resolve ${event} in time`)); + }, 5e3); + hot.on(`${event}:result`, function r(data) { + resolve(data); + clearTimeout(timeout); + hot.off(`${event}:result`, r); + }); + }); +} + +const { now } = Date; +class ModuleMocker { + registry = new MockerRegistry(); + queue = new Set(); + mockedIds = new Set(); + constructor(interceptor, rpc, createMockInstance, config) { + this.interceptor = interceptor; + this.rpc = rpc; + this.createMockInstance = createMockInstance; + this.config = config; + } + async prepare() { + if (!this.queue.size) { + return; + } + await Promise.all([...this.queue.values()]); + } + async resolveFactoryModule(id) { + const mock = this.registry.get(id); + if (!mock || mock.type !== "manual") { + throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + const result = await mock.resolve(); + return result; + } + getFactoryModule(id) { + const mock = this.registry.get(id); + if (!mock || mock.type !== "manual") { + throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + if (!mock.cache) { + throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`); + } + return mock.cache; + } + async invalidate() { + const ids = Array.from(this.mockedIds); + if (!ids.length) { + return; + } + await this.rpc.invalidate(ids); + await this.interceptor.invalidate(); + this.registry.clear(); + } + async importActual(id, importer) { + const resolved = await this.rpc.resolveId(id, importer); + if (resolved == null) { + throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`); + } + const ext = extname(resolved.id); + const url = new URL(resolved.url, this.getBaseUrl()); + const query = `_vitest_original&ext${ext}`; + const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`; + return this.wrapDynamicImport(() => import( + /* @vite-ignore */ + actualUrl +)).then((mod) => { + if (!resolved.optimized || typeof mod.default === "undefined") { + return mod; + } + // vite injects this helper for optimized modules, so we try to follow the same behavior + const m = mod.default; + return m?.__esModule ? m : { + ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, + default: m + }; + }); + } + getBaseUrl() { + return location.href; + } + async importMock(rawId, importer) { + await this.prepare(); + const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" }); + const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); + let mock = this.registry.get(mockUrl); + if (!mock) { + if (redirectUrl) { + const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString(); + mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect); + } else { + mock = new AutomockedModule(rawId, resolvedId, mockUrl); + } + } + if (mock.type === "manual") { + return await mock.resolve(); + } + if (mock.type === "automock" || mock.type === "autospy") { + const url = new URL(`/@id/${resolvedId}`, this.getBaseUrl()); + const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`; + const moduleObject = await import( + /* @vite-ignore */ + `${url.pathname}${query}&mock=${mock.type}${url.hash}` +); + return this.mockObject(moduleObject, mock.type); + } + return import( + /* @vite-ignore */ + mock.redirect +); + } + mockObject(object, mockExportsOrModuleType, moduleType) { + let mockExports; + if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") { + moduleType = mockExportsOrModuleType; + mockExports = undefined; + } else { + mockExports = mockExportsOrModuleType; + } + moduleType ??= "automock"; + const result = mockObject({ + globalConstructors: { + Object, + Function, + Array, + Map, + RegExp + }, + createMockInstance: this.createMockInstance, + type: moduleType + }, object, mockExports); + return result; + } + getMockContext() { + return { callstack: null }; + } + queueMock(rawId, importer, factoryOrOptions) { + const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : factoryOrOptions?.spy ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => { + const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); + this.mockedIds.add(resolvedId); + const factory = typeof factoryOrOptions === "function" ? async () => { + const data = await factoryOrOptions(); + // vite wraps all external modules that have "needsInterop" in a function that + // merges all exports from default into the module object + return needsInterop ? { default: data } : data; + } : undefined; + const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString() : null; + let module; + if (mockType === "manual") { + module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory); + } else if (mockType === "autospy") { + module = this.registry.register("autospy", rawId, resolvedId, mockUrl); + } else if (mockType === "redirect") { + module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect); + } else { + module = this.registry.register("automock", rawId, resolvedId, mockUrl); + } + await this.interceptor.register(module); + }).finally(() => { + this.queue.delete(promise); + }); + this.queue.add(promise); + } + queueUnmock(id, importer) { + const promise = this.rpc.resolveId(id, importer).then(async (resolved) => { + if (!resolved) { + return; + } + const mockUrl = this.resolveMockPath(cleanVersion(resolved.url)); + this.mockedIds.add(resolved.id); + this.registry.delete(mockUrl); + await this.interceptor.delete(mockUrl); + }).finally(() => { + this.queue.delete(promise); + }); + this.queue.add(promise); + } + // We need to await mock registration before importing the actual module + // In case there is a mocked module in the import chain + wrapDynamicImport(moduleFactory) { + if (typeof moduleFactory === "function") { + const promise = new Promise((resolve, reject) => { + this.prepare().finally(() => { + moduleFactory().then(resolve, reject); + }); + }); + return promise; + } + return moduleFactory; + } + getMockedModuleById(id) { + return this.registry.getById(id); + } + reset() { + this.registry.clear(); + this.mockedIds.clear(); + this.queue.clear(); + } + resolveMockPath(path) { + const config = this.config; + const fsRoot = join("/@fs/", config.root); + // URL can be /file/path.js, but path is resolved to /file/path + if (path.startsWith(config.root)) { + return path.slice(config.root.length); + } + if (path.startsWith(fsRoot)) { + return path.slice(fsRoot.length); + } + return path; + } +} +const versionRegexp = /(\?|&)v=\w{8}/; +function cleanVersion(url) { + return url.replace(versionRegexp, ""); +} + +export { ModuleMocker as M, createCompilerHints as c, hot as h, rpc as r }; diff --git a/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js b/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js new file mode 100644 index 000000000..11a98f06c --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js @@ -0,0 +1,174 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const _EXTNAME_RE = /.(\.[^./]+|\.)$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...segments) { + let path = ""; + for (const seg of segments) { + if (!seg) { + continue; + } + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) { + path += seg.slice(1); + } else { + path += pathTrailing || segLeading ? seg : `/${seg}`; + } + } else { + path += seg; + } + } + return normalize(path); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 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 = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const extname = function(p) { + if (p === "..") return ""; + const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); + return match && match[1] || ""; +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; +const basename = function(p, extension) { + const segments = normalizeWindowsPath(p).split("/"); + let lastSegment = ""; + for (let i = segments.length - 1; i >= 0; i--) { + const val = segments[i]; + if (val) { + lastSegment = val; + break; + } + } + return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; +}; + +export { basename as b, dirname as d, extname as e, isAbsolute as i, join as j, resolve as r }; diff --git a/node_modules/@vitest/mocker/dist/chunk-registry.js b/node_modules/@vitest/mocker/dist/chunk-registry.js new file mode 100644 index 000000000..40cbe466e --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-registry.js @@ -0,0 +1,199 @@ +class MockerRegistry { + registryByUrl = new Map(); + registryById = new Map(); + clear() { + this.registryByUrl.clear(); + this.registryById.clear(); + } + keys() { + return this.registryByUrl.keys(); + } + add(mock) { + this.registryByUrl.set(mock.url, mock); + this.registryById.set(mock.id, mock); + } + register(typeOrEvent, raw, id, url, factoryOrRedirect) { + const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent; + if (typeof typeOrEvent === "object") { + const event = typeOrEvent; + if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) { + throw new TypeError(`[vitest] Cannot register a mock that is already defined. ` + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". ` + `Use "registry.add()" to update a mock instead.`); + } + if (event.type === "automock") { + const module = AutomockedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "autospy") { + const module = AutospiedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "redirect") { + const module = RedirectedModule.fromJSON(event); + this.add(module); + return module; + } else if (event.type === "manual") { + throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`); + } else { + throw new Error(`Unknown mock type: ${event.type}`); + } + } + if (typeof raw !== "string") { + throw new TypeError("[vitest] Mocks require a raw string."); + } + if (typeof url !== "string") { + throw new TypeError("[vitest] Mocks require a url string."); + } + if (typeof id !== "string") { + throw new TypeError("[vitest] Mocks require an id string."); + } + if (type === "manual") { + if (typeof factoryOrRedirect !== "function") { + throw new TypeError("[vitest] Manual mocks require a factory function."); + } + const mock = new ManualMockedModule(raw, id, url, factoryOrRedirect); + this.add(mock); + return mock; + } else if (type === "automock" || type === "autospy") { + const mock = type === "automock" ? new AutomockedModule(raw, id, url) : new AutospiedModule(raw, id, url); + this.add(mock); + return mock; + } else if (type === "redirect") { + if (typeof factoryOrRedirect !== "string") { + throw new TypeError("[vitest] Redirect mocks require a redirect string."); + } + const mock = new RedirectedModule(raw, id, url, factoryOrRedirect); + this.add(mock); + return mock; + } else { + throw new Error(`[vitest] Unknown mock type: ${type}`); + } + } + delete(id) { + this.registryByUrl.delete(id); + } + deleteById(id) { + this.registryById.delete(id); + } + get(id) { + return this.registryByUrl.get(id); + } + getById(id) { + return this.registryById.get(id); + } + has(id) { + return this.registryByUrl.has(id); + } +} +class AutomockedModule { + type = "automock"; + constructor(raw, id, url) { + this.raw = raw; + this.id = id; + this.url = url; + } + static fromJSON(data) { + return new AutospiedModule(data.raw, data.id, data.url); + } + toJSON() { + return { + type: this.type, + url: this.url, + raw: this.raw, + id: this.id + }; + } +} +class AutospiedModule { + type = "autospy"; + constructor(raw, id, url) { + this.raw = raw; + this.id = id; + this.url = url; + } + static fromJSON(data) { + return new AutospiedModule(data.raw, data.id, data.url); + } + toJSON() { + return { + type: this.type, + url: this.url, + id: this.id, + raw: this.raw + }; + } +} +class RedirectedModule { + type = "redirect"; + constructor(raw, id, url, redirect) { + this.raw = raw; + this.id = id; + this.url = url; + this.redirect = redirect; + } + static fromJSON(data) { + return new RedirectedModule(data.raw, data.id, data.url, data.redirect); + } + toJSON() { + return { + type: this.type, + url: this.url, + raw: this.raw, + id: this.id, + redirect: this.redirect + }; + } +} +class ManualMockedModule { + cache; + type = "manual"; + constructor(raw, id, url, factory) { + this.raw = raw; + this.id = id; + this.url = url; + this.factory = factory; + } + resolve() { + if (this.cache) { + return this.cache; + } + let exports$1; + try { + exports$1 = this.factory(); + } catch (err) { + throw createHelpfulError(err); + } + if (typeof exports$1 === "object" && typeof exports$1?.then === "function") { + return exports$1.then((result) => { + assertValidExports(this.raw, result); + return this.cache = result; + }, (error) => { + throw createHelpfulError(error); + }); + } + assertValidExports(this.raw, exports$1); + return this.cache = exports$1; + } + static fromJSON(data, factory) { + return new ManualMockedModule(data.raw, data.id, data.url, factory); + } + toJSON() { + return { + type: this.type, + url: this.url, + id: this.id, + raw: this.raw + }; + } +} +function createHelpfulError(cause) { + const error = 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.html#vi-mock"); + error.cause = cause; + return error; +} +function assertValidExports(raw, exports$1) { + if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) { + throw new TypeError(`[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`); + } +} + +export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b }; diff --git a/node_modules/@vitest/mocker/dist/chunk-utils.js b/node_modules/@vitest/mocker/dist/chunk-utils.js new file mode 100644 index 000000000..411276951 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/chunk-utils.js @@ -0,0 +1,27 @@ +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ""); +} +function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") { + const source = ` +const __factoryModule__ = await globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}"); +`; + const keys = exports$1.map((name, index) => { + return `let __${index} = __factoryModule__["${name}"] +export { __${index} as "${name}" }`; + }).join("\n"); + let code = `${source}\n${keys}`; + // this prevents recursion + code += ` +if (__factoryModule__.__factoryPromise != null) { + __factoryModule__.__factoryPromise.then((resolvedModule) => { + ${exports$1.map((name, index) => { + return `__${index} = resolvedModule["${name}"];`; + }).join("\n")} + }) +} + `; + return code; +} + +export { cleanUrl as a, createManualModuleSource as c }; diff --git a/node_modules/@vitest/mocker/dist/hoistMocks.d-w2ILr1dG.d.ts b/node_modules/@vitest/mocker/dist/hoistMocks.d-w2ILr1dG.d.ts new file mode 100644 index 000000000..2b64274d2 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/hoistMocks.d-w2ILr1dG.d.ts @@ -0,0 +1,739 @@ +import MagicString from 'magic-string'; + +declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string; + +// This definition file follows a somewhat unusual format. ESTree allows +// runtime type checks based on the `type` parameter. In order to explain this +// to typescript we want to use discriminated union types: +// https://github.com/Microsoft/TypeScript/pull/9163 +// +// For ESTree this is a bit tricky because the high level interfaces like +// Node or Function are pulling double duty. We want to pass common fields down +// to the interfaces that extend them (like Identifier or +// ArrowFunctionExpression), but you can't extend a type union or enforce +// common fields on them. So we've split the high level interfaces into two +// types, a base type which passes down inherited fields, and a type union of +// all types which extend the base type. Only the type union is exported, and +// the union is how other types refer to the collection of inheriting types. +// +// This makes the definitions file here somewhat more difficult to maintain, +// but it has the notable advantage of making ESTree much easier to use as +// an end user. + +interface BaseNodeWithoutComments { + // Every leaf interface that extends BaseNode must specify a type property. + // The type property should be a string literal. For example, Identifier + // has: `type: "Identifier"` + type: string; + loc?: SourceLocation | null | undefined; + range?: [number, number] | undefined; +} + +interface BaseNode extends BaseNodeWithoutComments { + leadingComments?: Comment[] | undefined; + trailingComments?: Comment[] | undefined; +} + +interface NodeMap { + AssignmentProperty: AssignmentProperty; + CatchClause: CatchClause; + Class: Class; + ClassBody: ClassBody; + Expression: Expression; + Function: Function; + Identifier: Identifier; + Literal: Literal; + MethodDefinition: MethodDefinition; + ModuleDeclaration: ModuleDeclaration; + ModuleSpecifier: ModuleSpecifier; + Pattern: Pattern; + PrivateIdentifier: PrivateIdentifier; + Program: Program; + Property: Property; + PropertyDefinition: PropertyDefinition; + SpreadElement: SpreadElement; + Statement: Statement; + Super: Super; + SwitchCase: SwitchCase; + TemplateElement: TemplateElement; + VariableDeclarator: VariableDeclarator; +} + +type Node$1 = NodeMap[keyof NodeMap]; + +interface Comment extends BaseNodeWithoutComments { + type: "Line" | "Block"; + value: string; +} + +interface SourceLocation { + source?: string | null | undefined; + start: Position; + end: Position; +} + +interface Position { + /** >= 1 */ + line: number; + /** >= 0 */ + column: number; +} + +interface Program extends BaseNode { + type: "Program"; + sourceType: "script" | "module"; + body: Array; + comments?: Comment[] | undefined; +} + +interface Directive extends BaseNode { + type: "ExpressionStatement"; + expression: Literal; + directive: string; +} + +interface BaseFunction extends BaseNode { + params: Pattern[]; + generator?: boolean | undefined; + async?: boolean | undefined; + // The body is either BlockStatement or Expression because arrow functions + // can have a body that's either. FunctionDeclarations and + // FunctionExpressions have only BlockStatement bodies. + body: BlockStatement | Expression; +} + +type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; + +type Statement = + | ExpressionStatement + | BlockStatement + | StaticBlock + | EmptyStatement + | DebuggerStatement + | WithStatement + | ReturnStatement + | LabeledStatement + | BreakStatement + | ContinueStatement + | IfStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | WhileStatement + | DoWhileStatement + | ForStatement + | ForInStatement + | ForOfStatement + | Declaration; + +interface BaseStatement extends BaseNode {} + +interface EmptyStatement extends BaseStatement { + type: "EmptyStatement"; +} + +interface BlockStatement extends BaseStatement { + type: "BlockStatement"; + body: Statement[]; + innerComments?: Comment[] | undefined; +} + +interface StaticBlock extends Omit { + type: "StaticBlock"; +} + +interface ExpressionStatement extends BaseStatement { + type: "ExpressionStatement"; + expression: Expression; +} + +interface IfStatement extends BaseStatement { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate?: Statement | null | undefined; +} + +interface LabeledStatement extends BaseStatement { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +interface BreakStatement extends BaseStatement { + type: "BreakStatement"; + label?: Identifier | null | undefined; +} + +interface ContinueStatement extends BaseStatement { + type: "ContinueStatement"; + label?: Identifier | null | undefined; +} + +interface WithStatement extends BaseStatement { + type: "WithStatement"; + object: Expression; + body: Statement; +} + +interface SwitchStatement extends BaseStatement { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +interface ReturnStatement extends BaseStatement { + type: "ReturnStatement"; + argument?: Expression | null | undefined; +} + +interface ThrowStatement extends BaseStatement { + type: "ThrowStatement"; + argument: Expression; +} + +interface TryStatement extends BaseStatement { + type: "TryStatement"; + block: BlockStatement; + handler?: CatchClause | null | undefined; + finalizer?: BlockStatement | null | undefined; +} + +interface WhileStatement extends BaseStatement { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +interface DoWhileStatement extends BaseStatement { + type: "DoWhileStatement"; + body: Statement; + test: Expression; +} + +interface ForStatement extends BaseStatement { + type: "ForStatement"; + init?: VariableDeclaration | Expression | null | undefined; + test?: Expression | null | undefined; + update?: Expression | null | undefined; + body: Statement; +} + +interface BaseForXStatement extends BaseStatement { + left: VariableDeclaration | Pattern; + right: Expression; + body: Statement; +} + +interface ForInStatement extends BaseForXStatement { + type: "ForInStatement"; +} + +interface DebuggerStatement extends BaseStatement { + type: "DebuggerStatement"; +} + +type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; + +interface BaseDeclaration extends BaseStatement {} + +interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { + type: "FunctionDeclaration"; + /** It is null when a function declaration is a part of the `export default function` statement */ + id: Identifier | null; + body: BlockStatement; +} + +interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { + id: Identifier; +} + +interface VariableDeclaration extends BaseDeclaration { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const" | "using" | "await using"; +} + +interface VariableDeclarator extends BaseNode { + type: "VariableDeclarator"; + id: Pattern; + init?: Expression | null | undefined; +} + +interface ExpressionMap { + ArrayExpression: ArrayExpression; + ArrowFunctionExpression: ArrowFunctionExpression; + AssignmentExpression: AssignmentExpression; + AwaitExpression: AwaitExpression; + BinaryExpression: BinaryExpression; + CallExpression: CallExpression; + ChainExpression: ChainExpression; + ClassExpression: ClassExpression; + ConditionalExpression: ConditionalExpression; + FunctionExpression: FunctionExpression; + Identifier: Identifier; + ImportExpression: ImportExpression; + Literal: Literal; + LogicalExpression: LogicalExpression; + MemberExpression: MemberExpression; + MetaProperty: MetaProperty; + NewExpression: NewExpression; + ObjectExpression: ObjectExpression; + SequenceExpression: SequenceExpression; + TaggedTemplateExpression: TaggedTemplateExpression; + TemplateLiteral: TemplateLiteral; + ThisExpression: ThisExpression; + UnaryExpression: UnaryExpression; + UpdateExpression: UpdateExpression; + YieldExpression: YieldExpression; +} + +type Expression = ExpressionMap[keyof ExpressionMap]; + +interface BaseExpression extends BaseNode {} + +type ChainElement = SimpleCallExpression | MemberExpression; + +interface ChainExpression extends BaseExpression { + type: "ChainExpression"; + expression: ChainElement; +} + +interface ThisExpression extends BaseExpression { + type: "ThisExpression"; +} + +interface ArrayExpression extends BaseExpression { + type: "ArrayExpression"; + elements: Array; +} + +interface ObjectExpression extends BaseExpression { + type: "ObjectExpression"; + properties: Array; +} + +interface PrivateIdentifier extends BaseNode { + type: "PrivateIdentifier"; + name: string; +} + +interface Property extends BaseNode { + type: "Property"; + key: Expression | PrivateIdentifier; + value: Expression | Pattern; // Could be an AssignmentProperty + kind: "init" | "get" | "set"; + method: boolean; + shorthand: boolean; + computed: boolean; +} + +interface PropertyDefinition extends BaseNode { + type: "PropertyDefinition"; + key: Expression | PrivateIdentifier; + value?: Expression | null | undefined; + computed: boolean; + static: boolean; +} + +interface FunctionExpression extends BaseFunction, BaseExpression { + id?: Identifier | null | undefined; + type: "FunctionExpression"; + body: BlockStatement; +} + +interface SequenceExpression extends BaseExpression { + type: "SequenceExpression"; + expressions: Expression[]; +} + +interface UnaryExpression extends BaseExpression { + type: "UnaryExpression"; + operator: UnaryOperator; + prefix: true; + argument: Expression; +} + +interface BinaryExpression extends BaseExpression { + type: "BinaryExpression"; + operator: BinaryOperator; + left: Expression | PrivateIdentifier; + right: Expression; +} + +interface AssignmentExpression extends BaseExpression { + type: "AssignmentExpression"; + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; +} + +interface UpdateExpression extends BaseExpression { + type: "UpdateExpression"; + operator: UpdateOperator; + argument: Expression; + prefix: boolean; +} + +interface LogicalExpression extends BaseExpression { + type: "LogicalExpression"; + operator: LogicalOperator; + left: Expression; + right: Expression; +} + +interface ConditionalExpression extends BaseExpression { + type: "ConditionalExpression"; + test: Expression; + alternate: Expression; + consequent: Expression; +} + +interface BaseCallExpression extends BaseExpression { + callee: Expression | Super; + arguments: Array; +} +type CallExpression = SimpleCallExpression | NewExpression; + +interface SimpleCallExpression extends BaseCallExpression { + type: "CallExpression"; + optional: boolean; +} + +interface NewExpression extends BaseCallExpression { + type: "NewExpression"; +} + +interface MemberExpression extends BaseExpression, BasePattern { + type: "MemberExpression"; + object: Expression | Super; + property: Expression | PrivateIdentifier; + computed: boolean; + optional: boolean; +} + +type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; + +interface BasePattern extends BaseNode {} + +interface SwitchCase extends BaseNode { + type: "SwitchCase"; + test?: Expression | null | undefined; + consequent: Statement[]; +} + +interface CatchClause extends BaseNode { + type: "CatchClause"; + param: Pattern | null; + body: BlockStatement; +} + +interface Identifier extends BaseNode, BaseExpression, BasePattern { + type: "Identifier"; + name: string; +} + +type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; + +interface SimpleLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value: string | boolean | number | null; + raw?: string | undefined; +} + +interface RegExpLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: RegExp | null | undefined; + regex: { + pattern: string; + flags: string; + }; + raw?: string | undefined; +} + +interface BigIntLiteral extends BaseNode, BaseExpression { + type: "Literal"; + value?: bigint | null | undefined; + bigint: string; + raw?: string | undefined; +} + +type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + +type BinaryOperator = + | "==" + | "!=" + | "===" + | "!==" + | "<" + | "<=" + | ">" + | ">=" + | "<<" + | ">>" + | ">>>" + | "+" + | "-" + | "*" + | "/" + | "%" + | "**" + | "|" + | "^" + | "&" + | "in" + | "instanceof"; + +type LogicalOperator = "||" | "&&" | "??"; + +type AssignmentOperator = + | "=" + | "+=" + | "-=" + | "*=" + | "/=" + | "%=" + | "**=" + | "<<=" + | ">>=" + | ">>>=" + | "|=" + | "^=" + | "&=" + | "||=" + | "&&=" + | "??="; + +type UpdateOperator = "++" | "--"; + +interface ForOfStatement extends BaseForXStatement { + type: "ForOfStatement"; + await: boolean; +} + +interface Super extends BaseNode { + type: "Super"; +} + +interface SpreadElement extends BaseNode { + type: "SpreadElement"; + argument: Expression; +} + +interface ArrowFunctionExpression extends BaseExpression, BaseFunction { + type: "ArrowFunctionExpression"; + expression: boolean; + body: BlockStatement | Expression; +} + +interface YieldExpression extends BaseExpression { + type: "YieldExpression"; + argument?: Expression | null | undefined; + delegate: boolean; +} + +interface TemplateLiteral extends BaseExpression { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +interface TaggedTemplateExpression extends BaseExpression { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +interface TemplateElement extends BaseNode { + type: "TemplateElement"; + tail: boolean; + value: { + /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ + cooked?: string | null | undefined; + raw: string; + }; +} + +interface AssignmentProperty extends Property { + value: Pattern; + kind: "init"; + method: boolean; // false +} + +interface ObjectPattern extends BasePattern { + type: "ObjectPattern"; + properties: Array; +} + +interface ArrayPattern extends BasePattern { + type: "ArrayPattern"; + elements: Array; +} + +interface RestElement extends BasePattern { + type: "RestElement"; + argument: Pattern; +} + +interface AssignmentPattern extends BasePattern { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +type Class = ClassDeclaration | ClassExpression; +interface BaseClass extends BaseNode { + superClass?: Expression | null | undefined; + body: ClassBody; +} + +interface ClassBody extends BaseNode { + type: "ClassBody"; + body: Array; +} + +interface MethodDefinition extends BaseNode { + type: "MethodDefinition"; + key: Expression | PrivateIdentifier; + value: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; +} + +interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { + type: "ClassDeclaration"; + /** It is null when a class declaration is a part of the `export default class` statement */ + id: Identifier | null; +} + +interface ClassDeclaration extends MaybeNamedClassDeclaration { + id: Identifier; +} + +interface ClassExpression extends BaseClass, BaseExpression { + type: "ClassExpression"; + id?: Identifier | null | undefined; +} + +interface MetaProperty extends BaseExpression { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +type ModuleDeclaration = + | ImportDeclaration + | ExportNamedDeclaration + | ExportDefaultDeclaration + | ExportAllDeclaration; +interface BaseModuleDeclaration extends BaseNode {} + +type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; +interface BaseModuleSpecifier extends BaseNode { + local: Identifier; +} + +interface ImportDeclaration extends BaseModuleDeclaration { + type: "ImportDeclaration"; + specifiers: Array; + attributes: ImportAttribute[]; + source: Literal; +} + +interface ImportSpecifier extends BaseModuleSpecifier { + type: "ImportSpecifier"; + imported: Identifier | Literal; +} + +interface ImportAttribute extends BaseNode { + type: "ImportAttribute"; + key: Identifier | Literal; + value: Literal; +} + +interface ImportExpression extends BaseExpression { + type: "ImportExpression"; + source: Expression; + options?: Expression | null | undefined; +} + +interface ImportDefaultSpecifier extends BaseModuleSpecifier { + type: "ImportDefaultSpecifier"; +} + +interface ImportNamespaceSpecifier extends BaseModuleSpecifier { + type: "ImportNamespaceSpecifier"; +} + +interface ExportNamedDeclaration extends BaseModuleDeclaration { + type: "ExportNamedDeclaration"; + declaration?: Declaration | null | undefined; + specifiers: ExportSpecifier[]; + attributes: ImportAttribute[]; + source?: Literal | null | undefined; +} + +interface ExportSpecifier extends Omit { + type: "ExportSpecifier"; + local: Identifier | Literal; + exported: Identifier | Literal; +} + +interface ExportDefaultDeclaration extends BaseModuleDeclaration { + type: "ExportDefaultDeclaration"; + declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; +} + +interface ExportAllDeclaration extends BaseModuleDeclaration { + type: "ExportAllDeclaration"; + exported: Identifier | Literal | null; + attributes: ImportAttribute[]; + source: Literal; +} + +interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} + +type Positioned = T & { + start: number; + end: number; +}; +type Node = Positioned; + +interface HoistMocksOptions { + /** + * List of modules that should always be imported before compiler hints. + * @default 'vitest' + */ + hoistedModule?: string; + /** + * @default ["vi", "vitest"] + */ + utilsObjectNames?: string[]; + /** + * @default ["mock", "unmock"] + */ + hoistableMockMethodNames?: string[]; + /** + * @default ["mock", "unmock", "doMock", "doUnmock"] + */ + dynamicImportMockMethodNames?: string[]; + /** + * @default ["hoisted"] + */ + hoistedMethodNames?: string[]; + globalThisAccessor?: string; + regexpHoistable?: RegExp; + codeFrameGenerator?: CodeFrameGenerator; + magicString?: () => MagicString; +} +declare function hoistMocks(code: string, id: string, parse: (code: string) => any, options?: HoistMocksOptions): MagicString | undefined; +interface CodeFrameGenerator { + (node: Positioned, id: string, code: string): string; +} + +export { createManualModuleSource as c, hoistMocks as h }; +export type { HoistMocksOptions as H }; diff --git a/node_modules/@vitest/mocker/dist/index.d-B41z0AuW.d.ts b/node_modules/@vitest/mocker/dist/index.d-B41z0AuW.d.ts new file mode 100644 index 000000000..d78ee6605 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/index.d-B41z0AuW.d.ts @@ -0,0 +1,25 @@ +import './types.d-BjI5eAwu.js'; + +type Key = string | symbol; +type CreateMockInstanceProcedure = (options?: { + prototypeMembers?: (string | symbol)[]; + name?: string | symbol; + originalImplementation?: (...args: any[]) => any; + keepMembersImplementation?: boolean; +}) => any; +interface MockObjectOptions { + type: "automock" | "autospy"; + globalConstructors: GlobalConstructors; + createMockInstance: CreateMockInstanceProcedure; +} +declare function mockObject(options: MockObjectOptions, object: Record, mockExports?: Record): Record; +interface GlobalConstructors { + Object: ObjectConstructor; + Function: FunctionConstructor; + RegExp: RegExpConstructor; + Array: ArrayConstructor; + Map: MapConstructor; +} + +export { mockObject as m }; +export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M }; diff --git a/node_modules/@vitest/mocker/dist/index.d.ts b/node_modules/@vitest/mocker/dist/index.d.ts new file mode 100644 index 000000000..53943d434 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/index.d.ts @@ -0,0 +1,2 @@ +export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-B41z0AuW.js'; +export { A as AutomockedModule, g as AutomockedModuleSerialized, h as AutospiedModule, i as AutospiedModuleSerialized, j as ManualMockedModule, k as ManualMockedModuleSerialized, a as MockedModule, l as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, e as ModuleMockContext, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, n as RedirectedModuleSerialized, f as ServerIdResolution, S as ServerMockResolution, T as TestModuleMocker } from './types.d-BjI5eAwu.js'; diff --git a/node_modules/@vitest/mocker/dist/index.js b/node_modules/@vitest/mocker/dist/index.js new file mode 100644 index 000000000..fc66b3810 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/index.js @@ -0,0 +1,200 @@ +export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js'; + +function mockObject(options, object, mockExports = {}) { + const finalizers = new Array(); + const refs = new RefTracker(); + const define = (container, key, value) => { + try { + container[key] = value; + return true; + } catch { + return false; + } + }; + const createMock = (currentValue) => { + if (!options.createMockInstance) { + throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction."); + } + const createMockInstance = options.createMockInstance; + const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : []; + return createMockInstance({ + name: currentValue.name, + prototypeMembers, + originalImplementation: options.type === "autospy" ? currentValue : undefined, + keepMembersImplementation: options.type === "autospy" + }); + }; + const mockPropertiesOf = (container, newContainer) => { + const containerType = getType(container); + const isModule = containerType === "Module" || !!container.__esModule; + for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) { + // Modules define their exports as getters. We want to process those. + if (!isModule && descriptor.get) { + try { + if (options.type === "autospy") { + Object.defineProperty(newContainer, property, descriptor); + } else { + Object.defineProperty(newContainer, property, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get: () => {}, + set: descriptor.set ? () => {} : undefined + }); + } + } catch {} + continue; + } + // Skip special read-only props, we don't want to mess with those. + if (isReadonlyProp(container[property], property)) { + continue; + } + const value = container[property]; + // Special handling of references we've seen before to prevent infinite + // recursion in circular objects. + const refId = refs.getId(value); + if (refId !== undefined) { + finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId))); + continue; + } + const type = getType(value); + if (Array.isArray(value)) { + if (options.type === "automock") { + define(newContainer, property, []); + } else { + const array = value.map((value) => { + if (value && typeof value === "object") { + const newObject = {}; + mockPropertiesOf(value, newObject); + return newObject; + } + if (typeof value === "function") { + return createMock(value); + } + return value; + }); + define(newContainer, property, array); + } + continue; + } + const isFunction = type.includes("Function") && typeof value === "function"; + if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") { + define(newContainer, property, value); + continue; + } + if (options.type === "autospy" && type === "Module") { + // Replace with clean object to recursively autospy exported module objects: + // export * as ns from "./ns" + // or + // import * as ns from "./ns" + // export { ns } + const exports$1 = Object.create(null); + Object.defineProperty(exports$1, Symbol.toStringTag, { + value: "Module", + configurable: true, + writable: true + }); + try { + newContainer[property] = exports$1; + } catch { + continue; + } + } else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) { + continue; + } + if (isFunction) { + const mock = createMock(newContainer[property]); + newContainer[property] = mock; + } + refs.track(value, newContainer[property]); + mockPropertiesOf(value, newContainer[property]); + } + }; + const mockedObject = mockExports; + mockPropertiesOf(object, mockedObject); + // Plug together refs + for (const finalizer of finalizers) { + finalizer(); + } + return mockedObject; +} +class RefTracker { + idMap = new Map(); + mockedValueMap = 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 getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function isReadonlyProp(object, prop) { + if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") { + const typeName = getType(object); + return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction"; + } + if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") { + return getType(object) === "RegExp"; + } + return false; +} +function getAllMockableProperties(obj, isModule, constructors) { + const { Map, Object, Function, RegExp, Array } = constructors; + const allProps = new Map(); + let curr = obj; + do { + // we don't need properties from these + if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) { + break; + } + collectOwnProperties(curr, (key) => { + const descriptor = Object.getOwnPropertyDescriptor(curr, key); + if (descriptor) { + allProps.set(key, { + key, + descriptor + }); + } + }); + } while (curr = Object.getPrototypeOf(curr)); + // default is not specified in ownKeys, if module is interoped + if (isModule && !allProps.has("default") && "default" in obj) { + const descriptor = Object.getOwnPropertyDescriptor(obj, "default"); + if (descriptor) { + allProps.set("default", { + key: "default", + descriptor + }); + } + } + return Array.from(allProps.values()); +} +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 collectFunctionProperties(prototype) { + const properties = new Set(); + collectOwnProperties(prototype, (prop) => { + const descriptor = Object.getOwnPropertyDescriptor(prototype, prop); + if (!descriptor || descriptor.get) { + return; + } + const type = getType(descriptor.value); + if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) { + properties.add(prop); + } + }); + return Array.from(properties); +} + +export { mockObject }; diff --git a/node_modules/@vitest/mocker/dist/mocker.d-QEntlm6J.d.ts b/node_modules/@vitest/mocker/dist/mocker.d-QEntlm6J.d.ts new file mode 100644 index 000000000..ef2541343 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/mocker.d-QEntlm6J.d.ts @@ -0,0 +1,86 @@ +import { MaybeMockedDeep } from '@vitest/spy'; +import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, T as TestModuleMocker, M as MockerRegistry, d as MockedModuleType, e as ModuleMockContext } from './types.d-BjI5eAwu.js'; +import { C as CreateMockInstanceProcedure } from './index.d-B41z0AuW.js'; + +interface CompilerHintsOptions { + /** + * This is the key used to access the globalThis object in the worker. + * Unlike `globalThisAccessor` in other APIs, this is not injected into the script. + * ```ts + * // globalThisKey: '__my_variable__' produces: + * globalThis['__my_variable__'] + * // globalThisKey: '"__my_variable__"' produces: + * globalThis['"__my_variable__"'] // notice double quotes + * ``` + * @default '__vitest_mocker__' + */ + globalThisKey?: string; +} +interface ModuleMockerCompilerHints { + hoisted: (factory: () => T) => T; + mock: (path: string | Promise, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; + unmock: (path: string | Promise) => void; + doMock: (path: string | Promise, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; + doUnmock: (path: string | Promise) => void; + importActual: (path: string) => Promise; + importMock: (path: string) => Promise>; +} +declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints; + +interface ModuleMockerInterceptor { + register: (module: MockedModule) => Promise; + delete: (url: string) => Promise; + invalidate: () => Promise; +} + +declare class ModuleMocker implements TestModuleMocker { + private interceptor; + private rpc; + private createMockInstance; + private config; + protected registry: MockerRegistry; + private queue; + private mockedIds; + constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig); + prepare(): Promise; + resolveFactoryModule(id: string): Promise>; + getFactoryModule(id: string): any; + invalidate(): Promise; + importActual(id: string, importer: string): Promise; + protected getBaseUrl(): string; + importMock(rawId: string, importer: string): Promise; + mockObject(object: Record, moduleType?: "automock" | "autospy"): Record; + mockObject(object: Record, mockExports: Record | undefined, moduleType?: "automock" | "autospy"): Record; + getMockContext(): ModuleMockContext; + queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void; + queueUnmock(id: string, importer: string): void; + wrapDynamicImport(moduleFactory: () => Promise): Promise; + getMockedModuleById(id: string): MockedModule | undefined; + reset(): void; + private resolveMockPath; +} +interface ResolveIdResult { + id: string; + url: string; + optimized: boolean; +} +interface ResolveMockResult { + mockType: MockedModuleType; + resolvedId: string; + resolvedUrl: string; + redirectUrl?: string | null; + needsInterop?: boolean; +} +interface ModuleMockerRPC { + invalidate: (ids: string[]) => Promise; + resolveId: (id: string, importer: string) => Promise; + resolveMock: (id: string, importer: string, options: { + mock: "spy" | "factory" | "auto"; + }) => Promise; +} +interface ModuleMockerConfig { + root: string; +} + +export { ModuleMocker as b, createCompilerHints as f }; +export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as c, ModuleMockerRPC as d, ResolveMockResult as e }; diff --git a/node_modules/@vitest/mocker/dist/node.d.ts b/node_modules/@vitest/mocker/dist/node.d.ts new file mode 100644 index 000000000..235dc4c64 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/node.d.ts @@ -0,0 +1,71 @@ +import { H as HoistMocksOptions } from './hoistMocks.d-w2ILr1dG.js'; +export { c as createManualModuleSource } from './hoistMocks.d-w2ILr1dG.js'; +import { AutomockOptions } from './automock.js'; +export { automockModule } from './automock.js'; +import { Plugin, Rollup, ViteDevServer } from 'vite'; +import { SourceMap } from 'magic-string'; +import { M as MockerRegistry, S as ServerMockResolution, f as ServerIdResolution } from './types.d-BjI5eAwu.js'; +export { findMockRedirect } from './redirect.js'; + +declare function automockPlugin(options?: AutomockOptions): Plugin; + +interface DynamicImportPluginOptions { + /** + * @default `"__vitest_mocker__"` + */ + globalThisAccessor?: string; + filter?: (id: string) => boolean; +} +declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin; + +interface HoistMocksPluginOptions extends Omit { + include?: string | RegExp | (string | RegExp)[]; + exclude?: string | RegExp | (string | RegExp)[]; + /** + * overrides include/exclude options + */ + filter?: (id: string) => boolean; +} +declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin; +declare function hoistMockAndResolve(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined; +interface HoistMocksResult { + code: string; + map: SourceMap; +} + +interface InterceptorPluginOptions { + /** + * @default "__vitest_mocker__" + */ + globalThisAccessor?: string; + registry?: MockerRegistry; +} +declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin; + +interface MockerPluginOptions extends AutomockOptions { + hoistMocks?: HoistMocksPluginOptions; +} +declare function mockerPlugin(options?: MockerPluginOptions): Plugin[]; + +interface ServerResolverOptions { + /** + * @default ['/node_modules/'] + */ + moduleDirectories?: string[]; +} +declare class ServerMockResolver { + private server; + private options; + constructor(server: ViteDevServer, options?: ServerResolverOptions); + resolveMock(rawId: string, importer: string, options: { + mock: "spy" | "factory" | "auto"; + }): Promise; + invalidate(ids: string[]): void; + resolveId(id: string, importer?: string): Promise; + private normalizeResolveIdToUrl; + private resolveMockId; + private resolveModule; +} + +export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, dynamicImportPlugin, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; +export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions }; diff --git a/node_modules/@vitest/mocker/dist/node.js b/node_modules/@vitest/mocker/dist/node.js new file mode 100644 index 000000000..e1fda0aa6 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/node.js @@ -0,0 +1,409 @@ +import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js'; +import { a as automockModule, e as esmWalker } from './chunk-automock.js'; +import MagicString from 'magic-string'; +import { createFilter } from 'vite'; +import { h as hoistMocks } from './chunk-hoistMocks.js'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path/posix'; +import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js'; +import { fileURLToPath } from 'node:url'; +import { existsSync, readFileSync } from 'node:fs'; +import { findMockRedirect } from './redirect.js'; +import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js'; +import 'estree-walker'; +import 'node:module'; +import 'node:path'; +import './chunk-helpers.js'; + +function automockPlugin(options = {}) { + return { + name: "vitest:automock", + enforce: "post", + transform(code, id) { + if (id.includes("mock=automock") || id.includes("mock=autospy")) { + const mockType = id.includes("mock=automock") ? "automock" : "autospy"; + const ms = automockModule(code, mockType, this.parse, options); + return { + code: ms.toString(), + map: ms.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } + } + }; +} + +const regexDynamicImport = /import\s*\(/; +function dynamicImportPlugin(options = {}) { + return { + name: "vitest:browser:esm-injector", + enforce: "post", + transform(source, id) { + // TODO: test is not called for static imports + if (!regexDynamicImport.test(source)) { + return; + } + if (options.filter && !options.filter(id)) { + return; + } + return injectDynamicImport(source, id, this.parse, options); + } + }; +} +function injectDynamicImport(code, id, parse, options = {}) { + if (code.includes("wrapDynamicImport")) { + return; + } + const s = new MagicString(code); + let ast; + try { + ast = parse(code); + } catch (err) { + console.error(`Cannot parse ${id}:\n${err.message}`); + return; + } + // 3. convert references to import bindings & import.meta references + esmWalker(ast, { + onImportMeta() { + // s.update(node.start, node.end, viImportMetaKey) + }, + onDynamicImport(node) { + const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`; + const importSubstring = code.substring(node.start, node.end); + const hasIgnore = importSubstring.includes("/* @vite-ignore */"); + s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : "")); + s.overwrite(node.end - 1, node.end, "))"); + } + }); + return { + code: s.toString(), + map: s.generateMap({ + hires: "boundary", + source: id + }) + }; +} + +function hoistMocksPlugin(options = {}) { + const filter = options.filter || createFilter(options.include, options.exclude); + const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ + "mock", + "unmock", + "doMock", + "doUnmock" + ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options; + const methods = new Set([ + ...hoistableMockMethodNames, + ...hoistedMethodNames, + ...dynamicImportMockMethodNames + ]); + const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`); + return { + name: "vitest:mocks", + enforce: "post", + transform(code, id) { + if (!filter(id)) { + return; + } + const s = hoistMocks(code, id, this.parse, { + regexpHoistable, + hoistableMockMethodNames, + hoistedMethodNames, + utilsObjectNames, + dynamicImportMockMethodNames, + ...options + }); + if (s) { + return { + code: s.toString(), + map: s.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } + } + }; +} +// to keeb backwards compat +function hoistMockAndResolve(code, id, parse, options = {}) { + const s = hoistMocks(code, id, parse, options); + if (s) { + return { + code: s.toString(), + map: s.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } +} + +function interceptorPlugin(options = {}) { + const registry = options.registry || new MockerRegistry(); + return { + name: "vitest:mocks:interceptor", + enforce: "pre", + load: { + order: "pre", + async handler(id) { + const mock = registry.getById(id); + if (!mock) { + return; + } + if (mock.type === "manual") { + const exports$1 = Object.keys(await mock.resolve()); + const accessor = options.globalThisAccessor || "\"__vitest_mocker__\""; + return createManualModuleSource(mock.url, exports$1, accessor); + } + if (mock.type === "redirect") { + return readFile(mock.redirect, "utf-8"); + } + } + }, + transform: { + order: "post", + handler(code, id) { + const mock = registry.getById(id); + if (!mock) { + return; + } + if (mock.type === "automock" || mock.type === "autospy") { + const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor }); + return { + code: m.toString(), + map: m.generateMap({ + hires: "boundary", + source: cleanUrl(id) + }) + }; + } + } + }, + configureServer(server) { + server.ws.on("vitest:interceptor:register", (event) => { + if (event.type === "manual") { + const module = ManualMockedModule.fromJSON(event, async () => { + const keys = await getFactoryExports(event.url); + return Object.fromEntries(keys.map((key) => [key, null])); + }); + registry.add(module); + } else { + if (event.type === "redirect") { + const redirectUrl = new URL(event.redirect); + event.redirect = join(server.config.root, redirectUrl.pathname); + } + registry.register(event); + } + server.ws.send("vitest:interceptor:register:result"); + }); + server.ws.on("vitest:interceptor:delete", (id) => { + registry.delete(id); + server.ws.send("vitest:interceptor:delete:result"); + }); + server.ws.on("vitest:interceptor:invalidate", () => { + registry.clear(); + server.ws.send("vitest:interceptor:invalidate:result"); + }); + function getFactoryExports(url) { + server.ws.send("vitest:interceptor:resolve", url); + let timeout; + return new Promise((resolve, reject) => { + timeout = setTimeout(() => { + reject(new Error(`Timeout while waiting for factory exports of ${url}`)); + }, 1e4); + server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => { + if (resolvedUrl === url) { + clearTimeout(timeout); + resolve(keys); + } + }); + }); + } + } + }; +} + +const VALID_ID_PREFIX = "/@id/"; +class ServerMockResolver { + constructor(server, options = {}) { + this.server = server; + this.options = options; + } + async resolveMock(rawId, importer, options) { + const { id, fsPath, external } = await this.resolveMockId(rawId, importer); + const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url; + if (options.mock === "factory") { + const manifest = getViteDepsManifest(this.server.config); + const needsInterop = manifest?.[fsPath]?.needsInterop ?? false; + return { + mockType: "manual", + resolvedId: id, + resolvedUrl, + needsInterop + }; + } + if (options.mock === "spy") { + return { + mockType: "autospy", + resolvedId: id, + resolvedUrl + }; + } + const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external); + return { + mockType: redirectUrl === null ? "automock" : "redirect", + redirectUrl, + resolvedId: id, + resolvedUrl + }; + } + invalidate(ids) { + ids.forEach((id) => { + const moduleGraph = this.server.moduleGraph; + const module = moduleGraph.getModuleById(id); + if (module) { + module.transformResult = null; + } + }); + } + async resolveId(id, importer) { + const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false }); + if (!resolved) { + return null; + } + return this.normalizeResolveIdToUrl(resolved); + } + normalizeResolveIdToUrl(resolved) { + const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir)); + let url; + // normalise the URL to be acceptable by the browser + // https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103 + const root = this.server.config.root; + if (resolved.id.startsWith(withTrailingSlash(root))) { + url = resolved.id.slice(root.length); + } else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) { + url = join$1("/@fs/", resolved.id); + } else { + url = resolved.id; + } + if (url[0] !== "." && url[0] !== "/") { + url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__"); + } + return { + id: resolved.id, + url, + optimized: isOptimized + }; + } + async resolveMockId(rawId, importer) { + if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) { + importer = join$1(this.server.config.root, importer); + } + const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false }); + return this.resolveModule(rawId, resolved); + } + resolveModule(rawId, resolved) { + const id = resolved?.id || rawId; + const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null; + return { + id, + fsPath: cleanUrl(id), + external + }; + } +} +function isModuleDirectory(config, path) { + const moduleDirectories = config.moduleDirectories || ["/node_modules/"]; + return moduleDirectories.some((dir) => path.includes(dir)); +} +const metadata = new WeakMap(); +function getViteDepsManifest(config) { + if (metadata.has(config)) { + return metadata.get(config); + } + const cacheDirPath = getDepsCacheDir(config); + const metadataPath = resolve(cacheDirPath, "_metadata.json"); + if (!existsSync(metadataPath)) { + return null; + } + const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8")); + const newManifest = {}; + for (const name in optimized) { + const dep = optimized[name]; + const file = resolve(cacheDirPath, dep.file); + newManifest[file] = { + hash: dep.fileHash, + needsInterop: dep.needsInterop + }; + } + metadata.set(config, newManifest); + return newManifest; +} +function getDepsCacheDir(config) { + return resolve(config.cacheDir, "deps"); +} +function withTrailingSlash(path) { + if (path.at(-1) !== "/") { + return `${path}/`; + } + return path; +} + +// this is an implementation for public usage +// vitest doesn't use this plugin directly +function mockerPlugin(options = {}) { + let server; + const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url))); + return [ + { + name: "vitest:mocker:ws-rpc", + config(_, { command }) { + if (command !== "serve") { + return; + } + return { + server: { preTransformRequests: false }, + optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] } + }; + }, + configureServer(server_) { + server = server_; + const mockResolver = new ServerMockResolver(server); + server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => { + const resolved = await mockResolver.resolveId(id, importer); + server.ws.send("vitest:mocks:resolvedId:result", resolved); + }); + server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => { + const resolved = await mockResolver.resolveMock(id, importer, options); + server.ws.send("vitest:mocks:resolveMock:result", resolved); + }); + server.ws.on("vitest:mocks:invalidate", async ({ ids }) => { + mockResolver.invalidate(ids); + server.ws.send("vitest:mocks:invalidate:result"); + }); + }, + async load(id) { + if (id !== registerPath) { + return; + } + if (!server) { + // mocker doesn't work during build + return "export {}"; + } + const content = await readFile(registerPath, "utf-8"); + const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root)); + return result; + } + }, + hoistMocksPlugin(options.hoistMocks), + interceptorPlugin(options), + automockPlugin(options), + dynamicImportPlugin(options) + ]; +} + +export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; diff --git a/node_modules/@vitest/mocker/dist/redirect.d.ts b/node_modules/@vitest/mocker/dist/redirect.d.ts new file mode 100644 index 000000000..1f8256bad --- /dev/null +++ b/node_modules/@vitest/mocker/dist/redirect.d.ts @@ -0,0 +1,3 @@ +declare function findMockRedirect(root: string, mockPath: string, external: string | null): string | null; + +export { findMockRedirect }; diff --git a/node_modules/@vitest/mocker/dist/redirect.js b/node_modules/@vitest/mocker/dist/redirect.js new file mode 100644 index 000000000..b6efea138 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/redirect.js @@ -0,0 +1,79 @@ +import fs from 'node:fs'; +import module$1 from 'node:module'; +import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js'; + +const { existsSync, readdirSync, statSync } = fs; +function findMockRedirect(root, mockPath, external) { + const path = external || mockPath; + // it's a node_module alias + // all mocks should be inside /__mocks__ + if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) { + const mockDirname = dirname(path); + const mockFolder = join(root, "__mocks__", mockDirname); + if (!existsSync(mockFolder)) { + return null; + } + const baseOriginal = basename(path); + function findFile(mockFolder, baseOriginal) { + const files = readdirSync(mockFolder); + for (const file of files) { + const baseFile = basename(file, extname(file)); + if (baseFile === baseOriginal) { + const path = resolve(mockFolder, file); + // if the same name, return the file + if (statSync(path).isFile()) { + return path; + } else { + // find folder/index.{js,ts} + const indexFile = findFile(path, "index"); + if (indexFile) { + return indexFile; + } + } + } + } + return null; + } + return findFile(mockFolder, baseOriginal); + } + const dir = dirname(path); + const baseId = basename(path); + const fullPath = resolve(dir, "__mocks__", baseId); + return existsSync(fullPath) ? fullPath : null; +} +const builtins = new Set([ + ...module$1.builtinModules, + "assert/strict", + "diagnostics_channel", + "dns/promises", + "fs/promises", + "path/posix", + "path/win32", + "readline/promises", + "stream/consumers", + "stream/promises", + "stream/web", + "timers/promises", + "util/types", + "wasi" +]); +// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix +const prefixedBuiltins = new Set([ + "node:sea", + "node:sqlite", + "node:test", + "node:test/reporters" +]); +const NODE_BUILTIN_NAMESPACE = "node:"; +function isNodeBuiltin(id) { + // Added in v18.6.0 + if (module$1.isBuiltin) { + return module$1.isBuiltin(id); + } + if (prefixedBuiltins.has(id)) { + return true; + } + return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id); +} + +export { findMockRedirect }; diff --git a/node_modules/@vitest/mocker/dist/register.d.ts b/node_modules/@vitest/mocker/dist/register.d.ts new file mode 100644 index 000000000..8f80dee69 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/register.d.ts @@ -0,0 +1,9 @@ +import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-QEntlm6J.js'; +import '@vitest/spy'; +import './types.d-BjI5eAwu.js'; +import './index.d-B41z0AuW.js'; + +declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints; +declare function registerNativeFactoryResolver(mocker: ModuleMocker): void; + +export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/node_modules/@vitest/mocker/dist/register.js b/node_modules/@vitest/mocker/dist/register.js new file mode 100644 index 000000000..c8a0be8a6 --- /dev/null +++ b/node_modules/@vitest/mocker/dist/register.js @@ -0,0 +1,42 @@ +import { createMockInstance } from '@vitest/spy'; +import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js'; +import './chunk-helpers.js'; +import './index.js'; +import './chunk-registry.js'; +import './chunk-pathe.M-eThtNZ.js'; + +function registerModuleMocker(interceptor) { + const mocker = new ModuleMocker(interceptor(__VITEST_GLOBAL_THIS_ACCESSOR__), { + resolveId(id, importer) { + return rpc("vitest:mocks:resolveId", { + id, + importer + }); + }, + resolveMock(id, importer, options) { + return rpc("vitest:mocks:resolveMock", { + id, + importer, + options + }); + }, + async invalidate(ids) { + return rpc("vitest:mocks:invalidate", { ids }); + } + }, createMockInstance, { root: __VITEST_MOCKER_ROOT__ }); + globalThis[__VITEST_GLOBAL_THIS_ACCESSOR__] = mocker; + registerNativeFactoryResolver(mocker); + return createCompilerHints({ globalThisKey: __VITEST_GLOBAL_THIS_ACCESSOR__ }); +} +function registerNativeFactoryResolver(mocker) { + hot.on("vitest:interceptor:resolve", async (url) => { + const exports$1 = await mocker.resolveFactoryModule(url); + const keys = Object.keys(exports$1); + hot.send("vitest:interceptor:resolved", { + url, + keys + }); + }); +} + +export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/node_modules/@vitest/mocker/dist/transforms.d.ts b/node_modules/@vitest/mocker/dist/transforms.d.ts new file mode 100644 index 000000000..41d23ea9c --- /dev/null +++ b/node_modules/@vitest/mocker/dist/transforms.d.ts @@ -0,0 +1,8 @@ +export { c as createManualModuleSource, h as hoistMocks } from './hoistMocks.d-w2ILr1dG.js'; +export { automockModule } from './automock.js'; +import 'magic-string'; + +declare function initSyntaxLexers(): Promise; +declare function collectModuleExports(filename: string, code: string, format: "module" | "commonjs", exports?: string[]): string[]; + +export { collectModuleExports, initSyntaxLexers }; diff --git a/node_modules/@vitest/mocker/dist/transforms.js b/node_modules/@vitest/mocker/dist/transforms.js new file mode 100644 index 000000000..bfbae0bce --- /dev/null +++ b/node_modules/@vitest/mocker/dist/transforms.js @@ -0,0 +1,10 @@ +export { c as createManualModuleSource } from './chunk-utils.js'; +export { a as automockModule, c as collectModuleExports, i as initSyntaxLexers } from './chunk-automock.js'; +export { h as hoistMocks } from './chunk-hoistMocks.js'; +import 'node:fs'; +import 'node:url'; +import 'magic-string'; +import 'estree-walker'; +import 'node:module'; +import 'node:path'; +import './chunk-helpers.js'; diff --git a/node_modules/@vitest/mocker/dist/types.d-BjI5eAwu.d.ts b/node_modules/@vitest/mocker/dist/types.d-BjI5eAwu.d.ts new file mode 100644 index 000000000..e35ba702e --- /dev/null +++ b/node_modules/@vitest/mocker/dist/types.d-BjI5eAwu.d.ts @@ -0,0 +1,123 @@ +declare class MockerRegistry { + private readonly registryByUrl; + private readonly registryById; + clear(): void; + keys(): IterableIterator; + add(mock: MockedModule): void; + register(json: MockedModuleSerialized): MockedModule; + register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule; + register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule; + register(type: "automock", raw: string, id: string, url: string): AutomockedModule; + register(type: "autospy", id: string, raw: string, url: string): AutospiedModule; + delete(id: string): void; + deleteById(id: string): void; + get(id: string): MockedModule | undefined; + getById(id: string): MockedModule | undefined; + has(id: string): boolean; +} +type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule; +type MockedModuleType = "automock" | "autospy" | "manual" | "redirect"; +type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized; +declare class AutomockedModule { + raw: string; + id: string; + url: string; + readonly type = "automock"; + constructor(raw: string, id: string, url: string); + static fromJSON(data: AutomockedModuleSerialized): AutospiedModule; + toJSON(): AutomockedModuleSerialized; +} +interface AutomockedModuleSerialized { + type: "automock"; + url: string; + raw: string; + id: string; +} +declare class AutospiedModule { + raw: string; + id: string; + url: string; + readonly type = "autospy"; + constructor(raw: string, id: string, url: string); + static fromJSON(data: AutospiedModuleSerialized): AutospiedModule; + toJSON(): AutospiedModuleSerialized; +} +interface AutospiedModuleSerialized { + type: "autospy"; + url: string; + raw: string; + id: string; +} +declare class RedirectedModule { + raw: string; + id: string; + url: string; + redirect: string; + readonly type = "redirect"; + constructor(raw: string, id: string, url: string, redirect: string); + static fromJSON(data: RedirectedModuleSerialized): RedirectedModule; + toJSON(): RedirectedModuleSerialized; +} +interface RedirectedModuleSerialized { + type: "redirect"; + url: string; + id: string; + raw: string; + redirect: string; +} +declare class ManualMockedModule { + raw: string; + id: string; + url: string; + factory: () => T; + cache: T | undefined; + readonly type = "manual"; + constructor(raw: string, id: string, url: string, factory: () => T); + resolve(): T; + static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule; + toJSON(): ManualMockedModuleSerialized; +} +interface ManualMockedModuleSerialized { + type: "manual"; + url: string; + id: string; + raw: string; +} + +type Awaitable = T | PromiseLike; +type ModuleMockFactoryWithHelper = (importOriginal: () => Promise) => Awaitable>; +type ModuleMockFactory = () => any; +interface ModuleMockOptions { + spy?: boolean; +} +interface ServerMockResolution { + mockType: "manual" | "redirect" | "automock" | "autospy"; + resolvedId: string; + resolvedUrl: string; + needsInterop?: boolean; + redirectUrl?: string | null; +} +interface ServerIdResolution { + id: string; + url: string; + optimized: boolean; +} +interface ModuleMockContext { + /** + * When mocking with a factory, this refers to the module that imported the mock. + */ + callstack: null | string[]; +} +interface TestModuleMocker { + queueMock(id: string, importer: string, factoryOrOptions?: ModuleMockFactory | ModuleMockOptions): void; + queueUnmock(id: string, importer: string): void; + importActual(rawId: string, importer: string, callstack?: string[] | null): Promise; + importMock(rawId: string, importer: string): Promise; + mockObject(object: Record, moduleType?: "automock" | "autospy"): Record; + mockObject(object: Record, mockExports: Record | undefined, moduleType?: "automock" | "autospy"): Record; + getMockContext(): ModuleMockContext; + reset(): void; +} + +export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as h, ManualMockedModule as j }; +export type { ServerMockResolution as S, TestModuleMocker as T, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ModuleMockContext as e, ServerIdResolution as f, AutomockedModuleSerialized as g, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as k, MockedModuleSerialized as l, ModuleMockFactory as m, RedirectedModuleSerialized as n }; diff --git a/node_modules/@vitest/mocker/package.json b/node_modules/@vitest/mocker/package.json new file mode 100644 index 000000000..d67abe170 --- /dev/null +++ b/node_modules/@vitest/mocker/package.json @@ -0,0 +1,97 @@ +{ + "name": "@vitest/mocker", + "type": "module", + "version": "4.1.5", + "description": "Vitest module mocker implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/mocker" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "mock" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./node": { + "types": "./dist/node.d.ts", + "default": "./dist/node.js" + }, + "./browser": { + "types": "./dist/browser.d.ts", + "default": "./dist/browser.js" + }, + "./redirect": { + "types": "./dist/redirect.d.ts", + "default": "./dist/redirect.js" + }, + "./automock": { + "types": "./dist/automock.d.ts", + "default": "./dist/automock.js" + }, + "./register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./auto-register": { + "types": "./dist/register.d.ts", + "default": "./dist/register.js" + }, + "./transforms": { + "types": "./dist/transforms.d.ts", + "default": "./dist/transforms.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + }, + "dependencies": { + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21", + "@vitest/spy": "4.1.5" + }, + "devDependencies": { + "@types/estree": "^1.0.8", + "acorn-walk": "^8.3.5", + "cjs-module-lexer": "^2.2.0", + "es-module-lexer": "^2.0.0", + "msw": "^2.12.10", + "pathe": "^2.0.3", + "vite": "^6.3.5", + "@vitest/utils": "4.1.5", + "@vitest/spy": "4.1.5" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/pretty-format/LICENSE b/node_modules/@vitest/pretty-format/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/pretty-format/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/pretty-format/README.md b/node_modules/@vitest/pretty-format/README.md new file mode 100644 index 000000000..d36596330 --- /dev/null +++ b/node_modules/@vitest/pretty-format/README.md @@ -0,0 +1,7 @@ +# @vitest/pretty-format + +[![NPM version](https://img.shields.io/npm/v/@vitest/pretty-format?color=a1b858&label=)](https://npmx.dev/package/@vitest/pretty-format) + +Vitest's fork of Jest's [`pretty-format`](https://npmx.dev/package/pretty-format). + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/pretty-format/USAGE.md) diff --git a/node_modules/@vitest/pretty-format/dist/index.d.ts b/node_modules/@vitest/pretty-format/dist/index.d.ts new file mode 100644 index 000000000..d9409f2a3 --- /dev/null +++ b/node_modules/@vitest/pretty-format/dist/index.d.ts @@ -0,0 +1,195 @@ +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ +interface 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; + }; +} +type Indent = (arg0: string) => string; +type Refs = Array; +type Print = (arg0: unknown) => string; +type Theme = Required<{ + comment?: string; + content?: string; + prop?: string; + tag?: string; + value?: string; +}>; +/** +* compare function used when sorting object keys, `null` can be used to skip over sorting. +*/ +type CompareKeys = ((a: string, b: string) => number) | null | undefined; +type RequiredOptions = Required; +interface Options extends Omit { + compareKeys: CompareKeys; + theme: Theme; +} +interface PrettyFormatOptions { + /** + * Call `toJSON` on objects before formatting them. + * Ignored after the formatter has already called `toJSON` once for a value. + * @default true + */ + callToJSON?: boolean; + /** + * Whether to escape special characters in regular expressions. + * @default false + */ + escapeRegex?: boolean; + /** + * Whether to escape special characters in strings. + * @default true + */ + escapeString?: boolean; + /** + * Whether to highlight syntax using terminal colors. + * @default false + */ + highlight?: boolean; + /** + * Number of spaces to use for each level of indentation. + * @default 2 + */ + indent?: number; + /** + * Maximum depth to recurse into nested values. + * @default Infinity + */ + maxDepth?: number; + /** + * Maximum number of items to print in arrays, sets, maps, and similar collections. + * @default Infinity + */ + maxWidth?: number; + /** + * Approximate per-depth-level budget for output length. + * When the accumulated output at any single depth level exceeds this value, + * further nesting is collapsed. This is a heuristic safety valve, not a hard + * limit — total output can reach up to roughly `maxDepth × maxOutputLength`. + * @default 1_000_000 + */ + maxOutputLength?: number; + /** + * Whether to minimize added whitespace, including indentation and line breaks. + * @default false + */ + min?: boolean; + /** + * Whether to print `Object` / `Array` prefixes for plain objects and arrays. + * @default true + */ + printBasicPrototype?: boolean; + /** + * Whether to include the function name when formatting functions. + * @default true + */ + printFunctionName?: boolean; + /** + * Whether to include shadow-root contents when formatting DOM nodes. + * @default true + */ + printShadowRoot?: boolean; + /** + * Compare function used when sorting object keys. Set to `null` to disable sorting. + */ + compareKeys?: CompareKeys; + /** + * Plugins used to serialize application-specific data types. + * @default [] + */ + plugins?: Plugins; +} +type OptionsReceived = PrettyFormatOptions; +interface Config { + callToJSON: boolean; + compareKeys: CompareKeys; + colors: Colors; + escapeRegex: boolean; + escapeString: boolean; + indent: string; + maxDepth: number; + maxWidth: number; + min: boolean; + plugins: Plugins; + printBasicPrototype: boolean; + printFunctionName: boolean; + printShadowRoot: boolean; + spacingInner: string; + spacingOuter: string; + maxOutputLength: number; +} +type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string; +type Test = (arg0: any) => boolean; +interface NewPlugin { + serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; + test: Test; +} +interface PluginOptions { + edgeSpacing: string; + min: boolean; + spacing: string; +} +interface OldPlugin { + print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; + test: Test; +} +type Plugin = NewPlugin | OldPlugin; +type Plugins = Array; + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare function createDOMElementFilter(filterNode?: (node: any) => boolean): NewPlugin; + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare const DEFAULT_OPTIONS: Options; +/** +* Returns a presentation string of your `val` object +* @param val any potential JavaScript object +* @param options Custom settings +*/ +declare function format(val: unknown, options?: OptionsReceived): string; + +declare const plugins: { + AsymmetricMatcher: NewPlugin; + DOMCollection: NewPlugin; + DOMElement: NewPlugin; + Immutable: NewPlugin; + ReactElement: NewPlugin; + ReactTestComponent: NewPlugin; + Error: NewPlugin; +}; + +export { DEFAULT_OPTIONS, createDOMElementFilter, format, plugins }; +export type { Colors, CompareKeys, Config, NewPlugin, OldPlugin, Options, OptionsReceived, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme }; diff --git a/node_modules/@vitest/pretty-format/dist/index.js b/node_modules/@vitest/pretty-format/dist/index.js new file mode 100644 index 000000000..daae2b083 --- /dev/null +++ b/node_modules/@vitest/pretty-format/dist/index.js @@ -0,0 +1,1069 @@ +import styles from 'tinyrainbow'; + +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); +} + +function getKeysOfEnumerableProperties(object, compareKeys) { + const rawKeys = Object.keys(object); + const keys = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys); + if (Object.getOwnPropertySymbols) { + for (const symbol of Object.getOwnPropertySymbols(object)) { + 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, separator = ": ") { + let result = ""; + let width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += "…"; + break; + } + const name = printer(current.value[0], config, indentationNext, depth, refs); + const value = printer(current.value[1], config, indentationNext, depth, refs); + result += 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 width = 0; + let current = iterator.next(); + if (!current.done) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + while (!current.done) { + result += indentationNext; + if (width++ === config.maxWidth) { + result += "…"; + break; + } + result += 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 = ""; + list = list instanceof ArrayBuffer ? new DataView(list) : list; + const isDataView = (l) => l instanceof DataView; + const length = isDataView(list) ? list.byteLength : list.length; + if (length > 0) { + result += config.spacingOuter; + const indentationNext = indentation + config.indent; + for (let i = 0; i < length; i++) { + result += indentationNext; + if (i === config.maxWidth) { + result += "…"; + break; + } + if (isDataView(list) || i in list) { + result += printer(isDataView(list) ? list.getInt8(i) : list[i], config, indentationNext, depth, refs); + } + if (i < 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 > 0) { + 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; +} + +const asymmetricMatcher = typeof Symbol === "function" && Symbol.for ? Symbol.for("jest.asymmetricMatcher") : 1267621; +const SPACE$2 = " "; +const serialize$5 = (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}[${printListItems(val.sample, config, indentation, depth, refs, printer)}]`; + } + if (stringedValue === "ObjectContaining" || stringedValue === "ObjectNotContaining") { + if (++depth > config.maxDepth) { + return `[${stringedValue}]`; + } + return `${stringedValue + SPACE$2}{${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); + } + if (typeof val.toAsymmetricMatcher !== "function") { + throw new TypeError(`Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()`); + } + return val.toAsymmetricMatcher(); +}; +const test$5 = (val) => val && val.$$typeof === asymmetricMatcher; +const plugin$5 = { + serialize: serialize$5, + test: test$5 +}; + +const SPACE$1 = " "; +const OBJECT_NAMES = new Set(["DOMStringMap", "NamedNodeMap"]); +const ARRAY_REGEXP = /^(?:HTML\w*Collection|NodeList)$/; +function testName(name) { + return OBJECT_NAMES.has(name) || ARRAY_REGEXP.test(name); +} +const test$4 = (val) => val && val.constructor && !!val.constructor.name && testName(val.constructor.name); +function isNamedNodeMap(collection) { + return 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.has(name) ? `{${printObjectProperties(isNamedNodeMap(collection) ? [...collection].reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}) : { ...collection }, config, indentation, depth, refs, printer)}}` : `[${printListItems([...collection], config, indentation, depth, refs, printer)}]`); +}; +const plugin$4 = { + serialize: serialize$4, + test: test$4 +}; + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* 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.replaceAll("<", "<").replaceAll(">", ">"); +} + +// Return empty string if keys is empty. +function 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]; + // hidden injected value that should not be printed + if (typeof value === "string" && value[0] === "_" && value.startsWith("__vitest_") && value.match(/__vitest_\d+__/)) { + return ""; + } + let printed = printer(value, config, indentationNext, depth, refs); + if (typeof value !== "string") { + if (printed.includes("\n")) { + 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. +function printChildren(children, config, indentation, depth, refs, printer) { + return children.map((child) => config.spacingOuter + indentation + (typeof child === "string" ? printText(child, config) : printer(child, config, indentation, depth, refs))).join(""); +} +function printShadowRoot(children, config, indentation, depth, refs, printer) { + if (config.printShadowRoot === false) { + return ""; + } + return [`${config.spacingOuter + indentation}#shadow-root`, printChildren(children, config, indentation + config.indent, depth, refs, printer)].join(""); +} +function printText(text, config) { + const contentColor = config.colors.content; + return contentColor.open + escapeHTML(text) + contentColor.close; +} +function 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. +function 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}`; +} +function printElementAsLeaf(type, config) { + const tagColor = config.colors.tag; + return `${tagColor.open}<${type}${tagColor.close} …${tagColor.open} />${tagColor.close}`; +} + +const ELEMENT_NODE = 1; +const TEXT_NODE = 3; +const COMMENT_NODE = 8; +const FRAGMENT_NODE = 11; +const ELEMENT_REGEXP = /^(?:(?:HTML|SVG)\w*)?Element$/; +function testHasAttribute(val) { + try { + return typeof val.hasAttribute === "function" && val.hasAttribute("is"); + } catch { + return false; + } +} +function 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) => val?.constructor?.name && testNode(val); +function nodeIsText(node) { + return node.nodeType === TEXT_NODE; +} +function nodeIsComment(node) { + return node.nodeType === COMMENT_NODE; +} +function nodeIsFragment(node) { + return node.nodeType === FRAGMENT_NODE; +} +function filterChildren(children, filterNode) { + // Filter out text nodes that only contain whitespace to prevent empty lines + // This is done regardless of whether a filterNode is provided + let filtered = children.filter((node) => { + // Filter out text nodes that are only whitespace + if (node.nodeType === TEXT_NODE) { + const text = node.data || ""; + // Keep text nodes that have non-whitespace content + return text.trim().length > 0; + } + return true; + }); + // Apply additional user-provided filter if specified + if (filterNode) { + filtered = filtered.filter(filterNode); + } + return filtered; +} +function serializeDOM(node, config, indentation, depth, refs, printer, filterNode) { + if (nodeIsText(node)) { + return printText(node.data, config); + } + if (nodeIsComment(node)) { + return printComment(node.data, config); + } + const type = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase(); + if (++depth > config.maxDepth) { + return printElementAsLeaf(type, config); + } + const children = Array.prototype.slice.call(node.childNodes || node.children); + const shadowChildren = nodeIsFragment(node) || !node.shadowRoot ? [] : Array.prototype.slice.call(node.shadowRoot.children); + const resolvedChildren = filterNode ? filterChildren(children, filterNode) : children; + const resolvedShadowChildren = filterNode ? filterChildren(shadowChildren, filterNode) : shadowChildren; + return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes, (attr) => attr.name).sort(), nodeIsFragment(node) ? {} : [...node.attributes].reduce((props, attribute) => { + props[attribute.name] = attribute.value; + return props; + }, {}), config, indentation + config.indent, depth, refs, printer), (resolvedShadowChildren.length > 0 ? printShadowRoot(resolvedShadowChildren, config, indentation + config.indent, depth, refs, printer) : "") + printChildren(resolvedChildren, config, indentation + config.indent, depth, refs, printer), config, indentation); +} +const serialize$3 = (node, config, indentation, depth, refs, printer) => serializeDOM(node, config, indentation, depth, refs, printer); +function createDOMElementFilter(filterNode) { + return { + test: test$3, + serialize: (node, config, indentation, depth, refs, printer) => serializeDOM(node, config, indentation, depth, refs, printer, filterNode) + }; +} +const plugin$3 = { + serialize: serialize$3, + test: test$3 +}; + +// 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__@@"; +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 = "…"; +function printImmutableEntries(val, config, indentation, depth, refs, printer, type) { + return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}{${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 + }; + } }; +} +function 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}{${printIteratorEntries(getRecordEntries(val), config, indentation, depth, refs, printer)}}`; +} +function 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}{${val._iter || val._object ? printIteratorEntries(val.entries(), config, indentation, depth, refs, printer) : LAZY}}`; + } + return `${name + SPACE}[${val._iter || val._array || val._collection || val._iterable ? printIteratorValues(val.values(), config, indentation, depth, refs, printer) : LAZY}]`; +} +function printImmutableValues(val, config, indentation, depth, refs, printer, type) { + return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}[${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. +const test$2 = (val) => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); +const plugin$2 = { + serialize: serialize$2, + test: test$2 +}; + +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +var reactIs$1 = {exports: {}}; + +var reactIs_production = {}; + +/** + * @license React + * react-is.production.js + * + * Copyright (c) Meta Platforms, Inc. and 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; + +function requireReactIs_production () { + if (hasRequiredReactIs_production) return reactIs_production; + hasRequiredReactIs_production = 1; + var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); + function typeOf(object) { + if ("object" === typeof object && null !== object) { + var $$typeof = object.$$typeof; + switch ($$typeof) { + case REACT_ELEMENT_TYPE: + switch (((object = object.type), object)) { + case REACT_FRAGMENT_TYPE: + case REACT_PROFILER_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_SUSPENSE_TYPE: + case REACT_SUSPENSE_LIST_TYPE: + case REACT_VIEW_TRANSITION_TYPE: + return object; + default: + switch (((object = object && object.$$typeof), object)) { + case REACT_CONTEXT_TYPE: + case REACT_FORWARD_REF_TYPE: + case REACT_LAZY_TYPE: + case REACT_MEMO_TYPE: + return object; + case REACT_CONSUMER_TYPE: + return object; + default: + return $$typeof; + } + } + case REACT_PORTAL_TYPE: + return $$typeof; + } + } + } + reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE; + reactIs_production.ContextProvider = REACT_CONTEXT_TYPE; + reactIs_production.Element = REACT_ELEMENT_TYPE; + reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE; + reactIs_production.Fragment = REACT_FRAGMENT_TYPE; + reactIs_production.Lazy = REACT_LAZY_TYPE; + reactIs_production.Memo = REACT_MEMO_TYPE; + reactIs_production.Portal = REACT_PORTAL_TYPE; + reactIs_production.Profiler = REACT_PROFILER_TYPE; + reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE; + reactIs_production.Suspense = REACT_SUSPENSE_TYPE; + reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE; + reactIs_production.isContextConsumer = function (object) { + return typeOf(object) === REACT_CONSUMER_TYPE; + }; + reactIs_production.isContextProvider = function (object) { + return typeOf(object) === REACT_CONTEXT_TYPE; + }; + reactIs_production.isElement = function (object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + }; + reactIs_production.isForwardRef = function (object) { + return typeOf(object) === REACT_FORWARD_REF_TYPE; + }; + reactIs_production.isFragment = function (object) { + return typeOf(object) === REACT_FRAGMENT_TYPE; + }; + reactIs_production.isLazy = function (object) { + return typeOf(object) === REACT_LAZY_TYPE; + }; + reactIs_production.isMemo = function (object) { + return typeOf(object) === REACT_MEMO_TYPE; + }; + reactIs_production.isPortal = function (object) { + return typeOf(object) === REACT_PORTAL_TYPE; + }; + reactIs_production.isProfiler = function (object) { + return typeOf(object) === REACT_PROFILER_TYPE; + }; + reactIs_production.isStrictMode = function (object) { + return typeOf(object) === REACT_STRICT_MODE_TYPE; + }; + reactIs_production.isSuspense = function (object) { + return typeOf(object) === REACT_SUSPENSE_TYPE; + }; + reactIs_production.isSuspenseList = function (object) { + return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; + }; + reactIs_production.isValidElementType = function (type) { + return "string" === typeof type || + "function" === typeof type || + type === REACT_FRAGMENT_TYPE || + type === REACT_PROFILER_TYPE || + type === REACT_STRICT_MODE_TYPE || + type === REACT_SUSPENSE_TYPE || + type === REACT_SUSPENSE_LIST_TYPE || + ("object" === typeof type && + null !== type && + (type.$$typeof === REACT_LAZY_TYPE || + type.$$typeof === REACT_MEMO_TYPE || + type.$$typeof === REACT_CONTEXT_TYPE || + type.$$typeof === REACT_CONSUMER_TYPE || + type.$$typeof === REACT_FORWARD_REF_TYPE || + type.$$typeof === REACT_CLIENT_REFERENCE || + void 0 !== type.getModuleId)) + ? true + : false; + }; + reactIs_production.typeOf = typeOf; + return reactIs_production; +} + +var hasRequiredReactIs$1; + +function requireReactIs$1 () { + if (hasRequiredReactIs$1) return reactIs$1.exports; + hasRequiredReactIs$1 = 1; + + { + reactIs$1.exports = requireReactIs_production(); + } + return reactIs$1.exports; +} + +var reactIsExports$1 = requireReactIs$1(); +var index$1 = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports$1); + +var ReactIs19 = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index$1 +}, [reactIsExports$1]); + +var reactIs = {exports: {}}; + +var reactIs_production_min = {}; + +/** + * @license React + * 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=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference"); + function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=g;reactIs_production_min.Element=b;reactIs_production_min.ForwardRef=l;reactIs_production_min.Fragment=d;reactIs_production_min.Lazy=q;reactIs_production_min.Memo=p;reactIs_production_min.Portal=c;reactIs_production_min.Profiler=f;reactIs_production_min.StrictMode=e;reactIs_production_min.Suspense=m; + reactIs_production_min.SuspenseList=n;reactIs_production_min.isAsyncMode=function(){return false};reactIs_production_min.isConcurrentMode=function(){return false};reactIs_production_min.isContextConsumer=function(a){return v(a)===h};reactIs_production_min.isContextProvider=function(a){return v(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return v(a)===l};reactIs_production_min.isFragment=function(a){return v(a)===d};reactIs_production_min.isLazy=function(a){return v(a)===q};reactIs_production_min.isMemo=function(a){return v(a)===p}; + reactIs_production_min.isPortal=function(a){return v(a)===c};reactIs_production_min.isProfiler=function(a){return v(a)===f};reactIs_production_min.isStrictMode=function(a){return v(a)===e};reactIs_production_min.isSuspense=function(a){return v(a)===m};reactIs_production_min.isSuspenseList=function(a){return v(a)===n}; + reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?true:false};reactIs_production_min.typeOf=v; + return reactIs_production_min; +} + +var hasRequiredReactIs; + +function requireReactIs () { + if (hasRequiredReactIs) return reactIs.exports; + hasRequiredReactIs = 1; + + { + reactIs.exports = requireReactIs_production_min(); + } + return reactIs.exports; +} + +var reactIsExports = requireReactIs(); +var index = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports); + +var ReactIs18 = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index +}, [reactIsExports]); + +const reactIsMethods = [ + "isAsyncMode", + "isConcurrentMode", + "isContextConsumer", + "isContextProvider", + "isElement", + "isForwardRef", + "isFragment", + "isLazy", + "isMemo", + "isPortal", + "isProfiler", + "isStrictMode", + "isSuspense", + "isSuspenseList", + "isValidElementType" +]; +const ReactIs = Object.fromEntries(reactIsMethods.map((m) => [m, (v) => ReactIs18[m](v) || ReactIs19[m](v)])); +// Given element.props.children, or subtree during recursive traversal, +// return flattened array of children. +function getChildren(arg, children = []) { + if (Array.isArray(arg)) { + for (const item of arg) { + getChildren(item, children); + } + } else if (arg != null && arg !== false && arg !== "") { + children.push(arg); + } + return children; +} +function 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" : `ForwardRef(${functionName})`; + } + if (ReactIs.isMemo(element)) { + const functionName = type.displayName || type.type.displayName || type.type.name || ""; + return functionName === "" ? "Memo" : `Memo(${functionName})`; + } + } + return "UNDEFINED"; +} +function 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 ? printElementAsLeaf(getType(element), config) : printElement(getType(element), printProps(getPropKeys$1(element), element.props, config, indentation + config.indent, depth, refs, printer), printChildren(getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer), config, indentation); +const test$1 = (val) => val != null && ReactIs.isElement(val); +const plugin$1 = { + serialize: serialize$1, + test: test$1 +}; + +const testSymbol = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.test.json") : 245830487; +function 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 ? printElementAsLeaf(object.type, config) : printElement(object.type, object.props ? printProps(getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer) : "", object.children ? printChildren(object.children, config, indentation + config.indent, depth, refs, printer) : "", config, indentation); +const test = (val) => val && val.$$typeof === testSymbol; +const plugin = { + serialize, + test +}; + +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. +*/ +function getConstructorName(val) { + return typeof val.constructor === "function" && val.constructor.name || "Object"; +} +/** Is val is equal to global window object? Works even if it does not exist :) */ +function isWindow(val) { + return typeof window !== "undefined" && val === window; +} +// eslint-disable-next-line regexp/no-super-linear-backtracking +const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +const NEWLINE_REGEXP = /\n/g; +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.replaceAll(/"|\\/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 Number.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).replaceAll(/[$()*+.?[\\\]^{|}]/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.includes(val)) { + return "[Circular]"; + } + refs = [...refs]; + 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 "}[${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} `}[${printListItems(val, config, indentation, depth, refs, printer)}]`; + } + if (toStringed === "[object Map]") { + return hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer, " => ")}}`; + } + if (toStringed === "[object Set]") { + return hitMaxDepth ? "[Set]" : `Set {${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)} `}{${printObjectProperties(val, config, indentation, depth, refs, printer)}}`; +} +const ErrorPlugin = { + test: (val) => val && val instanceof Error, + serialize(val, config, indentation, depth, refs, printer) { + if (refs.includes(val)) { + return "[Circular]"; + } + refs = [...refs, val]; + const hitMaxDepth = ++depth > config.maxDepth; + const { message, cause, ...rest } = val; + const entries = { + message, + ...typeof cause !== "undefined" ? { cause } : {}, + ...val instanceof AggregateError ? { errors: val.errors } : {}, + ...rest + }; + const name = val.name !== "Error" ? val.name : getConstructorName(val); + return hitMaxDepth ? `[${name}]` : `${name} {${printIteratorEntries(Object.entries(entries).values(), 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.replaceAll(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 TypeError(`pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`); + } + return printed; +} +function findPlugin(plugins, val) { + for (const plugin of plugins) { + try { + if (plugin.test(val)) { + return plugin; + } + } catch (error) { + throw new PrettyFormatPluginError(error.message, error.stack); + } + } + return null; +} +function printer(val, config, indentation, depth, refs, hasCalledToJSON) { + let result; + const plugin = findPlugin(config.plugins, val); + if (plugin !== null) { + result = printPlugin(plugin, val, config, indentation, depth, refs); + } else { + const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString); + if (basicResult !== null) { + result = basicResult; + } else { + result = printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON); + } + } + // Per-depth output budget (inspired by Node's util.inspect). + // Each depth level tracks output independently, so nested results + // don't inflate a single counter (which would undercount by ~Nx for + // N levels of nesting). Nodes at the same depth produce disjoint spans + // in the output string, so each bucket accurately reflects output at + // that level. Total output is bounded by maxDepth × maxOutputLength. + config._outputLengthPerDepth[depth] ??= 0; + config._outputLengthPerDepth[depth] += result.length; + if (config._outputLengthPerDepth[depth] > config.maxOutputLength) { + config.maxDepth = 0; + } + return result; +} +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: Number.POSITIVE_INFINITY, + maxOutputLength: 1e6, + maxWidth: Number.POSITIVE_INFINITY, + min: false, + plugins: [], + printBasicPrototype: true, + printFunctionName: true, + printShadowRoot: true, + theme: DEFAULT_THEME +}; +function validateOptions(options) { + for (const key of Object.keys(options)) { + if (!Object.hasOwn(DEFAULT_OPTIONS, 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."); + } +} +function getColorsHighlight() { + return DEFAULT_THEME_KEYS.reduce((colors, key) => { + const value = DEFAULT_THEME[key]; + const color = value && styles[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)); +} +function getColorsEmpty() { + return DEFAULT_THEME_KEYS.reduce((colors, key) => { + colors[key] = { + close: "", + open: "" + }; + return colors; + }, Object.create(null)); +} +function getPrintFunctionName(options) { + return options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; +} +function getEscapeRegex(options) { + return options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; +} +function getEscapeString(options) { + return options?.escapeString ?? DEFAULT_OPTIONS.escapeString; +} +function getConfig(options) { + return { + callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, + colors: options?.highlight ? getColorsHighlight() : getColorsEmpty(), + compareKeys: typeof options?.compareKeys === "function" || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, + escapeRegex: getEscapeRegex(options), + escapeString: getEscapeString(options), + indent: options?.min ? "" : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), + maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, + maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, + min: options?.min ?? DEFAULT_OPTIONS.min, + plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, + printBasicPrototype: options?.printBasicPrototype ?? true, + printFunctionName: getPrintFunctionName(options), + printShadowRoot: options?.printShadowRoot ?? true, + spacingInner: options?.min ? " " : "\n", + spacingOuter: options?.min ? "" : "\n", + maxOutputLength: options?.maxOutputLength ?? DEFAULT_OPTIONS.maxOutputLength, + _outputLengthPerDepth: [] + }; +} +function createIndent(indent) { + return Array.from({ length: 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: plugin$5, + DOMCollection: plugin$4, + DOMElement: plugin$3, + Immutable: plugin$2, + ReactElement: plugin$1, + ReactTestComponent: plugin, + Error: ErrorPlugin +}; + +export { DEFAULT_OPTIONS, createDOMElementFilter, format, plugins }; diff --git a/node_modules/@vitest/pretty-format/package.json b/node_modules/@vitest/pretty-format/package.json new file mode 100644 index 000000000..8af2b4981 --- /dev/null +++ b/node_modules/@vitest/pretty-format/package.json @@ -0,0 +1,50 @@ +{ + "name": "@vitest/pretty-format", + "type": "module", + "version": "4.1.5", + "description": "Fork of pretty-format with support for ESM", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/pretty-format" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "pretty", + "pretty-format" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "devDependencies": { + "@types/react-is": "^19.2.0", + "react-is": "^19.2.4", + "react-is-18": "npm:react-is@18.3.1" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/runner/LICENSE b/node_modules/@vitest/runner/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/runner/README.md b/node_modules/@vitest/runner/README.md new file mode 100644 index 000000000..2f6884dd5 --- /dev/null +++ b/node_modules/@vitest/runner/README.md @@ -0,0 +1,7 @@ +# @vitest/runner + +[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner) + +Vitest mechanism to collect and run tests. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/runner) | [Documentation](https://vitest.dev/api/advanced/runner) diff --git a/node_modules/@vitest/runner/dist/chunk-artifact.js b/node_modules/@vitest/runner/dist/chunk-artifact.js new file mode 100644 index 000000000..6ea423434 --- /dev/null +++ b/node_modules/@vitest/runner/dist/chunk-artifact.js @@ -0,0 +1,3457 @@ +import { processError } from '@vitest/utils/error'; +import { isObject, filterOutComments, ordinal, createDefer, assertTypes, toArray, isNegativeNaN, unique, objectAttr, shuffle } from '@vitest/utils/helpers'; +import { getSafeTimers } from '@vitest/utils/timers'; +import { format, formatRegExp, objDisplay } from '@vitest/utils/display'; +import { parseSingleStack } from '@vitest/utils/source-map'; +import { relative } from 'pathe'; + +class PendingError extends Error { + code = "VITEST_PENDING"; + taskId; + constructor(message, task, note) { + super(message); + this.message = message; + this.note = note; + this.taskId = task.id; + } +} +class TestRunAbortError extends Error { + name = "TestRunAbortError"; + reason; + constructor(message, reason) { + super(message); + this.reason = reason; + } +} +class FixtureDependencyError extends Error { + name = "FixtureDependencyError"; +} +class FixtureAccessError extends Error { + name = "FixtureAccessError"; +} +class FixtureParseError extends Error { + name = "FixtureParseError"; +} +class AroundHookSetupError extends Error { + name = "AroundHookSetupError"; +} +class AroundHookTeardownError extends Error { + name = "AroundHookTeardownError"; +} +class AroundHookMultipleCallsError extends Error { + name = "AroundHookMultipleCallsError"; +} + +// use WeakMap here to make the Test and Suite object serializable +const fnMap = new WeakMap(); +const testFixtureMap = new WeakMap(); +const hooksMap = new WeakMap(); +function setFn(key, fn) { + fnMap.set(key, fn); +} +function getFn(key) { + return fnMap.get(key); +} +function setTestFixture(key, fixture) { + testFixtureMap.set(key, fixture); +} +function getTestFixtures(key) { + return testFixtureMap.get(key); +} +function setHooks(key, hooks) { + hooksMap.set(key, hooks); +} +function getHooks(key) { + return hooksMap.get(key); +} + +const FIXTURE_STACK_TRACE_KEY = Symbol.for("VITEST_FIXTURE_STACK_TRACE"); +class TestFixtures { + _suiteContexts; + _overrides = new WeakMap(); + _registrations; + static _definitions = []; + static _builtinFixtures = [ + "task", + "signal", + "onTestFailed", + "onTestFinished", + "skip", + "annotate" + ]; + static _fixtureOptionKeys = [ + "auto", + "injected", + "scope" + ]; + static _fixtureScopes = [ + "test", + "file", + "worker" + ]; + static _workerContextSuite = { type: "worker" }; + static clearDefinitions() { + TestFixtures._definitions.length = 0; + } + static getWorkerContexts() { + return TestFixtures._definitions.map((f) => f.getWorkerContext()); + } + static getFileContexts(file) { + return TestFixtures._definitions.map((f) => f.getFileContext(file)); + } + static isFixtureOptions(obj) { + return isObject(obj) && Object.keys(obj).some((key) => TestFixtures._fixtureOptionKeys.includes(key)); + } + constructor(registrations) { + this._registrations = registrations ?? new Map(); + this._suiteContexts = new WeakMap(); + TestFixtures._definitions.push(this); + } + extend(runner, userFixtures) { + const { suite } = getCurrentSuite(); + const isTopLevel = !suite || suite.file === suite; + const registrations = this.parseUserFixtures(runner, userFixtures, isTopLevel); + return new TestFixtures(registrations); + } + get(suite) { + let currentSuite = suite; + while (currentSuite) { + const overrides = this._overrides.get(currentSuite); + // return the closest override + if (overrides) { + return overrides; + } + if (currentSuite === currentSuite.file) { + break; + } + currentSuite = currentSuite.suite || currentSuite.file; + } + return this._registrations; + } + override(runner, userFixtures) { + const { suite: currentSuite, file } = getCurrentSuite(); + const suite = currentSuite || file; + const isTopLevel = !currentSuite || currentSuite.file === currentSuite; + // Create a copy of the closest parent's registrations to avoid modifying them + // For chained calls, this.get(suite) returns this suite's overrides; for first call, returns parent's + const suiteRegistrations = new Map(this.get(suite)); + const registrations = this.parseUserFixtures(runner, userFixtures, isTopLevel, suiteRegistrations); + // If defined in top-level, just override all registrations + // We don't support overriding suite-level fixtures anyway (it will throw an error) + if (isTopLevel) { + this._registrations = registrations; + } else { + this._overrides.set(suite, registrations); + } + } + getFileContext(file) { + if (!this._suiteContexts.has(file)) { + this._suiteContexts.set(file, Object.create(null)); + } + return this._suiteContexts.get(file); + } + getWorkerContext() { + if (!this._suiteContexts.has(TestFixtures._workerContextSuite)) { + this._suiteContexts.set(TestFixtures._workerContextSuite, Object.create(null)); + } + return this._suiteContexts.get(TestFixtures._workerContextSuite); + } + parseUserFixtures(runner, userFixtures, supportNonTest, registrations = new Map(this._registrations)) { + const errors = []; + Object.entries(userFixtures).forEach(([name, fn]) => { + let options; + let value; + let _options; + if (Array.isArray(fn) && fn.length >= 2 && TestFixtures.isFixtureOptions(fn[1])) { + _options = fn[1]; + options = { + auto: _options.auto ?? false, + scope: _options.scope ?? "test", + injected: _options.injected ?? false + }; + value = options.injected ? runner.injectValue?.(name) ?? fn[0] : fn[0]; + } else { + value = fn; + } + const parent = registrations.get(name); + if (parent && options) { + if (parent.scope !== options.scope) { + errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered with a "${options.scope}" scope.`)); + } + if (parent.auto !== options.auto) { + errors.push(new FixtureDependencyError(`The "${name}" fixture was already registered as { auto: ${options.auto} }.`)); + } + } else if (parent) { + options = { + auto: parent.auto, + scope: parent.scope, + injected: parent.injected + }; + } else if (!options) { + options = { + auto: false, + injected: false, + scope: "test" + }; + } + if (options.scope && !TestFixtures._fixtureScopes.includes(options.scope)) { + errors.push(new FixtureDependencyError(`The "${name}" fixture has unknown scope "${options.scope}".`)); + } + if (!supportNonTest && options.scope !== "test") { + errors.push(new FixtureDependencyError(`The "${name}" fixture cannot be defined with a ${options.scope} scope${!_options?.scope && parent?.scope ? " (inherited from the base fixture)" : ""} inside the describe block. Define it at the top level of the file instead.`)); + } + const deps = isFixtureFunction(value) ? getUsedProps(value) : new Set(); + const item = { + name, + value, + auto: options.auto ?? false, + injected: options.injected ?? false, + scope: options.scope ?? "test", + deps, + parent + }; + if (isFixtureFunction(value)) { + Object.assign(value, { [FIXTURE_STACK_TRACE_KEY]: new Error("STACK_TRACE_ERROR") }); + } + registrations.set(name, item); + if (item.scope === "worker" && (runner.pool === "vmThreads" || runner.pool === "vmForks")) { + item.scope = "file"; + } + }); + // validate fixture dependency scopes + for (const fixture of registrations.values()) { + for (const depName of fixture.deps) { + if (TestFixtures._builtinFixtures.includes(depName)) { + continue; + } + const dep = registrations.get(depName); + if (!dep) { + errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on unknown fixture "${depName}".`)); + continue; + } + if (depName === fixture.name && !fixture.parent) { + errors.push(new FixtureDependencyError(`The "${fixture.name}" fixture depends on itself, but does not have a base implementation.`)); + continue; + } + if (TestFixtures._fixtureScopes.indexOf(fixture.scope) > TestFixtures._fixtureScopes.indexOf(dep.scope)) { + errors.push(new FixtureDependencyError(`The ${fixture.scope} "${fixture.name}" fixture cannot depend on a ${dep.scope} fixture "${dep.name}".`)); + continue; + } + } + } + if (errors.length === 1) { + throw errors[0]; + } else if (errors.length > 1) { + throw new AggregateError(errors, "Cannot resolve user fixtures. See errors for more information."); + } + return registrations; + } +} +const cleanupFnArrayMap = new WeakMap(); +async function callFixtureCleanup(context) { + const cleanupFnArray = cleanupFnArrayMap.get(context) ?? []; + for (const cleanup of cleanupFnArray.reverse()) { + await cleanup(); + } + cleanupFnArrayMap.delete(context); +} +/** +* Returns the current number of cleanup functions registered for the context. +* This can be used as a checkpoint to later clean up only fixtures added after this point. +*/ +function getFixtureCleanupCount(context) { + return cleanupFnArrayMap.get(context)?.length ?? 0; +} +/** +* Cleans up only fixtures that were added after the given checkpoint index. +* This is used by aroundEach to clean up fixtures created inside runTest() +* while preserving fixtures that were created for aroundEach itself. +*/ +async function callFixtureCleanupFrom(context, fromIndex) { + const cleanupFnArray = cleanupFnArrayMap.get(context); + if (!cleanupFnArray || cleanupFnArray.length <= fromIndex) { + return; + } + // Get items added after the checkpoint + const toCleanup = cleanupFnArray.slice(fromIndex); + // Clean up in reverse order + for (const cleanup of toCleanup.reverse()) { + await cleanup(); + } + // Remove cleaned up items from the array, keeping items before checkpoint + cleanupFnArray.length = fromIndex; +} +const contextHasFixturesCache = new WeakMap(); +function withFixtures(fn, options) { + const collector = getCurrentSuite(); + const suite = options?.suite || collector.suite || collector.file; + return async (hookContext) => { + const context = hookContext || options?.context; + if (!context) { + if (options?.suiteHook) { + validateSuiteHook(fn, options.suiteHook, options.stackTraceError); + } + return fn({}); + } + const fixtures = options?.fixtures || getTestFixtures(context); + if (!fixtures) { + return fn(context); + } + const registrations = fixtures.get(suite); + if (!registrations.size) { + return fn(context); + } + const usedFixtures = []; + const usedProps = getUsedProps(fn); + for (const fixture of registrations.values()) { + if (isAutoFixture(fixture, options) || usedProps.has(fixture.name)) { + usedFixtures.push(fixture); + } + } + if (!usedFixtures.length) { + return fn(context); + } + if (!cleanupFnArrayMap.has(context)) { + cleanupFnArrayMap.set(context, []); + } + const cleanupFnArray = cleanupFnArrayMap.get(context); + const pendingFixtures = resolveDeps(usedFixtures, registrations); + if (!pendingFixtures.length) { + return fn(context); + } + // Check if suite-level hook is trying to access test-scoped fixtures + // Suite hooks (beforeAll/afterAll/aroundAll) can only access file/worker scoped fixtures + if (options?.suiteHook) { + const testScopedFixtures = pendingFixtures.filter((f) => f.scope === "test"); + if (testScopedFixtures.length > 0) { + const fixtureNames = testScopedFixtures.map((f) => `"${f.name}"`).join(", "); + const alternativeHook = { + aroundAll: "aroundEach", + beforeAll: "beforeEach", + afterAll: "afterEach" + }; + const error = new FixtureDependencyError(`Test-scoped fixtures cannot be used inside ${options.suiteHook} hook. ` + `The following fixtures are test-scoped: ${fixtureNames}. ` + `Use { scope: 'file' } or { scope: 'worker' } fixtures instead, or move the logic to ${alternativeHook[options.suiteHook]} hook.`); + // Use stack trace from hook registration for better error location + if (options.stackTraceError?.stack) { + error.stack = error.message + options.stackTraceError.stack.replace(options.stackTraceError.message, ""); + } + throw error; + } + } + if (!contextHasFixturesCache.has(context)) { + contextHasFixturesCache.set(context, new WeakSet()); + } + const cachedFixtures = contextHasFixturesCache.get(context); + for (const fixture of pendingFixtures) { + if (fixture.scope === "test") { + // fixture could be already initialized during "before" hook + // we can't check "fixture.name" in context because context may + // access the parent fixture ({ a: ({ a }) => {} }) + if (cachedFixtures.has(fixture)) { + continue; + } + cachedFixtures.add(fixture); + const resolvedValue = await resolveTestFixtureValue(fixture, context, cleanupFnArray); + context[fixture.name] = resolvedValue; + cleanupFnArray.push(() => { + cachedFixtures.delete(fixture); + }); + } else { + const resolvedValue = await resolveScopeFixtureValue(fixtures, suite, fixture); + context[fixture.name] = resolvedValue; + } + } + return fn(context); + }; +} +function isAutoFixture(fixture, options) { + if (!fixture.auto) { + return false; + } + // suite hook doesn't automatically trigger unused test-scoped fixtures. + if (options?.suiteHook && fixture.scope === "test") { + return false; + } + return true; +} +function isFixtureFunction(value) { + return typeof value === "function"; +} +function resolveTestFixtureValue(fixture, context, cleanupFnArray) { + if (!isFixtureFunction(fixture.value)) { + return fixture.value; + } + return resolveFixtureFunction(fixture.value, fixture.name, context, cleanupFnArray); +} +const scopedFixturePromiseCache = new WeakMap(); +async function resolveScopeFixtureValue(fixtures, suite, fixture) { + const workerContext = fixtures.getWorkerContext(); + const fileContext = fixtures.getFileContext(suite.file); + const fixtureContext = fixture.scope === "worker" ? workerContext : fileContext; + if (!isFixtureFunction(fixture.value)) { + fixtureContext[fixture.name] = fixture.value; + return fixture.value; + } + if (fixture.name in fixtureContext) { + return fixtureContext[fixture.name]; + } + if (scopedFixturePromiseCache.has(fixture)) { + return scopedFixturePromiseCache.get(fixture); + } + if (!cleanupFnArrayMap.has(fixtureContext)) { + cleanupFnArrayMap.set(fixtureContext, []); + } + const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext); + const promise = resolveFixtureFunction(fixture.value, fixture.name, fixture.scope === "file" ? { + ...workerContext, + ...fileContext + } : fixtureContext, cleanupFnFileArray).then((value) => { + fixtureContext[fixture.name] = value; + scopedFixturePromiseCache.delete(fixture); + return value; + }); + scopedFixturePromiseCache.set(fixture, promise); + return promise; +} +async function resolveFixtureFunction(fixtureFn, fixtureName, context, cleanupFnArray) { + // wait for `use` call to extract fixture value + const useFnArgPromise = createDefer(); + const stackTraceError = FIXTURE_STACK_TRACE_KEY in fixtureFn && fixtureFn[FIXTURE_STACK_TRACE_KEY] instanceof Error ? fixtureFn[FIXTURE_STACK_TRACE_KEY] : undefined; + let isUseFnArgResolved = false; + const fixtureReturn = fixtureFn(context, async (useFnArg) => { + // extract `use` argument + isUseFnArgResolved = true; + useFnArgPromise.resolve(useFnArg); + // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup + const useReturnPromise = createDefer(); + cleanupFnArray.push(async () => { + // start teardown by resolving `use` Promise + useReturnPromise.resolve(); + // wait for finishing teardown + await fixtureReturn; + }); + await useReturnPromise; + }).then(() => { + // fixture returned without calling use() + if (!isUseFnArgResolved) { + const error = new Error(`Fixture "${fixtureName}" returned without calling "use". Make sure to call "use" in every code path of the fixture function.`); + if (stackTraceError?.stack) { + error.stack = error.message + stackTraceError.stack.replace(stackTraceError.message, ""); + } + useFnArgPromise.reject(error); + } + }).catch((e) => { + // treat fixture setup error as test failure + if (!isUseFnArgResolved) { + useFnArgPromise.reject(e); + return; + } + // otherwise re-throw to avoid silencing error during cleanup + throw e; + }); + return useFnArgPromise; +} +function resolveDeps(usedFixtures, registrations, depSet = new Set(), pendingFixtures = []) { + usedFixtures.forEach((fixture) => { + if (pendingFixtures.includes(fixture)) { + return; + } + if (!isFixtureFunction(fixture.value) || !fixture.deps) { + pendingFixtures.push(fixture); + return; + } + if (depSet.has(fixture)) { + if (fixture.parent) { + fixture = fixture.parent; + } else { + throw new Error(`Circular fixture dependency detected: ${fixture.name} <- ${[...depSet].reverse().map((d) => d.name).join(" <- ")}`); + } + } + depSet.add(fixture); + resolveDeps([...fixture.deps].map((n) => n === fixture.name ? fixture.parent : registrations.get(n)).filter((n) => !!n), registrations, depSet, pendingFixtures); + pendingFixtures.push(fixture); + depSet.clear(); + }); + return pendingFixtures; +} +function validateSuiteHook(fn, hook, suiteError) { + const usedProps = getUsedProps(fn, { + sourceError: suiteError, + suiteHook: hook + }); + if (usedProps.size) { + const error = new FixtureAccessError(`The ${hook} hook uses fixtures "${[...usedProps].join("\", \"")}", but has no access to context. ` + `Did you forget to call it as "test.${hook}()" instead of "${hook}()"?\n` + `If you used internal "suite" task as the first argument previously, access it in the second argument instead. ` + `See https://vitest.dev/guide/test-context#suite-level-hooks`); + if (suiteError) { + error.stack = suiteError.stack?.replace(suiteError.message, error.message); + } + throw error; + } +} +const kPropsSymbol = Symbol("$vitest:fixture-props"); +const kPropNamesSymbol = Symbol("$vitest:fixture-prop-names"); +function configureProps(fn, options) { + Object.defineProperty(fn, kPropsSymbol, { + value: options, + enumerable: false + }); +} +function memoProps(fn, props) { + fn[kPropNamesSymbol] = props; + return props; +} +function getUsedProps(fn, { sourceError, suiteHook } = {}) { + if (kPropNamesSymbol in fn) { + return fn[kPropNamesSymbol]; + } + const { index: fixturesIndex = 0, original: implementation = fn } = kPropsSymbol in fn ? fn[kPropsSymbol] : {}; + let fnString = filterOutComments(implementation.toString()); + // match lowered async function and strip it off + // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9LAoKICBoMTogYXN5bmMgKCkgPT4ge30sCiAgLy8gY29tbWVudCBiZXR3ZWVuCiAgaDI6IGFzeW5jIChhKSA9PiB7fSwKfQ + // __async(this, null, function* + // __async(this, arguments, function* + // __async(this, [_0, _1], function* + if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) { + fnString = fnString.split(/__async\((?:this|null),/)[1]; + } + const match = fnString.match(/[^(]*\(([^)]*)/); + if (!match) { + return memoProps(fn, new Set()); + } + const args = splitByComma(match[1]); + if (!args.length) { + return memoProps(fn, new Set()); + } + const fixturesArgument = args[fixturesIndex]; + if (!fixturesArgument) { + return memoProps(fn, new Set()); + } + if (!(fixturesArgument[0] === "{" && fixturesArgument.endsWith("}"))) { + const ordinalArgument = ordinal(fixturesIndex + 1); + const error = new FixtureParseError(`The ${ordinalArgument} argument inside a fixture must use object destructuring pattern, e.g. ({ task } => {}). ` + `Instead, received "${fixturesArgument}".` + `${suiteHook ? ` If you used internal "suite" task as the ${ordinalArgument} argument previously, access it in the ${ordinal(fixturesIndex + 2)} argument instead.` : ""}`); + if (sourceError) { + error.stack = sourceError.stack?.replace(sourceError.message, error.message); + } + throw error; + } + const _first = fixturesArgument.slice(1, -1).replace(/\s/g, ""); + const props = splitByComma(_first).map((prop) => { + return prop.replace(/:.*|=.*/g, ""); + }); + const last = props.at(-1); + if (last && last.startsWith("...")) { + const error = new FixtureParseError(`Rest parameters are not supported in fixtures, received "${last}".`); + if (sourceError) { + error.stack = sourceError.stack?.replace(sourceError.message, error.message); + } + throw error; + } + return memoProps(fn, new Set(props)); +} +function splitByComma(s) { + const result = []; + const stack = []; + let start = 0; + for (let i = 0; i < s.length; i++) { + if (s[i] === "{" || s[i] === "[") { + stack.push(s[i] === "{" ? "}" : "]"); + } else if (s[i] === stack.at(-1)) { + stack.pop(); + } else if (!stack.length && s[i] === ",") { + const token = s.substring(start, i).trim(); + if (token) { + result.push(token); + } + start = i + 1; + } + } + const lastToken = s.substring(start).trim(); + if (lastToken) { + result.push(lastToken); + } + return result; +} + +let _test; +function setCurrentTest(test) { + _test = test; +} +function getCurrentTest() { + return _test; +} +const tests = []; +function addRunningTest(test) { + tests.push(test); + return () => { + tests.splice(tests.indexOf(test)); + }; +} +function getRunningTests() { + return tests; +} + +const kChainableContext = Symbol("kChainableContext"); +function getChainableContext(chainable) { + return chainable?.[kChainableContext]; +} +function createChainable(keys, fn, context) { + function create(context) { + const chain = function(...args) { + return fn.apply(context, args); + }; + Object.assign(chain, fn); + Object.defineProperty(chain, kChainableContext, { + value: { + withContext: () => chain.bind(context), + getFixtures: () => context.fixtures, + setContext: (key, value) => { + context[key] = value; + }, + mergeContext: (ctx) => { + Object.assign(context, ctx); + } + }, + enumerable: false + }); + for (const key of keys) { + Object.defineProperty(chain, key, { get() { + return create({ + ...context, + [key]: true + }); + } }); + } + return chain; + } + const chain = create(context ?? {}); + Object.defineProperty(chain, "fn", { + value: fn, + enumerable: false + }); + return chain; +} + +function getDefaultHookTimeout() { + return getRunner().config.hookTimeout; +} +const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT"); +const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE"); +const AROUND_TIMEOUT_KEY = Symbol.for("VITEST_AROUND_TIMEOUT"); +const AROUND_STACK_TRACE_KEY = Symbol.for("VITEST_AROUND_STACK_TRACE"); +function getBeforeHookCleanupCallback(hook, result, context) { + if (typeof result === "function") { + const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout(); + const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined; + return withTimeout(result, timeout, true, stackTraceError, (_, error) => { + if (context) { + abortContextSignal(context, error); + } + }); + } +} +/** +* Registers a callback function to be executed once before all tests within the current suite. +* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. +* +* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeAll to set up a database connection +* beforeAll(async () => { +* await database.connect(); +* }); +* ``` +*/ +function beforeAll(fn, timeout = getDefaultHookTimeout()) { + assertTypes(fn, "\"beforeAll\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + const context = getChainableContext(this); + return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(withSuiteFixtures("beforeAll", fn, context, stackTraceError), timeout, true, stackTraceError), { + [CLEANUP_TIMEOUT_KEY]: timeout, + [CLEANUP_STACK_TRACE_KEY]: stackTraceError + })); +} +/** +* Registers a callback function to be executed once after all tests within the current suite have completed. +* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. +* +* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterAll to close a database connection +* afterAll(async () => { +* await database.disconnect(); +* }); +* ``` +*/ +function afterAll(fn, timeout) { + assertTypes(fn, "\"afterAll\" callback", ["function"]); + const context = getChainableContext(this); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + return getCurrentSuite().on("afterAll", withTimeout(withSuiteFixtures("afterAll", fn, context, stackTraceError), timeout ?? getDefaultHookTimeout(), true, stackTraceError)); +} +/** +* Registers a callback function to be executed before each test within the current suite. +* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. +* +* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeEach to reset a database state +* beforeEach(async () => { +* await database.reset(); +* }); +* ``` +*/ +function beforeEach(fn, timeout = getDefaultHookTimeout()) { + assertTypes(fn, "\"beforeEach\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + const wrapper = (context, suite) => { + const fixtureResolver = withFixtures(fn, { suite }); + return fixtureResolver(context); + }; + return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), { + [CLEANUP_TIMEOUT_KEY]: timeout, + [CLEANUP_STACK_TRACE_KEY]: stackTraceError + })); +} +/** +* Registers a callback function to be executed after each test within the current suite has completed. +* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. +* +* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterEach to delete temporary files created during a test +* afterEach(async () => { +* await fileSystem.deleteTempFiles(); +* }); +* ``` +*/ +function afterEach(fn, timeout) { + assertTypes(fn, "\"afterEach\" callback", ["function"]); + const wrapper = (context, suite) => { + const fixtureResolver = withFixtures(fn, { suite }); + return fixtureResolver(context); + }; + return getCurrentSuite().on("afterEach", withTimeout(wrapper, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +} +/** +* Registers a callback function to be executed when a test fails within the current suite. +* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. +* +* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFailed to log failure details +* onTestFailed(({ errors }) => { +* console.log(`Test failed: ${test.name}`, errors); +* }); +* ``` +*/ +const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => { + test.onFailed ||= []; + test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +}); +/** +* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). +* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. +* +* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. +* +* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. +* +* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFinished for cleanup +* const db = await connectToDatabase(); +* onTestFinished(async () => { +* await db.disconnect(); +* }); +* ``` +*/ +const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => { + test.onFinished ||= []; + test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); +}); +/** +* Registers a callback function that wraps around all tests within the current suite. +* The callback receives a `runSuite` function that must be called to run the suite's tests. +* This hook is useful for scenarios where you need to wrap an entire suite in a context +* (e.g., starting a server, opening a database connection that all tests share). +* +* **Note:** When multiple `aroundAll` hooks are registered, they are nested inside each other. +* The first registered hook is the outermost wrapper. +* +* @param {Function} fn - The callback function that wraps the suite. Must call `runSuite()` to run the tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using aroundAll to wrap suite in a tracing span +* aroundAll(async (runSuite) => { +* await tracer.trace('test-suite', runSuite); +* }); +* ``` +* @example +* ```ts +* // Example of using aroundAll with fixtures +* aroundAll(async (runSuite, { db }) => { +* await db.transaction(() => runSuite()); +* }); +* ``` +*/ +function aroundAll(fn, timeout) { + assertTypes(fn, "\"aroundAll\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + const resolvedTimeout = timeout ?? getDefaultHookTimeout(); + const context = getChainableContext(this); + return getCurrentSuite().on("aroundAll", Object.assign(withSuiteFixtures("aroundAll", fn, context, stackTraceError, 1), { + [AROUND_TIMEOUT_KEY]: resolvedTimeout, + [AROUND_STACK_TRACE_KEY]: stackTraceError + })); +} +/** +* Registers a callback function that wraps around each test within the current suite. +* The callback receives a `runTest` function that must be called to run the test. +* This hook is useful for scenarios where you need to wrap tests in a context (e.g., database transactions). +* +* **Note:** When multiple `aroundEach` hooks are registered, they are nested inside each other. +* The first registered hook is the outermost wrapper. +* +* @param {Function} fn - The callback function that wraps the test. Must call `runTest()` to run the test. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using aroundEach to wrap tests in a database transaction +* aroundEach(async (runTest) => { +* await database.transaction(() => runTest()); +* }); +* ``` +* @example +* ```ts +* // Example of using aroundEach with fixtures +* aroundEach(async (runTest, { db }) => { +* await db.transaction(() => runTest()); +* }); +* ``` +*/ +function aroundEach(fn, timeout) { + assertTypes(fn, "\"aroundEach\" callback", ["function"]); + const stackTraceError = new Error("STACK_TRACE_ERROR"); + const resolvedTimeout = timeout ?? getDefaultHookTimeout(); + const wrapper = (runTest, context, suite) => { + const innerFn = (ctx) => fn(runTest, ctx, suite); + configureProps(innerFn, { + index: 1, + original: fn + }); + const fixtureResolver = withFixtures(innerFn, { suite }); + return fixtureResolver(context); + }; + return getCurrentSuite().on("aroundEach", Object.assign(wrapper, { + [AROUND_TIMEOUT_KEY]: resolvedTimeout, + [AROUND_STACK_TRACE_KEY]: stackTraceError + })); +} +function withSuiteFixtures(suiteHook, fn, context, stackTraceError, contextIndex = 0) { + return (...args) => { + const suite = args.at(-1); + const prefix = args.slice(0, -1); + const wrapper = (ctx) => fn(...prefix, ctx, suite); + configureProps(wrapper, { + index: contextIndex, + original: fn + }); + const fixtures = context?.getFixtures(); + const fileContext = fixtures?.getFileContext(suite.file); + const fixtured = withFixtures(wrapper, { + suiteHook, + fixtures, + context: fileContext, + stackTraceError + }); + return fixtured(); + }; +} +function getAroundHookTimeout(hook) { + return AROUND_TIMEOUT_KEY in hook && typeof hook[AROUND_TIMEOUT_KEY] === "number" ? hook[AROUND_TIMEOUT_KEY] : getDefaultHookTimeout(); +} +function getAroundHookStackTrace(hook) { + return AROUND_STACK_TRACE_KEY in hook && hook[AROUND_STACK_TRACE_KEY] instanceof Error ? hook[AROUND_STACK_TRACE_KEY] : undefined; +} +function createTestHook(name, handler) { + return (fn, timeout) => { + assertTypes(fn, `"${name}" callback`, ["function"]); + const current = getCurrentTest(); + if (!current) { + throw new Error(`Hook ${name}() can only be called inside a test`); + } + return handler(current, fn, timeout); + }; +} + +/** +* If any tasks been marked as `only`, mark all other tasks as `skip`. +*/ +function interpretTaskModes(file, namePattern, testLocations, testIds, testTagsFilter, onlyMode, parentIsOnly, allowOnly) { + const matchedLocations = []; + const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => { + const suiteIsOnly = parentIsOnly || suite.mode === "only"; + // Check if any tasks in this suite have `.only` - if so, only those should run + const hasSomeTasksOnly = onlyMode && suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); + suite.tasks.forEach((t) => { + // Check if either the parent suite or the task itself are marked as included + // If there are tasks with `.only` in this suite, only include those (not all tasks from describe.only) + const includeTask = hasSomeTasksOnly ? t.mode === "only" || t.type === "suite" && someTasksAreOnly(t) : suiteIsOnly || t.mode === "only"; + if (onlyMode) { + if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) { + // Don't skip this suite + 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"; + } + } + let hasLocationMatch = parentMatchedWithLocation; + // Match test location against provided locations, only run if present + // in `testLocations`. Note: if `includeTaskLocation` is not enabled, + // all test will be skipped. + if (testLocations !== undefined && testLocations.length !== 0) { + if (t.location && testLocations?.includes(t.location.line)) { + t.mode = "run"; + matchedLocations.push(t.location.line); + hasLocationMatch = true; + } else if (parentMatchedWithLocation) { + t.mode = "run"; + } else if (t.type === "test") { + t.mode = "skip"; + } + } + if (t.type === "test") { + if (namePattern && !getTaskFullName(t).match(namePattern)) { + t.mode = "skip"; + } + if (testIds && !testIds.includes(t.id)) { + t.mode = "skip"; + } + if (testTagsFilter && !testTagsFilter(t.tags || [])) { + t.mode = "skip"; + } + } else if (t.type === "suite") { + if (t.mode === "skip") { + skipAllTasks(t); + } else if (t.mode === "todo") { + todoAllTasks(t); + } else { + traverseSuite(t, includeTask, hasLocationMatch); + } + } + }); + // if all subtasks are skipped, mark as skip + if (suite.mode === "run" || suite.mode === "queued") { + if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) { + suite.mode = "skip"; + } + } + }; + traverseSuite(file, parentIsOnly, false); + const nonMatching = testLocations?.filter((loc) => !matchedLocations.includes(loc)); + if (nonMatching && nonMatching.length !== 0) { + const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`; + if (file.result === undefined) { + file.result = { + state: "fail", + errors: [] + }; + } + if (file.result.errors === undefined) { + file.result.errors = []; + } + file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`))); + } +} +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 === "queued") { + t.mode = "skip"; + if (t.type === "suite") { + skipAllTasks(t); + } + } + }); +} +function todoAllTasks(suite) { + suite.tasks.forEach((t) => { + if (t.mode === "run" || t.mode === "queued") { + t.mode = "todo"; + if (t.type === "suite") { + todoAllTasks(t); + } + } + }); +} +function checkAllowOnly(task, allowOnly) { + if (allowOnly) { + return; + } + const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error")); + task.result = { + state: "fail", + errors: [error] + }; +} +/* @__NO_SIDE_EFFECTS__ */ +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); + } + }); +} +function createFileTask(filepath, root, projectName, pool, viteEnvironment) { + const path = relative(root, filepath); + const file = { + id: generateFileHash(path, projectName), + name: path, + fullName: path, + type: "suite", + mode: "queued", + filepath, + tasks: [], + meta: Object.create(null), + projectName, + file: undefined, + pool, + viteEnvironment + }; + file.file = file; + return file; +} +/** +* Generate a unique ID for a file based on its path and project name +* @param file File relative to the root of the project to keep ID the same between different machines +* @param projectName The name of the test project +*/ +/* @__NO_SIDE_EFFECTS__ */ +function generateFileHash(file, projectName) { + return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`); +} +function findTestFileStackTrace(testFilePath, error) { + // first line is the error message + const lines = error.split("\n").slice(1); + for (const line of lines) { + const stack = parseSingleStack(line); + if (stack && stack.file === testFilePath) { + return stack; + } + } +} + +/** +* Return a function for running multiple async operations with limited concurrency. +*/ +function limitConcurrency(concurrency = Infinity) { + // The number of currently active + pending tasks. + let count = 0; + // The head and tail of the pending task queue, built using a singly linked list. + // Both head and tail are initially undefined, signifying an empty queue. + // They both become undefined again whenever there are no pending tasks. + let head; + let tail; + // A bookkeeping function executed whenever a task has been run to completion. + const finish = () => { + count--; + // Check if there are further pending tasks in the queue. + if (head) { + // Allow the next pending task to run and pop it from the queue. + head[0](); + head = head[1]; + // The head may now be undefined if there are no further pending tasks. + // In that case, set tail to undefined as well. + tail = head && tail; + } + }; + const acquire = () => { + let released = false; + const release = () => { + if (!released) { + released = true; + finish(); + } + }; + if (count++ < concurrency) { + return release; + } + return new Promise((resolve) => { + if (tail) { + // There are pending tasks, so append to the queue. + tail = tail[1] = [() => resolve(release)]; + } else { + // No other pending tasks, initialize the queue with a new tail and head. + head = tail = [() => resolve(release)]; + } + }); + }; + const limiterFn = (func, ...args) => { + function run(release) { + try { + const result = func(...args); + if (result instanceof Promise) { + return result.finally(release); + } + release(); + return Promise.resolve(result); + } catch (error) { + release(); + return Promise.reject(error); + } + } + const release = acquire(); + return release instanceof Promise ? release.then(run) : run(release); + }; + return Object.assign(limiterFn, { acquire }); +} + +/** +* Partition in tasks groups by consecutive concurrent +*/ +function partitionSuiteChildren(suite) { + let tasksGroup = []; + const tasksGroups = []; + for (const c of suite.tasks) { + if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) { + tasksGroup.push(c); + } else { + tasksGroups.push(tasksGroup); + tasksGroup = [c]; + } + } + if (tasksGroup.length > 0) { + tasksGroups.push(tasksGroup); + } + return tasksGroups; +} + +const filterMap = new WeakMap(); +/** +* @experimental +*/ +function matchesTags(testTags) { + const runner = getRunner(); + const tagsFilter = runner._currentSpecification?.testTagsFilter ?? runner.config.tagsFilter; + if (!tagsFilter) { + return true; + } + let tagsFilterPredicate = filterMap.get(tagsFilter); + if (!tagsFilterPredicate) { + tagsFilterPredicate = createTagsFilter(tagsFilter, runner.config.tags); + filterMap.set(tagsFilter, tagsFilterPredicate); + } + return tagsFilterPredicate(testTags); +} +function validateTags(config, tags) { + if (!config.strictTags) { + return; + } + const availableTags = new Set(config.tags.map((tag) => tag.name)); + for (const tag of tags) { + if (!availableTags.has(tag)) { + throw createNoTagsError(config.tags, tag); + } + } +} +function createNoTagsError(availableTags, tag, prefix = "tag") { + if (!availableTags.length) { + throw new Error(`The Vitest config does't define any "tags", cannot apply "${tag}" ${prefix} for this test. See: https://vitest.dev/guide/test-tags`); + } + throw new Error(`The ${prefix} "${tag}" is not defined in the configuration. Available tags are:\n${availableTags.map((t) => `- ${t.name}${t.description ? `: ${t.description}` : ""}`).join("\n")}`); +} +function createTagsFilter(tagsExpr, availableTags) { + const matchers = tagsExpr.map((expr) => parseTagsExpression(expr, availableTags)); + return (testTags) => { + return matchers.every((matcher) => matcher(testTags)); + }; +} +function parseTagsExpression(expr, availableTags) { + const tokens = tokenize(expr); + const stream = new TokenStream(tokens, expr); + const ast = parseOrExpression(stream, availableTags); + if (stream.peek().type !== "EOF") { + throw new Error(`Invalid tags expression: unexpected "${formatToken(stream.peek())}" in "${expr}"`); + } + return (tags) => evaluateNode(ast, tags); +} +function formatToken(token) { + switch (token.type) { + case "TAG": return token.value; + default: return formatTokenType(token.type); + } +} +function tokenize(expr) { + const tokens = []; + let i = 0; + while (i < expr.length) { + if (expr[i] === " " || expr[i] === " ") { + i++; + continue; + } + if (expr[i] === "(") { + tokens.push({ type: "LPAREN" }); + i++; + continue; + } + if (expr[i] === ")") { + tokens.push({ type: "RPAREN" }); + i++; + continue; + } + if (expr[i] === "!") { + tokens.push({ type: "NOT" }); + i++; + continue; + } + if (expr.slice(i, i + 2) === "&&") { + tokens.push({ type: "AND" }); + i += 2; + continue; + } + if (expr.slice(i, i + 2) === "||") { + tokens.push({ type: "OR" }); + i += 2; + continue; + } + if (/^and(?:\s|\)|$)/i.test(expr.slice(i))) { + tokens.push({ type: "AND" }); + i += 3; + continue; + } + if (/^or(?:\s|\)|$)/i.test(expr.slice(i))) { + tokens.push({ type: "OR" }); + i += 2; + continue; + } + if (/^not\s/i.test(expr.slice(i))) { + tokens.push({ type: "NOT" }); + i += 3; + continue; + } + let tag = ""; + while (i < expr.length && expr[i] !== " " && expr[i] !== " " && expr[i] !== "(" && expr[i] !== ")" && expr[i] !== "!" && expr[i] !== "&" && expr[i] !== "|") { + const remaining = expr.slice(i); + // Only treat and/or/not as operators if we're at the start of a tag (after whitespace) + // This allows tags like "demand", "editor", "cannot" to work correctly + if (tag === "" && (/^and(?:\s|\)|$)/i.test(remaining) || /^or(?:\s|\)|$)/i.test(remaining) || /^not\s/i.test(remaining))) { + break; + } + tag += expr[i]; + i++; + } + if (tag) { + tokens.push({ + type: "TAG", + value: tag + }); + } + } + tokens.push({ type: "EOF" }); + return tokens; +} +class TokenStream { + pos = 0; + constructor(tokens, expr) { + this.tokens = tokens; + this.expr = expr; + } + peek() { + return this.tokens[this.pos]; + } + next() { + return this.tokens[this.pos++]; + } + expect(type) { + const token = this.next(); + if (token.type !== type) { + if (type === "RPAREN" && token.type === "EOF") { + throw new Error(`Invalid tags expression: missing closing ")" in "${this.expr}"`); + } + throw new Error(`Invalid tags expression: expected "${formatTokenType(type)}" but got "${formatToken(token)}" in "${this.expr}"`); + } + return token; + } + unexpectedToken() { + const token = this.peek(); + if (token.type === "EOF") { + throw new Error(`Invalid tags expression: unexpected end of expression in "${this.expr}"`); + } + throw new Error(`Invalid tags expression: unexpected "${formatToken(token)}" in "${this.expr}"`); + } +} +function formatTokenType(type) { + switch (type) { + case "TAG": return "tag"; + case "AND": return "and"; + case "OR": return "or"; + case "NOT": return "not"; + case "LPAREN": return "("; + case "RPAREN": return ")"; + case "EOF": return "end of expression"; + } +} +function parseOrExpression(stream, availableTags) { + let left = parseAndExpression(stream, availableTags); + while (stream.peek().type === "OR") { + stream.next(); + const right = parseAndExpression(stream, availableTags); + left = { + type: "or", + left, + right + }; + } + return left; +} +function parseAndExpression(stream, availableTags) { + let left = parseUnaryExpression(stream, availableTags); + while (stream.peek().type === "AND") { + stream.next(); + const right = parseUnaryExpression(stream, availableTags); + left = { + type: "and", + left, + right + }; + } + return left; +} +function parseUnaryExpression(stream, availableTags) { + if (stream.peek().type === "NOT") { + stream.next(); + const operand = parseUnaryExpression(stream, availableTags); + return { + type: "not", + operand + }; + } + return parsePrimaryExpression(stream, availableTags); +} +function parsePrimaryExpression(stream, availableTags) { + const token = stream.peek(); + if (token.type === "LPAREN") { + stream.next(); + const expr = parseOrExpression(stream, availableTags); + stream.expect("RPAREN"); + return expr; + } + if (token.type === "TAG") { + stream.next(); + const tagValue = token.value; + const pattern = resolveTagPattern(tagValue, availableTags); + return { + type: "tag", + value: tagValue, + pattern + }; + } + stream.unexpectedToken(); +} +function createWildcardRegex(pattern) { + return new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`); +} +function resolveTagPattern(tagPattern, availableTags) { + if (tagPattern.includes("*")) { + const regex = createWildcardRegex(tagPattern); + const hasMatch = availableTags.some((tag) => regex.test(tag.name)); + if (!hasMatch) { + throw createNoTagsError(availableTags, tagPattern, "tag pattern"); + } + return regex; + } + if (!availableTags.length || !availableTags.some((tag) => tag.name === tagPattern)) { + throw createNoTagsError(availableTags, tagPattern, "tag pattern"); + } + return null; +} +function evaluateNode(node, tags) { + switch (node.type) { + case "tag": + if (node.pattern) { + return tags.some((tag) => node.pattern.test(tag)); + } + return tags.includes(node.value); + case "not": return !evaluateNode(node.operand, tags); + case "and": return evaluateNode(node.left, tags) && evaluateNode(node.right, tags); + case "or": return evaluateNode(node.left, tags) || evaluateNode(node.right, tags); + } +} + +function isTestCase(s) { + return s.type === "test"; +} +function getTests(suite) { + const tests = []; + const arraySuites = toArray(suite); + for (const s of arraySuites) { + if (isTestCase(s)) { + tests.push(s); + } else { + for (const task of s.tasks) { + if (isTestCase(task)) { + tests.push(task); + } else { + const taskTests = getTests(task); + for (const test of taskTests) { + tests.push(test); + } + } + } + } + } + return tests; +} +function getTasks(tasks = []) { + return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]); +} +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) => isTestCase(c) || hasTests(c))); +} +function hasFailed(suite) { + return toArray(suite).some((s) => s.result?.state === "fail" || s.type === "suite" && hasFailed(s.tasks)); +} +function getNames(task) { + const names = [task.name]; + let current = task; + while (current?.suite) { + current = current.suite; + if (current?.name) { + names.unshift(current.name); + } + } + if (current !== task.file) { + names.unshift(task.file.name); + } + return names; +} +function getFullName(task, separator = " > ") { + return getNames(task).join(separator); +} +function getTestName(task, separator = " > ") { + return getNames(task).slice(1).join(separator); +} +function createTaskName(names, separator = " > ") { + return names.filter((name) => name !== undefined).join(separator); +} + +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* suite('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* suite('String operations', () => { +* suite('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* suite('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +const suite = createSuite(); +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* test('should subtract two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +const test = createTest(function(name, optionsOrFn, optionsOrTest) { + if (getCurrentTest()) { + throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected."); + } + getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest); +}); +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* describe('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* describe('String operations', () => { +* describe('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* describe('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +const describe = suite; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* it('adds two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* it('subtracts two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +const it = test; +let runner; +let defaultSuite; +let currentTestFilepath; +function assert(condition, message) { + if (!condition) { + throw new Error(`Vitest failed to find ${message}. One of the following is possible:` + "\n- \"vitest\" is imported directly without running \"vitest\" command" + "\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)" + "\n- \"vitest\" is imported inside Vite / Vitest config file" + "\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n"); + } +} +function getDefaultSuite() { + assert(defaultSuite, "the default suite"); + return defaultSuite; +} +function getRunner() { + assert(runner, "the runner"); + return runner; +} +function createDefaultSuite(runner) { + const config = runner.config.sequence; + const options = {}; + if (config.concurrent != null) { + options.concurrent = config.concurrent; + } + const collector = suite("", options, () => {}); + // no parent suite for top-level tests + delete collector.suite; + return collector; +} +function clearCollectorContext(file, currentRunner) { + currentTestFilepath = file.filepath; + runner = currentRunner; + if (!defaultSuite) { + defaultSuite = createDefaultSuite(currentRunner); + } + defaultSuite.file = file; + collectorContext.tasks.length = 0; + defaultSuite.clear(); + collectorContext.currentSuite = defaultSuite; +} +function getCurrentSuite() { + const currentSuite = collectorContext.currentSuite || defaultSuite; + assert(currentSuite, "the current suite"); + return currentSuite; +} +function createSuiteHooks() { + return { + beforeAll: [], + afterAll: [], + beforeEach: [], + afterEach: [], + aroundEach: [], + aroundAll: [] + }; +} +const POSITIVE_INFINITY = Number.POSITIVE_INFINITY; +function parseArguments(optionsOrFn, timeoutOrTest) { + if (timeoutOrTest != null && typeof timeoutOrTest === "object") { + throw new TypeError(`Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.`); + } + let options = {}; + let fn; + // it('', () => {}, 1000) + if (typeof timeoutOrTest === "number") { + options = { timeout: timeoutOrTest }; + } else if (typeof optionsOrFn === "object") { + options = optionsOrFn; + } + if (typeof optionsOrFn === "function") { + if (typeof timeoutOrTest === "function") { + throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options."); + } + fn = optionsOrFn; + } else if (typeof timeoutOrTest === "function") { + fn = timeoutOrTest; + } + return { + options, + handler: fn + }; +} +// implementations +function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions) { + const tasks = []; + let suite; + initSuite(true); + const task = function(name = "", options = {}) { + const currentSuite = collectorContext.currentSuite?.suite; + const parentTask = currentSuite ?? collectorContext.currentSuite?.file; + const parentTags = parentTask?.tags || []; + const testTags = unique([...parentTags, ...toArray(options.tags)]); + const tagsOptions = testTags.map((tag) => { + const tagDefinition = runner.config.tags?.find((t) => t.name === tag); + if (!tagDefinition && runner.config.strictTags) { + throw createNoTagsError(runner.config.tags, tag); + } + return tagDefinition; + }).filter((r) => r != null).sort((tag1, tag2) => (tag2.priority ?? POSITIVE_INFINITY) - (tag1.priority ?? POSITIVE_INFINITY)).reduce((acc, tag) => { + const { name, description, priority, meta, ...options } = tag; + Object.assign(acc, options); + if (meta) { + acc.meta = Object.assign(acc.meta ?? Object.create(null), meta); + } + return acc; + }, {}); + const testOwnMeta = options.meta; + options = { + ...tagsOptions, + ...options + }; + const timeout = options.timeout ?? runner.config.testTimeout; + const parentMeta = currentSuite?.meta; + const tagMeta = tagsOptions.meta; + const testMeta = Object.create(null); + if (tagMeta) { + Object.assign(testMeta, tagMeta); + } + if (parentMeta) { + Object.assign(testMeta, parentMeta); + } + if (testOwnMeta) { + Object.assign(testMeta, testOwnMeta); + } + const task = { + id: "", + name, + fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name]), + fullTestName: createTaskName([currentSuite?.fullTestName, name]), + suite: currentSuite, + each: options.each, + fails: options.fails, + context: undefined, + type: "test", + file: currentSuite?.file ?? collectorContext.currentSuite?.file, + timeout, + retry: options.retry ?? runner.config.retry, + repeats: options.repeats, + mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run", + meta: testMeta, + annotations: [], + artifacts: [], + tags: testTags + }; + const handler = options.handler; + if (task.mode === "run" && !handler) { + task.mode = "todo"; + } + if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) { + task.concurrent = true; + } + task.shuffle = suiteOptions?.shuffle; + const context = createTestContext(task, runner); + // create test context + Object.defineProperty(task, "context", { + value: context, + enumerable: false + }); + setTestFixture(context, options.fixtures ?? new TestFixtures()); + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + const stackTraceError = new Error("STACK_TRACE_ERROR"); + Error.stackTraceLimit = limit; + if (handler) { + setFn(task, withTimeout(withCancel(withAwaitAsyncAssertions(withFixtures(handler, { context }), task), task.context.signal), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error))); + } + if (runner.config.includeTaskLocation) { + const error = stackTraceError.stack; + const stack = findTestFileStackTrace(currentTestFilepath, error); + if (stack) { + task.location = { + line: stack.line, + column: stack.column + }; + } + } + tasks.push(task); + return task; + }; + const test = createTest(function(name, optionsOrFn, timeoutOrTest) { + let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest); + // inherit repeats, retry, timeout from suite + if (typeof suiteOptions === "object") { + options = Object.assign({}, suiteOptions, options); + } + // inherit concurrent / sequential from suite + const concurrent = this.concurrent ?? (!this.sequential && options?.concurrent); + if (options.concurrent != null && concurrent != null) { + options.concurrent = concurrent; + } + const sequential = this.sequential ?? (!this.concurrent && options?.sequential); + if (options.sequential != null && sequential != null) { + options.sequential = sequential; + } + const test = task(formatName(name), { + ...this, + ...options, + handler + }); + test.type = "test"; + }); + const collector = { + type: "collector", + name, + mode, + suite, + options: suiteOptions, + test, + file: suite.file, + tasks, + collect, + task, + clear, + on: addHook + }; + function addHook(name, ...fn) { + getHooks(suite)[name].push(...fn); + } + function initSuite(includeLocation) { + if (typeof suiteOptions === "number") { + suiteOptions = { timeout: suiteOptions }; + } + const currentSuite = collectorContext.currentSuite?.suite; + const parentTask = currentSuite ?? collectorContext.currentSuite?.file; + const suiteTags = toArray(suiteOptions?.tags); + validateTags(runner.config, suiteTags); + suite = { + id: "", + type: "suite", + name, + fullName: createTaskName([currentSuite?.fullName ?? collectorContext.currentSuite?.file?.fullName, name]), + fullTestName: createTaskName([currentSuite?.fullTestName, name]), + suite: currentSuite, + mode, + each, + file: currentSuite?.file ?? collectorContext.currentSuite?.file, + shuffle: suiteOptions?.shuffle, + tasks: [], + meta: suiteOptions?.meta ?? Object.create(null), + concurrent: suiteOptions?.concurrent, + tags: unique([...parentTask?.tags || [], ...suiteTags]) + }; + if (runner && includeLocation && runner.config.includeTaskLocation) { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 15; + const error = new Error("stacktrace").stack; + Error.stackTraceLimit = limit; + const stack = findTestFileStackTrace(currentTestFilepath, error); + if (stack) { + suite.location = { + line: stack.line, + column: stack.column + }; + } + } + setHooks(suite, createSuiteHooks()); + } + function clear() { + tasks.length = 0; + initSuite(false); + } + async function collect(file) { + if (!file) { + throw new TypeError("File is required to collect tasks."); + } + if (factory) { + await runWithSuite(collector, () => factory(test)); + } + const allChildren = []; + for (const i of tasks) { + allChildren.push(i.type === "collector" ? await i.collect(file) : i); + } + suite.tasks = allChildren; + return suite; + } + collectTask(collector); + return collector; +} +function withAwaitAsyncAssertions(fn, task) { + return (async (...args) => { + const fnResult = await fn(...args); + // some async expect will be added to this array, in case user forget to await them + if (task.promises) { + const result = await Promise.allSettled(task.promises); + const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean); + if (errors.length) { + throw errors; + } + } + return fnResult; + }); +} +function createSuite() { + function suiteFn(name, factoryOrOptions, optionsOrFactory) { + if (getCurrentTest()) { + throw new Error("Calling the suite function inside test function is not allowed. It can be only called at the top level or inside another suite function."); + } + const currentSuite = collectorContext.currentSuite || defaultSuite; + let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory); + const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false; + const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false; + const { meta: parentMeta, ...parentOptions } = currentSuite?.options || {}; + // inherit options from current suite + options = { + ...parentOptions, + ...options + }; + const shuffle = this.shuffle ?? options.shuffle ?? currentSuite?.options?.shuffle ?? runner?.config.sequence.shuffle; + if (shuffle != null) { + options.shuffle = shuffle; + } + let mode = this.only ?? options.only ? "only" : this.skip ?? options.skip ? "skip" : this.todo ?? options.todo ? "todo" : "run"; + // passed as test(name), assume it's a "todo" + if (mode === "run" && !factory) { + mode = "todo"; + } + // inherit concurrent / sequential from suite + const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified; + const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified; + if (isConcurrent != null) { + options.concurrent = isConcurrent && !isSequential; + } + if (isSequential != null) { + options.sequential = isSequential && !isConcurrent; + } + if (parentMeta) { + options.meta = Object.assign(Object.create(null), parentMeta, options.meta); + } + return createSuiteCollector(formatName(name), factory, mode, this.each, options); + } + suiteFn.each = function(cases, ...args) { + const context = getChainableContext(this); + const suite = context.withContext(); + context.setContext("each", true); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + const fnFirst = typeof optionsOrFn === "function"; + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + if (fnFirst) { + if (arrayOnlyCases) { + suite(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); + } else { + suite(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); + } + } else { + if (arrayOnlyCases) { + suite(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); + } else { + suite(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); + } + } + }); + context.setContext("each", undefined); + }; + }; + suiteFn.for = function(cases, ...args) { + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const name_ = formatName(name); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + cases.forEach((item, idx) => { + suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : undefined); + }); + }; + }; + suiteFn.skipIf = (condition) => condition ? suite.skip : suite; + suiteFn.runIf = (condition) => condition ? suite : suite.skip; + return createChainable([ + "concurrent", + "sequential", + "shuffle", + "skip", + "only", + "todo" + ], suiteFn); +} +function createTaskCollector(fn) { + const taskFn = fn; + taskFn.each = function(cases, ...args) { + const context = getChainableContext(this); + const test = context.withContext(); + context.setContext("each", true); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const arrayOnlyCases = cases.every(Array.isArray); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + const fnFirst = typeof optionsOrFn === "function"; + cases.forEach((i, idx) => { + const items = Array.isArray(i) ? i : [i]; + if (fnFirst) { + if (arrayOnlyCases) { + test(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); + } else { + test(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); + } + } else { + if (arrayOnlyCases) { + test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); + } else { + test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); + } + } + }); + context.setContext("each", undefined); + }; + }; + taskFn.for = function(cases, ...args) { + const context = getChainableContext(this); + const test = context.withContext(); + if (Array.isArray(cases) && args.length) { + cases = formatTemplateString(cases, args); + } + return (name, optionsOrFn, fnOrOptions) => { + const _name = formatName(name); + const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); + cases.forEach((item, idx) => { + // monkey-patch handler to allow parsing fixture + const handlerWrapper = handler ? (ctx) => handler(item, ctx) : undefined; + if (handlerWrapper) { + configureProps(handlerWrapper, { + index: 1, + original: handler + }); + } + test(formatTitle(_name, toArray(item), idx), options, handlerWrapper); + }); + }; + }; + taskFn.skipIf = function(condition) { + return condition ? this.skip : this; + }; + taskFn.runIf = function(condition) { + return condition ? this : this.skip; + }; + /** + * Parse builder pattern arguments into a fixtures object. + * Handles both builder pattern (name, options?, value) and object syntax. + */ + function parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn) { + // Object syntax: just return as-is + if (typeof fixturesOrName !== "string") { + return fixturesOrName; + } + const fixtureName = fixturesOrName; + let fixtureOptions; + let fixtureValue; + if (maybeFn !== undefined) { + // (name, options, value) or (name, options, fn) + fixtureOptions = optionsOrFn; + fixtureValue = maybeFn; + } else { + // (name, value) or (name, fn) + // Check if optionsOrFn looks like fixture options (has scope or auto) + if (optionsOrFn !== null && typeof optionsOrFn === "object" && !Array.isArray(optionsOrFn) && TestFixtures.isFixtureOptions(optionsOrFn)) { + // (name, options) with no value - treat as empty object fixture + fixtureOptions = optionsOrFn; + fixtureValue = {}; + } else { + // (name, value) or (name, fn) + fixtureOptions = undefined; + fixtureValue = optionsOrFn; + } + } + // Function value: wrap with onCleanup pattern + if (typeof fixtureValue === "function") { + const builderFn = fixtureValue; + // Wrap builder pattern function (returns value) to use() pattern + const fixture = async (ctx, use) => { + let cleanup; + const onCleanup = (fn) => { + if (cleanup !== undefined) { + throw new Error(`onCleanup can only be called once per fixture. ` + `Define separate fixtures if you need multiple cleanup functions.`); + } + cleanup = fn; + }; + const value = await builderFn(ctx, { onCleanup }); + await use(value); + if (cleanup) { + await cleanup(); + } + }; + configureProps(fixture, { original: builderFn }); + if (fixtureOptions) { + return { [fixtureName]: [fixture, fixtureOptions] }; + } + return { [fixtureName]: fixture }; + } + // Non-function value: use directly + if (fixtureOptions) { + return { [fixtureName]: [fixtureValue, fixtureOptions] }; + } + return { [fixtureName]: fixtureValue }; + } + taskFn.override = function(fixturesOrName, optionsOrFn, maybeFn) { + const userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn); + getChainableContext(this).getFixtures().override(runner, userFixtures); + return this; + }; + taskFn.scoped = function(fixtures) { + console.warn(`test.scoped() is deprecated and will be removed in future versions. Please use test.override() instead.`); + return this.override(fixtures); + }; + taskFn.extend = function(fixturesOrName, optionsOrFn, maybeFn) { + const userFixtures = parseBuilderFixtures(fixturesOrName, optionsOrFn, maybeFn); + const fixtures = getChainableContext(this).getFixtures().extend(runner, userFixtures); + const _test = createTest(function(name, optionsOrFn, optionsOrTest) { + fn.call(this, formatName(name), optionsOrFn, optionsOrTest); + }); + getChainableContext(_test).mergeContext({ fixtures }); + return _test; + }; + taskFn.describe = suite; + taskFn.suite = suite; + taskFn.beforeEach = beforeEach; + taskFn.afterEach = afterEach; + taskFn.beforeAll = beforeAll; + taskFn.afterAll = afterAll; + taskFn.aroundEach = aroundEach; + taskFn.aroundAll = aroundAll; + const _test = createChainable([ + "concurrent", + "sequential", + "skip", + "only", + "todo", + "fails" + ], taskFn, { fixtures: new TestFixtures() }); + return _test; +} +function createTest(fn) { + return createTaskCollector(fn); +} +function formatName(name) { + return typeof name === "string" ? name : typeof name === "function" ? name.name || "" : String(name); +} +function formatTitle(template, items, idx) { + if (template.includes("%#") || template.includes("%$")) { + // '%#' match index of the test case + template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%"); + } + const count = template.split("%").length - 1; + if (template.includes("%f")) { + const placeholders = template.match(/%f/g) || []; + placeholders.forEach((_, i) => { + if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) { + // Replace the i-th occurrence of '%f' with '-%f' + let occurrence = 0; + template = template.replace(/%f/g, (match) => { + occurrence++; + return occurrence === i + 1 ? "-%f" : match; + }); + } + }); + } + const isObjectItem = isObject(items[0]); + function formatAttribute(s) { + return s.replace(/\$([$\w.]+)/g, (_, key) => { + const isArrayKey = /^\d+$/.test(key); + if (!isObjectItem && !isArrayKey) { + return `$${key}`; + } + const arrayElement = isArrayKey ? objectAttr(items, key) : undefined; + const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement; + return objDisplay(value, { truncate: runner?.config?.chaiConfig?.truncateThreshold }); + }); + } + let output = ""; + let i = 0; + handleRegexMatch( + template, + formatRegExp, + // format "%" + (match) => { + if (i < count) { + output += format(match[0], items[i++]); + } else { + output += match[0]; + } + }, + // format "$" + (nonMatch) => { + output += formatAttribute(nonMatch); + } + ); + return output; +} +// based on https://github.com/unocss/unocss/blob/2e74b31625bbe3b9c8351570749aa2d3f799d919/packages/autocomplete/src/parse.ts#L11 +function handleRegexMatch(input, regex, onMatch, onNonMatch) { + let lastIndex = 0; + for (const m of input.matchAll(regex)) { + if (lastIndex < m.index) { + onNonMatch(input.slice(lastIndex, m.index)); + } + onMatch(m); + lastIndex = m.index + m[0].length; + } + if (lastIndex < input.length) { + onNonMatch(input.slice(lastIndex)); + } +} +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; +} + +const now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; +const collectorContext = { + tasks: [], + currentSuite: null +}; +function collectTask(task) { + collectorContext.currentSuite?.tasks.push(task); +} +async function runWithSuite(suite, fn) { + const prev = collectorContext.currentSuite; + collectorContext.currentSuite = suite; + await fn(); + collectorContext.currentSuite = prev; +} +function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) { + if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) { + return fn; + } + const { setTimeout, clearTimeout } = getSafeTimers(); + // this function name is used to filter error in test/cli/test/fails.test.ts + return (function runWithTimeout(...args) { + const startTime = now$2(); + const runner = getRunner(); + runner._currentTaskStartTime = startTime; + runner._currentTaskTimeout = timeout; + return new Promise((resolve_, reject_) => { + const timer = setTimeout(() => { + clearTimeout(timer); + rejectTimeoutError(); + }, timeout); + // `unref` might not exist in browser + timer.unref?.(); + function rejectTimeoutError() { + const error = makeTimeoutError(isHook, timeout, stackTraceError); + onTimeout?.(args, error); + reject_(error); + } + function resolve(result) { + runner._currentTaskStartTime = undefined; + runner._currentTaskTimeout = undefined; + clearTimeout(timer); + // if test/hook took too long in microtask, setTimeout won't be triggered, + // but we still need to fail the test, see + // https://github.com/vitest-dev/vitest/issues/2920 + if (now$2() - startTime >= timeout) { + rejectTimeoutError(); + return; + } + resolve_(result); + } + function reject(error) { + runner._currentTaskStartTime = undefined; + runner._currentTaskTimeout = undefined; + clearTimeout(timer); + reject_(error); + } + // sync test/hook will be caught by try/catch + try { + const result = fn(...args); + // the result is a thenable, we don't wrap this in Promise.resolve + // to avoid creating new promises + if (typeof result === "object" && result != null && typeof result.then === "function") { + result.then(resolve, reject); + } else { + resolve(result); + } + } + // user sync test/hook throws an error +catch (error) { + reject(error); + } + }); + }); +} +function withCancel(fn, signal) { + return (function runWithCancel(...args) { + return new Promise((resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason)); + try { + const result = fn(...args); + if (typeof result === "object" && result != null && typeof result.then === "function") { + result.then(resolve, reject); + } else { + resolve(result); + } + } catch (error) { + reject(error); + } + }); + }); +} +const abortControllers = new WeakMap(); +function abortIfTimeout([context], error) { + if (context) { + abortContextSignal(context, error); + } +} +function abortContextSignal(context, error) { + const abortController = abortControllers.get(context); + abortController?.abort(error); +} +function createTestContext(test, runner) { + const context = function() { + throw new Error("done() callback is deprecated, use promise instead"); + }; + let abortController = abortControllers.get(context); + if (!abortController) { + abortController = new AbortController(); + abortControllers.set(context, abortController); + } + context.signal = abortController.signal; + context.task = test; + context.skip = (condition, note) => { + if (condition === false) { + // do nothing + return undefined; + } + test.result ??= { state: "skip" }; + test.result.pending = true; + throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note); + }; + context.annotate = ((message, type, attachment) => { + if (test.result && test.result.state !== "run") { + throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`); + } + const annotation = { + message, + type: typeof type === "object" || type === undefined ? "notice" : type + }; + const annotationAttachment = typeof type === "object" ? type : attachment; + if (annotationAttachment) { + annotation.attachment = annotationAttachment; + manageArtifactAttachment(annotation.attachment); + } + return recordAsyncOperation(test, recordArtifact(test, { + type: "internal:annotation", + annotation + }).then(async ({ annotation }) => { + if (!runner.onTestAnnotate) { + throw new Error(`Test runner doesn't support test annotations.`); + } + await finishSendTasksUpdate(runner); + const resolvedAnnotation = await runner.onTestAnnotate(test, annotation); + test.annotations.push(resolvedAnnotation); + return resolvedAnnotation; + })); + }); + context.onTestFailed = (handler, timeout) => { + test.onFailed ||= []; + test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); + }; + context.onTestFinished = (handler, timeout) => { + test.onFinished ||= []; + test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); + }; + return runner.extendTaskContext?.(context) || context; +} +function makeTimeoutError(isHook, timeout, stackTraceError) { + const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf 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 error = new Error(message); + if (stackTraceError?.stack) { + error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message); + } + return error; +} + +async function runSetupFiles(config, files, runner) { + if (config.sequence.setupFiles === "parallel") { + await Promise.all(files.map(async (fsPath) => { + await runner.importFile(fsPath, "setup"); + })); + } else { + for (const fsPath of files) { + await runner.importFile(fsPath, "setup"); + } + } +} + +const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; +async function collectTests(specs, runner) { + const files = []; + const config = runner.config; + const $ = runner.trace; + let defaultTagsFilter; + for (const spec of specs) { + const filepath = typeof spec === "string" ? spec : spec.filepath; + await $("collect_spec", { "code.file.path": filepath }, async () => { + runner._currentSpecification = typeof spec === "string" ? { filepath: spec } : spec; + const testLocations = typeof spec === "string" ? undefined : spec.testLocations; + const testNamePattern = typeof spec === "string" ? undefined : spec.testNamePattern; + const testIds = typeof spec === "string" ? undefined : spec.testIds; + const testTagsFilter = typeof spec === "object" && spec.testTagsFilter ? createTagsFilter(spec.testTagsFilter, config.tags) : undefined; + const fileTags = typeof spec === "string" ? [] : spec.fileTags || []; + const file = createFileTask(filepath, config.root, config.name, runner.pool, runner.viteEnvironment); + file.tags = fileTags; + file.shuffle = config.sequence.shuffle; + try { + validateTags(runner.config, fileTags); + runner.onCollectStart?.(file); + clearCollectorContext(file, runner); + const setupFiles = toArray(config.setupFiles); + if (setupFiles.length) { + const setupStart = now$1(); + await runSetupFiles(config, setupFiles, runner); + const setupEnd = now$1(); + file.setupDuration = setupEnd - setupStart; + } else { + file.setupDuration = 0; + } + const collectStart = now$1(); + await runner.importFile(filepath, "collect"); + const durations = runner.getImportDurations?.(); + if (durations) { + file.importDurations = durations; + } + const defaultTasks = await getDefaultSuite().collect(file); + const fileHooks = createSuiteHooks(); + mergeHooks(fileHooks, getHooks(defaultTasks)); + for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) { + if (c.type === "test" || c.type === "suite") { + file.tasks.push(c); + } else if (c.type === "collector") { + const suite = await c.collect(file); + if (suite.name || suite.tasks.length) { + mergeHooks(fileHooks, getHooks(suite)); + file.tasks.push(suite); + } + } else { + // check that types are exhausted + c; + } + } + setHooks(file, fileHooks); + file.collectDuration = now$1() - collectStart; + } catch (e) { + const errors = e instanceof AggregateError ? e.errors.map((e) => processError(e, runner.config.diffOptions)) : [processError(e, runner.config.diffOptions)]; + file.result = { + state: "fail", + errors + }; + const durations = runner.getImportDurations?.(); + if (durations) { + file.importDurations = durations; + } + } + calculateSuiteHash(file); + const hasOnlyTasks = someTasksAreOnly(file); + if (!testTagsFilter && !defaultTagsFilter && config.tagsFilter) { + defaultTagsFilter = createTagsFilter(config.tagsFilter, config.tags); + } + interpretTaskModes(file, testNamePattern ?? config.testNamePattern, testLocations, testIds, testTagsFilter ?? defaultTagsFilter, hasOnlyTasks, false, config.allowOnly); + if (file.mode === "queued") { + file.mode = "run"; + } + files.push(file); + }); + } + return files; +} +function mergeHooks(baseHooks, hooks) { + for (const _key in hooks) { + const key = _key; + baseHooks[key].push(...hooks[key]); + } + return baseHooks; +} + +const now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; +const unixNow = Date.now; +const { clearTimeout, setTimeout } = getSafeTimers(); +let limitMaxConcurrency; +/** +* Normalizes retry configuration to extract individual values. +* Handles both number and object forms. +*/ +function getRetryCount(retry) { + if (retry === undefined) { + return 0; + } + if (typeof retry === "number") { + return retry; + } + return retry.count ?? 0; +} +function getRetryDelay(retry) { + if (retry === undefined) { + return 0; + } + if (typeof retry === "number") { + return 0; + } + return retry.delay ?? 0; +} +function getRetryCondition(retry) { + if (retry === undefined) { + return undefined; + } + if (typeof retry === "number") { + return undefined; + } + return retry.condition; +} +function updateSuiteHookState(task, name, state, runner) { + if (!task.result) { + task.result = { state: "run" }; + } + if (!task.result.hooks) { + task.result.hooks = {}; + } + const suiteHooks = task.result.hooks; + if (suiteHooks) { + suiteHooks[name] = state; + let event = state === "run" ? "before-hook-start" : "before-hook-end"; + if (name === "afterAll" || name === "afterEach") { + event = state === "run" ? "after-hook-start" : "after-hook-end"; + } + updateTask(event, task, runner); + } +} +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 callTestHooks(runner, test, hooks, sequence) { + if (sequence === "stack") { + hooks = hooks.slice().reverse(); + } + if (!hooks.length) { + return; + } + const context = test.context; + const onTestFailed = test.context.onTestFailed; + const onTestFinished = test.context.onTestFinished; + context.onTestFailed = () => { + throw new Error(`Cannot call "onTestFailed" inside a test hook.`); + }; + context.onTestFinished = () => { + throw new Error(`Cannot call "onTestFinished" inside a test hook.`); + }; + if (sequence === "parallel") { + try { + await Promise.all(hooks.map((fn) => limitMaxConcurrency(() => fn(test.context)))); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + } else { + for (const fn of hooks) { + try { + await limitMaxConcurrency(() => fn(test.context)); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + } + } + context.onTestFailed = onTestFailed; + context.onTestFinished = onTestFinished; +} +async function callSuiteHook(suite, currentTask, name, runner, args) { + const sequence = runner.config.sequence.hooks; + const callbacks = []; + // stop at file level + const parentSuite = "filepath" in suite ? null : suite.suite || suite.file; + if (name === "beforeEach" && parentSuite) { + callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); + } + const hooks = getSuiteHooks(suite, name, sequence); + if (hooks.length > 0) { + updateSuiteHookState(currentTask, name, "run", runner); + } + async function runHook(hook) { + return limitMaxConcurrency(async () => { + return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined); + }); + } + if (sequence === "parallel") { + callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook)))); + } else { + for (const hook of hooks) { + callbacks.push(await runHook(hook)); + } + } + if (hooks.length > 0) { + updateSuiteHookState(currentTask, name, "pass", runner); + } + if (name === "afterEach" && parentSuite) { + callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); + } + return callbacks; +} +function getAroundEachHooks(suite) { + const hooks = []; + const parentSuite = "filepath" in suite ? null : suite.suite || suite.file; + if (parentSuite) { + hooks.push(...getAroundEachHooks(parentSuite)); + } + hooks.push(...getHooks(suite).aroundEach); + return hooks; +} +function getAroundAllHooks(suite) { + return getHooks(suite).aroundAll; +} +function makeAroundHookTimeoutError(hookName, phase, timeout, stackTraceError) { + const message = `The ${phase} phase of "${hookName}" hook timed out after ${timeout}ms.`; + const ErrorClass = phase === "setup" ? AroundHookSetupError : AroundHookTeardownError; + const error = new ErrorClass(message); + if (stackTraceError?.stack) { + error.stack = stackTraceError.stack.replace(stackTraceError.message, error.message); + } + return error; +} +async function callAroundHooks(runInner, options) { + const { hooks, hookName, callbackName, onTimeout, invokeHook } = options; + if (!hooks.length) { + await runInner(); + return; + } + const hookErrors = []; + const createTimeoutPromise = (timeout, phase, stackTraceError) => { + let timer; + let timedout = false; + const promise = new Promise((_, reject) => { + if (timeout > 0 && timeout !== Number.POSITIVE_INFINITY) { + timer = setTimeout(() => { + timedout = true; + const error = makeAroundHookTimeoutError(hookName, phase, timeout, stackTraceError); + onTimeout?.(error); + reject(error); + }, timeout); + timer.unref?.(); + } + }); + const clear = () => { + if (timer) { + clearTimeout(timer); + timer = undefined; + } + }; + return { + promise, + clear, + isTimedOut: () => timedout + }; + }; + const runNextHook = async (index) => { + if (index >= hooks.length) { + return runInner(); + } + const hook = hooks[index]; + const timeout = getAroundHookTimeout(hook); + const stackTraceError = getAroundHookStackTrace(hook); + let useCalled = false; + let setupTimeout; + let teardownTimeout; + let setupLimitConcurrencyRelease; + let teardownLimitConcurrencyRelease; + // Promise that resolves when use() is called (setup phase complete) + let resolveUseCalled; + const useCalledPromise = new Promise((resolve) => { + resolveUseCalled = resolve; + }); + // Promise that resolves when use() returns (inner hooks complete, teardown phase starts) + let resolveUseReturned; + const useReturnedPromise = new Promise((resolve) => { + resolveUseReturned = resolve; + }); + // Promise that resolves when hook completes + let resolveHookComplete; + let rejectHookComplete; + const hookCompletePromise = new Promise((resolve, reject) => { + resolveHookComplete = resolve; + rejectHookComplete = reject; + }); + const use = async () => { + // shouldn't continue to next (runTest/Suite or inner aroundEach/All) when aroundEach/All setup timed out. + if (setupTimeout.isTimedOut()) { + // we can throw any error to bail out. + // this error is not seen by end users since `runNextHook` already rejected with timeout error + // and this error is caught by `rejectHookComplete`. + throw new Error("__VITEST_INTERNAL_AROUND_HOOK_ABORT__"); + } + if (useCalled) { + throw new AroundHookMultipleCallsError(`The \`${callbackName}\` callback was called multiple times in the \`${hookName}\` hook. ` + `The callback can only be called once per hook.`); + } + useCalled = true; + resolveUseCalled(); + // Setup phase completed - clear setup timer + setupTimeout.clear(); + setupLimitConcurrencyRelease?.(); + // Run inner hooks - don't time this against our teardown timeout + await runNextHook(index + 1).catch((e) => hookErrors.push(e)); + teardownLimitConcurrencyRelease = await limitMaxConcurrency.acquire(); + // Start teardown timer after inner hooks complete - only times this hook's teardown code + teardownTimeout = createTimeoutPromise(timeout, "teardown", stackTraceError); + // Signal that use() is returning (teardown phase starting) + resolveUseReturned(); + }; + setupLimitConcurrencyRelease = await limitMaxConcurrency.acquire(); + // Start setup timeout + setupTimeout = createTimeoutPromise(timeout, "setup", stackTraceError); + (async () => { + try { + await invokeHook(hook, use); + if (!useCalled) { + throw new AroundHookSetupError(`The \`${callbackName}\` callback was not called in the \`${hookName}\` hook. ` + `Make sure to call \`${callbackName}\` to run the ${hookName === "aroundEach" ? "test" : "suite"}.`); + } + resolveHookComplete(); + } catch (error) { + rejectHookComplete(error); + } finally { + setupLimitConcurrencyRelease?.(); + teardownLimitConcurrencyRelease?.(); + } + })(); + // Wait for either: use() to be called OR hook to complete (error) OR setup timeout + try { + await Promise.race([ + useCalledPromise, + hookCompletePromise, + setupTimeout.promise + ]); + } finally { + setupLimitConcurrencyRelease?.(); + setupTimeout.clear(); + } + // Wait for use() to return (inner hooks complete) OR hook to complete (error during inner hooks) + await Promise.race([useReturnedPromise, hookCompletePromise]); + // Now teardownTimeout is guaranteed to be set + // Wait for hook to complete (teardown) OR teardown timeout + try { + await Promise.race([hookCompletePromise, teardownTimeout?.promise]); + } finally { + teardownLimitConcurrencyRelease?.(); + teardownTimeout?.clear(); + } + }; + await runNextHook(0).catch((e) => hookErrors.push(e)); + if (hookErrors.length > 0) { + throw hookErrors; + } +} +async function callAroundAllHooks(suite, runSuiteInner) { + await callAroundHooks(runSuiteInner, { + hooks: getAroundAllHooks(suite), + hookName: "aroundAll", + callbackName: "runSuite()", + invokeHook: (hook, use) => hook(use, suite) + }); +} +async function callAroundEachHooks(suite, test, runTest) { + await callAroundHooks( + // Take checkpoint right before runTest - at this point all aroundEach fixtures + // have been resolved, so we can correctly identify which fixtures belong to + // aroundEach (before checkpoint) vs inside runTest (after checkpoint) + () => runTest(getFixtureCleanupCount(test.context)), + { + hooks: getAroundEachHooks(suite), + hookName: "aroundEach", + callbackName: "runTest()", + onTimeout: (error) => abortContextSignal(test.context, error), + invokeHook: (hook, use) => hook(use, test.context, suite) + } + ); +} +const packs = new Map(); +const eventsPacks = []; +const pendingTasksUpdates = []; +function sendTasksUpdate(runner) { + if (packs.size) { + const taskPacks = Array.from(packs).map(([id, task]) => { + return [ + id, + task[0], + task[1] + ]; + }); + const p = runner.onTaskUpdate?.(taskPacks, eventsPacks); + if (p) { + pendingTasksUpdates.push(p); + // remove successful promise to not grow array indefinitely, + // but keep rejections so finishSendTasksUpdate can handle them + p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {}); + } + eventsPacks.length = 0; + packs.clear(); + } +} +async function finishSendTasksUpdate(runner) { + sendTasksUpdate(runner); + await Promise.all(pendingTasksUpdates); +} +function throttle(fn, ms) { + let last = 0; + let pendingCall; + return function call(...args) { + const now = unixNow(); + if (now - last > ms) { + last = now; + clearTimeout(pendingCall); + pendingCall = undefined; + return fn.apply(this, args); + } + // Make sure fn is still called even if there are no further calls + pendingCall ??= setTimeout(() => call.bind(this)(...args), ms); + }; +} +// throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS +const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100); +function updateTask(event, task, runner) { + eventsPacks.push([ + task.id, + event, + undefined + ]); + packs.set(task.id, [task.result, task.meta]); + sendTasksUpdateThrottled(runner); +} +async function callCleanupHooks(runner, cleanups) { + const sequence = runner.config.sequence.hooks; + if (sequence === "stack") { + cleanups = cleanups.slice().reverse(); + } + if (sequence === "parallel") { + await Promise.all(cleanups.map(async (fn) => { + if (typeof fn !== "function") { + return; + } + await limitMaxConcurrency(() => fn()); + })); + } else { + for (const fn of cleanups) { + if (typeof fn !== "function") { + continue; + } + await limitMaxConcurrency(() => fn()); + } + } +} +/** +* Determines if a test should be retried based on its retryCondition configuration +*/ +function passesRetryCondition(test, errors) { + const condition = getRetryCondition(test.retry); + if (!errors || errors.length === 0) { + return false; + } + if (!condition) { + return true; + } + const error = errors[errors.length - 1]; + if (condition instanceof RegExp) { + return condition.test(error.message || ""); + } else if (typeof condition === "function") { + return condition(error); + } + return false; +} +async function runTest(test, runner) { + await runner.onBeforeRunTask?.(test); + if (test.mode !== "run" && test.mode !== "queued") { + updateTask("test-prepare", test, runner); + updateTask("test-finished", test, runner); + return; + } + if (test.result?.state === "fail") { + // should not be possible to get here, I think this is just copy pasted from suite + // TODO: maybe someone fails tests in `beforeAll` hooks? + // https://github.com/vitest-dev/vitest/pull/7069 + updateTask("test-failed-early", test, runner); + return; + } + const start = now(); + test.result = { + state: "run", + startTime: unixNow(), + retryCount: 0 + }; + updateTask("test-prepare", test, runner); + const cleanupRunningTest = addRunningTest(test); + setCurrentTest(test); + const suite = test.suite || test.file; + const $ = runner.trace; + const repeats = test.repeats ?? 0; + for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) { + const retry = getRetryCount(test.retry); + for (let retryCount = 0; retryCount <= retry; retryCount++) { + let beforeEachCleanups = []; + // fixtureCheckpoint is passed by callAroundEachHooks - it represents the count + // of fixture cleanup functions AFTER all aroundEach fixtures have been resolved + // but BEFORE the test runs. This allows us to clean up only fixtures created + // inside runTest while preserving aroundEach fixtures for teardown. + await callAroundEachHooks(suite, test, async (fixtureCheckpoint) => { + try { + await runner.onBeforeTryTask?.(test, { + retry: retryCount, + repeats: repeatCount + }); + test.result.repeatCount = repeatCount; + beforeEachCleanups = await $("test.beforeEach", () => callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite])); + if (runner.runTask) { + await $("test.callback", () => limitMaxConcurrency(() => runner.runTask(test))); + } else { + const fn = getFn(test); + if (!fn) { + throw new Error("Test function is not found. Did you add it using `setFn`?"); + } + await $("test.callback", () => limitMaxConcurrency(() => fn())); + } + await runner.onAfterTryTask?.(test, { + retry: retryCount, + repeats: repeatCount + }); + if (test.result.state !== "fail") { + test.result.state = "pass"; + } + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + try { + await runner.onTaskFinished?.(test); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + try { + await $("test.afterEach", () => callSuiteHook(suite, test, "afterEach", runner, [test.context, suite])); + if (beforeEachCleanups.length) { + await $("test.cleanup", () => callCleanupHooks(runner, beforeEachCleanups)); + } + // Only clean up fixtures created inside runTest (after the checkpoint) + // Fixtures created for aroundEach will be cleaned up after aroundEach teardown + await callFixtureCleanupFrom(test.context, fixtureCheckpoint); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + if (test.onFinished?.length) { + await $("test.onFinished", () => callTestHooks(runner, test, test.onFinished, "stack")); + } + if (test.result.state === "fail" && test.onFailed?.length) { + await $("test.onFailed", () => callTestHooks(runner, test, test.onFailed, runner.config.sequence.hooks)); + } + test.onFailed = undefined; + test.onFinished = undefined; + await runner.onAfterRetryTask?.(test, { + retry: retryCount, + repeats: repeatCount + }); + }).catch((error) => { + failTask(test.result, error, runner.config.diffOptions); + }); + // Clean up fixtures that were created for aroundEach (before the checkpoint) + // This runs after aroundEach teardown has completed + try { + await callFixtureCleanup(test.context); + } catch (e) { + failTask(test.result, e, runner.config.diffOptions); + } + // skipped with new PendingError + if (test.result?.pending || test.result?.state === "skip") { + test.mode = "skip"; + test.result = { + state: "skip", + note: test.result?.note, + pending: true, + duration: now() - start + }; + updateTask("test-finished", test, runner); + setCurrentTest(undefined); + cleanupRunningTest(); + return; + } + if (test.result.state === "pass") { + break; + } + if (retryCount < retry) { + const shouldRetry = passesRetryCondition(test, test.result.errors); + if (!shouldRetry) { + break; + } + test.result.state = "run"; + test.result.retryCount = (test.result.retryCount ?? 0) + 1; + const delay = getRetryDelay(test.retry); + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + // update retry info + updateTask("test-retried", test, runner); + } + } + // if test is marked to be failed, flip the result + if (test.fails) { + if (test.result.state === "pass") { + const error = processError(new Error("Expect test to fail")); + test.result.state = "fail"; + test.result.errors = [error]; + } else { + test.result.state = "pass"; + test.result.errors = undefined; + } + } + cleanupRunningTest(); + setCurrentTest(undefined); + test.result.duration = now() - start; + await runner.onAfterRunTask?.(test); + updateTask("test-finished", test, runner); +} +function failTask(result, err, diffOptions) { + if (err instanceof PendingError) { + result.state = "skip"; + result.note = err.note; + result.pending = true; + return; + } + if (err instanceof TestRunAbortError) { + result.state = "skip"; + result.note = err.message; + return; + } + result.state = "fail"; + const errors = Array.isArray(err) ? err : [err]; + for (const e of errors) { + const errors = e instanceof AggregateError ? e.errors.map((e) => processError(e, diffOptions)) : [processError(e, diffOptions)]; + result.errors ??= []; + result.errors.push(...errors); + } +} +function markTasksAsSkipped(suite, runner) { + suite.tasks.forEach((t) => { + t.mode = "skip"; + t.result = { + ...t.result, + state: "skip" + }; + updateTask("test-finished", t, runner); + if (t.type === "suite") { + markTasksAsSkipped(t, runner); + } + }); +} +function markPendingTasksAsSkipped(suite, runner, note) { + suite.tasks.forEach((t) => { + if (!t.result || t.result.state === "run") { + t.mode = "skip"; + t.result = { + ...t.result, + state: "skip", + note + }; + updateTask("test-cancel", t, runner); + } + if (t.type === "suite") { + markPendingTasksAsSkipped(t, runner, note); + } + }); +} +async function runSuite(suite, runner) { + await runner.onBeforeRunSuite?.(suite); + if (suite.result?.state === "fail") { + markTasksAsSkipped(suite, runner); + // failed during collection + updateTask("suite-failed-early", suite, runner); + return; + } + const start = now(); + const mode = suite.mode; + suite.result = { + state: mode === "skip" || mode === "todo" ? mode : "run", + startTime: unixNow() + }; + const $ = runner.trace; + updateTask("suite-prepare", suite, runner); + let beforeAllCleanups = []; + if (suite.mode === "skip") { + suite.result.state = "skip"; + updateTask("suite-finished", suite, runner); + } else if (suite.mode === "todo") { + suite.result.state = "todo"; + updateTask("suite-finished", suite, runner); + } else { + let suiteRan = false; + try { + await callAroundAllHooks(suite, async () => { + suiteRan = true; + try { + // beforeAll + try { + beforeAllCleanups = await $("suite.beforeAll", () => callSuiteHook(suite, suite, "beforeAll", runner, [suite])); + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + markTasksAsSkipped(suite, runner); + return; + } + // run suite children + if (runner.runSuite) { + await runner.runSuite(suite); + } else { + for (let tasksGroup of partitionSuiteChildren(suite)) { + if (tasksGroup[0].concurrent === true) { + await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner))); + } else { + const { sequence } = runner.config; + if (suite.shuffle) { + // run describe block independently from tests + 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, runner); + } + } + } + } + } finally { + // afterAll runs even if beforeAll or suite children fail + try { + await $("suite.afterAll", () => callSuiteHook(suite, suite, "afterAll", runner, [suite])); + if (beforeAllCleanups.length) { + await $("suite.cleanup", () => callCleanupHooks(runner, beforeAllCleanups)); + } + if (suite.file === suite) { + const contexts = TestFixtures.getFileContexts(suite.file); + await Promise.all(contexts.map((context) => callFixtureCleanup(context))); + } + } catch (e) { + failTask(suite.result, e, runner.config.diffOptions); + } + } + }); + } catch (e) { + // mark tasks as skipped if aroundAll failed before the suite callback was executed + if (!suiteRan) { + markTasksAsSkipped(suite, runner); + } + failTask(suite.result, e, runner.config.diffOptions); + } + if (suite.mode === "run" || suite.mode === "queued") { + if (!runner.config.passWithNoTests && !hasTests(suite)) { + suite.result.state = "fail"; + if (!suite.result.errors?.length) { + const error = processError(new Error(`No test found in suite ${suite.name}`)); + suite.result.errors = [error]; + } + } else if (hasFailed(suite)) { + suite.result.state = "fail"; + } else { + suite.result.state = "pass"; + } + } + suite.result.duration = now() - start; + await runner.onAfterRunSuite?.(suite); + updateTask("suite-finished", suite, runner); + } +} +async function runSuiteChild(c, runner) { + const $ = runner.trace; + if (c.type === "test") { + return $("run.test", { + "vitest.test.id": c.id, + "vitest.test.name": c.name, + "vitest.test.mode": c.mode, + "vitest.test.timeout": c.timeout, + "code.file.path": c.file.filepath, + "code.line.number": c.location?.line, + "code.column.number": c.location?.column + }, () => runTest(c, runner)); + } else if (c.type === "suite") { + return $("run.suite", { + "vitest.suite.id": c.id, + "vitest.suite.name": c.name, + "vitest.suite.mode": c.mode, + "code.file.path": c.file.filepath, + "code.line.number": c.location?.line, + "code.column.number": c.location?.column + }, () => runSuite(c, runner)); + } +} +async function runFiles(files, runner) { + limitMaxConcurrency ??= limitConcurrency(runner.config.maxConcurrency); + for (const file of files) { + if (!file.tasks.length && !runner.config.passWithNoTests) { + if (!file.result?.errors?.length) { + const error = processError(new Error(`No test suite found in file ${file.filepath}`)); + file.result = { + state: "fail", + errors: [error] + }; + } + } + await runner.trace("run.spec", { + "code.file.path": file.filepath, + "vitest.suite.tasks.length": file.tasks.length + }, () => runSuite(file, runner)); + } +} +const workerRunners = new WeakSet(); +function defaultTrace(_, attributes, cb) { + if (typeof attributes === "function") { + return attributes(); + } + return cb(); +} +async function startTests(specs, runner) { + runner.trace ??= defaultTrace; + const cancel = runner.cancel?.bind(runner); + // Ideally, we need to have an event listener for this, but only have a runner here. + // Adding another onCancel felt wrong (maybe it needs to be refactored) + runner.cancel = (reason) => { + // We intentionally create only one error since there is only one test run that can be cancelled + const error = new TestRunAbortError("The test run was aborted by the user.", reason); + getRunningTests().forEach((test) => { + abortContextSignal(test.context, error); + markPendingTasksAsSkipped(test.file, runner, error.message); + }); + return cancel?.(reason); + }; + if (!workerRunners.has(runner)) { + runner.onCleanupWorkerContext?.(async () => { + await Promise.all([...TestFixtures.getWorkerContexts()].map((context) => callFixtureCleanup(context))).finally(() => { + TestFixtures.clearDefinitions(); + }); + }); + workerRunners.add(runner); + } + try { + const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); + await runner.onBeforeCollect?.(paths); + const files = await collectTests(specs, runner); + await runner.onCollected?.(files); + await runner.onBeforeRunFiles?.(files); + await runFiles(files, runner); + await runner.onAfterRunFiles?.(files); + await finishSendTasksUpdate(runner); + return files; + } finally { + runner.cancel = cancel; + } +} +async function publicCollect(specs, runner) { + runner.trace ??= defaultTrace; + const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); + await runner.onBeforeCollect?.(paths); + const files = await collectTests(specs, runner); + await runner.onCollected?.(files); + return files; +} + +/** +* @experimental +* @advanced +* +* Records a custom test artifact during test execution. +* +* This function allows you to attach structured data, files, or metadata to a test. +* +* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. +* +* **Note:** artifacts must be recorded before the task is reported. Any artifacts recorded after that will not be included in the task. +* +* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests +* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} +* +* @returns A promise that resolves to the recorded artifact with location injected +* +* @throws {Error} If the test runner doesn't support artifacts +* +* @example +* ```ts +* // In a custom assertion +* async function toHaveValidSchema(this: MatcherState, actual: unknown) { +* const validation = validateSchema(actual) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:schema-validation', +* passed: validation.valid, +* errors: validation.errors, +* }) +* +* return { pass: validation.valid, message: () => '...' } +* } +* ``` +*/ +async function recordArtifact(task, artifact) { + const runner = getRunner(); + const stack = findTestFileStackTrace(task.file.filepath, new Error("STACK_TRACE").stack); + if (stack) { + artifact.location = { + file: stack.file, + line: stack.line, + column: stack.column + }; + if (artifact.type === "internal:annotation") { + artifact.annotation.location = artifact.location; + } + } + if (Array.isArray(artifact.attachments)) { + for (const attachment of artifact.attachments) { + manageArtifactAttachment(attachment); + } + } + // annotations won't resolve as artifacts for backwards compatibility until next major + if (artifact.type === "internal:annotation") { + return artifact; + } + if (!runner.onTestArtifactRecord) { + throw new Error(`Test runner doesn't support test artifacts.`); + } + await finishSendTasksUpdate(runner); + const resolvedArtifact = await runner.onTestArtifactRecord(task, artifact); + task.artifacts.push(resolvedArtifact); + return resolvedArtifact; +} +const table = []; +for (let i = 65; i < 91; i++) { + table.push(String.fromCharCode(i)); +} +for (let i = 97; i < 123; i++) { + table.push(String.fromCharCode(i)); +} +for (let i = 0; i < 10; i++) { + table.push(i.toString(10)); +} +table.push("+", "/"); +function encodeUint8Array(bytes) { + let base64 = ""; + const len = bytes.byteLength; + for (let i = 0; i < len; i += 3) { + if (len === i + 1) { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4; + base64 += table[a]; + base64 += table[b]; + base64 += "=="; + } else if (len === i + 2) { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; + const c = (bytes[i + 1] & 15) << 2; + base64 += table[a]; + base64 += table[b]; + base64 += table[c]; + base64 += "="; + } else { + const a = (bytes[i] & 252) >> 2; + const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; + const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6; + const d = bytes[i + 2] & 63; + base64 += table[a]; + base64 += table[b]; + base64 += table[c]; + base64 += table[d]; + } + } + return base64; +} +/** +* Records an async operation associated with a test task. +* +* This function tracks promises that should be awaited before a test completes. +* The promise is automatically removed from the test's promise list once it settles. +*/ +function recordAsyncOperation(test, promise) { + // if promise is explicitly awaited, remove it from the list + promise = promise.finally(() => { + if (!test.promises) { + return; + } + const index = test.promises.indexOf(promise); + if (index !== -1) { + test.promises.splice(index, 1); + } + }); + // record promise + if (!test.promises) { + test.promises = []; + } + test.promises.push(promise); + return promise; +} +/** +* Validates and prepares a test attachment for serialization. +* +* This function ensures attachments have either `body` or `path` set (but not both), and converts `Uint8Array` bodies to base64-encoded strings for easier serialization. +* +* @param attachment - The attachment to validate and prepare +* +* @throws {TypeError} If neither `body` nor `path` is provided +* @throws {TypeError} If both `body` and `path` are provided +*/ +function manageArtifactAttachment(attachment) { + if (attachment.body == null && !attachment.path) { + throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`); + } + if (attachment.body && attachment.path) { + throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`); + } + if (attachment.path && attachment.bodyEncoding) { + throw new TypeError(`Test attachment with "path" should not have "bodyEncoding" specified.`); + } + // convert to a string so it's easier to serialise + if (attachment.body instanceof Uint8Array) { + attachment.body = encodeUint8Array(attachment.body); + } + if (attachment.body != null) { + attachment.bodyEncoding ??= "base64"; + } +} + +export { createTagsFilter as A, createTaskName as B, findTestFileStackTrace as C, generateFileHash as D, generateHash as E, getFullName as F, getNames as G, getSuites as H, getTasks as I, getTestName as J, getTests as K, hasFailed as L, hasTests as M, interpretTaskModes as N, isTestCase as O, limitConcurrency as P, matchesTags as Q, partitionSuiteChildren as R, someTasksAreOnly as S, validateTags as T, afterAll as a, afterEach as b, aroundAll as c, aroundEach as d, beforeAll as e, beforeEach as f, createTaskCollector as g, describe as h, getCurrentSuite as i, getCurrentTest as j, getFn as k, getHooks as l, it as m, onTestFinished as n, onTestFailed as o, publicCollect as p, setHooks as q, recordArtifact as r, setFn as s, startTests as t, suite as u, test as v, updateTask as w, calculateSuiteHash as x, createChainable as y, createFileTask as z }; diff --git a/node_modules/@vitest/runner/dist/index.d.ts b/node_modules/@vitest/runner/dist/index.d.ts new file mode 100644 index 000000000..b52deed9e --- /dev/null +++ b/node_modules/@vitest/runner/dist/index.d.ts @@ -0,0 +1,179 @@ +import { T as TestArtifact, a as Test, S as Suite, b as SuiteHooks, F as FileSpecification, V as VitestRunner, c as File, d as TaskUpdateEvent, e as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-Bh0IjN67.js'; +export { A as AfterAllListener, i as AfterEachListener, j as AroundAllListener, k as AroundEachListener, B as BeforeAllListener, l as BeforeEachListener, C as CancelReason, m as FailureScreenshotArtifact, n as Fixture, o as FixtureFn, p as FixtureOptions, q as Fixtures, I as ImportDuration, r as InferFixturesTypes, O as OnTestFailedHandler, s as OnTestFinishedHandler, R as Retry, t as RunMode, u as RuntimeContext, v as SequenceHooks, w as SequenceSetupFiles, x as SerializableRetry, y as SuiteFactory, z as SuiteOptions, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, W as TestArtifactBase, X as TestArtifactLocation, Y as TestArtifactRegistry, Z as TestAttachment, _ as TestContext, $ as TestFunction, a0 as TestOptions, a1 as TestTagDefinition, a2 as TestTags, a3 as Use, a4 as VisualRegressionArtifact, a5 as VitestRunnerConfig, a6 as VitestRunnerConstructor, a7 as VitestRunnerImportSource, a8 as afterAll, a9 as afterEach, aa as aroundAll, ab as aroundEach, ac as beforeAll, ad as beforeEach, ae as onTestFailed, af as onTestFinished } from './tasks.d-Bh0IjN67.js'; +import { Awaitable } from '@vitest/utils'; +import '@vitest/utils/diff'; + +/** +* @experimental +* @advanced +* +* Records a custom test artifact during test execution. +* +* This function allows you to attach structured data, files, or metadata to a test. +* +* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. +* +* **Note:** artifacts must be recorded before the task is reported. Any artifacts recorded after that will not be included in the task. +* +* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests +* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} +* +* @returns A promise that resolves to the recorded artifact with location injected +* +* @throws {Error} If the test runner doesn't support artifacts +* +* @example +* ```ts +* // In a custom assertion +* async function toHaveValidSchema(this: MatcherState, actual: unknown) { +* const validation = validateSchema(actual) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:schema-validation', +* passed: validation.valid, +* errors: validation.errors, +* }) +* +* return { pass: validation.valid, message: () => '...' } +* } +* ``` +*/ +declare function recordArtifact(task: Test, artifact: Artifact): Promise; + +declare function setFn(key: Test, fn: () => Awaitable): void; +declare function getFn(key: Task): () => Awaitable; +declare function setHooks(key: Suite, hooks: SuiteHooks): void; +declare function getHooks(key: Suite): SuiteHooks; + +declare function updateTask(event: TaskUpdateEvent, task: Task, runner: VitestRunner): void; +declare function startTests(specs: string[] | FileSpecification[], runner: VitestRunner): Promise; +declare function publicCollect(specs: string[] | FileSpecification[], runner: VitestRunner): Promise; + +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* suite('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* suite('String operations', () => { +* suite('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* suite('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +declare const suite: SuiteAPI; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* test('should subtract two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +declare const test: TestAPI; +/** +* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. +* Suites can contain both tests and other suites, enabling complex test structures. +* +* @param {string} name - The name of the suite, used for identification and reporting. +* @param {Function} fn - A function that defines the tests and suites within this suite. +* @example +* ```ts +* // Define a suite with two tests +* describe('Math operations', () => { +* test('should add two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* +* test('should subtract two numbers', () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* }); +* ``` +* @example +* ```ts +* // Define nested suites +* describe('String operations', () => { +* describe('Trimming', () => { +* test('should trim whitespace from start and end', () => { +* expect(' hello '.trim()).toBe('hello'); +* }); +* }); +* +* describe('Concatenation', () => { +* test('should concatenate two strings', () => { +* expect('hello' + ' ' + 'world').toBe('hello world'); +* }); +* }); +* }); +* ``` +*/ +declare const describe: SuiteAPI; +/** +* Defines a test case with a given name and test function. The test function can optionally be configured with test options. +* +* @param {string | Function} name - The name of the test or a function that will be used as a test name. +* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. +* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. +* @throws {Error} If called inside another test function. +* @example +* ```ts +* // Define a simple test +* it('adds two numbers', () => { +* expect(add(1, 2)).toBe(3); +* }); +* ``` +* @example +* ```ts +* // Define a test with options +* it('subtracts two numbers', { retry: 3 }, () => { +* expect(subtract(5, 2)).toBe(3); +* }); +* ``` +*/ +declare const it: TestAPI; +declare function getCurrentSuite(): SuiteCollector; +declare function createTaskCollector(fn: (...args: any[]) => any): TestAPI; + +declare function getCurrentTest(): T; + +export { File, FileSpecification, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, TaskUpdateEvent, Test, TestAPI, TestArtifact, VitestRunner, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/node_modules/@vitest/runner/dist/index.js b/node_modules/@vitest/runner/dist/index.js new file mode 100644 index 000000000..e81f04a99 --- /dev/null +++ b/node_modules/@vitest/runner/dist/index.js @@ -0,0 +1,7 @@ +export { a as afterAll, b as afterEach, c as aroundAll, d as aroundEach, e as beforeAll, f as beforeEach, p as collectTests, g as createTaskCollector, h as describe, i as getCurrentSuite, j as getCurrentTest, k as getFn, l as getHooks, m as it, o as onTestFailed, n as onTestFinished, r as recordArtifact, s as setFn, q as setHooks, t as startTests, u as suite, v as test, w as updateTask } from './chunk-artifact.js'; +import '@vitest/utils/error'; +import '@vitest/utils/helpers'; +import '@vitest/utils/timers'; +import '@vitest/utils/display'; +import '@vitest/utils/source-map'; +import 'pathe'; diff --git a/node_modules/@vitest/runner/dist/tasks.d-Bh0IjN67.d.ts b/node_modules/@vitest/runner/dist/tasks.d-Bh0IjN67.d.ts new file mode 100644 index 000000000..c9ee26f5c --- /dev/null +++ b/node_modules/@vitest/runner/dist/tasks.d-Bh0IjN67.d.ts @@ -0,0 +1,1513 @@ +import { TestError, Awaitable } from '@vitest/utils'; +import { DiffOptions } from '@vitest/utils/diff'; + +/** +* This is a subset of Vitest config that's required for the runner to work. +*/ +interface VitestRunnerConfig { + root: string; + setupFiles: string[]; + name: string | undefined; + passWithNoTests: boolean; + testNamePattern: RegExp | undefined; + allowOnly: boolean; + sequence: { + shuffle?: boolean; + concurrent?: boolean; + seed: number; + hooks: SequenceHooks; + setupFiles: SequenceSetupFiles; + }; + chaiConfig: { + truncateThreshold?: number; + } | undefined; + maxConcurrency: number; + testTimeout: number; + hookTimeout: number; + retry: SerializableRetry; + includeTaskLocation: boolean | undefined; + diffOptions?: DiffOptions; + tags: TestTagDefinition[]; + tagsFilter: string[] | undefined; + strictTags: boolean; +} +/** +* Possible options to run a single file in a test. +*/ +interface FileSpecification { + filepath: string; + fileTags?: string[]; + testLocations?: number[] | undefined; + testNamePattern?: RegExp | undefined; + testTagsFilter?: string[] | undefined; + testIds?: string[] | undefined; +} +interface TestTagDefinition extends Omit { + /** + * The name of the tag. This is what you use in the `tags` array in tests. + */ + name: keyof TestTags extends never ? string : TestTags[keyof TestTags]; + /** + * A description for the tag. This will be shown in the CLI help and UI. + */ + description?: string; + /** + * Priority for merging options when multiple tags with the same options are applied to a test. + * + * Lower number means higher priority. E.g., priority 1 takes precedence over priority 3. + */ + priority?: number; +} +type VitestRunnerImportSource = "collect" | "setup"; +interface VitestRunnerConstructor { + new (config: VitestRunnerConfig): VitestRunner; +} +type CancelReason = "keyboard-input" | "test-failure" | (string & Record); +interface VitestRunner { + /** + * First thing that's getting called before actually collecting and running tests. + */ + onBeforeCollect?: (paths: string[]) => unknown; + /** + * Called after the file task was created but not collected yet. + */ + onCollectStart?: (file: File) => unknown; + /** + * Called after collecting tests and before "onBeforeRun". + */ + onCollected?: (files: File[]) => unknown; + /** + * Called when test runner should cancel next test runs. + * Runner should listen for this method and mark tests and suites as skipped in + * "onBeforeRunSuite" and "onBeforeRunTask" when called. + */ + cancel?: (reason: CancelReason) => unknown; + /** + * Called before running a single test. Doesn't have "result" yet. + */ + onBeforeRunTask?: (test: Test) => unknown; + /** + * Called before actually running the test function. Already has "result" with "state" and "startTime". + */ + onBeforeTryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * When the task has finished running, but before cleanup hooks are called + */ + onTaskFinished?: (test: Test) => unknown; + /** + * Called after result and state are set. + */ + onAfterRunTask?: (test: Test) => unknown; + /** + * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws. + */ + onAfterTryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called after the retry resolution happened. Unlike `onAfterTryTask`, the test now has a new state. + * All `after` hooks were also called by this point. + */ + onAfterRetryTask?: (test: Test, options: { + retry: number; + repeats: number; + }) => unknown; + /** + * Called before running a single suite. Doesn't have "result" yet. + */ + onBeforeRunSuite?: (suite: Suite) => unknown; + /** + * Called after running a single suite. Has state and result. + */ + onAfterRunSuite?: (suite: Suite) => unknown; + /** + * If defined, will be called instead of usual Vitest suite partition and handling. + * "before" and "after" hooks will not be ignored. + */ + runSuite?: (suite: Suite) => Promise; + /** + * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function. + * "before" and "after" hooks will not be ignored. + */ + runTask?: (test: Test) => Promise; + /** + * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests. + */ + onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise; + /** + * Called when annotation is added via the `context.annotate` method. + */ + onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise; + /** + * @experimental + * + * Called when artifacts are recorded on tests via the `recordArtifact` utility. + */ + onTestArtifactRecord?: (test: Test, artifact: Artifact) => Promise; + /** + * Called before running all tests in collected paths. + */ + onBeforeRunFiles?: (files: File[]) => unknown; + /** + * Called right after running all tests in collected paths. + */ + onAfterRunFiles?: (files: File[]) => unknown; + /** + * Called when new context for a test is defined. Useful if you want to add custom properties to the context. + * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead. + * + * @see https://vitest.dev/advanced/runner#your-task-function + */ + extendTaskContext?: (context: TestContext) => TestContext; + /** + * Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files. + */ + importFile: (filepath: string, source: VitestRunnerImportSource) => unknown; + /** + * Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }` + */ + injectValue?: (key: string) => unknown; + /** + * Gets the time spent importing each individual non-externalized file that Vitest collected. + */ + getImportDurations?: () => Record; + /** + * Publicly available configuration. + */ + config: VitestRunnerConfig; + /** + * The name of the current pool. Can affect how stack trace is inferred on the server side. + */ + pool?: string; + /** + * The current Vite environment that processes the files on the server. + */ + viteEnvironment?: string; + onCleanupWorkerContext?: (cleanup: () => unknown) => void; + trace?(name: string, cb: () => T): T; + trace?(name: string, attributes: Record, cb: () => T): T; +} + +interface TestFixtureItem extends FixtureOptions { + name: string; + value: unknown; + scope: "test" | "file" | "worker"; + deps: Set; + parent?: TestFixtureItem; +} +type UserFixtures = Record; +type FixtureRegistrations = Map; +declare class TestFixtures { + private _suiteContexts; + private _overrides; + private _registrations; + private static _definitions; + private static _builtinFixtures; + private static _fixtureOptionKeys; + private static _fixtureScopes; + private static _workerContextSuite; + static clearDefinitions(): void; + static getWorkerContexts(): Record[]; + static getFileContexts(file: File): Record[]; + static isFixtureOptions(obj: unknown): boolean; + constructor(registrations?: FixtureRegistrations); + extend(runner: VitestRunner, userFixtures: UserFixtures): TestFixtures; + get(suite: Suite): FixtureRegistrations; + override(runner: VitestRunner, userFixtures: UserFixtures): void; + getFileContext(file: File): Record; + getWorkerContext(): Record; + private parseUserFixtures; +} + +/** +* Registers a callback function to be executed once before all tests within the current suite. +* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. +* +* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeAll to set up a database connection +* beforeAll(async () => { +* await database.connect(); +* }); +* ``` +*/ +declare function beforeAll(this: unknown, fn: BeforeAllListener, timeout?: number): void; +/** +* Registers a callback function to be executed once after all tests within the current suite have completed. +* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. +* +* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after all tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterAll to close a database connection +* afterAll(async () => { +* await database.disconnect(); +* }); +* ``` +*/ +declare function afterAll(this: unknown, fn: AfterAllListener, timeout?: number): void; +/** +* Registers a callback function to be executed before each test within the current suite. +* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. +* +* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using beforeEach to reset a database state +* beforeEach(async () => { +* await database.reset(); +* }); +* ``` +*/ +declare function beforeEach(fn: BeforeEachListener, timeout?: number): void; +/** +* Registers a callback function to be executed after each test within the current suite has completed. +* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. +* +* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using afterEach to delete temporary files created during a test +* afterEach(async () => { +* await fileSystem.deleteTempFiles(); +* }); +* ``` +*/ +declare function afterEach(fn: AfterEachListener, timeout?: number): void; +/** +* Registers a callback function to be executed when a test fails within the current suite. +* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. +* +* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFailed to log failure details +* onTestFailed(({ errors }) => { +* console.log(`Test failed: ${test.name}`, errors); +* }); +* ``` +*/ +declare const onTestFailed: TaskHook; +/** +* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). +* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. +* +* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. +* +* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. +* +* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. +* +* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @throws {Error} Throws an error if the function is not called within a test. +* @returns {void} +* @example +* ```ts +* // Example of using onTestFinished for cleanup +* const db = await connectToDatabase(); +* onTestFinished(async () => { +* await db.disconnect(); +* }); +* ``` +*/ +declare const onTestFinished: TaskHook; +/** +* Registers a callback function that wraps around all tests within the current suite. +* The callback receives a `runSuite` function that must be called to run the suite's tests. +* This hook is useful for scenarios where you need to wrap an entire suite in a context +* (e.g., starting a server, opening a database connection that all tests share). +* +* **Note:** When multiple `aroundAll` hooks are registered, they are nested inside each other. +* The first registered hook is the outermost wrapper. +* +* @param {Function} fn - The callback function that wraps the suite. Must call `runSuite()` to run the tests. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using aroundAll to wrap suite in a tracing span +* aroundAll(async (runSuite) => { +* await tracer.trace('test-suite', runSuite); +* }); +* ``` +* @example +* ```ts +* // Example of using aroundAll with fixtures +* aroundAll(async (runSuite, { db }) => { +* await db.transaction(() => runSuite()); +* }); +* ``` +*/ +declare function aroundAll(this: unknown, fn: AroundAllListener, timeout?: number): void; +/** +* Registers a callback function that wraps around each test within the current suite. +* The callback receives a `runTest` function that must be called to run the test. +* This hook is useful for scenarios where you need to wrap tests in a context (e.g., database transactions). +* +* **Note:** When multiple `aroundEach` hooks are registered, they are nested inside each other. +* The first registered hook is the outermost wrapper. +* +* @param {Function} fn - The callback function that wraps the test. Must call `runTest()` to run the test. +* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. +* @returns {void} +* @example +* ```ts +* // Example of using aroundEach to wrap tests in a database transaction +* aroundEach(async (runTest) => { +* await database.transaction(() => runTest()); +* }); +* ``` +* @example +* ```ts +* // Example of using aroundEach with fixtures +* aroundEach(async (runTest, { db }) => { +* await db.transaction(() => runTest()); +* }); +* ``` +*/ +declare function aroundEach(fn: AroundEachListener, timeout?: number): void; + +type ChainableFunction< + T extends string, + F extends (...args: any) => any, + C = object +> = F & { [x in T] : ChainableFunction } & { + fn: (this: Record, ...args: Parameters) => ReturnType; +} & C; +declare function createChainable< + T extends string, + Args extends any[], + R = any +>(keys: T[], fn: (this: Record, ...args: Args) => R, context?: Record): ChainableFunction R>; + +type RunMode = "run" | "skip" | "only" | "todo" | "queued"; +type TaskState = RunMode | "pass" | "fail"; +interface TaskBase { + /** + * Unique task identifier. Based on the file id and the position of the task. + * The id of the file task is based on the file path relative to root and project name. + * It will not change between runs. + * @example `1201091390`, `1201091390_0`, `1201091390_0_1` + */ + id: string; + /** + * Task name provided by the user. If no name was provided, it will be an empty string. + */ + name: string; + /** + * Full name including the file path, any parent suites, and this task's name. + * + * Uses ` > ` as the separator between levels. + * + * @example + * // file + * 'test/task-names.test.ts' + * @example + * // suite + * 'test/task-names.test.ts > meal planning' + * 'test/task-names.test.ts > meal planning > grocery lists' + * @example + * // test + * 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients' + */ + fullName: string; + /** + * Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks. + * + * Uses ` > ` as the separator between levels. + * + * @example + * // file + * undefined + * @example + * // suite + * 'meal planning' + * 'meal planning > grocery lists' + * @example + * // test + * 'meal planning > grocery lists > calculates ingredients' + */ + fullTestName?: string; + /** + * Task mode. + * - **skip**: task is skipped + * - **only**: only this task and other tasks with `only` mode will run + * - **todo**: task is marked as a todo, alias for `skip` + * - **run**: task will run or already ran + * - **queued**: task will start running next. It can only exist on the File + */ + mode: RunMode; + /** + * Custom metadata for the task. JSON reporter will save this data. + */ + meta: TaskMeta; + /** + * Whether the task was produced with `.each()` method. + */ + each?: boolean; + /** + * Whether the task should run concurrently with other tasks. + */ + concurrent?: boolean; + /** + * Whether the tasks of the suite run in a random order. + */ + shuffle?: boolean; + /** + * Suite that this task is part of. File task or the global suite will have no parent. + */ + suite?: Suite; + /** + * Result of the task. Suite and file tasks will only have the result if there + * was an error during collection or inside `afterAll`/`beforeAll`. + */ + result?: TaskResult; + /** + * Retry configuration for the task. + * - If a number, specifies how many times to retry + * - If an object, allows fine-grained retry control + * @default 0 + */ + retry?: Retry; + /** + * The amount of times the task should be repeated after the successful run. + * If the task fails, it will not be retried unless `retry` is specified. + * @default 0 + */ + repeats?: number; + /** + * Location of the task in the file. This field is populated only if + * `includeTaskLocation` option is set. It is generated by calling `new Error` + * and parsing the stack trace, so the location might differ depending on the runtime. + */ + location?: Location; + /** + * If the test was collected by parsing the file AST, and the name + * is not a static string, this property will be set to `true`. + * @experimental + */ + dynamic?: boolean; + /** + * Custom tags of the task. Useful for filtering tasks. + */ + tags?: string[]; +} +interface TaskPopulated extends TaskBase { + /** + * File task. It's the root task of the file. + */ + file: File; + /** + * Whether the task should succeed if it fails. If the task fails, it will be marked as passed. + */ + fails?: boolean; + /** + * Store promises (from async expects) to wait for them before finishing the test + */ + promises?: Promise[]; +} +/** +* Custom metadata that can be used in reporters. +*/ +interface TaskMeta {} +/** +* The result of calling a task. +*/ +interface TaskResult { + /** + * State of the task. Inherits the `task.mode` during collection. + * When the task has finished, it will be changed to `pass` or `fail`. + * - **pass**: task ran successfully + * - **fail**: task failed + */ + state: TaskState; + /** + * Errors that occurred during the task execution. It is possible to have several errors + * if `expect.soft()` failed multiple times or `retry` was triggered. + */ + errors?: TestError[]; + /** + * How long in milliseconds the task took to run. + */ + duration?: number; + /** + * Time in milliseconds when the task started running. + */ + startTime?: number; + /** + * Heap size in bytes after the task finished. + * Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined. + */ + heap?: number; + /** + * State of related to this task hooks. Useful during reporting. + */ + hooks?: Partial>; + /** + * The amount of times the task was retried. The task is retried only if it + * failed and `retry` option is set. + */ + retryCount?: number; + /** + * The amount of times the task was repeated. The task is repeated only if + * `repeats` option is set. This number also contains `retryCount`. + */ + repeatCount?: number; +} +/** The time spent importing & executing a non-externalized file. */ +interface ImportDuration { + /** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */ + selfTime: number; + /** The time spent importing & executing the file and all its imports. */ + totalTime: number; + /** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */ + external?: boolean; + /** Which module imported this module first. All subsequent imports are cached. */ + importer?: string; +} +/** +* The tuple representing a single task update. +* Usually reported after the task finishes. +*/ +type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta]; +interface TaskEventData { + annotation?: TestAnnotation | undefined; + artifact?: TestArtifact | undefined; +} +type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined]; +type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "test-cancel" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact"; +interface Suite extends TaskBase { + type: "suite"; + /** + * File task. It's the root task of the file. + */ + file: File; + /** + * An array of tasks that are part of the suite. + */ + tasks: Task[]; +} +interface File extends Suite { + /** + * The name of the pool that the file belongs to. + * @default 'forks' + */ + pool?: string; + /** + * The environment that processes the file on the server. + */ + viteEnvironment?: string; + /** + * The path to the file in UNIX format. + */ + filepath: string; + /** + * The name of the workspace project the file belongs to. + */ + projectName: string | undefined; + /** + * The time it took to collect all tests in the file. + * This time also includes importing all the file dependencies. + */ + collectDuration?: number; + /** + * The time it took to import the setup file. + */ + setupDuration?: number; + /** The time spent importing every non-externalized dependency that Vitest has processed. */ + importDurations?: Record; +} +interface Test extends TaskPopulated { + type: "test"; + /** + * Test context that will be passed to the test function. + */ + context: TestContext & ExtraContext; + /** + * The test timeout in milliseconds. + */ + timeout: number; + /** + * An array of custom annotations. + */ + annotations: TestAnnotation[]; + /** + * An array of artifacts produced by the test. + * + * @experimental + */ + artifacts: TestArtifact[]; + fullTestName: string; +} +type Task = Test | Suite | File; +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 EachFunctionReturn { + (name: string | Function, fn: (...args: T) => Awaitable, options?: number): void; + (name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable): void; +} +interface TestEachFunction { + (cases: ReadonlyArray): EachFunctionReturn; + >(cases: ReadonlyArray): EachFunctionReturn>; + (cases: ReadonlyArray): EachFunctionReturn; + (...args: [TemplateStringsArray, ...any]): EachFunctionReturn; +} +interface TestForFunctionReturn< + Arg, + Context +> { + (name: string | Function, fn: (arg: Arg, context: Context) => Awaitable): void; + (name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable): void; +} +interface TestForFunction { + (cases: ReadonlyArray): TestForFunctionReturn; + (strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn; +} +interface SuiteForFunction { + (cases: ReadonlyArray): EachFunctionReturn<[T]>; + (...args: [TemplateStringsArray, ...any]): EachFunctionReturn; +} +interface TestCollectorCallable { + (name: string | Function, fn?: TestFunction, options?: number): void; + (name: string | Function, options?: TestCollectorOptions, fn?: TestFunction): void; +} +type ChainableTestAPI = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "fails", TestCollectorCallable, { + each: TestEachFunction; + for: TestForFunction; +}>; +type TestCollectorOptions = Omit; +/** +* Retry configuration for tests. +* Can be a number for simple retry count, or an object for advanced retry control. +*/ +type Retry = number | { + /** + * The number of times to retry the test if it fails. + * @default 0 + */ + count?: number; + /** + * Delay in milliseconds between retry attempts. + * @default 0 + */ + delay?: number; + /** + * Condition to determine if a test should be retried based on the error. + * - If a RegExp, it is tested against the error message + * - If a function, called with the TestError object; return true to retry + * + * NOTE: Functions can only be used in test files, not in vitest.config.ts, + * because the configuration is serialized when passed to worker threads. + * + * @default undefined (retry on all errors) + */ + condition?: RegExp | ((error: TestError) => boolean); +}; +/** +* Serializable retry configuration (used in config files). +* Functions cannot be serialized, so only string conditions are allowed. +*/ +type SerializableRetry = number | { + /** + * The number of times to retry the test if it fails. + * @default 0 + */ + count?: number; + /** + * Delay in milliseconds between retry attempts. + * @default 0 + */ + delay?: number; + /** + * Condition to determine if a test should be retried based on the error. + * Must be a RegExp tested against the error message. + * + * @default undefined (retry on all errors) + */ + condition?: RegExp; +}; +interface TestOptions { + /** + * Test timeout. + */ + timeout?: number; + /** + * Retry configuration for the test. + * - If a number, specifies how many times to retry + * - If an object, allows fine-grained retry control + * @default 0 + */ + retry?: Retry; + /** + * How many times the test will run again. + * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default. + * + * @default 0 + */ + repeats?: number; + /** + * Whether suites and tests run concurrently. + * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`. + */ + concurrent?: boolean; + /** + * Whether tests run sequentially. + * Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`. + */ + sequential?: boolean; + /** + * Whether the test should be skipped. + */ + skip?: boolean; + /** + * Should this test be the only one running in a suite. + */ + only?: boolean; + /** + * Whether the test should be skipped and marked as a todo. + */ + todo?: boolean; + /** + * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail. + */ + fails?: boolean; + /** + * Custom tags of the test. Useful for filtering tests. + */ + tags?: keyof TestTags extends never ? string[] | string : TestTags[keyof TestTags] | TestTags[keyof TestTags][]; + /** + * Custom test metadata available to reporters. + */ + meta?: Partial; +} +interface TestTags {} +interface SuiteOptions extends TestOptions { + /** + * Whether the tasks of the suite run in a random order. + */ + shuffle?: boolean; +} +interface ExtendedAPI { + skipIf: (condition: any) => ChainableTestAPI; + runIf: (condition: any) => ChainableTestAPI; +} +interface Hooks { + /** + * Suite-level hooks only receive file/worker scoped fixtures. + * Test-scoped fixtures are NOT available in beforeAll/afterAll/aroundAll. + */ + beforeAll: typeof beforeAll>; + afterAll: typeof afterAll>; + aroundAll: typeof aroundAll>; + /** + * Test-level hooks receive all fixtures including test-scoped ones. + */ + beforeEach: typeof beforeEach; + afterEach: typeof afterEach; + aroundEach: typeof aroundEach; +} +type TestAPI = ChainableTestAPI & ExtendedAPI & Hooks & { + /** + * Extend the test API with custom fixtures. + * + * @example + * ```ts + * // Simple test fixtures (backward compatible) + * const myTest = test.extend<{ foo: string }>({ + * foo: 'value', + * }) + * + * // With scoped fixtures - use $test/$file/$worker structure + * const myTest = test.extend<{ + * $test: { testData: string } + * $file: { fileDb: Database } + * $worker: { workerConfig: Config } + * }>({ + * testData: async ({ fileDb }, use) => { + * await use(await fileDb.getData()) + * }, + * fileDb: [async ({ workerConfig }, use) => { + * // File fixture can only access workerConfig, NOT testData + * const db = new Database(workerConfig) + * await use(db) + * await db.close() + * }, { scope: 'file' }], + * workerConfig: [async ({}, use) => { + * // Worker fixture can only access other worker fixtures + * await use(loadConfig()) + * }, { scope: 'worker' }], + * }) + * + * // Builder pattern with automatic type inference + * const myTest = test + * .extend('config', { scope: 'worker' }, async ({}) => { + * return { port: 3000 } // Type inferred as { port: number } + * }) + * .extend('db', { scope: 'file' }, async ({ config }, { onCleanup }) => { + * // TypeScript knows config is { port: number } + * const db = new Database(config.port) + * onCleanup(() => db.close()) // Register cleanup + * return db // Type inferred as Database + * }) + * .extend('data', async ({ db }) => { + * // TypeScript knows db is Database + * return await db.getData() // Type inferred from return + * }) + * ``` + */ + extend: { + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: WorkerScopeFixtureOptions, fn: BuilderFixtureFn>): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: FileScopeFixtureOptions, fn: BuilderFixtureFn>): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: TestScopeFixtureOptions, fn: BuilderFixtureFn>): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, fn: BuilderFixtureFn>): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: WorkerScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: FileScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, options: TestScopeFixtureOptions, value: T extends (...args: any[]) => any ? never : T): TestAPI>; + < + K extends string, + T extends (K extends keyof ExtraContext ? ExtraContext[K] : unknown) + >(name: K, value: T extends (...args: any[]) => any ? never : T): TestAPI>; + (fixtures: ScopedFixturesObject): TestAPI & ExtraContext>; + = object>(fixtures: Fixtures): TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>; + }; + /** + * Overwrite fixture values for the current suite scope. + * Supports both object syntax and builder pattern. + * + * @example + * ```ts + * describe('with custom config', () => { + * // Object syntax + * test.override({ config: { port: 4000 } }) + * + * // Builder pattern - value + * test.override('config', { port: 4000 }) + * + * // Builder pattern - function + * test.override('config', () => ({ port: 4000 })) + * + * // Builder pattern - function with cleanup + * test.override('db', async ({ config }, { onCleanup }) => { + * const db = await createDb(config) + * onCleanup(() => db.close()) + * return db + * }) + * }) + * ``` + */ + override: { + (name: K, options: FixtureOptions, fn: BuilderFixtureFn): TestAPI; + (name: K, fn: BuilderFixtureFn): TestAPI; + (name: K, options: FixtureOptions, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI; + (name: K, value: ExtraContext[K] extends (...args: any[]) => any ? never : ExtraContext[K]): TestAPI; + (fixtures: Partial>): TestAPI; + }; + /** + * @deprecated Use `test.override()` instead + */ + scoped: (fixtures: Partial>) => TestAPI; + describe: SuiteAPI; + suite: SuiteAPI; +}; +interface FixtureOptions { + /** + * Whether to automatically set up current fixture, even though it's not being used. + * Test-scoped auto fixtures are not initialized in suite-level hooks (`beforeAll`/`afterAll`/`aroundAll`). + * @default false + */ + auto?: boolean; + /** + * Indicated if the injected value from the config should be preferred over the fixture value + */ + injected?: boolean; + /** + * When should the fixture be set up. + * - **test**: fixture will be set up before every test + * - **worker**: fixture will be set up once per worker + * - **file**: fixture will be set up once per file + * + * **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file. + * @default 'test' + */ + scope?: "test" | "worker" | "file"; +} +/** +* Options for test-scoped fixtures. +* Test fixtures are set up before each test and have access to all fixtures. +*/ +interface TestScopeFixtureOptions extends Omit { + /** + * @default 'test' + */ + scope?: "test"; +} +/** +* Options for file-scoped fixtures. +* File fixtures are set up once per file and can only access other file fixtures and worker fixtures. +*/ +interface FileScopeFixtureOptions extends Omit { + /** + * Must be 'file' for file-scoped fixtures. + */ + scope: "file"; +} +/** +* Options for worker-scoped fixtures. +* Worker fixtures are set up once per worker and can only access other worker fixtures. +*/ +interface WorkerScopeFixtureOptions extends Omit { + /** + * Must be 'worker' for worker-scoped fixtures. + */ + scope: "worker"; +} +type Use = (value: T) => Promise; +/** +* Cleanup registration function for builder pattern fixtures. +* Call this to register a cleanup function that runs after the test/file/worker completes. +* +* **Note:** This function can only be called once per fixture. If you need multiple +* cleanup operations, either combine them into a single cleanup function or split +* your fixture into multiple smaller fixtures. +*/ +type OnCleanup = (cleanup: () => Awaitable) => void; +/** +* Builder pattern fixture function with automatic type inference. +* Returns the fixture value directly (type is inferred from return). +* Use onCleanup to register teardown logic. +* +* Parameters can be omitted if not needed: +* - `async () => value` - no dependencies, no cleanup +* - `async ({ dep }) => value` - with dependencies, no cleanup +* - `async ({ dep }, { onCleanup }) => value` - with dependencies and cleanup +*/ +type BuilderFixtureFn< + T, + Context +> = (context: Context, fixture: { + onCleanup: OnCleanup; +}) => T | Promise; +type ExtractSuiteContext = C extends { + $__worker?: any; +} | { + $__file?: any; +} | { + $__test?: any; +} ? ExtractBuilderWorker & ExtractBuilderFile : C; +/** +* Extracts worker-scoped fixtures from a context that includes scope info. +*/ +type ExtractBuilderWorker = C extends { + $__worker?: infer W; +} ? W extends Record ? W : object : object; +/** +* Extracts file-scoped fixtures from a context that includes scope info. +*/ +type ExtractBuilderFile = C extends { + $__file?: infer F; +} ? F extends Record ? F : object : object; +/** +* Extracts test-scoped fixtures from a context that includes scope info. +*/ +type ExtractBuilderTest = C extends { + $__test?: infer T; +} ? T extends Record ? T : object : object; +/** +* Adds a worker fixture to the context with proper scope tracking. +*/ +type AddBuilderWorker< + C, + K extends string, + V +> = Omit & Record & { + readonly $__worker?: ExtractBuilderWorker & Record; + readonly $__file?: ExtractBuilderFile; + readonly $__test?: ExtractBuilderTest; +}; +/** +* Adds a file fixture to the context with proper scope tracking. +*/ +type AddBuilderFile< + C, + K extends string, + V +> = Omit & Record & { + readonly $__worker?: ExtractBuilderWorker; + readonly $__file?: ExtractBuilderFile & Record; + readonly $__test?: ExtractBuilderTest; +}; +/** +* Adds a test fixture to the context with proper scope tracking. +*/ +type AddBuilderTest< + C, + K extends string, + V +> = Omit & Record & { + readonly $__worker?: ExtractBuilderWorker; + readonly $__file?: ExtractBuilderFile; + readonly $__test?: ExtractBuilderTest & Record; +}; +/** +* Context available to worker-scoped fixtures. +* Worker fixtures can only access other worker fixtures. +* They do NOT have access to test context (task, expect, onTestFailed, etc.) +* since they run once per worker, outside of any specific test. +*/ +type WorkerScopeContext = ExtractBuilderWorker; +/** +* Context available to file-scoped fixtures. +* File fixtures can access worker and other file fixtures. +* They do NOT have access to test context (task, expect, onTestFailed, etc.) +* since they run once per file, outside of any specific test. +*/ +type FileScopeContext = ExtractBuilderWorker & ExtractBuilderFile; +/** +* Context available to test-scoped fixtures (all fixtures + test context). +*/ +type TestScopeContext = C & TestContext; +type FixtureFn< + T, + K extends keyof T, + ExtraContext +> = (context: Omit & ExtraContext, use: Use) => Promise; +type Fixture< + T, + K extends keyof T, + ExtraContext = object +> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn>> : never : T[K] | (T[K] extends any ? FixtureFn>> : never); +/** +* Fixture function with explicit context type for scoped fixtures. +*/ +type ScopedFixtureFn< + Value, + Context +> = (context: Context, use: Use) => Promise; +/** +* Fixtures definition for backward compatibility. +* All fixtures are in T and any scope is allowed. +*/ +type Fixtures< + T, + ExtraContext = object +> = { [K in keyof T] : Fixture | [Fixture, FixtureOptions?] }; +/** +* Scoped fixtures definition using a single generic with optional scope keys. +* This provides better ergonomics than multiple generics. +* Uses $ prefix to avoid conflicts with fixture names. +* +* @example +* ```ts +* test.extend<{ +* $worker?: { config: Config } +* $file?: { db: Database } +* $test?: { data: string } +* }>({ ... }) +* ``` +*/ +interface ScopedFixturesDef { + $test?: Record; + $file?: Record; + $worker?: Record; +} +/** +* Extracts fixture types from a ScopedFixturesDef. +* Handles optional properties by using Exclude to remove undefined. +*/ +type ExtractScopedFixtures = ([Exclude] extends [never] ? object : Exclude) & ([Exclude] extends [never] ? object : Exclude) & ([Exclude] extends [never] ? object : Exclude); +/** +* Creates the fixtures object type for ScopedFixturesDef with proper scope validation. +* - Test fixtures: can be defined as value, function, or tuple with optional scope +* - File fixtures: MUST have { scope: 'file' } +* - Worker fixtures: MUST have { scope: 'worker' } +*/ +type ScopedFixturesObject< + T extends ScopedFixturesDef, + ExtraContext = object +> = { [K in keyof NonNullable] : NonNullable[K] | ScopedFixtureFn[K], ExtractScopedFixtures & ExtraContext & TestContext> | [ScopedFixtureFn[K], ExtractScopedFixtures & ExtraContext & TestContext>, TestScopeFixtureOptions?] } & { [K in keyof NonNullable] : [ScopedFixtureFn[K], (NonNullable & NonNullable) & ExtraContext>, FileScopeFixtureOptions] } & { [K in keyof NonNullable] : [ScopedFixtureFn[K], NonNullable & ExtraContext>, WorkerScopeFixtureOptions] }; +type InferFixturesTypes = T extends TestAPI ? C : T; +interface SuiteCollectorCallable { + (name: string | Function, fn?: SuiteFactory, options?: number): SuiteCollector; + (name: string | Function, options: SuiteOptions, fn?: SuiteFactory): SuiteCollector; +} +type ChainableSuiteAPI = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "shuffle", SuiteCollectorCallable, { + each: TestEachFunction; + for: SuiteForFunction; +}>; +type SuiteAPI = ChainableSuiteAPI & { + skipIf: (condition: any) => ChainableSuiteAPI; + runIf: (condition: any) => ChainableSuiteAPI; +}; +interface BeforeAllListener { + (context: ExtraContext, suite: Readonly): Awaitable; +} +interface AfterAllListener { + (context: ExtraContext, suite: Readonly): Awaitable; +} +interface BeforeEachListener { + (context: TestContext & ExtraContext, suite: Readonly): Awaitable; +} +interface AfterEachListener { + (context: TestContext & ExtraContext, suite: Readonly): Awaitable; +} +interface AroundEachListener { + (runTest: () => Promise, context: TestContext & ExtraContext, suite: Readonly): Awaitable; +} +interface AroundAllListener { + (runSuite: () => Promise, context: ExtraContext, suite: Readonly): Awaitable; +} +interface RegisteredAllListener { + (suite: Readonly): Awaitable; +} +interface RegisteredAroundAllListener { + (runSuite: () => Promise, suite: Readonly): Awaitable; +} +interface SuiteHooks { + beforeAll: RegisteredAllListener[]; + afterAll: RegisteredAllListener[]; + aroundAll: RegisteredAroundAllListener[]; + beforeEach: BeforeEachListener[]; + afterEach: AfterEachListener[]; + aroundEach: AroundEachListener[]; +} +interface TaskCustomOptions extends TestOptions { + /** + * Whether the task was produced with `.each()` method. + */ + each?: boolean; + /** + * Task fixtures. + */ + fixtures?: TestFixtures; + /** + * Function that will be called when the task is executed. + * If nothing is provided, the runner will try to get the function using `getFn(task)`. + * If the runner cannot find the function, the task will be marked as failed. + */ + handler?: (context: TestContext) => Awaitable; +} +interface SuiteCollector { + readonly name: string; + readonly mode: RunMode; + options?: SuiteOptions; + type: "collector"; + test: TestAPI; + tasks: (Suite | Test | SuiteCollector)[]; + file: File; + suite?: Suite; + task: (name: string, options?: TaskCustomOptions) => Test; + collect: (file: File) => Promise; + clear: () => void; + on: >(name: T, ...fn: SuiteHooks[T]) => void; +} +type SuiteFactory = (test: TestAPI) => Awaitable; +interface RuntimeContext { + tasks: (SuiteCollector | Test)[]; + currentSuite: SuiteCollector | null; +} +/** +* User's custom test context. +*/ +interface TestContext { + /** + * Metadata of the current test + */ + readonly task: Readonly; + /** + * An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or + * the test run was cancelled. + * @see {@link https://vitest.dev/guide/test-context#signal} + */ + readonly signal: AbortSignal; + /** + * Register a callback to run when this specific test fails. + * Useful when tests run concurrently. + * @see {@link https://vitest.dev/guide/test-context#ontestfailed} + */ + readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void; + /** + * Register a callback to run when this specific test finishes. + * Useful when tests run concurrently. + * @see {@link https://vitest.dev/guide/test-context#ontestfinished} + */ + readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void; + /** + * Mark tests as skipped. All execution after this call will be skipped. + * This function throws an error, so make sure you are not catching it accidentally. + * @see {@link https://vitest.dev/guide/test-context#skip} + */ + readonly skip: { + (note?: string): never; + (condition: boolean, note?: string): void; + }; + /** + * Add a test annotation that will be displayed by your reporter. + * @see {@link https://vitest.dev/guide/test-context#annotate} + */ + readonly annotate: { + (message: string, type?: string, attachment?: TestAttachment): Promise; + (message: string, attachment?: TestAttachment): Promise; + }; +} +type OnTestFailedHandler = (context: TestContext) => Awaitable; +type OnTestFinishedHandler = (context: TestContext) => Awaitable; +interface TaskHook { + (fn: HookListener, timeout?: number): void; +} +type SequenceHooks = "stack" | "list" | "parallel"; +type SequenceSetupFiles = "list" | "parallel"; +/** +* Represents a file or data attachment associated with a test artifact. +* +* Attachments can be either file-based (via `path`) or inline content (via `body`). +* The `contentType` helps consumers understand how to interpret the attachment data. +*/ +interface TestAttachment { + /** MIME type of the attachment (e.g., 'image/png', 'text/plain') */ + contentType?: string; + /** File system path to the attachment */ + path?: string; + /** Inline attachment content as a string or raw binary data */ + body?: string | Uint8Array | undefined; + /** + * @experimental + * How the string `body` is encoded. + * - `'base64'` (default): body is already base64-encoded + * - `'utf-8'`: body is a utf8 string + * + * `body: Uint8Array` is always auto-encoded to string with `bodyEncoding: 'base64'` + * regardless of this option. + */ + bodyEncoding?: "base64" | "utf-8"; +} +interface Location { + /** Line number in the source file (1-indexed) */ + line: number; + /** Column number in the line (1-indexed) */ + column: number; +} +interface FileLocation extends Location { + /** Line number in the source file (1-indexed) */ + line: number; + /** Column number in the line (1-indexed) */ + column: number; + /** Path to the source file */ + file: string; +} +/** +* Source code location information for a test artifact. +* +* Indicates where in the source code the artifact originated from. +*/ +interface TestArtifactLocation extends FileLocation {} +/** +* @experimental +* +* Base interface for all test artifacts. +* +* Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code. +* +* **Important**: when running with [`api.allowWrite`](https://vitest.dev/config/api#api-allowwrite) or [`browser.api.allowWrite`](https://vitest.dev/config/browser/api#api-allowwrite) disabled, Vitest empties the `attachments` array on every artifact before reporting it. +*/ +interface TestArtifactBase { + /** File or data attachments associated with this artifact */ + attachments?: TestAttachment[]; + /** Source location where this artifact was created */ + location?: TestArtifactLocation; +} +/** +* @deprecated Use {@linkcode TestArtifactLocation} instead. +* +* Kept for backwards compatibility. +*/ +type TestAnnotationLocation = TestArtifactLocation; +interface TestAnnotation { + message: string; + type: string; + location?: TestArtifactLocation; + attachment?: TestAttachment; +} +/** +* @experimental +* +* Artifact type for test annotations. +*/ +interface TestAnnotationArtifact extends TestArtifactBase { + type: "internal:annotation"; + annotation: TestAnnotation; +} +interface VisualRegressionArtifactAttachment extends TestAttachment { + name: "reference" | "actual" | "diff"; + width: number; + height: number; +} +/** +* @experimental +* +* Artifact type for visual regressions. +*/ +interface VisualRegressionArtifact extends TestArtifactBase { + type: "internal:toMatchScreenshot"; + kind: "visual-regression"; + message: string; + attachments: VisualRegressionArtifactAttachment[]; +} +interface FailureScreenshotArtifactAttachment extends TestAttachment { + path: string; + /** Original file system path to the screenshot, before attachment resolution */ + originalPath: string; + body?: undefined; +} +/** +* @experimental +* +* Artifact type for failure screenshots. +*/ +interface FailureScreenshotArtifact extends TestArtifactBase { + type: "internal:failureScreenshot"; + attachments: [FailureScreenshotArtifactAttachment] | []; +} +/** +* @experimental +* @advanced +* +* Registry for custom test artifact types. +* +* Augment this interface to register custom artifact types that your tests can produce. +* +* Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property. +* +* @remarks +* - Use a `Symbol` as the **registry key** to guarantee uniqueness +* - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix +* - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata +* - `location` property is automatically injected to indicate where the artifact was created +* +* @example +* ```ts +* // Define custom attachment type for generated PDF +* interface PDFAttachment extends TestAttachment { +* contentType: 'application/pdf' +* body: Uint8Array +* pageCount: number +* fileSize: number +* } +* +* interface PDFGenerationArtifact extends TestArtifactBase { +* type: 'my-plugin:pdf-generation' +* templateName: string +* isValid: boolean +* attachments: [PDFAttachment] +* } +* +* // Use a symbol to guarantee key uniqueness +* const pdfKey = Symbol('pdf-generation') +* +* declare module 'vitest' { +* interface TestArtifactRegistry { +* [pdfKey]: PDFGenerationArtifact +* } +* } +* +* // Custom assertion for PDF generation +* async function toGenerateValidPDF( +* this: MatcherState, +* actual: PDFTemplate, +* data: Record +* ): AsyncExpectationResult { +* const pdfBuffer = await actual.render(data) +* const validation = await validatePDF(pdfBuffer) +* +* await recordArtifact(this.task, { +* type: 'my-plugin:pdf-generation', +* templateName: actual.name, +* isValid: validation.success, +* attachments: [{ +* contentType: 'application/pdf', +* body: pdfBuffer, +* pageCount: validation.pageCount, +* fileSize: pdfBuffer.byteLength +* }] +* }) +* +* return { +* pass: validation.success, +* message: () => validation.success +* ? `Generated valid PDF with ${validation.pageCount} pages` +* : `Invalid PDF: ${validation.error}` +* } +* } +* ``` +*/ +interface TestArtifactRegistry {} +/** +* @experimental +* +* Union type of all test artifacts, including built-in and custom registered artifacts. +* +* This type automatically includes all artifacts registered via {@link TestArtifactRegistry}. +*/ +type TestArtifact = FailureScreenshotArtifact | TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry]; + +export { afterAll as a8, afterEach as a9, aroundAll as aa, aroundEach as ab, beforeAll as ac, beforeEach as ad, onTestFailed as ae, onTestFinished as af, createChainable as ah }; +export type { TestFunction as $, AfterAllListener as A, BeforeAllListener as B, CancelReason as C, TaskBase as D, TaskCustomOptions as E, FileSpecification as F, TaskEventPack as G, TaskHook as H, ImportDuration as I, TaskMeta as J, TaskPopulated as K, TaskResult as L, TaskResultPack as M, TaskState as N, OnTestFailedHandler as O, TestAnnotation as P, TestAnnotationArtifact as Q, Retry as R, Suite as S, TestArtifact as T, TestAnnotationLocation as U, VitestRunner as V, TestArtifactBase as W, TestArtifactLocation as X, TestArtifactRegistry as Y, TestAttachment as Z, TestContext as _, Test as a, TestOptions as a0, TestTagDefinition as a1, TestTags as a2, Use as a3, VisualRegressionArtifact as a4, VitestRunnerConfig as a5, VitestRunnerConstructor as a6, VitestRunnerImportSource as a7, ChainableFunction as ag, SuiteHooks as b, File as c, TaskUpdateEvent as d, Task as e, TestAPI as f, SuiteAPI as g, SuiteCollector as h, AfterEachListener as i, AroundAllListener as j, AroundEachListener as k, BeforeEachListener as l, FailureScreenshotArtifact as m, Fixture as n, FixtureFn as o, FixtureOptions as p, Fixtures as q, InferFixturesTypes as r, OnTestFinishedHandler as s, RunMode as t, RuntimeContext as u, SequenceHooks as v, SequenceSetupFiles as w, SerializableRetry as x, SuiteFactory as y, SuiteOptions as z }; diff --git a/node_modules/@vitest/runner/dist/types.d.ts b/node_modules/@vitest/runner/dist/types.d.ts new file mode 100644 index 000000000..7af681f1d --- /dev/null +++ b/node_modules/@vitest/runner/dist/types.d.ts @@ -0,0 +1,3 @@ +export { A as AfterAllListener, i as AfterEachListener, j as AroundAllListener, k as AroundEachListener, B as BeforeAllListener, l as BeforeEachListener, C as CancelReason, m as FailureScreenshotArtifact, c as File, F as FileSpecification, n as Fixture, o as FixtureFn, p as FixtureOptions, q as Fixtures, I as ImportDuration, r as InferFixturesTypes, O as OnTestFailedHandler, s as OnTestFinishedHandler, R as Retry, t as RunMode, u as RuntimeContext, v as SequenceHooks, w as SequenceSetupFiles, x as SerializableRetry, S as Suite, g as SuiteAPI, h as SuiteCollector, y as SuiteFactory, b as SuiteHooks, z as SuiteOptions, e as Task, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, d as TaskUpdateEvent, a as Test, f as TestAPI, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, T as TestArtifact, W as TestArtifactBase, X as TestArtifactLocation, Y as TestArtifactRegistry, Z as TestAttachment, _ as TestContext, $ as TestFunction, a0 as TestOptions, a1 as TestTagDefinition, a2 as TestTags, a3 as Use, a4 as VisualRegressionArtifact, V as VitestRunner, a5 as VitestRunnerConfig, a6 as VitestRunnerConstructor, a7 as VitestRunnerImportSource } from './tasks.d-Bh0IjN67.js'; +import '@vitest/utils'; +import '@vitest/utils/diff'; diff --git a/node_modules/@vitest/runner/dist/types.js b/node_modules/@vitest/runner/dist/types.js new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/node_modules/@vitest/runner/dist/types.js @@ -0,0 +1 @@ + diff --git a/node_modules/@vitest/runner/dist/utils.d.ts b/node_modules/@vitest/runner/dist/utils.d.ts new file mode 100644 index 000000000..ced761292 --- /dev/null +++ b/node_modules/@vitest/runner/dist/utils.d.ts @@ -0,0 +1,57 @@ +import { S as Suite, c as File, e as Task, a1 as TestTagDefinition, a5 as VitestRunnerConfig, a as Test } from './tasks.d-Bh0IjN67.js'; +export { ag as ChainableFunction, ah as createChainable } from './tasks.d-Bh0IjN67.js'; +import { ParsedStack, Arrayable } from '@vitest/utils'; +import '@vitest/utils/diff'; + +/** +* If any tasks been marked as `only`, mark all other tasks as `skip`. +*/ +declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, testIds?: string[] | undefined, testTagsFilter?: ((testTags: string[]) => boolean) | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void; +declare function someTasksAreOnly(suite: Suite): boolean; +declare function generateHash(str: string): string; +declare function calculateSuiteHash(parent: Suite): void; +declare function createFileTask(filepath: string, root: string, projectName: string | undefined, pool?: string, viteEnvironment?: string): File; +/** +* Generate a unique ID for a file based on its path and project name +* @param file File relative to the root of the project to keep ID the same between different machines +* @param projectName The name of the test project +*/ +declare function generateFileHash(file: string, projectName: string | undefined): string; +declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined; + +interface ConcurrencyLimiter extends ConcurrencyLimiterFn { + acquire: () => (() => void) | Promise<() => void>; +} +type ConcurrencyLimiterFn = < + Args extends unknown[], + T +>(func: (...args: Args) => PromiseLike | T, ...args: Args) => Promise; +/** +* Return a function for running multiple async operations with limited concurrency. +*/ +declare function limitConcurrency(concurrency?: number): ConcurrencyLimiter; + +/** +* Partition in tasks groups by consecutive concurrent +*/ +declare function partitionSuiteChildren(suite: Suite): Task[][]; + +/** +* @experimental +*/ +declare function matchesTags(testTags: string[]): boolean; +declare function validateTags(config: VitestRunnerConfig, tags: string[]): void; +declare function createTagsFilter(tagsExpr: string[], availableTags: TestTagDefinition[]): (testTags: string[]) => boolean; + +declare function isTestCase(s: Task): s is Test; +declare function getTests(suite: Arrayable): Test[]; +declare function getTasks(tasks?: Arrayable): Task[]; +declare function getSuites(suite: Arrayable): Suite[]; +declare function hasTests(suite: Arrayable): boolean; +declare function hasFailed(suite: Arrayable): boolean; +declare function getNames(task: Task): string[]; +declare function getFullName(task: Task, separator?: string): string; +declare function getTestName(task: Task, separator?: string): string; +declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string; + +export { calculateSuiteHash, createFileTask, createTagsFilter, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, matchesTags, partitionSuiteChildren, someTasksAreOnly, validateTags }; diff --git a/node_modules/@vitest/runner/dist/utils.js b/node_modules/@vitest/runner/dist/utils.js new file mode 100644 index 000000000..f693b3bd5 --- /dev/null +++ b/node_modules/@vitest/runner/dist/utils.js @@ -0,0 +1,7 @@ +export { x as calculateSuiteHash, y as createChainable, z as createFileTask, A as createTagsFilter, B as createTaskName, C as findTestFileStackTrace, D as generateFileHash, E as generateHash, F as getFullName, G as getNames, H as getSuites, I as getTasks, J as getTestName, K as getTests, L as hasFailed, M as hasTests, N as interpretTaskModes, O as isTestCase, P as limitConcurrency, Q as matchesTags, R as partitionSuiteChildren, S as someTasksAreOnly, T as validateTags } from './chunk-artifact.js'; +import '@vitest/utils/error'; +import '@vitest/utils/helpers'; +import '@vitest/utils/timers'; +import '@vitest/utils/display'; +import '@vitest/utils/source-map'; +import 'pathe'; diff --git a/node_modules/@vitest/runner/package.json b/node_modules/@vitest/runner/package.json new file mode 100644 index 000000000..0323e31de --- /dev/null +++ b/node_modules/@vitest/runner/package.json @@ -0,0 +1,53 @@ +{ + "name": "@vitest/runner", + "type": "module", + "version": "4.1.5", + "description": "Vitest test runner", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/advanced/runner", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/runner" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "test-runner" + ], + "sideEffects": true, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./utils": { + "types": "./dist/utils.d.ts", + "default": "./dist/utils.js" + }, + "./types": { + "types": "./dist/types.d.ts", + "default": "./dist/types.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "pathe": "^2.0.3", + "@vitest/utils": "4.1.5" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/runner/types.d.ts b/node_modules/@vitest/runner/types.d.ts new file mode 100644 index 000000000..26a125423 --- /dev/null +++ b/node_modules/@vitest/runner/types.d.ts @@ -0,0 +1 @@ +export * from './dist/types.js' diff --git a/node_modules/@vitest/runner/utils.d.ts b/node_modules/@vitest/runner/utils.d.ts new file mode 100644 index 000000000..e3f344e48 --- /dev/null +++ b/node_modules/@vitest/runner/utils.d.ts @@ -0,0 +1 @@ +export * from './dist/utils.js' diff --git a/node_modules/@vitest/snapshot/LICENSE b/node_modules/@vitest/snapshot/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/snapshot/README.md b/node_modules/@vitest/snapshot/README.md new file mode 100644 index 000000000..db0e4f81e --- /dev/null +++ b/node_modules/@vitest/snapshot/README.md @@ -0,0 +1,88 @@ +# @vitest/snapshot + +[![NPM version](https://img.shields.io/npm/v/@vitest/snapshot?color=a1b858&label=)](https://npmx.dev/package/@vitest/snapshot) + +Lightweight implementation of Jest's snapshots. + +## Usage + +```js +import { SnapshotClient } from '@vitest/snapshot' +import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' +import { SnapshotManager } from '@vitest/snapshot/manager' + +const client = new SnapshotClient({ + // you need to provide your own equality check implementation if you use it + // this function is called when `.toMatchSnapshot({ property: 1 })` is called + isEqual: (received, expected) => + equals(received, expected, [iterableEquality, subsetEquality]), +}) + +// class that implements snapshot saving and reading +// by default uses fs module, but you can provide your own implementation depending on the environment +const environment = new NodeSnapshotEnvironment() + +// you need to implement this yourselves, +// this depends on your runner +function getCurrentFilepath() { + return '/file.spec.js' +} +function getCurrentTestName() { + return 'test1' +} + +// example for inline snapshots, nothing is required to support regular snapshots, +// just call `assert` with `isInline: false` +function wrapper(received) { + function __INLINE_SNAPSHOT__(inlineSnapshot, message) { + client.assert({ + received, + message, + isInline: true, + inlineSnapshot, + filepath: getCurrentFilepath(), + name: getCurrentTestName(), + }) + } + return { + // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) + // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor + toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), + } +} + +const options = { + updateSnapshot: 'new', + snapshotEnvironment: environment, +} + +await client.startCurrentRun( + getCurrentFilepath(), + getCurrentTestName(), + options +) + +// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" +client.assert({ + received: 'some text', + isInline: false, +}) + +// uses "pretty-format", so it requires quotes +// also naming is hard-coded when parsing test files +wrapper('text 1').toMatchInlineSnapshot() +wrapper('text 2').toMatchInlineSnapshot('"text 2"') + +const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult + +// you can use manager to manage several clients +const manager = new SnapshotManager(options) +manager.add(result) + +// do something +// and then read the summary + +console.log(manager.summary) +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/snapshot) | [Documentation](https://vitest.dev/guide/snapshot) diff --git a/node_modules/@vitest/snapshot/dist/environment.d-DOJxxZV9.d.ts b/node_modules/@vitest/snapshot/dist/environment.d-DOJxxZV9.d.ts new file mode 100644 index 000000000..f68fe4d16 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/environment.d-DOJxxZV9.d.ts @@ -0,0 +1,17 @@ +import { ParsedStack } from '@vitest/utils'; + +interface SnapshotEnvironment { + getVersion: () => string; + getHeader: () => string; + resolvePath: (filepath: string) => Promise; + resolveRawPath: (testPath: string, rawPath: string) => Promise; + saveSnapshotFile: (filepath: string, snapshot: string) => Promise; + readSnapshotFile: (filepath: string) => Promise; + removeSnapshotFile: (filepath: string) => Promise; + processStackTrace?: (stack: ParsedStack) => ParsedStack; +} +interface SnapshotEnvironmentOptions { + snapshotsDirName?: string; +} + +export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a }; diff --git a/node_modules/@vitest/snapshot/dist/environment.d.ts b/node_modules/@vitest/snapshot/dist/environment.d.ts new file mode 100644 index 000000000..d9a26029d --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/environment.d.ts @@ -0,0 +1,17 @@ +import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DOJxxZV9.js'; +import '@vitest/utils'; + +declare class NodeSnapshotEnvironment implements SnapshotEnvironment { + private options; + constructor(options?: SnapshotEnvironmentOptions); + getVersion(): string; + getHeader(): string; + resolveRawPath(testPath: string, rawPath: string): Promise; + resolvePath(filepath: string): Promise; + prepareDirectory(dirPath: string): Promise; + saveSnapshotFile(filepath: string, snapshot: string): Promise; + readSnapshotFile(filepath: string): Promise; + removeSnapshotFile(filepath: string): Promise; +} + +export { NodeSnapshotEnvironment, SnapshotEnvironment }; diff --git a/node_modules/@vitest/snapshot/dist/environment.js b/node_modules/@vitest/snapshot/dist/environment.js new file mode 100644 index 000000000..f5ef725d7 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/environment.js @@ -0,0 +1,40 @@ +import { promises, existsSync } from 'node:fs'; +import { isAbsolute, resolve, dirname, join, basename } from 'pathe'; + +class NodeSnapshotEnvironment { + constructor(options = {}) { + this.options = options; + } + getVersion() { + return "1"; + } + getHeader() { + return `// Snapshot v${this.getVersion()}`; + } + async resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } + async resolvePath(filepath) { + return join(join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), `${basename(filepath)}.snap`); + } + async prepareDirectory(dirPath) { + await promises.mkdir(dirPath, { recursive: true }); + } + async saveSnapshotFile(filepath, snapshot) { + await promises.mkdir(dirname(filepath), { recursive: true }); + await promises.writeFile(filepath, snapshot, "utf-8"); + } + async readSnapshotFile(filepath) { + if (!existsSync(filepath)) { + return null; + } + return promises.readFile(filepath, "utf-8"); + } + async removeSnapshotFile(filepath) { + if (existsSync(filepath)) { + await promises.unlink(filepath); + } + } +} + +export { NodeSnapshotEnvironment }; diff --git a/node_modules/@vitest/snapshot/dist/index.d.ts b/node_modules/@vitest/snapshot/dist/index.d.ts new file mode 100644 index 000000000..396393943 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/index.d.ts @@ -0,0 +1,74 @@ +import { S as SnapshotState, a as SnapshotStateOptions, b as SnapshotResult, R as RawSnapshotInfo, D as DomainSnapshotAdapter } from './rawSnapshot.d-D_X3-62x.js'; +export { c as DomainMatchResult, d as SnapshotData, e as SnapshotMatchOptions, f as SnapshotSerializer, g as SnapshotSummary, h as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-D_X3-62x.js'; +import { Plugin, Plugins } from '@vitest/pretty-format'; +export { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js'; +import '@vitest/utils'; + +interface AssertOptions { + received: unknown; + filepath: string; + name: string; + /** + * Not required but needed for `SnapshotClient.clearTest` to implement test-retry behavior. + * @default name + */ + testId?: string; + message?: string; + isInline?: boolean; + properties?: object; + inlineSnapshot?: string; + error?: Error; + errorMessage?: string; + rawSnapshot?: RawSnapshotInfo; + assertionName?: string; +} +interface AssertDomainOptions extends Omit { + received: unknown; + adapter: DomainSnapshotAdapter; +} +interface AssertDomainPollOptions extends Omit { + poll: () => Promise | unknown; + timeout?: number; + interval?: number; +} +/** Same shape as expect.extend custom matcher result (SyncExpectationResult from @vitest/expect) */ +interface MatchResult { + pass: boolean; + message: () => string; + actual?: unknown; + expected?: unknown; +} +interface SnapshotClientOptions { + isEqual?: (received: unknown, expected: unknown) => boolean; +} +declare class SnapshotClient { + private options; + snapshotStateMap: Map; + constructor(options?: SnapshotClientOptions); + setup(filepath: string, options: SnapshotStateOptions): Promise; + finish(filepath: string): Promise; + skipTest(filepath: string, testName: string): void; + clearTest(filepath: string, testId: string): void; + getSnapshotState(filepath: string): SnapshotState; + match(options: AssertOptions): MatchResult; + assert(options: AssertOptions): void; + matchDomain(options: AssertDomainOptions): MatchResult; + pollMatchDomain(options: AssertDomainPollOptions): Promise; + assertRaw(options: AssertOptions): Promise; + clear(): void; +} + +declare function stripSnapshotIndentation(inlineSnapshot: string): string; + +/** +* 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 function addSerializer(plugin: Plugin): void; +declare function getSerializers(): Plugins; + +export { DomainSnapshotAdapter, SnapshotClient, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation }; +export type { MatchResult }; diff --git a/node_modules/@vitest/snapshot/dist/index.js b/node_modules/@vitest/snapshot/dist/index.js new file mode 100644 index 000000000..1a6147779 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/index.js @@ -0,0 +1,1188 @@ +import { parseErrorStacktrace } from '@vitest/utils/source-map'; +import { isObject, getCallLastIndex } from '@vitest/utils/helpers'; +import { positionToOffset, offsetToLineNumber, lineSplitRE } from '@vitest/utils/offset'; +import { plugins, format } from '@vitest/pretty-format'; + +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +var naturalCompare$1 = {exports: {}}; + +var hasRequiredNaturalCompare; + +function requireNaturalCompare () { + if (hasRequiredNaturalCompare) return naturalCompare$1.exports; + hasRequiredNaturalCompare = 1; + /* + * @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; + } + return naturalCompare$1.exports; +} + +var naturalCompareExports = requireNaturalCompare(); +var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports); + +const serialize$1 = (val, config, indentation, depth, refs, printer) => { + // Serialize a non-default name, even if config.printFunctionName is false. + 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 = (val) => val && !!val._isMockFunction; +const plugin = { + serialize: serialize$1, + test +}; + +const { DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent, AsymmetricMatcher } = plugins; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugin +]; +function addSerializer(plugin) { + PLUGINS = [plugin].concat(PLUGINS); +} +function getSerializers() { + return PLUGINS; +} + +// TODO: rewrite and clean up +function testNameToKey(testName, count) { + return `${testName} ${count}`; +} +function keyToTestName(key) { + if (!/ \d+$/.test(key)) { + throw new Error("Snapshot keys must end with a number."); + } + return key.replace(/ \d+$/, ""); +} +function getSnapshotData(content, options) { + const update = options.updateSnapshot; + const data = Object.create(null); + let snapshotContents = ""; + let dirty = false; + if (content != null) { + try { + snapshotContents = content; + // eslint-disable-next-line no-new-func + const populate = new Function("exports", snapshotContents); + populate(data); + } catch {} + } + // const validationResult = validateSnapshotVersion(snapshotContents) + const isInvalid = snapshotContents; + // if (update === 'none' && isInvalid) + // throw validationResult + if ((update === "all" || update === "new") && isInvalid) { + dirty = true; + } + return { + data, + dirty + }; +} +// Add extra line breaks at beginning and end of multiline snapshot +// to make the content easier to read. +function addExtraLineBreaks(string) { + return string.includes("\n") ? `\n${string}\n` : string; +} +// Remove extra line breaks at beginning and end of multiline snapshot. +// Instead of trim, which can remove additional newlines or spaces +// at beginning or end of the content from a custom serializer. +function removeExtraLineBreaks(string) { + return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string; +} +// export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => { +// const lines = stack.split('\n') +// for (let i = 0; i < lines.length; i += 1) { +// // It's a function name specified in `packages/expect/src/index.ts` +// // for external custom matchers. +// if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) +// return lines.slice(i + 1).join('\n') +// } +// return stack +// } +const escapeRegex = true; +const printFunctionName = false; +function serialize(val, indent = 2, formatOverrides = {}) { + return normalizeNewlines(format(val, { + escapeRegex, + indent, + plugins: getSerializers(), + printFunctionName, + ...formatOverrides + })); +} +function escapeBacktickString(str) { + return str.replace(/`|\\|\$\{/g, "\\$&"); +} +function printBacktickString(str) { + return `\`${escapeBacktickString(str)}\``; +} +function normalizeNewlines(string) { + return string.replace(/\r\n|\r/g, "\n"); +} +async function saveSnapshotFile(environment, snapshotData, snapshotPath) { + const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`); + const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`; + const oldContent = await environment.readSnapshotFile(snapshotPath); + const skipWriting = oldContent != null && oldContent === content; + if (skipWriting) { + return; + } + await environment.saveSnapshotFile(snapshotPath, content); +} +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(targetElement)) { + mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement); + } else { + // Source does not exist in target or target is primitive and cannot be deep merged + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +} +/** +* Deep merge, but considers asymmetric matchers. Unlike base util's deep merge, +* will merge any object-like instance. +* Compatible with Jest's snapshot matcher. Should not be used outside of snapshot. +* +* @example +* ```ts +* toMatchSnapshot({ +* name: expect.stringContaining('text') +* }) +* ``` +*/ +function deepMergeSnapshot(target, source) { + if (isObject(target) && isObject(source)) { + const mergedOutput = { ...target }; + Object.keys(source).forEach((key) => { + if (isObject(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; +} +class DefaultMap extends Map { + constructor(defaultFn, entries) { + super(entries); + this.defaultFn = defaultFn; + } + get(key) { + if (!this.has(key)) { + this.set(key, this.defaultFn(key)); + } + return super.get(key); + } +} +class CounterMap extends DefaultMap { + constructor() { + super(() => 0); + } + // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322 + // `valueOf` and `Snapshot.added` setter allows + // snapshotState.added = snapshotState.added + 1 + // to function as + // snapshotState.added.total_ = snapshotState.added.total() + 1 + _total; + valueOf() { + return this._total = this.total(); + } + increment(key) { + if (typeof this._total !== "undefined") { + this._total++; + } + this.set(key, this.get(key) + 1); + } + total() { + if (typeof this._total !== "undefined") { + return this._total; + } + let total = 0; + for (const x of this.values()) { + total += x; + } + return total; + } +} +/* @__NO_SIDE_EFFECTS__ */ +function memo(fn) { + const cache = new Map(); + return (arg) => { + if (!cache.has(arg)) { + cache.set(arg, fn(arg)); + } + return cache.get(arg); + }; +} + +async function saveInlineSnapshots(environment, snapshots) { + const MagicString = (await import('magic-string')).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 environment.readSnapshotFile(file); + if (code == null) { + throw new Error(`cannot read ${file} when saving inline snapshot`); + } + const s = new MagicString(code); + for (const snap of snaps) { + const index = positionToOffset(code, snap.line, snap.column); + replaceInlineSnap(code, s, index, snap.snapshot, snap.assertionName); + } + const transformed = s.toString(); + if (transformed !== code) { + await environment.saveSnapshotFile(file, transformed); + } + })); +} +const defaultStartObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/; +function escapeRegExp(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +const buildStartObjectRegex = memo((assertionName) => { + const replaced = defaultStartObjectRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName)); + return new RegExp(replaced); +}); +function replaceObjectSnap(code, s, index, newSnap, assertionName) { + let _code = code.slice(index); + const regex = assertionName ? buildStartObjectRegex(assertionName) : defaultStartObjectRegex; + const startMatch = regex.exec(_code); + if (!startMatch) { + return false; + } + _code = _code.slice(startMatch.index); + let callEnd = getCallLastIndex(_code); + if (callEnd === null) { + return false; + } + callEnd += index + startMatch.index; + const shapeStart = index + startMatch.index + startMatch[0].length; + const shapeEnd = getObjectShapeEndIndex(code, shapeStart); + const snap = `, ${prepareSnapString(newSnap, code, index)}`; + if (shapeEnd === callEnd) { + // toMatchInlineSnapshot({ foo: expect.any(String) }) + s.appendLeft(callEnd, snap); + } else { + // toMatchInlineSnapshot({ foo: expect.any(String) }, ``) + s.overwrite(shapeEnd, callEnd, snap); + } + return true; +} +function getObjectShapeEndIndex(code, index) { + let startBraces = 1; + let endBraces = 0; + while (startBraces !== endBraces && index < code.length) { + const s = code[index++]; + if (s === "{") { + startBraces++; + } else if (s === "}") { + endBraces++; + } + } + return index; +} +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}\t` : `${indent} `; + const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); + const isOneline = lines.length <= 1; + const quote = "`"; + if (isOneline) { + return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`; + } + return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`; +} +const defaultMethodNames = ["toMatchInlineSnapshot", "toThrowErrorMatchingInlineSnapshot"]; +// on webkit, the line number is at the end of the method, not at the start +function getCodeStartingAtIndex(code, index, methodNames) { + for (const name of methodNames) { + const adjusted = index - name.length; + if (adjusted >= 0 && code.slice(adjusted, index) === name) { + return { + code: code.slice(adjusted), + index: adjusted + }; + } + } + return { + code: code.slice(index), + index + }; +} +const defaultStartRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/; +const buildStartRegex = memo((assertionName) => { + const replaced = defaultStartRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName)); + return new RegExp(replaced); +}); +function replaceInlineSnap(code, s, currentIndex, newSnap, assertionName) { + const methodNames = assertionName ? [assertionName] : defaultMethodNames; + const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex, methodNames); + const startRegex = assertionName ? buildStartRegex(assertionName) : defaultStartRegex; + const startMatch = startRegex.exec(codeStartingAtIndex); + const keywordRegex = assertionName ? new RegExp(escapeRegExp(assertionName)) : /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/; + const firstKeywordMatch = keywordRegex.exec(codeStartingAtIndex); + if (!startMatch || startMatch.index !== firstKeywordMatch?.index) { + return replaceObjectSnap(code, s, index, newSnap, assertionName); + } + 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) { + // Find indentation if exists. + const match = inlineSnapshot.match(INDENTATION_REGEX); + if (!match || !match[1]) { + // No indentation. + return inlineSnapshot; + } + const indentation = match[1]; + const lines = inlineSnapshot.split(/\n/g); + if (lines.length <= 2) { + // Must be at least 3 lines. + return inlineSnapshot; + } + if (lines[0].trim() !== "" || lines.at(-1)?.trim() !== "") { + // If not blank first and last lines, abort. + return inlineSnapshot; + } + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== "") { + if (lines[i].indexOf(indentation) !== 0) { + // All lines except first and last should either be blank or have the same + // indent as the first line (or more). If this isn't the case we don't + // want to touch the snapshot at all. + return inlineSnapshot; + } + lines[i] = lines[i].substring(indentation.length); + } + } + // Last line is a special case because it won't have the same indent as others + // but may still have been given some indent to line up. + lines[lines.length - 1] = ""; + // Return inline snapshot, now at indent 0. + inlineSnapshot = lines.join("\n"); + return inlineSnapshot; +} + +async function saveRawSnapshots(environment, snapshots) { + await Promise.all(snapshots.map(async (snap) => { + if (!snap.readonly) { + await environment.saveSnapshotFile(snap.file, snap.snapshot); + } + })); +} + +function isSameStackPosition(x, y) { + return x.file === y.file && x.column === y.column && x.line === y.line; +} +class SnapshotState { + _counters = new CounterMap(); + _dirty; + _updateSnapshot; + _snapshotData; + _initialData; + _inlineSnapshots; + _inlineSnapshotStacks; + _testIdToKeys = new DefaultMap(() => []); + _rawSnapshots; + _uncheckedKeys; + _snapshotFormat; + _environment; + _fileExists; + expand; + // getter/setter for jest-image-snapshot compat + // https://github.com/vitest-dev/vitest/issues/7322 + _added = new CounterMap(); + _matched = new CounterMap(); + _unmatched = new CounterMap(); + _updated = new CounterMap(); + get added() { + return this._added; + } + set added(value) { + this._added._total = value; + } + get matched() { + return this._matched; + } + set matched(value) { + this._matched._total = value; + } + get unmatched() { + return this._unmatched; + } + set unmatched(value) { + this._unmatched._total = value; + } + get updated() { + return this._updated; + } + set updated(value) { + this._updated._total = value; + } + constructor(testFilePath, snapshotPath, snapshotContent, options) { + this.testFilePath = testFilePath; + this.snapshotPath = snapshotPath; + const { data, dirty } = getSnapshotData(snapshotContent, options); + this._fileExists = snapshotContent != null; + this._initialData = { ...data }; + this._snapshotData = { ...data }; + this._dirty = dirty; + this._inlineSnapshots = []; + this._inlineSnapshotStacks = []; + this._rawSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this.expand = options.expand || false; + this._updateSnapshot = options.updateSnapshot; + this._snapshotFormat = { + printBasicPrototype: false, + escapeString: false, + maxOutputLength: 2 ** 27, + ...options.snapshotFormat + }; + this._environment = options.snapshotEnvironment; + } + static async create(testFilePath, options) { + const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath); + const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath); + return new SnapshotState(testFilePath, snapshotPath, content, options); + } + get snapshotUpdateState() { + return this._updateSnapshot; + } + get environment() { + return this._environment; + } + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach((uncheckedKey) => { + // skip snapshots with following keys + // testName n + // testName > xxx n (this is for toMatchSnapshot("xxx") API) + if (/ \d+$| > /.test(uncheckedKey.slice(testName.length))) { + this._uncheckedKeys.delete(uncheckedKey); + } + }); + } + clearTest(testId) { + // clear inline + this._inlineSnapshots = this._inlineSnapshots.filter((s) => s.testId !== testId); + this._inlineSnapshotStacks = this._inlineSnapshotStacks.filter((s) => s.testId !== testId); + // clear file + for (const key of this._testIdToKeys.get(testId)) { + const name = keyToTestName(key); + const count = this._counters.get(name); + if (count > 0) { + if (key in this._snapshotData || key in this._initialData) { + this._snapshotData[key] = this._initialData[key]; + } + this._counters.set(name, count - 1); + } + } + this._testIdToKeys.delete(testId); + // clear stats + this.added.delete(testId); + this.updated.delete(testId); + this.matched.delete(testId); + this.unmatched.delete(testId); + } + _inferInlineSnapshotStack(stacks) { + // if called inside resolves/rejects, stacktrace is different + const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); + if (promiseIndex !== -1) { + return stacks[promiseIndex + 3]; + } + // support poll + inline snapshot + const pollChainIndex = stacks.findIndex((i) => i.method.match(/__VITEST_POLL_CHAIN__/)); + if (pollChainIndex !== -1) { + return stacks[pollChainIndex + 1]; + } + // inline snapshot function can be named __INLINE_SNAPSHOT_OFFSET___ + // to specify a custom stack offset + for (let i = 0; i < stacks.length; i++) { + const match = stacks[i].method.match(/__INLINE_SNAPSHOT_OFFSET_(\d+)__/); + if (match) { + return stacks[i + Number(match[1])] ?? null; + } + } + // custom matcher registered via expect.extend() — the wrapper function + // in jest-extend.ts is named __VITEST_EXTEND_ASSERTION__ + const customMatcherIndex = stacks.findIndex((i) => i.method.includes("__VITEST_EXTEND_ASSERTION__")); + if (customMatcherIndex !== -1) { + return stacks[customMatcherIndex + 3] ?? null; + } + // inline snapshot function is called __INLINE_SNAPSHOT__ + // in integrations/snapshot/chai.ts + const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__")); + return stackIndex !== -1 ? stacks[stackIndex + 2] : null; + } + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + if (options.stack) { + this._inlineSnapshots.push({ + ...options.stack, + snapshot: receivedSerialized, + testId: options.testId, + assertionName: options.assertionName + }); + } else if (options.rawSnapshot) { + this._rawSnapshots.push({ + ...options.rawSnapshot, + snapshot: receivedSerialized + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + _resolveKey(testId, testName, key) { + this._counters.increment(testName); + const count = this._counters.get(testName); + if (!key) { + key = testNameToKey(testName, count); + } + this._testIdToKeys.get(testId).push(key); + return { + key, + count + }; + } + _resolveInlineStack(options) { + const { testId, snapshot, assertionName, error } = options; + const stacks = parseErrorStacktrace(error, { ignoreStackEntries: [] }); + const _stack = this._inferInlineSnapshotStack(stacks); + if (!_stack) { + const message = stacks.map((s) => ` ${s.file}:${s.line}:${s.column}${s.method ? ` (${s.method})` : ""}`).join("\n"); + throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.\n${message}`); + } + const stack = this.environment.processStackTrace?.(_stack) || _stack; + // removing 1 column, because source map points to the wrong + // location for js files, but `column-1` points to the same in both js/ts + // https://github.com/vitejs/vite/issues/8657 + stack.column--; + // reject multiple inline snapshots at the same location if snapshot is different + const snapshotsWithSameStack = this._inlineSnapshotStacks.filter((s) => isSameStackPosition(s, stack)); + if (snapshotsWithSameStack.length > 0) { + // ensure only one snapshot will be written at the same location + this._inlineSnapshots = this._inlineSnapshots.filter((s) => !isSameStackPosition(s, stack)); + const differentSnapshot = snapshotsWithSameStack.find((s) => s.snapshot !== snapshot); + if (differentSnapshot) { + throw Object.assign(new Error(`${assertionName} with different snapshots cannot be called at the same location`), { + actual: snapshot, + expected: differentSnapshot.snapshot + }); + } + } + this._inlineSnapshotStacks.push({ + ...stack, + testId, + snapshot + }); + return stack; + } + _reconcile(opts) { + // These are the conditions on when to write snapshots: + // * There's no snapshot file in a non-CI environment. + // * There is a snapshot file and we decided to update the snapshot. + // * There is a snapshot file, but it doesn't have this snapshot. + // These are the conditions on when not to write snapshots: + // * The update flag is set to 'none'. + // * There's no snapshot file or a file without this snapshot on a CI environment. + if (opts.hasSnapshot && this._updateSnapshot === "all" || (!opts.hasSnapshot || !opts.snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { + if (this._updateSnapshot === "all") { + if (!opts.pass) { + if (opts.hasSnapshot) { + this.updated.increment(opts.testId); + } else { + this.added.increment(opts.testId); + } + this._addSnapshot(opts.key, opts.addValue, { + stack: opts.stack, + testId: opts.testId, + rawSnapshot: opts.rawSnapshot, + assertionName: opts.assertionName + }); + } else { + this.matched.increment(opts.testId); + } + } else { + this._addSnapshot(opts.key, opts.addValue, { + stack: opts.stack, + testId: opts.testId, + rawSnapshot: opts.rawSnapshot, + assertionName: opts.assertionName + }); + this.added.increment(opts.testId); + } + return { + actual: "", + count: opts.count, + expected: "", + key: opts.key, + pass: true + }; + } else { + if (!opts.pass) { + this.unmatched.increment(opts.testId); + return { + actual: opts.actualDisplay, + count: opts.count, + expected: opts.expectedDisplay, + key: opts.key, + pass: false + }; + } else { + this.matched.increment(opts.testId); + return { + actual: "", + count: opts.count, + expected: "", + key: opts.key, + pass: true + }; + } + } + } + async save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const hasRawSnapshots = this._rawSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots; + const status = { + deleted: false, + saved: false + }; + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) { + await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath); + this._fileExists = true; + } + if (hasInlineSnapshots) { + await saveInlineSnapshots(this._environment, this._inlineSnapshots); + } + if (hasRawSnapshots) { + await saveRawSnapshots(this._environment, this._rawSnapshots); + } + status.saved = true; + } else if (!hasExternalSnapshots && this._fileExists) { + if (this._updateSnapshot === "all") { + await this._environment.removeSnapshotFile(this.snapshotPath); + this._fileExists = false; + } + 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(); + } + } + probeExpectedSnapshot(options) { + const count = this._counters.get(options.testName) + 1; + const key = testNameToKey(options.testName, count); + return { + key, + count, + data: options?.isInline ? options.inlineSnapshot : this._snapshotData[key], + markAsChecked: () => { + this._counters.increment(options.testName); + this._testIdToKeys.get(options.testId).push(key); + this._uncheckedKeys.delete(key); + } + }; + } + match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }) { + const resolved = this._resolveKey(testId, testName, key); + key = resolved.key; + const count = resolved.count; + // Do not mark the snapshot as "checked" if the snapshot is inline and + // there's an external snapshot. This way the external snapshot can be + // removed with `--updateSnapshot`. + if (!(isInline && this._snapshotData[key] !== undefined)) { + this._uncheckedKeys.delete(key); + } + let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, undefined, this._snapshotFormat); + if (!rawSnapshot) { + receivedSerialized = addExtraLineBreaks(receivedSerialized); + } + if (rawSnapshot) { + // normalize EOL when snapshot contains CRLF but received is LF + if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) { + rawSnapshot.content = normalizeNewlines(rawSnapshot.content); + } + } + const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key]; + const expectedTrimmed = rawSnapshot ? expected : expected?.trim(); + const pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim()); + const hasSnapshot = expected !== undefined; + const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null; + if (pass && !isInline && !rawSnapshot) { + // When the file is re-saved (because other snapshots changed), the JS + // round-trip can lose proper escaping. Refresh in-memory data with the + // freshly serialized string so the file is written correctly. + // _reconcile does not write _snapshotData on pass, so this is the only + // place it gets refreshed. Domain snapshots skip this because the stored + // value may contain match patterns that differ from the received output. + this._snapshotData[key] = receivedSerialized; + } + const stack = isInline ? this._resolveInlineStack({ + testId, + snapshot: receivedSerialized, + assertionName: assertionName || "toMatchInlineSnapshot", + error: error || new Error("snapshot") + }) : undefined; + return this._reconcile({ + testId, + key, + count, + pass, + hasSnapshot, + snapshotIsPersisted: !!snapshotIsPersisted, + addValue: receivedSerialized, + actualDisplay: rawSnapshot ? receivedSerialized : removeExtraLineBreaks(receivedSerialized), + expectedDisplay: expectedTrimmed !== undefined ? rawSnapshot ? expectedTrimmed : removeExtraLineBreaks(expectedTrimmed) : undefined, + stack, + rawSnapshot, + assertionName + }); + } + processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }) { + const stack = isInline ? this._resolveInlineStack({ + testId, + snapshot: received, + assertionName, + error: error || new Error("STACK_TRACE_ERROR") + }) : undefined; + const actualResolved = matchResult?.resolved ?? received; + const expectedResolved = matchResult?.expected ?? expectedSnapshot.data; + return this._reconcile({ + testId, + key: expectedSnapshot.key, + count: expectedSnapshot.count, + pass: matchResult?.pass ?? false, + hasSnapshot: !!expectedSnapshot.data, + snapshotIsPersisted: isInline ? true : this._fileExists, + addValue: actualResolved, + actualDisplay: removeExtraLineBreaks(actualResolved), + expectedDisplay: expectedResolved !== undefined ? removeExtraLineBreaks(expectedResolved) : undefined, + stack, + assertionName + }); + } + 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.total(); + snapshot.matched = this.matched.total(); + snapshot.unmatched = this.unmatched.total(); + snapshot.updated = this.updated.total(); + snapshot.unchecked = !status.deleted ? uncheckedCount : 0; + snapshot.uncheckedKeys = Array.from(uncheckedKeys); + return snapshot; + } +} + +function createMismatchError(message, expand, actual, expected) { + const error = new Error(message); + Object.defineProperty(error, "actual", { + value: actual, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "expected", { + value: expected, + enumerable: true, + configurable: true, + writable: true + }); + Object.defineProperty(error, "diffOptions", { value: { expand } }); + return error; +} +class SnapshotClient { + snapshotStateMap = new Map(); + constructor(options = {}) { + this.options = options; + } + async setup(filepath, options) { + if (this.snapshotStateMap.has(filepath)) { + return; + } + this.snapshotStateMap.set(filepath, await SnapshotState.create(filepath, options)); + } + async finish(filepath) { + const state = this.getSnapshotState(filepath); + const result = await state.pack(); + this.snapshotStateMap.delete(filepath); + return result; + } + skipTest(filepath, testName) { + const state = this.getSnapshotState(filepath); + state.markSnapshotsAsCheckedForTest(testName); + } + clearTest(filepath, testId) { + const state = this.getSnapshotState(filepath); + state.clearTest(testId); + } + getSnapshotState(filepath) { + const state = this.snapshotStateMap.get(filepath); + if (!state) { + throw new Error(`The snapshot state for '${filepath}' is not found. Did you call 'SnapshotClient.setup()'?`); + } + return state; + } + match(options) { + const { filepath, name, testId = name, message, isInline = false, properties, inlineSnapshot, error, errorMessage, rawSnapshot, assertionName } = options; + let { received } = options; + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const snapshotState = this.getSnapshotState(filepath); + const testName = [name, ...message ? [message] : []].join(" > "); + // Probe first so we can mark as checked even on early return + const expectedSnapshot = snapshotState.probeExpectedSnapshot({ + testName, + testId, + isInline, + inlineSnapshot + }); + if (typeof properties === "object") { + if (typeof received !== "object" || !received) { + expectedSnapshot.markAsChecked(); + throw new Error("Received value must be an object when the matcher has properties"); + } + let propertiesPass; + try { + propertiesPass = this.options.isEqual?.(received, properties) ?? false; + } catch (err) { + expectedSnapshot.markAsChecked(); + throw err; + } + if (!propertiesPass) { + expectedSnapshot.markAsChecked(); + return { + pass: false, + message: () => errorMessage || "Snapshot properties mismatched", + actual: received, + expected: properties + }; + } + received = deepMergeSnapshot(received, properties); + } + const { actual, expected, key, pass } = snapshotState.match({ + testId, + testName, + received, + isInline, + error, + inlineSnapshot, + rawSnapshot, + assertionName + }); + return { + pass, + message: () => `Snapshot \`${key || "unknown"}\` mismatched`, + actual: rawSnapshot ? actual : actual?.trim(), + expected: rawSnapshot ? expected : expected?.trim() + }; + } + assert(options) { + const result = this.match(options); + if (!result.pass) { + const snapshotState = this.getSnapshotState(options.filepath); + throw createMismatchError(result.message(), snapshotState.expand, result.actual, result.expected); + } + } + matchDomain(options) { + const { received, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error } = options; + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const captured = adapter.capture(received); + const rendered = adapter.render(captured); + const snapshotState = this.getSnapshotState(filepath); + const testName = [name, ...message ? [message] : []].join(" > "); + const expectedSnapshot = snapshotState.probeExpectedSnapshot({ + testName, + testId, + isInline, + inlineSnapshot + }); + expectedSnapshot.markAsChecked(); + const matchResult = expectedSnapshot.data ? adapter.match(captured, adapter.parseExpected(expectedSnapshot.data)) : undefined; + const { actual, expected, key, pass } = snapshotState.processDomainSnapshot({ + testId, + received: rendered, + expectedSnapshot, + matchResult, + isInline, + error, + assertionName: options.assertionName + }); + return { + pass, + message: () => `Snapshot \`${key}\` mismatched`, + actual: actual?.trim(), + expected: expected?.trim() + }; + } + async pollMatchDomain(options) { + const { poll, filepath, name, testId = name, message, adapter, isInline = false, inlineSnapshot, error, timeout = 1e3, interval = 50 } = options; + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const snapshotState = this.getSnapshotState(filepath); + const testName = [name, ...message ? [message] : []].join(" > "); + const expectedSnapshot = snapshotState.probeExpectedSnapshot({ + testName, + testId, + isInline, + inlineSnapshot + }); + const reference = expectedSnapshot.data && snapshotState.snapshotUpdateState !== "all" ? adapter.parseExpected(expectedSnapshot.data) : undefined; + const timedOut = timeout > 0 ? new Promise((r) => setTimeout(r, timeout)) : undefined; + const stableResult = await getStableSnapshot({ + adapter, + poll, + interval, + timedOut, + match: reference ? (captured) => adapter.match(captured, reference).pass : undefined + }); + expectedSnapshot.markAsChecked(); + if (!stableResult?.rendered) { + // the original caller `expect.poll` later manipulates error via `throwWithCause`, + // so here we can directly throw `lastPollError` if exists. + if (stableResult?.lastPollError) { + throw stableResult.lastPollError; + } + return { + pass: false, + message: () => `poll() did not produce a stable snapshot within the timeout` + }; + } + // TODO: should `all` mode ignore parse error? + // Sielently hiding the error and creating snaphsot full scratch isn't good either. + // Users can fix or purge the broken snapshot manually and that decision affects how domain snapshot gets updated. + const matchResult = expectedSnapshot.data ? adapter.match(stableResult.captured, adapter.parseExpected(expectedSnapshot.data)) : undefined; + const { actual, expected, key, pass } = snapshotState.processDomainSnapshot({ + testId, + received: stableResult.rendered, + expectedSnapshot, + matchResult, + isInline, + error, + assertionName: options.assertionName + }); + return { + pass, + message: () => `Snapshot \`${key}\` mismatched`, + actual: actual?.trim(), + expected: expected?.trim() + }; + } + async assertRaw(options) { + if (!options.rawSnapshot) { + throw new Error("Raw snapshot is required"); + } + const { filepath, rawSnapshot } = options; + if (rawSnapshot.content == null) { + if (!filepath) { + throw new Error("Snapshot cannot be used outside of test"); + } + const snapshotState = this.getSnapshotState(filepath); + // save the filepath, so it don't lose even if the await make it out-of-context + options.filepath ||= filepath; + // resolve and read the raw snapshot file + rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); + rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? undefined; + } + return this.assert(options); + } + clear() { + this.snapshotStateMap.clear(); + } +} +/** +* Polls repeatedly until the value reaches a stable state. +* +* Compares consecutive rendered outputs from the current session — +* when two consecutive polls produce the same rendered string, +* the value is considered stable. +* +* Every `await` (poll call, interval delay) races against `timedOut` +* so that hanging polls and delays are interrupted. +*/ +async function getStableSnapshot({ adapter, poll, interval, timedOut, match }) { + let lastRendered; + let lastPollError; + let lastStable; + while (true) { + try { + const pollResult = await raceWith(Promise.resolve(poll()), timedOut); + if (!pollResult.ok) { + break; + } + const captured = adapter.capture(pollResult.value); + const rendered = adapter.render(captured); + if (lastRendered !== undefined && rendered === lastRendered) { + lastStable = { + captured, + rendered + }; + if (!match || match(captured)) { + break; + } + } else { + lastRendered = rendered; + lastStable = undefined; + } + } catch (pollError) { + // poll() threw — reset stability baseline and retry + lastRendered = undefined; + lastStable = undefined; + lastPollError = pollError; + } + const delayed = await raceWith(new Promise((r) => setTimeout(r, interval)), timedOut); + if (!delayed.ok) { + break; + } + } + return { + ...lastStable, + lastPollError + }; +} +/** Type-safe `Promise.race` — tells you which promise won. */ +function raceWith(promise, other) { + const left = promise.then((value) => ({ + ok: true, + value + })); + if (!other) { + return left; + } + return Promise.race([left, other.then((value) => ({ + ok: false, + value + }))]); +} + +export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/node_modules/@vitest/snapshot/dist/manager.d.ts b/node_modules/@vitest/snapshot/dist/manager.d.ts new file mode 100644 index 000000000..0b406f233 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/manager.d.ts @@ -0,0 +1,19 @@ +import { a as SnapshotStateOptions, g as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-D_X3-62x.js'; +import '@vitest/pretty-format'; +import '@vitest/utils'; +import './environment.d-DOJxxZV9.js'; + +declare class SnapshotManager { + options: Omit; + summary: SnapshotSummary; + extension: string; + constructor(options: Omit); + clear(): void; + add(result: SnapshotResult): void; + resolvePath(testPath: string, context?: T): string; + resolveRawPath(testPath: string, rawPath: string): string; +} +declare function emptySummary(options: Omit): SnapshotSummary; +declare function addSnapshotResult(summary: SnapshotSummary, result: SnapshotResult): void; + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/node_modules/@vitest/snapshot/dist/manager.js b/node_modules/@vitest/snapshot/dist/manager.js new file mode 100644 index 000000000..4632d5ac1 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/manager.js @@ -0,0 +1,73 @@ +import { join, dirname, basename, isAbsolute, resolve } from 'pathe'; + +class SnapshotManager { + summary; + extension = ".snap"; + constructor(options) { + this.options = options; + this.clear(); + } + clear() { + this.summary = emptySummary(this.options); + } + add(result) { + addSnapshotResult(this.summary, result); + } + resolvePath(testPath, context) { + const resolver = this.options.resolveSnapshotPath || (() => { + return join(join(dirname(testPath), "__snapshots__"), `${basename(testPath)}${this.extension}`); + }); + const path = resolver(testPath, this.extension, context); + return path; + } + resolveRawPath(testPath, rawPath) { + return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); + } +} +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; +} + +export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/node_modules/@vitest/snapshot/dist/rawSnapshot.d-D_X3-62x.d.ts b/node_modules/@vitest/snapshot/dist/rawSnapshot.d-D_X3-62x.d.ts new file mode 100644 index 000000000..bae9defa7 --- /dev/null +++ b/node_modules/@vitest/snapshot/dist/rawSnapshot.d-D_X3-62x.d.ts @@ -0,0 +1,205 @@ +import { OptionsReceived, Plugin } from '@vitest/pretty-format'; +import { ParsedStack } from '@vitest/utils'; +import { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js'; + +interface DomainMatchResult { + pass: boolean; + message?: string; + /** + * The captured value viewed through the template's lens. + * + * Where the template uses patterns (e.g. regexes) or omits details, + * the resolved string adopts those patterns. Where the template doesn't + * match, the resolved string uses literal captured values instead. + * + * Used for two purposes: + * - **Diff display** (actual side): compared against `expected` + * so the diff highlights only genuine mismatches, not pattern-vs-literal noise. + * - **Snapshot update** (`--update`): written as the new snapshot content, + * preserving user-edited patterns from matched regions while incorporating + * actual values for mismatched regions. + * + * When omitted, falls back to `render(capture(received))` (the raw rendered value). + */ + resolved?: string; + /** + * The stored template re-rendered as a string, representing what the user + * originally wrote or last saved. + * + * Used as the expected side in diff display. + * + * When omitted, falls back to the raw snapshot string from the snap file + * or inline snapshot. + */ + expected?: string; +} +interface DomainSnapshotAdapter< + Captured = unknown, + Expected = unknown +> { + name: string; + capture: (received: unknown) => Captured; + render: (captured: Captured) => string; + parseExpected: (input: string) => Expected; + match: (captured: Captured, expected: Expected) => DomainMatchResult; +} + +/** +* 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 class DefaultMap< + K, + V +> extends Map { + private defaultFn; + constructor(defaultFn: (key: K) => V, entries?: Iterable); + get(key: K): V; +} +declare class CounterMap extends DefaultMap { + constructor(); + _total: number | undefined; + valueOf(): number; + increment(key: K): void; + total(): number; +} + +interface SnapshotReturnOptions { + actual: string; + count: number; + expected?: string; + key: string; + pass: boolean; +} +interface SaveStatus { + deleted: boolean; + saved: boolean; +} +interface ExpectedSnapshot { + key: string; + count: number; + data?: string; + markAsChecked: () => void; +} +declare class SnapshotState { + testFilePath: string; + snapshotPath: string; + private _counters; + private _dirty; + private _updateSnapshot; + private _snapshotData; + private _initialData; + private _inlineSnapshots; + private _inlineSnapshotStacks; + private _testIdToKeys; + private _rawSnapshots; + private _uncheckedKeys; + private _snapshotFormat; + private _environment; + private _fileExists; + expand: boolean; + private _added; + private _matched; + private _unmatched; + private _updated; + get added(): CounterMap; + set added(value: number); + get matched(): CounterMap; + set matched(value: number); + get unmatched(): CounterMap; + set unmatched(value: number); + get updated(): CounterMap; + set updated(value: number); + private constructor(); + static create(testFilePath: string, options: SnapshotStateOptions): Promise; + get snapshotUpdateState(): SnapshotUpdateState; + get environment(): SnapshotEnvironment; + markSnapshotsAsCheckedForTest(testName: string): void; + clearTest(testId: string): void; + protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null; + private _addSnapshot; + private _resolveKey; + private _resolveInlineStack; + private _reconcile; + save(): Promise; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + probeExpectedSnapshot(options: Pick): ExpectedSnapshot; + match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, assertionName }: SnapshotMatchOptions): SnapshotReturnOptions; + processDomainSnapshot({ testId, received, expectedSnapshot, matchResult, isInline, error, assertionName }: ProcessDomainSnapshotOptions): SnapshotReturnOptions; + pack(): Promise; +} + +type SnapshotData = Record; +type SnapshotUpdateState = "all" | "new" | "none"; +type SnapshotSerializer = Plugin; +interface SnapshotStateOptions { + updateSnapshot: SnapshotUpdateState; + snapshotEnvironment: SnapshotEnvironment; + expand?: boolean; + snapshotFormat?: OptionsReceived; + resolveSnapshotPath?: (path: string, extension: string, context?: any) => string; +} +interface SnapshotMatchOptions { + testId: string; + testName: string; + received: unknown; + key?: string; + inlineSnapshot?: string; + isInline: boolean; + error?: Error; + rawSnapshot?: RawSnapshotInfo; + assertionName?: string; +} +interface ProcessDomainSnapshotOptions { + testId: string; + received: string; + expectedSnapshot: ExpectedSnapshot; + matchResult?: DomainMatchResult; + isInline?: boolean; + assertionName?: string; + 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 RawSnapshotInfo { + file: string; + readonly?: boolean; + content?: string; +} + +export { SnapshotState as S }; +export type { DomainSnapshotAdapter as D, RawSnapshotInfo as R, UncheckedSnapshot as U, SnapshotStateOptions as a, SnapshotResult as b, DomainMatchResult as c, SnapshotData as d, SnapshotMatchOptions as e, SnapshotSerializer as f, SnapshotSummary as g, SnapshotUpdateState as h }; diff --git a/node_modules/@vitest/snapshot/environment.d.ts b/node_modules/@vitest/snapshot/environment.d.ts new file mode 100644 index 000000000..855f0d10a --- /dev/null +++ b/node_modules/@vitest/snapshot/environment.d.ts @@ -0,0 +1 @@ +export * from './dist/environment.js' diff --git a/node_modules/@vitest/snapshot/manager.d.ts b/node_modules/@vitest/snapshot/manager.d.ts new file mode 100644 index 000000000..f3e80774b --- /dev/null +++ b/node_modules/@vitest/snapshot/manager.d.ts @@ -0,0 +1 @@ +export * from './dist/manager.js' diff --git a/node_modules/@vitest/snapshot/package.json b/node_modules/@vitest/snapshot/package.json new file mode 100644 index 000000000..ec43a199e --- /dev/null +++ b/node_modules/@vitest/snapshot/package.json @@ -0,0 +1,59 @@ +{ + "name": "@vitest/snapshot", + "type": "module", + "version": "4.1.5", + "description": "Vitest snapshot manager", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/guide/snapshot", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/snapshot" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "snapshot" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./environment": { + "types": "./dist/environment.d.ts", + "default": "./dist/environment.js" + }, + "./manager": { + "types": "./dist/manager.d.ts", + "default": "./dist/manager.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "magic-string": "^0.30.21", + "pathe": "^2.0.3", + "@vitest/pretty-format": "4.1.5", + "@vitest/utils": "4.1.5" + }, + "devDependencies": { + "@types/natural-compare": "^1.4.3", + "natural-compare": "^1.4.0" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/spy/LICENSE b/node_modules/@vitest/spy/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/spy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/spy/README.md b/node_modules/@vitest/spy/README.md new file mode 100644 index 000000000..97129c5ea --- /dev/null +++ b/node_modules/@vitest/spy/README.md @@ -0,0 +1,7 @@ +# @vitest/spy + +[![NPM version](https://img.shields.io/npm/v/@vitest/spy?color=a1b858&label=)](https://npmx.dev/package/@vitest/spy) + +Lightweight Jest-compatible mocking implementation. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/spy) | [Documentation](https://vitest.dev/api/mock) diff --git a/node_modules/@vitest/spy/dist/index.d.ts b/node_modules/@vitest/spy/dist/index.d.ts new file mode 100644 index 000000000..bd483c0cf --- /dev/null +++ b/node_modules/@vitest/spy/dist/index.d.ts @@ -0,0 +1,416 @@ +import { Disposable } from '@vitest/spy/optional-types.js'; + +interface MockResultReturn { + type: "return"; + /** + * The value that was returned from the function. If function returned a Promise, then this will be a resolved value. + */ + value: T; +} +interface MockResultIncomplete { + type: "incomplete"; + value: undefined; +} +interface MockResultThrow { + type: "throw"; + /** + * An error that was thrown during function execution. + */ + value: any; +} +interface MockSettledResultIncomplete { + type: "incomplete"; + value: undefined; +} +interface MockSettledResultFulfilled { + type: "fulfilled"; + value: T; +} +interface MockSettledResultRejected { + type: "rejected"; + value: any; +} +type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; +type MockSettledResult = MockSettledResultFulfilled | MockSettledResultRejected | MockSettledResultIncomplete; +type MockParameters = T extends Constructable ? ConstructorParameters : T extends Procedure ? Parameters : never; +type MockReturnType = T extends Constructable ? InstanceType : T extends Procedure ? ReturnType : never; +type MockProcedureContext = T extends Constructable ? InstanceType : ThisParameterType; +interface MockContext { + /** + * This is an array containing all arguments for each call. One item of the array is the arguments of that call. + * + * @see https://vitest.dev/api/mock#mock-calls + * @example + * const fn = vi.fn() + * + * fn('arg1', 'arg2') + * fn('arg3') + * + * fn.mock.calls === [ + * ['arg1', 'arg2'], // first call + * ['arg3'], // second call + * ] + */ + calls: MockParameters[]; + /** + * This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value. + * @see https://vitest.dev/api/mock#mock-instances + */ + instances: MockProcedureContext[]; + /** + * An array of `this` values that were used during each call to the mock function. + * @see https://vitest.dev/api/mock#mock-contexts + */ + contexts: MockProcedureContext[]; + /** + * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks. + * + * @see https://vitest.dev/api/mock#mock-invocationcallorder + * @example + * const fn1 = vi.fn() + * const fn2 = vi.fn() + * + * fn1() + * fn2() + * fn1() + * + * fn1.mock.invocationCallOrder === [1, 3] + * fn2.mock.invocationCallOrder === [2] + */ + invocationCallOrder: number[]; + /** + * This is an array containing all values that were `returned` from the function. + * + * The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected. + * + * @see https://vitest.dev/api/mock#mock-results + * @example + * const fn = vi.fn() + * .mockReturnValueOnce('result') + * .mockImplementationOnce(() => { throw new Error('thrown error') }) + * + * const result = fn() + * + * try { + * fn() + * } + * catch {} + * + * fn.mock.results === [ + * { + * type: 'return', + * value: 'result', + * }, + * { + * type: 'throw', + * value: Error, + * }, + * ] + */ + results: MockResult>[]; + /** + * An array containing all values that were `resolved` or `rejected` from the function. + * + * This array will be empty if the function was never resolved or rejected. + * + * @see https://vitest.dev/api/mock#mock-settledresults + * @example + * const fn = vi.fn().mockResolvedValueOnce('result') + * + * const result = fn() + * + * fn.mock.settledResults === [ + * { + * type: 'incomplete', + * value: undefined, + * } + * ] + * fn.mock.results === [ + * { + * type: 'return', + * value: Promise<'result'>, + * }, + * ] + * + * await result + * + * fn.mock.settledResults === [ + * { + * type: 'fulfilled', + * value: 'result', + * }, + * ] + */ + settledResults: MockSettledResult>>[]; + /** + * This contains the arguments of the last call. If spy wasn't called, will return `undefined`. + * @see https://vitest.dev/api/mock#mock-lastcall + */ + lastCall: MockParameters | undefined; +} +type Procedure = (...args: any[]) => any; +type NormalizedProcedure = T extends Constructable ? ({ + new (...args: ConstructorParameters): InstanceType; +}) | ({ + (this: InstanceType, ...args: ConstructorParameters): void; +}) : T extends Procedure ? (...args: Parameters) => ReturnType : never; +type Methods = keyof { [K in keyof T as T[K] extends Procedure ? K : never] : T[K] }; +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 MockInstance extends Disposable { + /** + * Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`. + * @see https://vitest.dev/api/mock#getmockname + */ + getMockName(): string; + /** + * Sets the internal mock name. This is useful for identifying the mock when an assertion fails. + * @see https://vitest.dev/api/mock#mockname + */ + mockName(name: string): this; + /** + * Current context of the mock. It stores information about all invocation calls, instances, and results. + */ + mock: MockContext; + /** + * Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions. + * + * To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/clearmocks) setting in the configuration. + * @see https://vitest.dev/api/mock#mockclear + */ + mockClear(): this; + /** + * Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations. + * + * Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. + * Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state. + * + * To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/mockreset) setting in the configuration. + * @see https://vitest.dev/api/mock#mockreset + */ + mockReset(): this; + /** + * Does what `mockReset` does and restores original descriptors of spied-on objects. + * @see https://vitest.dev/api/mock#mockrestore + */ + mockRestore(): void; + /** + * Returns current permanent mock implementation if there is one. + * + * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation. + * + * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided. + */ + getMockImplementation(): NormalizedProcedure | undefined; + /** + * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. + * @see https://vitest.dev/api/mock#mockimplementation + * @example + * const increment = vi.fn().mockImplementation(count => count + 1); + * expect(increment(3)).toBe(4); + */ + mockImplementation(fn: NormalizedProcedure): this; + /** + * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls. + * + * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. + * @see https://vitest.dev/api/mock#mockimplementationonce + * @example + * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1); + * expect(fn(3)).toBe(4); + * expect(fn(3)).toBe(3); + */ + mockImplementationOnce(fn: NormalizedProcedure): this; + /** + * Overrides the original mock implementation temporarily while the callback is being executed. + * + * Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce). + * @see https://vitest.dev/api/mock#withimplementation + * @example + * const myMockFn = vi.fn(() => 'original') + * + * myMockFn.withImplementation(() => 'temp', () => { + * myMockFn() // 'temp' + * }) + * + * myMockFn() // 'original' + */ + withImplementation(fn: NormalizedProcedure, cb: () => Promise): Promise; + withImplementation(fn: NormalizedProcedure, cb: () => unknown): this; + /** + * Use this if you need to return the `this` context from the method without invoking the actual implementation. + * @see https://vitest.dev/api/mock#mockreturnthis + */ + mockReturnThis(): this; + /** + * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. + * @see https://vitest.dev/api/mock#mockreturnvalue + * @example + * const mock = vi.fn() + * mock.mockReturnValue(42) + * mock() // 42 + * mock.mockReturnValue(43) + * mock() // 43 + */ + mockReturnValue(value: MockReturnType): this; + /** + * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. + * + * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. + * @example + * const myMockFn = vi + * .fn() + * .mockReturnValue('default') + * .mockReturnValueOnce('first call') + * .mockReturnValueOnce('second call') + * + * // 'first call', 'second call', 'default' + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockReturnValueOnce(value: MockReturnType): this; + /** + * Accepts a value that will be thrown whenever the mock function is called. + * @see https://vitest.dev/api/mock#mockthrow + * @example + * const myMockFn = vi.fn().mockThrow(new Error('error')) + * myMockFn() // throws 'error' + */ + mockThrow(value: unknown): this; + /** + * Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value. + * @example + * const myMockFn = vi + * .fn() + * .mockReturnValue('default') + * .mockThrowOnce(new Error('first call error')) + * .mockThrowOnce('second call error') + * + * expect(() => myMockFn()).toThrowError('first call error') + * expect(() => myMockFn()).toThrowError('second call error') + * expect(myMockFn()).toEqual('default') + */ + mockThrowOnce(value: unknown): this; + /** + * Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function. + * @example + * const asyncMock = vi.fn().mockResolvedValue(42) + * asyncMock() // Promise<42> + */ + mockResolvedValue(value: Awaited>): this; + /** + * Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value. + * @example + * const myMockFn = vi + * .fn() + * .mockResolvedValue('default') + * .mockResolvedValueOnce('first call') + * .mockResolvedValueOnce('second call') + * + * // Promise<'first call'>, Promise<'second call'>, Promise<'default'> + * console.log(myMockFn(), myMockFn(), myMockFn()) + */ + mockResolvedValueOnce(value: Awaited>): this; + /** + * Accepts an error that will be rejected when async function is called. + * @example + * const asyncMock = vi.fn().mockRejectedValue(new Error('Async error')) + * await asyncMock() // throws Error<'Async error'> + */ + mockRejectedValue(error: unknown): this; + /** + * Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value. + * @example + * const asyncMock = vi + * .fn() + * .mockResolvedValueOnce('first call') + * .mockRejectedValueOnce(new Error('Async error')) + * + * await asyncMock() // first call + * await asyncMock() // throws Error<'Async error'> + */ + mockRejectedValueOnce(error: unknown): this; +} +type Mock = MockInstance & (T extends Constructable ? (T extends Procedure ? { + new (...args: ConstructorParameters): InstanceType; + (...args: Parameters): ReturnType; +} : { + new (...args: ConstructorParameters): InstanceType; +}) : { + new (...args: MockParameters): MockReturnType; + (...args: MockParameters): MockReturnType; +}) & { [P in keyof T] : T[P] }; +type PartialMaybePromise = T extends Promise> ? Promise>> : Partial; +type PartialResultFunction = T extends Constructable ? ({ + new (...args: ConstructorParameters): InstanceType; +}) | ({ + (this: InstanceType, ...args: ConstructorParameters): void; +}) : T extends Procedure ? (...args: Parameters) => PartialMaybePromise> : T; +type PartialMock = Mock> : T>>; +type DeepPartial = T extends Procedure ? T : T extends Array ? Array> : T extends object ? { [K in keyof T]? : DeepPartial } : T; +type DeepPartialMaybePromise = T extends Promise> ? Promise>> : DeepPartial; +type DeepPartialResultFunction = T extends Constructable ? ({ + new (...args: ConstructorParameters): InstanceType; +}) | ({ + (this: InstanceType, ...args: ConstructorParameters): void; +}) : T extends Procedure ? (...args: Parameters) => DeepPartialMaybePromise> : T; +type DeepPartialMock = Mock> : T>>; +type MaybeMockedConstructor = T extends Constructable ? Mock : T; +type MockedFunction = Mock & MockedObject; +type PartiallyMockedFunction = PartialMock & MockedObject; +type MockedFunctionDeep = Mock & MockedObjectDeep; +type PartiallyMockedFunctionDeep = DeepPartialMock & 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 | Constructable ? MockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybePartiallyMockedDeep = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep : T extends object ? MockedObjectDeep : T; +type MaybeMocked = T extends Procedure | Constructable ? MockedFunction : T extends object ? MockedObject : T; +type MaybePartiallyMocked = T extends Procedure | Constructable ? PartiallyMockedFunction : T extends object ? MockedObject : T; +interface Constructable { + new (...args: any[]): any; +} +type MockedClass = MockInstance & { + prototype: T extends { + prototype: any; + } ? Mocked : never; +} & T; +type Mocked = { [P in keyof T] : T[P] extends Procedure ? MockInstance : T[P] extends Constructable ? MockedClass : T[P] } & T; +interface MockConfig { + mockImplementation: Procedure | Constructable | undefined; + mockOriginal: Procedure | Constructable | undefined; + mockName: string; + onceMockImplementations: Array; +} +interface MockInstanceOption { + originalImplementation?: Procedure | Constructable; + mockImplementation?: Procedure | Constructable; + resetToMockImplementation?: boolean; + restore?: () => void; + prototypeMembers?: (string | symbol)[]; + keepMembersImplementation?: boolean; + prototypeState?: MockContext; + prototypeConfig?: MockConfig; + resetToMockName?: boolean; + name?: string | symbol; +} + +declare function isMockFunction(fn: any): fn is Mock; +declare function createMockInstance(options?: MockInstanceOption): Mock; +declare function fn(originalImplementation?: T): Mock; +declare function spyOn< + T extends object, + S extends Properties> +>(object: T, key: S, accessor: "get"): Mock<() => T[S]>; +declare function spyOn< + T extends object, + G extends Properties> +>(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>; +declare function spyOn< + T extends object, + M extends Classes> | Methods> +>(object: T, key: M): Required[M] extends Constructable | Procedure ? Mock[M]> : never; +declare function restoreAllMocks(): void; +declare function clearAllMocks(): void; +declare function resetAllMocks(): void; + +export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; +export type { Constructable, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep, Mock, MockContext, MockInstance, MockInstanceOption, MockParameters, MockProcedureContext, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockReturnType, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, PartialMock, PartiallyMockedFunction, PartiallyMockedFunctionDeep, Procedure }; diff --git a/node_modules/@vitest/spy/dist/index.js b/node_modules/@vitest/spy/dist/index.js new file mode 100644 index 000000000..6d907fc02 --- /dev/null +++ b/node_modules/@vitest/spy/dist/index.js @@ -0,0 +1,483 @@ +function isMockFunction(fn) { + return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true; +} +const MOCK_RESTORE = new Set(); +// Jest keeps the state in a separate WeakMap which is good for memory, +// but it makes the state slower to access and return different values +// if you stored it before calling `mockClear` where it will be recreated +const REGISTERED_MOCKS = new Set(); +const MOCK_CONFIGS = new WeakMap(); +function createMockInstance(options = {}) { + const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options; + if (restore) { + MOCK_RESTORE.add(restore); + } + const config = getDefaultConfig(originalImplementation); + const state = getDefaultState(); + const mock = createMock({ + config, + state, + ...options + }); + const mockLength = (mockImplementation || originalImplementation)?.length ?? 0; + Object.defineProperty(mock, "length", { + writable: true, + enumerable: false, + value: mockLength, + configurable: true + }); + // inherit the default name so it appears in snapshots and logs + // this is used by `vi.spyOn()` for better debugging. + // when `vi.fn()` is called, we just use the default string + if (resetToMockName) { + config.mockName = mock.name || "vi.fn()"; + } + MOCK_CONFIGS.set(mock, config); + REGISTERED_MOCKS.add(mock); + mock._isMockFunction = true; + mock.getMockImplementation = () => { + // Jest only returns `config.mockImplementation` here, + // but we think it makes sense to return what the next function will be called + return config.onceMockImplementations[0] || config.mockImplementation; + }; + Object.defineProperty(mock, "mock", { + configurable: false, + enumerable: true, + writable: false, + value: state + }); + mock.mockImplementation = function mockImplementation(implementation) { + config.mockImplementation = implementation; + return mock; + }; + mock.mockImplementationOnce = function mockImplementationOnce(implementation) { + config.onceMockImplementations.push(implementation); + return mock; + }; + mock.withImplementation = function withImplementation(implementation, callback) { + const previousImplementation = config.mockImplementation; + const previousOnceImplementations = config.onceMockImplementations; + const reset = () => { + config.mockImplementation = previousImplementation; + config.onceMockImplementations = previousOnceImplementations; + }; + config.mockImplementation = implementation; + config.onceMockImplementations = []; + const returnValue = callback(); + if (typeof returnValue === "object" && typeof returnValue?.then === "function") { + return returnValue.then(() => { + reset(); + return mock; + }); + } else { + reset(); + } + return mock; + }; + mock.mockReturnThis = function mockReturnThis() { + return mock.mockImplementation(function() { + return this; + }); + }; + mock.mockReturnValue = function mockReturnValue(value) { + return mock.mockImplementation(function() { + if (new.target) { + throwConstructorError("mockReturnValue"); + } + return value; + }); + }; + mock.mockReturnValueOnce = function mockReturnValueOnce(value) { + return mock.mockImplementationOnce(function() { + if (new.target) { + throwConstructorError("mockReturnValueOnce"); + } + return value; + }); + }; + mock.mockThrow = function mockThrow(value) { + // eslint-disable-next-line prefer-arrow-callback + return mock.mockImplementation(function() { + throw value; + }); + }; + mock.mockThrowOnce = function mockThrowOnce(value) { + // eslint-disable-next-line prefer-arrow-callback + return mock.mockImplementationOnce(function() { + throw value; + }); + }; + mock.mockResolvedValue = function mockResolvedValue(value) { + return mock.mockImplementation(function() { + if (new.target) { + throwConstructorError("mockResolvedValue"); + } + return Promise.resolve(value); + }); + }; + mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) { + return mock.mockImplementationOnce(function() { + if (new.target) { + throwConstructorError("mockResolvedValueOnce"); + } + return Promise.resolve(value); + }); + }; + mock.mockRejectedValue = function mockRejectedValue(value) { + return mock.mockImplementation(function() { + if (new.target) { + throwConstructorError("mockRejectedValue"); + } + return Promise.reject(value); + }); + }; + mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) { + return mock.mockImplementationOnce(function() { + if (new.target) { + throwConstructorError("mockRejectedValueOnce"); + } + return Promise.reject(value); + }); + }; + mock.mockClear = function mockClear() { + state.calls = []; + state.contexts = []; + state.instances = []; + state.invocationCallOrder = []; + state.results = []; + state.settledResults = []; + return mock; + }; + mock.mockReset = function mockReset() { + mock.mockClear(); + config.mockImplementation = resetToMockImplementation ? mockImplementation : undefined; + config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()"; + config.onceMockImplementations = []; + return mock; + }; + mock.mockRestore = function mockRestore() { + mock.mockReset(); + return restore?.(); + }; + mock.mockName = function mockName(name) { + if (typeof name === "string") { + config.mockName = name; + } + return mock; + }; + mock.getMockName = function getMockName() { + return config.mockName || "vi.fn()"; + }; + if (Symbol.dispose) { + mock[Symbol.dispose] = () => mock.mockRestore(); + } + if (mockImplementation) { + mock.mockImplementation(mockImplementation); + } + return mock; +} +function fn(originalImplementation) { + // if the function is already a mock, just return the same function, + // similarly to how vi.spyOn() works + if (originalImplementation != null && isMockFunction(originalImplementation)) { + return originalImplementation; + } + return createMockInstance({ + mockImplementation: originalImplementation, + resetToMockImplementation: true + }); +} +function spyOn(object, key, accessor) { + assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined."); + assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value."); + const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || []; + assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`); + let accessType = accessor || "value"; + let ssr = false; + // vite ssr support - actual function is stored inside a getter + if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) { + accessType = "get"; + ssr = true; + } + let original; + if (originalDescriptor) { + original = originalDescriptor[accessType]; + // weird Proxy edge case where descriptor's value is undefined, + // but there's still a value on the object when called + // https://github.com/vitest-dev/vitest/issues/9439 + if (original == null && accessType === "value") { + original = object[key]; + } + } else if (accessType !== "value") { + original = () => object[key]; + } else { + original = object[key]; + } + const originalImplementation = ssr && original ? original() : original; + const originalType = typeof originalImplementation; + assert( + // allow only functions + originalType === "function" || accessType !== "value" && original == null, + `vi.spyOn() can only spy on a function. Received ${originalType}.` + ); + if (isMockFunction(originalImplementation)) { + return originalImplementation; + } + const reassign = (cb) => { + const { value, ...desc } = originalDescriptor || { + configurable: true, + writable: true + }; + if (accessType !== "value") { + delete desc.writable; + } + desc[accessType] = cb; + Object.defineProperty(object, key, desc); + }; + const restore = () => { + // if method is defined on the prototype, we can just remove it from + // the current object instead of redefining a copy of it + if (originalDescriptorObject !== object) { + Reflect.deleteProperty(object, key); + } else if (originalDescriptor && !original) { + Object.defineProperty(object, key, originalDescriptor); + } else { + reassign(original); + } + }; + const mock = createMockInstance({ + restore, + originalImplementation, + resetToMockName: true + }); + try { + reassign(ssr ? () => mock : mock); + } catch (error) { + if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) { + throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error }); + } + throw error; + } + return mock; +} +function getDescriptor(obj, method) { + const objDescriptor = Object.getOwnPropertyDescriptor(obj, method); + if (objDescriptor) { + return [obj, objDescriptor]; + } + let currentProto = Object.getPrototypeOf(obj); + while (currentProto !== null) { + const descriptor = Object.getOwnPropertyDescriptor(currentProto, method); + if (descriptor) { + return [currentProto, descriptor]; + } + currentProto = Object.getPrototypeOf(currentProto); + } +} +function assert(condition, message) { + if (!condition) { + throw new Error(message); + } +} +let invocationCallCounter = 1; +function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) { + const original = config.mockOriginal; + const pseudoOriginal = mockImplementation; + const name = mockName || original?.name || "Mock"; + const namedObject = { [name]: (function(...args) { + registerCalls(args, state, prototypeState); + registerInvocationOrder(invocationCallCounter++, state, prototypeState); + const result = { + type: "incomplete", + value: undefined + }; + const settledResult = { + type: "incomplete", + value: undefined + }; + registerResult(result, state, prototypeState); + registerSettledResult(settledResult, state, prototypeState); + const context = new.target ? undefined : this; + const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState); + const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState); + const implementation = config.onceMockImplementations.shift() || config.mockImplementation || prototypeConfig?.onceMockImplementations.shift() || prototypeConfig?.mockImplementation || original || function() {}; + let returnValue; + let thrownValue; + let didThrow = false; + try { + if (new.target) { + returnValue = Reflect.construct(implementation, args, new.target); + // jest calls this before the implementation, but we have to resolve this _after_ + // because we cannot do it before the `Reflect.construct` called the custom implementation. + // fortunately, the constructor is always an empty function because `prototypeMethods` + // are only used by the automocker, so this doesn't matter + for (const prop of prototypeMembers) { + const prototypeMock = returnValue[prop]; + // the method was overridden because of inheritance, ignore it + // eslint-disable-next-line ts/no-use-before-define + if (prototypeMock !== mock.prototype[prop]) { + continue; + } + const isMock = isMockFunction(prototypeMock); + const prototypeState = isMock ? prototypeMock.mock : undefined; + const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined; + returnValue[prop] = createMockInstance({ + originalImplementation: keepMembersImplementation ? prototypeConfig?.mockOriginal : undefined, + prototypeState, + prototypeConfig, + keepMembersImplementation + }); + } + } else { + returnValue = implementation.apply(this, args); + } + } catch (error) { + thrownValue = error; + didThrow = true; + if (error instanceof TypeError && error.message.includes("is not a constructor")) { + console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`); + } + throw error; + } finally { + if (didThrow) { + result.type = "throw"; + result.value = thrownValue; + settledResult.type = "rejected"; + settledResult.value = thrownValue; + } else { + result.type = "return"; + result.value = returnValue; + if (new.target) { + state.contexts[contextIndex - 1] = returnValue; + state.instances[instanceIndex - 1] = returnValue; + if (contextPrototypeIndex != null && prototypeState) { + prototypeState.contexts[contextPrototypeIndex - 1] = returnValue; + } + if (instancePrototypeIndex != null && prototypeState) { + prototypeState.instances[instancePrototypeIndex - 1] = returnValue; + } + } + if (returnValue instanceof Promise) { + returnValue.then((settledValue) => { + settledResult.type = "fulfilled"; + settledResult.value = settledValue; + }, (rejectedValue) => { + settledResult.type = "rejected"; + settledResult.value = rejectedValue; + }); + } else { + settledResult.type = "fulfilled"; + settledResult.value = returnValue; + } + } + } + return returnValue; + }) }; + const mock = namedObject[name]; + const copyPropertiesFrom = original || pseudoOriginal; + if (copyPropertiesFrom) { + copyOriginalStaticProperties(mock, copyPropertiesFrom); + } + return mock; +} +function registerCalls(args, state, prototypeState) { + state.calls.push(args); + prototypeState?.calls.push(args); +} +function registerInvocationOrder(order, state, prototypeState) { + state.invocationCallOrder.push(order); + prototypeState?.invocationCallOrder.push(order); +} +function registerResult(result, state, prototypeState) { + state.results.push(result); + prototypeState?.results.push(result); +} +function registerSettledResult(result, state, prototypeState) { + state.settledResults.push(result); + prototypeState?.settledResults.push(result); +} +function registerInstance(instance, state, prototypeState) { + const instanceIndex = state.instances.push(instance); + const instancePrototypeIndex = prototypeState?.instances.push(instance); + return [instanceIndex, instancePrototypeIndex]; +} +function registerContext(context, state, prototypeState) { + const contextIndex = state.contexts.push(context); + const contextPrototypeIndex = prototypeState?.contexts.push(context); + return [contextIndex, contextPrototypeIndex]; +} +function copyOriginalStaticProperties(mock, original) { + const { properties, descriptors } = getAllProperties(original); + for (const key of properties) { + const descriptor = descriptors[key]; + const mockDescriptor = getDescriptor(mock, key); + if (mockDescriptor) { + continue; + } + Object.defineProperty(mock, key, descriptor); + } +} +const ignoreProperties = new Set([ + "length", + "name", + "prototype", + Symbol.for("nodejs.util.promisify.custom") +]); +function getAllProperties(original) { + const properties = new Set(); + const descriptors = {}; + while (original && original !== Object.prototype && original !== Function.prototype) { + const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)]; + for (const prop of ownProperties) { + if (descriptors[prop] || ignoreProperties.has(prop)) { + continue; + } + properties.add(prop); + descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop); + } + original = Object.getPrototypeOf(original); + } + return { + properties, + descriptors + }; +} +function getDefaultConfig(original) { + return { + mockImplementation: undefined, + mockOriginal: original, + mockName: "vi.fn()", + onceMockImplementations: [] + }; +} +function getDefaultState() { + const state = { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + settledResults: [], + results: [], + get lastCall() { + return state.calls.at(-1); + } + }; + return state; +} +function restoreAllMocks() { + for (const restore of MOCK_RESTORE) { + restore(); + } + MOCK_RESTORE.clear(); +} +function clearAllMocks() { + REGISTERED_MOCKS.forEach((mock) => mock.mockClear()); +} +function resetAllMocks() { + REGISTERED_MOCKS.forEach((mock) => mock.mockReset()); +} +function throwConstructorError(shorthand) { + throw new TypeError(`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`); +} + +export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; diff --git a/node_modules/@vitest/spy/optional-types.d.ts b/node_modules/@vitest/spy/optional-types.d.ts new file mode 100644 index 000000000..ba9433668 --- /dev/null +++ b/node_modules/@vitest/spy/optional-types.d.ts @@ -0,0 +1,6 @@ +/* eslint-disable ts/ban-ts-comment */ + +export interface Disposable { + // @ts-ignore -- Symbol.dispose might not be in user types + [Symbol.dispose]: () => void +} diff --git a/node_modules/@vitest/spy/package.json b/node_modules/@vitest/spy/package.json new file mode 100644 index 000000000..7dbce2d3d --- /dev/null +++ b/node_modules/@vitest/spy/package.json @@ -0,0 +1,46 @@ +{ + "name": "@vitest/spy", + "type": "module", + "version": "4.1.5", + "description": "Lightweight Jest compatible spy implementation", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/api/mock", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/spy" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "vitest", + "test", + "mock", + "spy", + "intercept" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./optional-types.js": { + "types": "./optional-types.d.ts" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist", + "optional-types.d.ts" + ], + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/@vitest/utils/LICENSE b/node_modules/@vitest/utils/LICENSE new file mode 100644 index 000000000..0e5771ddd --- /dev/null +++ b/node_modules/@vitest/utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest 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/@vitest/utils/README.md b/node_modules/@vitest/utils/README.md new file mode 100644 index 000000000..ee3b768a0 --- /dev/null +++ b/node_modules/@vitest/utils/README.md @@ -0,0 +1,7 @@ +# @vitest/utils + +[![NPM version](https://img.shields.io/npm/v/@vitest/utils?color=a1b858&label=)](https://npmx.dev/package/@vitest/utils) + +Internal shared utilities used by other Vitest packages. + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/utils) | [Documentation](https://vitest.dev/) diff --git a/node_modules/@vitest/utils/diff.d.ts b/node_modules/@vitest/utils/diff.d.ts new file mode 100644 index 000000000..0a66b8659 --- /dev/null +++ b/node_modules/@vitest/utils/diff.d.ts @@ -0,0 +1 @@ +export * from './dist/diff.js' diff --git a/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js b/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js new file mode 100644 index 000000000..74d0daba3 --- /dev/null +++ b/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js @@ -0,0 +1,156 @@ +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +const join = function(...segments) { + let path = ""; + for (const seg of segments) { + if (!seg) { + continue; + } + if (path.length > 0) { + const pathTrailing = path[path.length - 1] === "/"; + const segLeading = seg[0] === "/"; + const both = pathTrailing && segLeading; + if (both) { + path += seg.slice(1); + } else { + path += pathTrailing || segLeading ? seg : `/${seg}`; + } + } else { + path += seg; + } + } + return normalize(path); +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 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 = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; + +export { dirname as d, join as j, resolve as r }; diff --git a/node_modules/@vitest/utils/dist/constants.d.ts b/node_modules/@vitest/utils/dist/constants.d.ts new file mode 100644 index 000000000..bd5ad6582 --- /dev/null +++ b/node_modules/@vitest/utils/dist/constants.d.ts @@ -0,0 +1,21 @@ +declare const KNOWN_ASSET_TYPES: string[]; +declare const KNOWN_ASSET_RE: RegExp; +declare const CSS_LANGS_RE: RegExp; +/** +* Prefix for resolved Ids that are not valid browser import specifiers +*/ +declare 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}` +*/ +declare const NULL_BYTE_PLACEHOLDER = "__x00__"; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/node_modules/@vitest/utils/dist/constants.js b/node_modules/@vitest/utils/dist/constants.js new file mode 100644 index 000000000..385045b6a --- /dev/null +++ b/node_modules/@vitest/utils/dist/constants.js @@ -0,0 +1,49 @@ +// TODO: this is all copy pasted from Vite - can they expose a module that exports only constants? +const KNOWN_ASSET_TYPES = [ + "apng", + "bmp", + "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 KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`); +const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; +/** +* 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__`; + +export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/node_modules/@vitest/utils/dist/diff.d.ts b/node_modules/@vitest/utils/dist/diff.d.ts new file mode 100644 index 000000000..603569d2d --- /dev/null +++ b/node_modules/@vitest/utils/dist/diff.d.ts @@ -0,0 +1,93 @@ +import { D as DiffOptions } from './types.d-BCElaP-c.js'; +export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js'; +import '@vitest/pretty-format'; + +/** +* Diff Match and Patch +* Copyright 2018 The diff-match-patch Authors. +* https://github.com/google/diff-match-patch +* +* 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. +*/ +/** +* @fileoverview Computes the difference between two texts to create a patch. +* Applies the patch onto another text, allowing for errors. +* @author fraser@google.com (Neil Fraser) +*/ +/** +* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: +* +* 1. Delete anything not needed to use diff_cleanupSemantic method +* 2. Convert from prototype properties to var declarations +* 3. Convert Diff to class from constructor and prototype +* 4. Add type annotations for arguments and return values +* 5. Add exports +*/ +/** +* The data structure representing a diff is an array of tuples: +* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] +* which means: delete 'Hello', add 'Goodbye' and keep ' world.' +*/ +declare const DIFF_DELETE = -1; +declare const DIFF_INSERT = 1; +declare const DIFF_EQUAL = 0; +/** +* Class representing one diff tuple. +* Attempts to look like a two-element array (which is what this used to be). +* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. +* @param {string} text Text to be deleted, inserted, or retained. +* @constructor +*/ +declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); +} + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare function diffLinesUnified(aLines: Array, bLines: Array, options?: DiffOptions): string; +declare function diffLinesUnified2(aLinesDisplay: Array, bLinesDisplay: Array, aLinesCompare: Array, bLinesCompare: Array, options?: DiffOptions): string; +declare function diffLinesRaw(aLines: Array, bLines: Array, options?: DiffOptions): [Array, boolean]; + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string; +declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array, boolean]; + +/** +* @param a Expected value +* @param b Received value +* @param options Diff options +* @returns {string | null} a string diff +*/ +declare function diff(a: any, b: any, options?: DiffOptions): string | undefined; +declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions): string | undefined; +declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet, expectedReplaced?: WeakSet): { + replacedActual: any; + replacedExpected: any; +}; +type PrintLabel = (string: string) => string; +declare function getLabelPrinter(...strings: Array): PrintLabel; + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/node_modules/@vitest/utils/dist/diff.js b/node_modules/@vitest/utils/dist/diff.js new file mode 100644 index 000000000..37a9c9f19 --- /dev/null +++ b/node_modules/@vitest/utils/dist/diff.js @@ -0,0 +1,2201 @@ +import { plugins, format } from '@vitest/pretty-format'; +import c from 'tinyrainbow'; +import { stringify } from './display.js'; +import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js'; +import './constants.js'; + +/** +* Diff Match and Patch +* Copyright 2018 The diff-match-patch Authors. +* https://github.com/google/diff-match-patch +* +* 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. +*/ +/** +* @fileoverview Computes the difference between two texts to create a patch. +* Applies the patch onto another text, allowing for errors. +* @author fraser@google.com (Neil Fraser) +*/ +/** +* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: +* +* 1. Delete anything not needed to use diff_cleanupSemantic method +* 2. Convert from prototype properties to var declarations +* 3. Convert Diff to class from constructor and prototype +* 4. Add type annotations for arguments and return values +* 5. Add exports +*/ +/** +* The data structure representing a diff is an array of tuples: +* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] +* which means: delete 'Hello', add 'Goodbye' and keep ' world.' +*/ +const DIFF_DELETE = -1; +const DIFF_INSERT = 1; +const DIFF_EQUAL = 0; +/** +* Class representing one diff tuple. +* Attempts to look like a two-element array (which is what this used to be). +* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. +* @param {string} text Text to be deleted, inserted, or retained. +* @constructor +*/ +class Diff { + 0; + 1; + constructor(op, text) { + this[0] = op; + this[1] = text; + } +} +/** +* Determine the common prefix of two strings. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the start of each +* string. +*/ +function diff_commonPrefix(text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +} +/** +* Determine the common suffix of two strings. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the end of each string. +*/ +function diff_commonSuffix(text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + let pointermin = 0; + let pointermax = Math.min(text1.length, text2.length); + let pointermid = pointermax; + let pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +} +/** +* Determine if the suffix of one string is the prefix of another. +* @param {string} text1 First string. +* @param {string} text2 Second string. +* @return {number} The number of characters common to the end of the first +* string and the start of the second string. +* @private +*/ +function diff_commonOverlap_(text1, text2) { + // Cache the text lengths to prevent multiple calls. + const text1_length = text1.length; + const text2_length = text2.length; + // Eliminate the null case. + if (text1_length === 0 || text2_length === 0) { + return 0; + } + // Truncate the longer string. + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + const text_length = Math.min(text1_length, text2_length); + // Quick check for the worst case. + if (text1 === text2) { + return text_length; + } + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + let best = 0; + let length = 1; + while (true) { + const pattern = text1.substring(text_length - length); + const found = text2.indexOf(pattern); + if (found === -1) { + return best; + } + length += found; + if (found === 0 || text1.substring(text_length - length) === text2.substring(0, length)) { + best = length; + length++; + } + } +} +/** +* Reduce the number of edits by eliminating semantically trivial equalities. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupSemantic(diffs) { + let changes = false; + const equalities = []; + let equalitiesLength = 0; + /** @type {?string} */ + let lastEquality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + let pointer = 0; + // Number of characters that changed prior to the equality. + let length_insertions1 = 0; + let length_deletions1 = 0; + // Number of characters that changed after the equality. + let length_insertions2 = 0; + let length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] === DIFF_INSERT) { + length_insertions2 += diffs[pointer][1].length; + } else { + length_deletions2 += diffs[pointer][1].length; + } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + // Throw away the equality we just deleted. + equalitiesLength--; + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + // Normalize the diff. + if (changes) { + diff_cleanupMerge(diffs); + } + diff_cleanupSemanticLossless(diffs); + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { + const deletion = diffs[pointer - 1][1]; + const insertion = diffs[pointer][1]; + const overlap_length1 = diff_commonOverlap_(deletion, insertion); + const overlap_length2 = diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); + diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); + diffs[pointer + 1][1] = insertion.substring(overlap_length1); + pointer++; + } + } else { + if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } +} +// Define some regex patterns for matching boundaries. +const nonAlphaNumericRegex_ = /[^a-z0-9]/i; +const whitespaceRegex_ = /\s/; +const linebreakRegex_ = /[\r\n]/; +const blanklineEndRegex_ = /\n\r?\n$/; +const blanklineStartRegex_ = /^\r?\n\r?\n/; +/** +* Look for single edits surrounded on both sides by equalities +* which can be shifted sideways to align the edit to a word boundary. +* e.g: The cat came. -> The cat came. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupSemanticLossless(diffs) { + let pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + let equality1 = diffs[pointer - 1][1]; + let edit = diffs[pointer][1]; + let equality2 = diffs[pointer + 1][1]; + // First, shift the edit as far left as possible. + const commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset) { + const commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + // Second, step character by character right, looking for the best fit. + let bestEquality1 = equality1; + let bestEdit = edit; + let bestEquality2 = equality2; + let bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + const score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); + // The >= encourages trailing rather than leading whitespace on edits. + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (diffs[pointer - 1][1] !== bestEquality1) { + // We have an improvement, save it back to the diff. + if (bestEquality1) { + diffs[pointer - 1][1] = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer][1] = bestEdit; + if (bestEquality2) { + diffs[pointer + 1][1] = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } +} +/** +* Reorder and merge like edit sections. Merge equalities. +* Any edit section can move as long as it doesn't cross an equality. +* @param {!Array.} diffs Array of diff tuples. +*/ +function diff_cleanupMerge(diffs) { + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, "")); + let pointer = 0; + let count_delete = 0; + let count_insert = 0; + let text_delete = ""; + let text_insert = ""; + let commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + // Factor out any common prefixes. + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) { + diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); + } else { + diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + // Factor out any common suffixes. + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; + text_insert = text_insert.substring(0, text_insert.length - commonlength); + text_delete = text_delete.substring(0, text_delete.length - commonlength); + } + } + // Delete the offending records and add the merged ones. + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + break; + } + } + if (diffs.at(-1)?.[1] === "") { + diffs.pop(); + } + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + let changes = false; + pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + // This is a single edit surrounded by equalities. + if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { + // Shift the edit over the previous equality. + diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + diff_cleanupMerge(diffs); + } +} +/** +* Given two strings, compute a score representing whether the internal +* boundary falls on logical boundaries. +* Scores range from 6 (best) to 0 (worst). +* Closure, but does not reference any external variables. +* @param {string} one First string. +* @param {string} two Second string. +* @return {number} The score. +* @private +*/ +function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + // Edges are the best. + return 6; + } + // Each port of this function behaves slightly differently due to + // subtle differences in each language's definition of things like + // 'whitespace'. Since this function's purpose is largely cosmetic, + // the choice has been made to use each language's native features + // rather than force total conformity. + const char1 = one.charAt(one.length - 1); + const char2 = two.charAt(0); + const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); + const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); + const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); + const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); + const lineBreak1 = whitespace1 && char1.match(linebreakRegex_); + const lineBreak2 = whitespace2 && char2.match(linebreakRegex_); + const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); + const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); + if (blankLine1 || blankLine2) { + // Five points for blank lines. + return 5; + } else if (lineBreak1 || lineBreak2) { + // Four points for line breaks. + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + // Three points for end of sentences. + return 3; + } else if (whitespace1 || whitespace2) { + // Two points for whitespace. + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + // One point for non-alphanumeric. + return 1; + } + return 0; +} + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ +const NO_DIFF_MESSAGE = "Compared values have no visual difference."; +const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead."; + +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} + +var build = {}; + +var hasRequiredBuild; + +function requireBuild () { + if (hasRequiredBuild) return build; + hasRequiredBuild = 1; + + Object.defineProperty(build, '__esModule', { + value: true + }); + build.default = diffSequence; + /** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + + // This diff-sequences package implements the linear space variation in + // An O(ND) Difference Algorithm and Its Variations by Eugene W. Myers + + // Relationship in notation between Myers paper and this package: + // A is a + // N is aLength, aEnd - aStart, and so on + // x is aIndex, aFirst, aLast, and so on + // B is b + // M is bLength, bEnd - bStart, and so on + // y is bIndex, bFirst, bLast, and so on + // Δ = N - M is negative of baDeltaLength = bLength - aLength + // D is d + // k is kF + // k + Δ is kF = kR - baDeltaLength + // V is aIndexesF or aIndexesR (see comment below about Indexes type) + // index intervals [1, N] and [1, M] are [0, aLength) and [0, bLength) + // starting point in forward direction (0, 0) is (-1, -1) + // starting point in reverse direction (N + 1, M + 1) is (aLength, bLength) + + // The “edit graph” for sequences a and b corresponds to items: + // in a on the horizontal axis + // in b on the vertical axis + // + // Given a-coordinate of a point in a diagonal, you can compute b-coordinate. + // + // Forward diagonals kF: + // zero diagonal intersects top left corner + // positive diagonals intersect top edge + // negative diagonals insersect left edge + // + // Reverse diagonals kR: + // zero diagonal intersects bottom right corner + // positive diagonals intersect right edge + // negative diagonals intersect bottom edge + + // The graph contains a directed acyclic graph of edges: + // horizontal: delete an item from a + // vertical: insert an item from b + // diagonal: common item in a and b + // + // The algorithm solves dual problems in the graph analogy: + // Find longest common subsequence: path with maximum number of diagonal edges + // Find shortest edit script: path with minimum number of non-diagonal edges + + // Input callback function compares items at indexes in the sequences. + + // Output callback function receives the number of adjacent items + // and starting indexes of each common subsequence. + // Either original functions or wrapped to swap indexes if graph is transposed. + // Indexes in sequence a of last point of forward or reverse paths in graph. + // Myers algorithm indexes by diagonal k which for negative is bad deopt in V8. + // This package indexes by iF and iR which are greater than or equal to zero. + // and also updates the index arrays in place to cut memory in half. + // kF = 2 * iF - d + // kR = d - 2 * iR + // Division of index intervals in sequences a and b at the middle change. + // Invariant: intervals do not have common items at the start or end. + const pkg = 'diff-sequences'; // for error messages + const NOT_YET_SET = 0; // small int instead of undefined to avoid deopt in V8 + + // Return the number of common items that follow in forward direction. + // The length of what Myers paper calls a “snake” in a forward path. + const countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => { + let nCommon = 0; + while (aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex)) { + aIndex += 1; + bIndex += 1; + nCommon += 1; + } + return nCommon; + }; + + // Return the number of common items that precede in reverse direction. + // The length of what Myers paper calls a “snake” in a reverse path. + const countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => { + let nCommon = 0; + while (aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex)) { + aIndex -= 1; + bIndex -= 1; + nCommon += 1; + } + return nCommon; + }; + + // A simple function to extend forward paths from (d - 1) to d changes + // when forward and reverse paths cannot yet overlap. + const extendPathsF = ( + d, + aEnd, + bEnd, + bF, + isCommon, + aIndexesF, + iMaxF // return the value because optimization might decrease it + ) => { + // Unroll the first iteration. + let iF = 0; + let kF = -d; // kF = 2 * iF - d + let aFirst = aIndexesF[iF]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iF - 1] in next iteration + aIndexesF[iF] += countCommonItemsF( + aFirst + 1, + aEnd, + bF + aFirst - kF + 1, + bEnd, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF are odd when d is odd and even when d is even. + for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iF === d and kF === d always delete. + if (iF !== d && aIndexPrev1 < aIndexesF[iF]) { + aFirst = aIndexesF[iF]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 + 1; // horizontal to delete from a + + if (aEnd <= aFirst) { + // Optimization: delete moved past right of graph. + return iF - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = + aFirst + + countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); + } + return iMaxF; + }; + + // A simple function to extend reverse paths from (d - 1) to d changes + // when reverse and forward paths cannot yet overlap. + const extendPathsR = ( + d, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR // return the value because optimization might decrease it + ) => { + // Unroll the first iteration. + let iR = 0; + let kR = d; // kR = d - 2 * iR + let aFirst = aIndexesR[iR]; // in first iteration always insert + let aIndexPrev1 = aFirst; // prev value of [iR - 1] in next iteration + aIndexesR[iR] -= countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR are odd when d is odd and even when d is even. + for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In last possible iteration when iR === d and kR === -d always delete. + if (iR !== d && aIndexesR[iR] < aIndexPrev1) { + aFirst = aIndexesR[iR]; // vertical to insert from b + } else { + aFirst = aIndexPrev1 - 1; // horizontal to delete from a + + if (aFirst < aStart) { + // Optimization: delete moved past left of graph. + return iR - 1; + } + } + + // To get last point of path segment, move along diagonal of common items. + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = + aFirst - + countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bR + aFirst - kR - 1, + isCommon + ); + } + return iMaxR; + }; + + // A complete function to extend forward paths from (d - 1) to d changes. + // Return true if a path overlaps reverse path of (d - 1) changes in its diagonal. + const extendOverlappablePathsF = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true + ) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kF = kR - baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapF = -baDeltaLength - (d - 1); // -(d - 1) <= kR + const kMaxOverlapF = -baDeltaLength + (d - 1); // kR <= (d - 1) + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nF = d < iMaxF ? d : iMaxF; + + // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even. + for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { + // To get first point of path segment, move one change in forward direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iF === 0 and kF === -d always insert. + // In last possible iteration when iF === d and kF === d always delete. + const insert = iF === 0 || (iF !== d && aIndexPrev1 < aIndexesF[iF]); + const aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev + 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bF + aFirst - kF; + const nCommonF = countCommonItemsF( + aFirst + 1, + aEnd, + bFirst + 1, + bEnd, + isCommon + ); + const aLast = aFirst + nCommonF; + aIndexPrev1 = aIndexesF[iF]; + aIndexesF[iF] = aLast; + if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { + // Solve for iR of reverse path with (d - 1) changes in diagonal kF: + // kR = kF + baDeltaLength + // kR = (d - 1) - 2 * iR + const iR = (d - 1 - (kF + baDeltaLength)) / 2; + + // If this forward path overlaps the reverse path in this diagonal, + // then this is the middle change of the index intervals. + if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); + + // Because of invariant that intervals preceding the middle change + // cannot have common items at the end, + // move in reverse direction along a diagonal of common items. + const nCommonR = countCommonItemsR( + aStart, + aLastPrev, + bStart, + bLastPrev, + isCommon + ); + const aIndexPrevFirst = aLastPrev - nCommonR; + const bIndexPrevFirst = bLastPrev - nCommonR; + const aEndPreceding = aIndexPrevFirst + 1; + const bEndPreceding = bIndexPrevFirst + 1; + division.nChangePreceding = d - 1; + if (d - 1 === aEndPreceding + bEndPreceding - aStart - bStart) { + // Optimization: number of preceding changes in forward direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aEndPreceding; + division.bEndPreceding = bEndPreceding; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + division.aCommonPreceding = aEndPreceding; + division.bCommonPreceding = bEndPreceding; + } + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + division.aCommonFollowing = aFirst + 1; + division.bCommonFollowing = bFirst + 1; + } + const aStartFollowing = aLast + 1; + const bStartFollowing = bFirst + nCommonF + 1; + division.nChangeFollowing = d - 1; + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in reverse direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + return true; + } + } + } + return false; + }; + + // A complete function to extend reverse paths from (d - 1) to d changes. + // Return true if a path overlaps forward path of d changes in its diagonal. + const extendOverlappablePathsR = ( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division // update prop values if return true + ) => { + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + const baDeltaLength = bLength - aLength; // kR = kF + baDeltaLength + + // Range of diagonals in which forward and reverse paths might overlap. + const kMinOverlapR = baDeltaLength - d; // -d <= kF + const kMaxOverlapR = baDeltaLength + d; // kF <= d + + let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration + + // Optimization: skip diagonals in which paths cannot ever overlap. + const nR = d < iMaxR ? d : iMaxR; + + // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even. + for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { + // To get first point of path segment, move one change in reverse direction + // from last point of previous path segment in an adjacent diagonal. + // In first iteration when iR === 0 and kR === d always insert. + // In last possible iteration when iR === d and kR === -d always delete. + const insert = iR === 0 || (iR !== d && aIndexesR[iR] < aIndexPrev1); + const aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; + const aFirst = insert + ? aLastPrev // vertical to insert from b + : aLastPrev - 1; // horizontal to delete from a + + // To get last point of path segment, move along diagonal of common items. + const bFirst = bR + aFirst - kR; + const nCommonR = countCommonItemsR( + aStart, + aFirst - 1, + bStart, + bFirst - 1, + isCommon + ); + const aLast = aFirst - nCommonR; + aIndexPrev1 = aIndexesR[iR]; + aIndexesR[iR] = aLast; + if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { + // Solve for iF of forward path with d changes in diagonal kR: + // kF = kR - baDeltaLength + // kF = 2 * iF - d + const iF = (d + (kR - baDeltaLength)) / 2; + + // If this reverse path overlaps the forward path in this diagonal, + // then this is a middle change of the index intervals. + if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { + const bLast = bFirst - nCommonR; + division.nChangePreceding = d; + if (d === aLast + bLast - aStart - bStart) { + // Optimization: number of changes in reverse direction + // is equal to number of items in preceding interval, + // therefore it cannot contain any common items. + division.aEndPreceding = aStart; + division.bEndPreceding = bStart; + } else { + division.aEndPreceding = aLast; + division.bEndPreceding = bLast; + } + division.nCommonPreceding = nCommonR; + if (nCommonR !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonPreceding = aLast; + division.bCommonPreceding = bLast; + } + division.nChangeFollowing = d - 1; + if (d === 1) { + // There is no previous path segment. + division.nCommonFollowing = 0; + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + // Unlike the Myers algorithm which finds only the middle “snake” + // this package can find two common subsequences per division. + // Last point of previous path segment is on an adjacent diagonal. + const bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); + + // Because of invariant that intervals following the middle change + // cannot have common items at the start, + // move in forward direction along a diagonal of common items. + const nCommonF = countCommonItemsF( + aLastPrev, + aEnd, + bLastPrev, + bEnd, + isCommon + ); + division.nCommonFollowing = nCommonF; + if (nCommonF !== 0) { + // The last point of reverse path segment is start of common subsequence. + division.aCommonFollowing = aLastPrev; + division.bCommonFollowing = bLastPrev; + } + const aStartFollowing = aLastPrev + nCommonF; // aFirstPrev + const bStartFollowing = bLastPrev + nCommonF; // bFirstPrev + + if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { + // Optimization: number of changes in forward direction + // is equal to number of items in following interval, + // therefore it cannot contain any common items. + division.aStartFollowing = aEnd; + division.bStartFollowing = bEnd; + } else { + division.aStartFollowing = aStartFollowing; + division.bStartFollowing = bStartFollowing; + } + } + return true; + } + } + } + return false; + }; + + // Given index intervals and input function to compare items at indexes, + // divide at the middle change. + // + // DO NOT CALL if start === end, because interval cannot contain common items + // and because this function will throw the “no overlap” error. + const divide = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division // output + ) => { + const bF = bStart - aStart; // bIndex = bF + aIndex - kF + const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR + const aLength = aEnd - aStart; + const bLength = bEnd - bStart; + + // Because graph has square or portrait orientation, + // length difference is minimum number of items to insert from b. + // Corresponding forward and reverse diagonals in graph + // depend on length difference of the sequences: + // kF = kR - baDeltaLength + // kR = kF + baDeltaLength + const baDeltaLength = bLength - aLength; + + // Optimization: max diagonal in graph intersects corner of shorter side. + let iMaxF = aLength; + let iMaxR = aLength; + + // Initialize no changes yet in forward or reverse direction: + aIndexesF[0] = aStart - 1; // at open start of interval, outside closed start + aIndexesR[0] = aEnd; // at open end of interval + + if (baDeltaLength % 2 === 0) { + // The number of changes in paths is 2 * d if length difference is even. + const dMin = (nChange || baDeltaLength) / 2; + const dMax = (aLength + bLength) / 2; + for (let d = 1; d <= dMax; d += 1) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + if (d < dMin) { + iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); + } else if ( + // If a reverse path overlaps a forward path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsR( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } else { + // The number of changes in paths is 2 * d - 1 if length difference is odd. + const dMin = ((nChange || baDeltaLength) + 1) / 2; + const dMax = (aLength + bLength + 1) / 2; + + // Unroll first half iteration so loop extends the relevant pairs of paths. + // Because of invariant that intervals have no common items at start or end, + // and limitation not to call divide with empty intervals, + // therefore it cannot be called if a forward path with one change + // would overlap a reverse path with no changes, even if dMin === 1. + let d = 1; + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + for (d += 1; d <= dMax; d += 1) { + iMaxR = extendPathsR( + d - 1, + aStart, + bStart, + bR, + isCommon, + aIndexesR, + iMaxR + ); + if (d < dMin) { + iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); + } else if ( + // If a forward path overlaps a reverse path in the same diagonal, + // return a division of the index intervals at the middle change. + extendOverlappablePathsF( + d, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + iMaxF, + aIndexesR, + iMaxR, + division + ) + ) { + return; + } + } + } + + /* istanbul ignore next */ + throw new Error( + `${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}` + ); + }; + + // Given index intervals and input function to compare items at indexes, + // return by output function the number of adjacent items and starting indexes + // of each common subsequence. Divide and conquer with only linear space. + // + // The index intervals are half open [start, end) like array slice method. + // DO NOT CALL if start === end, because interval cannot contain common items + // and because divide function will throw the “no overlap” error. + const findSubsequences = ( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division // temporary memory, not input nor output + ) => { + if (bEnd - bStart < aEnd - aStart) { + // Transpose graph so it has portrait instead of landscape orientation. + // Always compare shorter to longer sequence for consistency and optimization. + transposed = !transposed; + if (transposed && callbacks.length === 1) { + // Lazily wrap callback functions to swap args if graph is transposed. + const {foundSubsequence, isCommon} = callbacks[0]; + callbacks[1] = { + foundSubsequence: (nCommon, bCommon, aCommon) => { + foundSubsequence(nCommon, aCommon, bCommon); + }, + isCommon: (bIndex, aIndex) => isCommon(aIndex, bIndex) + }; + } + const tStart = aStart; + const tEnd = aEnd; + aStart = bStart; + aEnd = bEnd; + bStart = tStart; + bEnd = tEnd; + } + const {foundSubsequence, isCommon} = callbacks[transposed ? 1 : 0]; + + // Divide the index intervals at the middle change. + divide( + nChange, + aStart, + aEnd, + bStart, + bEnd, + isCommon, + aIndexesF, + aIndexesR, + division + ); + const { + nChangePreceding, + aEndPreceding, + bEndPreceding, + nCommonPreceding, + aCommonPreceding, + bCommonPreceding, + nCommonFollowing, + aCommonFollowing, + bCommonFollowing, + nChangeFollowing, + aStartFollowing, + bStartFollowing + } = division; + + // Unless either index interval is empty, they might contain common items. + if (aStart < aEndPreceding && bStart < bEndPreceding) { + // Recursely find and return common subsequences preceding the division. + findSubsequences( + nChangePreceding, + aStart, + aEndPreceding, + bStart, + bEndPreceding, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + + // Return common subsequences that are adjacent to the middle change. + if (nCommonPreceding !== 0) { + foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); + } + if (nCommonFollowing !== 0) { + foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); + } + + // Unless either index interval is empty, they might contain common items. + if (aStartFollowing < aEnd && bStartFollowing < bEnd) { + // Recursely find and return common subsequences following the division. + findSubsequences( + nChangeFollowing, + aStartFollowing, + aEnd, + bStartFollowing, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + }; + const validateLength = (name, arg) => { + if (typeof arg !== 'number') { + throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`); + } + if (!Number.isSafeInteger(arg)) { + throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`); + } + if (arg < 0) { + throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`); + } + }; + const validateCallback = (name, arg) => { + const type = typeof arg; + if (type !== 'function') { + throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`); + } + }; + + // Compare items in two sequences to find a longest common subsequence. + // Given lengths of sequences and input function to compare items at indexes, + // return by output function the number of adjacent items and starting indexes + // of each common subsequence. + function diffSequence(aLength, bLength, isCommon, foundSubsequence) { + validateLength('aLength', aLength); + validateLength('bLength', bLength); + validateCallback('isCommon', isCommon); + validateCallback('foundSubsequence', foundSubsequence); + + // Count common items from the start in the forward direction. + const nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); + if (nCommonF !== 0) { + foundSubsequence(nCommonF, 0, 0); + } + + // Unless both sequences consist of common items only, + // find common items in the half-trimmed index intervals. + if (aLength !== nCommonF || bLength !== nCommonF) { + // Invariant: intervals do not have common items at the start. + // The start of an index interval is closed like array slice method. + const aStart = nCommonF; + const bStart = nCommonF; + + // Count common items from the end in the reverse direction. + const nCommonR = countCommonItemsR( + aStart, + aLength - 1, + bStart, + bLength - 1, + isCommon + ); + + // Invariant: intervals do not have common items at the end. + // The end of an index interval is open like array slice method. + const aEnd = aLength - nCommonR; + const bEnd = bLength - nCommonR; + + // Unless one sequence consists of common items only, + // therefore the other trimmed index interval consists of changes only, + // find common items in the trimmed index intervals. + const nCommonFR = nCommonF + nCommonR; + if (aLength !== nCommonFR && bLength !== nCommonFR) { + const nChange = 0; // number of change items is not yet known + const transposed = false; // call the original unwrapped functions + const callbacks = [ + { + foundSubsequence, + isCommon + } + ]; + + // Indexes in sequence a of last points in furthest reaching paths + // from outside the start at top left in the forward direction: + const aIndexesF = [NOT_YET_SET]; + // from the end at bottom right in the reverse direction: + const aIndexesR = [NOT_YET_SET]; + + // Initialize one object as output of all calls to divide function. + const division = { + aCommonFollowing: NOT_YET_SET, + aCommonPreceding: NOT_YET_SET, + aEndPreceding: NOT_YET_SET, + aStartFollowing: NOT_YET_SET, + bCommonFollowing: NOT_YET_SET, + bCommonPreceding: NOT_YET_SET, + bEndPreceding: NOT_YET_SET, + bStartFollowing: NOT_YET_SET, + nChangeFollowing: NOT_YET_SET, + nChangePreceding: NOT_YET_SET, + nCommonFollowing: NOT_YET_SET, + nCommonPreceding: NOT_YET_SET + }; + + // Find and return common subsequences in the trimmed index intervals. + findSubsequences( + nChange, + aStart, + aEnd, + bStart, + bEnd, + transposed, + callbacks, + aIndexesF, + aIndexesR, + division + ); + } + if (nCommonR !== 0) { + foundSubsequence(nCommonR, aEnd, bEnd); + } + } + } + return build; +} + +var buildExports = /*@__PURE__*/ requireBuild(); +var diffSequences = /*@__PURE__*/getDefaultExportFromCjs(buildExports); + +function formatTrailingSpaces(line, trailingSpaceFormatter) { + return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match)); +} +function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) { + return line.length !== 0 ? color(`${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}`) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : ""; +} +function printDeleteLine(line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +function printInsertLine(line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +function printCommonLine(line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { + return printDiffLine(line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); +} +// In GNU diff format, indexes are one-based instead of zero-based. +function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) { + return patchColor(`@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@`); +} +// jest --no-expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting (and patch marks, if needed). +function joinAlignedDiffsNoExpand(diffs, options) { + const iLength = diffs.length; + const nContextLines = options.contextLines; + const nContextLines2 = nContextLines + nContextLines; + // First pass: count output lines and see if it has patches. + let jLength = iLength; + let hasExcessAtStartOrEnd = false; + let nExcessesBetweenChanges = 0; + let i = 0; + while (i !== iLength) { + const iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at start + if (i > nContextLines) { + jLength -= i - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else if (i === iLength) { + // at end + const n = i - iStart; + if (n > nContextLines) { + jLength -= n - nContextLines; + hasExcessAtStartOrEnd = true; + } + } else { + // between changes + const n = i - iStart; + if (n > nContextLines2) { + jLength -= n - nContextLines2; + nExcessesBetweenChanges += 1; + } + } + } + while (i !== iLength && diffs[i][0] !== DIFF_EQUAL) { + i += 1; + } + } + const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; + if (nExcessesBetweenChanges !== 0) { + jLength += nExcessesBetweenChanges + 1; + } else if (hasExcessAtStartOrEnd) { + jLength += 1; + } + const jLast = jLength - 1; + const lines = []; + let jPatchMark = 0; + if (hasPatch) { + lines.push(""); + } + // Indexes of expected or received lines in current patch: + let aStart = 0; + let bStart = 0; + let aEnd = 0; + let bEnd = 0; + const pushCommonLine = (line) => { + const j = lines.length; + lines.push(printCommonLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + bEnd += 1; + }; + const pushDeleteLine = (line) => { + const j = lines.length; + lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + }; + const pushInsertLine = (line) => { + const j = lines.length; + lines.push(printInsertLine(line, j === 0 || j === jLast, options)); + bEnd += 1; + }; + // Second pass: push lines with diff formatting (and patch marks, if needed). + i = 0; + while (i !== iLength) { + let iStart = i; + while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at beginning + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd = aStart; + bEnd = bStart; + } + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else if (i === iLength) { + // at end + const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + // between changes + const nCommon = i - iStart; + if (nCommon > nContextLines2) { + const iEnd = iStart + nContextLines; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + jPatchMark = lines.length; + lines.push(""); + const nOmit = nCommon - nContextLines2; + aStart = aEnd + nOmit; + bStart = bEnd + nOmit; + aEnd = aStart; + bEnd = bStart; + for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } + } + } + while (i !== iLength && diffs[i][0] === DIFF_DELETE) { + pushDeleteLine(diffs[i][1]); + i += 1; + } + while (i !== iLength && diffs[i][0] === DIFF_INSERT) { + pushInsertLine(diffs[i][1]); + i += 1; + } + } + if (hasPatch) { + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + } + return lines.join("\n"); +} +// jest --expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting. +function joinAlignedDiffsExpand(diffs, options) { + return diffs.map((diff, i, diffs) => { + const line = diff[1]; + const isFirstOrLast = i === 0 || i === diffs.length - 1; + switch (diff[0]) { + case DIFF_DELETE: return printDeleteLine(line, isFirstOrLast, options); + case DIFF_INSERT: return printInsertLine(line, isFirstOrLast, options); + default: return printCommonLine(line, isFirstOrLast, options); + } + }).join("\n"); +} + +const noColor = (string) => string; +const DIFF_CONTEXT_DEFAULT = 5; +const DIFF_TRUNCATE_THRESHOLD_DEFAULT = 0; +function getDefaultOptions() { + return { + aAnnotation: "Expected", + aColor: c.green, + aIndicator: "-", + bAnnotation: "Received", + bColor: c.red, + bIndicator: "+", + changeColor: c.inverse, + changeLineTrailingSpaceColor: noColor, + commonColor: c.dim, + commonIndicator: " ", + commonLineTrailingSpaceColor: noColor, + compareKeys: undefined, + contextLines: DIFF_CONTEXT_DEFAULT, + emptyFirstOrLastLinePlaceholder: "", + expand: false, + includeChangeCounts: false, + omitAnnotationLines: false, + patchColor: c.yellow, + printBasicPrototype: false, + truncateThreshold: DIFF_TRUNCATE_THRESHOLD_DEFAULT, + truncateAnnotation: "... Diff result is truncated", + truncateAnnotationColor: noColor + }; +} +function getCompareKeys(compareKeys) { + return compareKeys && typeof compareKeys === "function" ? compareKeys : undefined; +} +function getContextLines(contextLines) { + return typeof contextLines === "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; +} +// Pure function returns options with all properties. +function normalizeDiffOptions(options = {}) { + return { + ...getDefaultOptions(), + ...options, + compareKeys: getCompareKeys(options.compareKeys), + contextLines: getContextLines(options.contextLines) + }; +} + +function isEmptyString(lines) { + return lines.length === 1 && lines[0].length === 0; +} +function countChanges(diffs) { + let a = 0; + let b = 0; + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + a += 1; + break; + case DIFF_INSERT: + b += 1; + break; + } + }); + return { + a, + b + }; +} +function printAnnotation({ aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts) { + if (omitAnnotationLines) { + return ""; + } + let aRest = ""; + let bRest = ""; + if (includeChangeCounts) { + const aCount = String(changeCounts.a); + const bCount = String(changeCounts.b); + // Padding right aligns the ends of the annotations. + const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; + const aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff)); + const bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff)); + // Padding left aligns the ends of the counts. + const baCountLengthDiff = bCount.length - aCount.length; + const aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff)); + const bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff)); + aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; + bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; + } + const a = `${aIndicator} ${aAnnotation}${aRest}`; + const b = `${bIndicator} ${bAnnotation}${bRest}`; + return `${aColor(a)}\n${bColor(b)}\n\n`; +} +function printDiffLines(diffs, truncated, options) { + return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)) + (truncated ? options.truncateAnnotationColor(`\n${options.truncateAnnotation}`) : ""); +} +// Compare two arrays of strings line-by-line. Format as comparison lines. +function diffLinesUnified(aLines, bLines, options) { + const normalizedOptions = normalizeDiffOptions(options); + const [diffs, truncated] = diffLinesRaw(isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines, normalizedOptions); + return printDiffLines(diffs, truncated, normalizedOptions); +} +// Given two pairs of arrays of strings: +// Compare the pair of comparison arrays line-by-line. +// Format the corresponding lines in the pair of displayable arrays. +function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = []; + aLinesCompare = []; + } + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = []; + bLinesCompare = []; + } + if (aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length) { + // Fall back to diff of display lines. + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + const [diffs, truncated] = diffLinesRaw(aLinesCompare, bLinesCompare, options); + // Replace comparison lines with displayable lines. + let aIndex = 0; + let bIndex = 0; + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + diff[1] = aLinesDisplay[aIndex]; + aIndex += 1; + break; + case DIFF_INSERT: + diff[1] = bLinesDisplay[bIndex]; + bIndex += 1; + break; + default: + diff[1] = bLinesDisplay[bIndex]; + aIndex += 1; + bIndex += 1; + } + }); + return printDiffLines(diffs, truncated, normalizeDiffOptions(options)); +} +// Compare two arrays of strings line-by-line. +function diffLinesRaw(aLines, bLines, options) { + const truncate = options?.truncateThreshold ?? false; + const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0); + const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length; + const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length; + const truncated = aLength !== aLines.length || bLength !== bLines.length; + const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; + const diffs = []; + let aIndex = 0; + let bIndex = 0; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) { + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + } + for (; bIndex !== bCommon; bIndex += 1) { + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + } + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { + diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex])); + } + }; + diffSequences(aLength, bLength, isCommon, foundSubsequence); + // After the last common subsequence, push remaining change items. + for (; aIndex !== aLength; aIndex += 1) { + diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); + } + for (; bIndex !== bLength; bIndex += 1) { + diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); + } + return [diffs, truncated]; +} + +// get the type of a value with handling the edge cases like `typeof []` +// and `typeof null` +function getType(value) { + if (value === undefined) { + return "undefined"; + } else if (value === null) { + return "null"; + } else if (Array.isArray(value)) { + return "array"; + } else if (typeof value === "boolean") { + return "boolean"; + } else if (typeof value === "function") { + return "function"; + } else if (typeof value === "number") { + return "number"; + } else if (typeof value === "string") { + return "string"; + } else if (typeof value === "bigint") { + return "bigint"; + } else if (typeof value === "object") { + if (value != null) { + if (value.constructor === RegExp) { + return "regexp"; + } else if (value.constructor === Map) { + return "map"; + } else if (value.constructor === Set) { + return "set"; + } else if (value.constructor === Date) { + return "date"; + } + } + return "object"; + } else if (typeof value === "symbol") { + return "symbol"; + } + throw new Error(`value of unknown type: ${value}`); +} + +// platforms compatible +function getNewLineSymbol(string) { + return string.includes("\r\n") ? "\r\n" : "\n"; +} +function diffStrings(a, b, options) { + const truncate = options?.truncateThreshold ?? false; + const truncateThreshold = Math.max(Math.floor(options?.truncateThreshold ?? 0), 0); + let aLength = a.length; + let bLength = b.length; + if (truncate) { + const aMultipleLines = a.includes("\n"); + const bMultipleLines = b.includes("\n"); + const aNewLineSymbol = getNewLineSymbol(a); + const bNewLineSymbol = getNewLineSymbol(b); + // multiple-lines string expects a newline to be appended at the end + const _a = aMultipleLines ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}\n` : a; + const _b = bMultipleLines ? `${b.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}\n` : b; + aLength = _a.length; + bLength = _b.length; + } + const truncated = aLength !== a.length || bLength !== b.length; + const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; + let aIndex = 0; + let bIndex = 0; + const diffs = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) { + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))); + } + if (bIndex !== bCommon) { + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))); + } + aIndex = aCommon + nCommon; + bIndex = bCommon + nCommon; + diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))); + }; + diffSequences(aLength, bLength, isCommon, foundSubsequence); + // After the last common subsequence, push remaining change items. + if (aIndex !== aLength) { + diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))); + } + if (bIndex !== bLength) { + diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex))); + } + return [diffs, truncated]; +} + +// Given change op and array of diffs, return concatenated string: +// * include common strings +// * include change strings which have argument op with changeColor +// * exclude change strings which have opposite op +function concatenateRelevantDiffs(op, diffs, changeColor) { + return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 ? changeColor(diff[1]) : ""), ""); +} +// Encapsulate change lines until either a common newline or the end. +class ChangeBuffer { + op; + line; + lines; + changeColor; + constructor(op, changeColor) { + this.op = op; + this.line = []; + this.lines = []; + this.changeColor = changeColor; + } + pushSubstring(substring) { + this.pushDiff(new Diff(this.op, substring)); + } + pushLine() { + // Assume call only if line has at least one diff, + // therefore an empty line must have a diff which has an empty string. + // If line has multiple diffs, then assume it has a common diff, + // therefore change diffs have change color; + // otherwise then it has line color only. + this.lines.push(this.line.length !== 1 ? new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1])); + this.line.length = 0; + } + isLineEmpty() { + return this.line.length === 0; + } + // Minor input to buffer. + pushDiff(diff) { + this.line.push(diff); + } + // Main input to buffer. + align(diff) { + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i < iLast) { + // The first substring completes the current change line. + // A middle substring is a change line. + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushSubstring(substring); + } + }); + } else { + // Append non-multiline string to current change line. + this.pushDiff(diff); + } + } + // Output from buffer. + moveLinesTo(lines) { + if (!this.isLineEmpty()) { + this.pushLine(); + } + lines.push(...this.lines); + this.lines.length = 0; + } +} +// Encapsulate common and change lines. +class CommonBuffer { + deleteBuffer; + insertBuffer; + lines; + constructor(deleteBuffer, insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = []; + } + pushDiffCommonLine(diff) { + this.lines.push(diff); + } + pushDiffChangeLines(diff) { + const isDiffEmpty = diff[1].length === 0; + // An empty diff string is redundant, unless a change line is empty. + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { + this.deleteBuffer.pushDiff(diff); + } + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { + this.insertBuffer.pushDiff(diff); + } + } + flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } + // Input to buffer. + align(diff) { + const op = diff[0]; + const string = diff[1]; + if (string.includes("\n")) { + const substrings = string.split("\n"); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i === 0) { + const subdiff = new Diff(op, substring); + if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { + // If both current change lines are empty, + // then the first substring is a common line. + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + // If either current change line is non-empty, + // then the first substring completes the change lines. + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + // A middle substring is a common line. + this.pushDiffCommonLine(new Diff(op, substring)); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushDiffChangeLines(new Diff(op, substring)); + } + }); + } else { + // Append non-multiline string to current change lines. + // Important: It cannot be at the end following empty change lines, + // because newline appended to the end of expected and received strings. + this.pushDiffChangeLines(diff); + } + } + // Output from buffer. + getLines() { + this.flushChangeLines(); + return this.lines; + } +} +// Given diffs from expected and received strings, +// return new array of diffs split or joined into lines. +// +// To correctly align a change line at the end, the algorithm: +// * assumes that a newline was appended to the strings +// * omits the last newline from the output array +// +// Assume the function is not called: +// * if either expected or received is empty string +// * if neither expected nor received is multiline string +function getAlignedDiffs(diffs, changeColor) { + const deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); + const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); + const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + diffs.forEach((diff) => { + switch (diff[0]) { + case DIFF_DELETE: + deleteBuffer.align(diff); + break; + case DIFF_INSERT: + insertBuffer.align(diff); + break; + default: commonBuffer.align(diff); + } + }); + return commonBuffer.getLines(); +} + +function hasCommonDiff(diffs, isMultiline) { + if (isMultiline) { + // Important: Ignore common newline that was appended to multiline strings! + const iLast = diffs.length - 1; + return diffs.some((diff, i) => diff[0] === DIFF_EQUAL && (i !== iLast || diff[1] !== "\n")); + } + return diffs.some((diff) => diff[0] === DIFF_EQUAL); +} +// Compare two strings character-by-character. +// Format as comparison lines in which changed substrings have inverse colors. +function diffStringsUnified(a, b, options) { + if (a !== b && a.length !== 0 && b.length !== 0) { + const isMultiline = a.includes("\n") || b.includes("\n"); + // getAlignedDiffs assumes that a newline was appended to the strings. + const [diffs, truncated] = diffStringsRaw(isMultiline ? `${a}\n` : a, isMultiline ? `${b}\n` : b, true, options); + if (hasCommonDiff(diffs, isMultiline)) { + const optionsNormalized = normalizeDiffOptions(options); + const lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); + return printDiffLines(lines, truncated, optionsNormalized); + } + } + // Fall back to line-by-line diff. + return diffLinesUnified(a.split("\n"), b.split("\n"), options); +} +// Compare two strings character-by-character. +// Optionally clean up small common substrings, also known as chaff. +function diffStringsRaw(a, b, cleanup, options) { + const [diffs, truncated] = diffStrings(a, b, options); + if (cleanup) { + diff_cleanupSemantic(diffs); + } + return [diffs, truncated]; +} + +function getCommonMessage(message, options) { + const { commonColor } = normalizeDiffOptions(options); + return commonColor(message); +} +const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher, + plugins.Error +]; +const FORMAT_OPTIONS = { + maxDepth: 20, + plugins: PLUGINS +}; +const FALLBACK_FORMAT_OPTIONS = { + callToJSON: false, + maxDepth: 8, + plugins: PLUGINS +}; +// Generate a string that will highlight the difference between two values +// with green and red. (similar to how github does code diffing) +/** +* @param a Expected value +* @param b Received value +* @param options Diff options +* @returns {string | null} a string diff +*/ +function diff(a, b, options) { + if (Object.is(a, b)) { + return ""; + } + const aType = getType(a); + let expectedType = aType; + let omitDifference = false; + if (aType === "object" && typeof a.asymmetricMatch === "function") { + if (a.$$typeof !== Symbol.for("jest.asymmetricMatcher")) { + // Do not know expected type of user-defined asymmetric matcher. + return undefined; + } + if (typeof a.getExpectedType !== "function") { + // For example, expect.anything() matches either null or undefined + return undefined; + } + expectedType = a.getExpectedType(); + // Primitive types boolean and number omit difference below. + // For example, omit difference for expect.stringMatching(regexp) + omitDifference = expectedType === "string"; + } + if (expectedType !== getType(b)) { + const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options); + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + let aDisplay = format(a, formatOptions); + let bDisplay = format(b, formatOptions); + // even if prettyFormat prints successfully big objects, + // large string can choke later on (concatenation? RPC?), + // so truncate it to a reasonable length here. + // (For example, playwright's ElementHandle can become about 200_000_000 length string) + const MAX_LENGTH = 1e5; + function truncate(s) { + return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`; + } + aDisplay = truncate(aDisplay); + bDisplay = truncate(bDisplay); + const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)}\n${aDisplay}`; + const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)}\n${bDisplay}`; + return `${aDiff}\n\n${bDiff}`; + } + if (omitDifference) { + return undefined; + } + switch (aType) { + case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options); + case "boolean": + case "number": return comparePrimitive(a, b, options); + case "map": return compareObjects(sortMap(a), sortMap(b), options); + case "set": return compareObjects(sortSet(a), sortSet(b), options); + default: return compareObjects(a, b, options); + } +} +function comparePrimitive(a, b, options) { + const aFormat = format(a, FORMAT_OPTIONS); + const bFormat = format(b, FORMAT_OPTIONS); + return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options); +} +function sortMap(map) { + return new Map(Array.from(map.entries()).sort()); +} +function sortSet(set) { + return new Set(Array.from(set.values()).sort()); +} +function compareObjects(a, b, options) { + let difference; + let hasThrown = false; + try { + const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch { + hasThrown = true; + } + const noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); + // If the comparison yields no results, compare again but this time + // without calling `toJSON`. It's also possible that toJSON might throw. + if (difference === undefined || difference === noDiffMessage) { + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + if (difference !== noDiffMessage && !hasThrown) { + difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`; + } + } + return difference; +} +function getFormatOptions(formatOptions, options) { + const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options); + return { + ...formatOptions, + compareKeys, + printBasicPrototype, + maxDepth: maxDepth ?? formatOptions.maxDepth + }; +} +function getObjectsDifference(a, b, formatOptions, options) { + const formatOptionsZeroIndent = { + ...formatOptions, + indent: 0 + }; + const aCompare = format(a, formatOptionsZeroIndent); + const bCompare = format(b, formatOptionsZeroIndent); + if (aCompare === bCompare) { + return getCommonMessage(NO_DIFF_MESSAGE, options); + } else { + const aDisplay = format(a, formatOptions); + const bDisplay = format(b, formatOptions); + return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options); + } +} +const MAX_DIFF_STRING_LENGTH = 2e4; +function isAsymmetricMatcher(data) { + const type = getType$1(data); + return type === "Object" && typeof data.asymmetricMatch === "function"; +} +function isReplaceable(obj1, obj2) { + const obj1Type = getType$1(obj1); + const obj2Type = getType$1(obj2); + return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array"); +} +function printDiffOrStringify(received, expected, options) { + const { aAnnotation, bAnnotation } = normalizeDiffOptions(options); + if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) { + if (expected.includes("\n") || received.includes("\n")) { + return diffStringsUnified(expected, received, options); + } + const [diffs] = diffStringsRaw(expected, received, true); + const hasCommonDiff = diffs.some((diff) => diff[0] === DIFF_EQUAL); + const printLabel = getLabelPrinter(aAnnotation, bAnnotation); + const expectedLine = printLabel(aAnnotation) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff)); + const receivedLine = printLabel(bAnnotation) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff)); + return `${expectedLine}\n${receivedLine}`; + } + // if (isLineDiffable(expected, received)) { + const clonedExpected = deepClone(expected, { forceWritable: true }); + const clonedReceived = deepClone(received, { forceWritable: true }); + const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected); + const difference = diff(replacedExpected, replacedActual, options); + return difference; + // } + // const printLabel = getLabelPrinter(aAnnotation, bAnnotation) + // const expectedLine = printLabel(aAnnotation) + printExpected(expected) + // const receivedLine + // = printLabel(bAnnotation) + // + (stringify(expected) === stringify(received) + // ? 'serializes to the same string' + // : printReceived(received)) + // return `${expectedLine}\n${receivedLine}` +} +function replaceAsymmetricMatcher(actual, expected, actualReplaced = new WeakSet(), expectedReplaced = new WeakSet()) { + // handle asymmetric Error.cause diff + if (actual instanceof Error && expected instanceof Error && typeof actual.cause !== "undefined" && typeof expected.cause === "undefined") { + delete actual.cause; + return { + replacedActual: actual, + replacedExpected: expected + }; + } + 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); + getOwnProperties(expected).forEach((key) => { + const expectedValue = expected[key]; + const actualValue = actual[key]; + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(actualValue)) { + // When matcher matches, replace expected with actual value + // so they appear the same in the diff + expected[key] = actualValue; + } else if ("sample" in expectedValue && expectedValue.sample !== undefined && isReplaceable(actualValue, expectedValue.sample)) { + // For container matchers (ArrayContaining, ObjectContaining), unwrap and recursively process + // Matcher doesn't match: unwrap but keep structure to show mismatch + const replaced = replaceAsymmetricMatcher(actualValue, expectedValue.sample, actualReplaced, expectedReplaced); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + } else if (isAsymmetricMatcher(actualValue)) { + if (actualValue.asymmetricMatch(expectedValue)) { + actual[key] = expectedValue; + } else if ("sample" in actualValue && actualValue.sample !== undefined && isReplaceable(actualValue.sample, expectedValue)) { + const replaced = replaceAsymmetricMatcher(actualValue.sample, expectedValue, actualReplaced, expectedReplaced); + actual[key] = replaced.replacedActual; + expected[key] = replaced.replacedExpected; + } + } 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 + }; +} +function getLabelPrinter(...strings) { + const maxLength = strings.reduce((max, string) => string.length > max ? string.length : max, 0); + return (string) => `${string}: ${" ".repeat(maxLength - string.length)}`; +} +const SPACE_SYMBOL = "·"; +function replaceTrailingSpaces(text) { + return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); +} +function printReceived(object) { + return c.red(replaceTrailingSpaces(stringify(object))); +} +function printExpected(value) { + return c.green(replaceTrailingSpaces(stringify(value))); +} +function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) { + return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), ""); +} + +export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/node_modules/@vitest/utils/dist/display.d.ts b/node_modules/@vitest/utils/dist/display.d.ts new file mode 100644 index 000000000..55f96396f --- /dev/null +++ b/node_modules/@vitest/utils/dist/display.d.ts @@ -0,0 +1,30 @@ +import { PrettyFormatOptions } from '@vitest/pretty-format'; + +type Inspect = (value: unknown, options: Options) => string; +interface Options { + showHidden: boolean; + depth: number; + colors: boolean; + customInspect: boolean; + showProxy: boolean; + maxArrayLength: number; + breakLength: number; + truncate: number; + seen: unknown[]; + inspect: Inspect; + stylize: (value: string, styleType: string) => string; +} +type LoupeOptions = Partial; +interface StringifyOptions extends PrettyFormatOptions { + maxLength?: number; + filterNode?: string | ((node: any) => boolean); +} +declare function stringify(object: unknown, maxDepth?: number, { maxLength, filterNode, ...options }?: StringifyOptions): string; +declare const formatRegExp: RegExp; +declare function format(...args: unknown[]): string; +declare function browserFormat(...args: unknown[]): string; +declare function inspect(obj: unknown, options?: LoupeOptions): string; +declare function objDisplay(obj: unknown, options?: LoupeOptions): string; + +export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; +export type { LoupeOptions, StringifyOptions }; diff --git a/node_modules/@vitest/utils/dist/display.js b/node_modules/@vitest/utils/dist/display.js new file mode 100644 index 000000000..42403d0ec --- /dev/null +++ b/node_modules/@vitest/utils/dist/display.js @@ -0,0 +1,775 @@ +import { plugins, createDOMElementFilter, format as format$1 } from '@vitest/pretty-format'; + +const ansiColors = { + bold: ['1', '22'], + dim: ['2', '22'], + italic: ['3', '23'], + underline: ['4', '24'], + // 5 & 6 are blinking + inverse: ['7', '27'], + hidden: ['8', '28'], + strike: ['9', '29'], + // 10-20 are fonts + // 21-29 are resets for 1-9 + black: ['30', '39'], + red: ['31', '39'], + green: ['32', '39'], + yellow: ['33', '39'], + blue: ['34', '39'], + magenta: ['35', '39'], + cyan: ['36', '39'], + white: ['37', '39'], + brightblack: ['30;1', '39'], + brightred: ['31;1', '39'], + brightgreen: ['32;1', '39'], + brightyellow: ['33;1', '39'], + brightblue: ['34;1', '39'], + brightmagenta: ['35;1', '39'], + brightcyan: ['36;1', '39'], + brightwhite: ['37;1', '39'], + grey: ['90', '39'], +}; +const styles = { + special: 'cyan', + number: 'yellow', + bigint: 'yellow', + boolean: 'yellow', + undefined: 'grey', + null: 'bold', + string: 'green', + symbol: 'green', + date: 'magenta', + regexp: 'red', +}; +const truncator = '…'; +function colorise(value, styleType) { + const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ''; + if (!color) { + return String(value); + } + return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`; +} +function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [], +// eslint-disable-next-line no-shadow +truncate = Infinity, stylize = String, } = {}, inspect) { + const options = { + showHidden: Boolean(showHidden), + depth: Number(depth), + colors: Boolean(colors), + customInspect: Boolean(customInspect), + showProxy: Boolean(showProxy), + maxArrayLength: Number(maxArrayLength), + breakLength: Number(breakLength), + truncate: Number(truncate), + seen, + inspect, + stylize, + }; + if (options.colors) { + options.stylize = colorise; + } + return options; +} +function isHighSurrogate(char) { + return char >= '\ud800' && char <= '\udbff'; +} +function truncate(string, length, tail = truncator) { + string = String(string); + const tailLength = tail.length; + const stringLength = string.length; + if (tailLength > length && stringLength > tailLength) { + return tail; + } + if (stringLength > length && stringLength > tailLength) { + let end = length - tailLength; + if (end > 0 && isHighSurrogate(string[end - 1])) { + end = end - 1; + } + return `${string.slice(0, end)}${tail}`; + } + return string; +} +// eslint-disable-next-line complexity +function inspectList(list, options, inspectItem, separator = ', ') { + inspectItem = inspectItem || options.inspect; + const size = list.length; + if (size === 0) + return ''; + const originalLength = options.truncate; + let output = ''; + let peek = ''; + let truncated = ''; + for (let i = 0; i < size; i += 1) { + const last = i + 1 === list.length; + const secondToLast = i + 2 === list.length; + truncated = `${truncator}(${list.length - i})`; + const value = list[i]; + // If there is more than one remaining we need to account for a separator of `, ` + options.truncate = originalLength - output.length - (last ? 0 : separator.length); + const string = peek || inspectItem(value, options) + (last ? '' : separator); + const nextLength = output.length + string.length; + const truncatedLength = nextLength + truncated.length; + // If this is the last element, and adding it would + // take us over length, but adding the truncator wouldn't - then break now + if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { + break; + } + // If this isn't the last or second to last element to scan, + // but the string is already over length then break here + if (!last && !secondToLast && truncatedLength > originalLength) { + break; + } + // Peek at the next string to determine if we should + // break early before adding this item to the output + peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); + // If we have one element left, but this element and + // the next takes over length, the break early + if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { + break; + } + output += string; + // If the next element takes us to length - + // but there are more after that, then we should truncate now + if (!last && !secondToLast && nextLength + peek.length >= originalLength) { + truncated = `${truncator}(${list.length - i - 1})`; + break; + } + truncated = ''; + } + return `${output}${truncated}`; +} +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key; + } + return JSON.stringify(key) + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); +} +function inspectProperty([key, value], options) { + options.truncate -= 2; + if (typeof key === 'string') { + key = quoteComplexKey(key); + } + else if (typeof key !== 'number') { + key = `[${options.inspect(key, options)}]`; + } + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key}: ${value}`; +} + +function inspectArray(array, options) { + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return '[]'; + options.truncate -= 4; + const listContents = inspectList(array, options); + options.truncate -= listContents.length; + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} + +const getArrayName = (array) => { + // We need to special case Node.js' Buffers, which report to be Uint8Array + // @ts-ignore + if (typeof Buffer === 'function' && array instanceof Buffer) { + return 'Buffer'; + } + if (array[Symbol.toStringTag]) { + return array[Symbol.toStringTag]; + } + return array.constructor.name; +}; +function inspectTypedArray(array, options) { + const name = getArrayName(array); + options.truncate -= name.length + 4; + // Object.keys will always output the Array indices first, so we can slice by + // `array.length` to get non-index properties + const nonIndexProperties = Object.keys(array).slice(array.length); + if (!array.length && !nonIndexProperties.length) + return `${name}[]`; + // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply + // stylise the toString() value of them + let output = ''; + for (let i = 0; i < array.length; i++) { + const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`; + options.truncate -= string.length; + if (array[i] !== array.length && options.truncate <= 3) { + output += `${truncator}(${array.length - array[i] + 1})`; + break; + } + output += string; + } + let propertyContents = ''; + if (nonIndexProperties.length) { + propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); + } + return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`; +} + +function inspectDate(dateObject, options) { + const stringRepresentation = dateObject.toJSON(); + if (stringRepresentation === null) { + return 'Invalid Date'; + } + const split = stringRepresentation.split('T'); + const date = split[0]; + // If we need to - truncate the time portion, but never the date + return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date'); +} + +function inspectFunction(func, options) { + const functionType = func[Symbol.toStringTag] || 'Function'; + const name = func.name; + if (!name) { + return options.stylize(`[${functionType}]`, 'special'); + } + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special'); +} + +function inspectMapEntry([key, value], options) { + options.truncate -= 4; + key = options.inspect(key, options); + options.truncate -= key.length; + value = options.inspect(value, options); + return `${key} => ${value}`; +} +// IE11 doesn't support `map.entries()` +function mapToEntries(map) { + const entries = []; + map.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +} +function inspectMap(map, options) { + if (map.size === 0) + return 'Map{}'; + options.truncate -= 7; + return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; +} + +const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare +function inspectNumber(number, options) { + if (isNaN(number)) { + return options.stylize('NaN', 'number'); + } + if (number === Infinity) { + return options.stylize('Infinity', 'number'); + } + if (number === -Infinity) { + return options.stylize('-Infinity', 'number'); + } + if (number === 0) { + return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); + } + return options.stylize(truncate(String(number), options.truncate), 'number'); +} + +function inspectBigInt(number, options) { + let nums = truncate(number.toString(), options.truncate - 1); + if (nums !== truncator) + nums += 'n'; + return options.stylize(nums, 'bigint'); +} + +function inspectRegExp(value, options) { + const flags = value.toString().split('/')[2]; + const sourceLength = options.truncate - (2 + flags.length); + const source = value.source; + return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp'); +} + +// IE11 doesn't support `Array.from(set)` +function arrayFromSet(set) { + const values = []; + set.forEach(value => { + values.push(value); + }); + return values; +} +function inspectSet(set, options) { + if (set.size === 0) + return 'Set{}'; + options.truncate -= 7; + return `Set{ ${inspectList(arrayFromSet(set), options)} }`; +} + +const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + + '\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g'); +const escapeCharacters = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + "'": "\\'", + '\\': '\\\\', +}; +const hex = 16; +function escape(char) { + return (escapeCharacters[char] || + `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`); +} +function inspectString(string, options) { + if (stringEscapeChars.test(string)) { + string = string.replace(stringEscapeChars, escape); + } + return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string'); +} + +function inspectSymbol(value) { + if ('description' in Symbol.prototype) { + return value.description ? `Symbol(${value.description})` : 'Symbol()'; + } + return value.toString(); +} + +const getPromiseValue = () => 'Promise{…}'; + +function inspectObject$1(object, options) { + const properties = Object.getOwnPropertyNames(object); + const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; + if (properties.length === 0 && symbols.length === 0) { + return '{}'; + } + options.truncate -= 4; + options.seen = options.seen || []; + if (options.seen.includes(object)) { + return '[Circular]'; + } + options.seen.push(object); + const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty); + const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty); + options.seen.pop(); + let sep = ''; + if (propertyContents && symbolContents) { + sep = ', '; + } + return `{ ${propertyContents}${sep}${symbolContents} }`; +} + +const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; +function inspectClass(value, options) { + let name = ''; + if (toStringTag && toStringTag in value) { + name = value[toStringTag]; + } + name = name || value.constructor.name; + // Babel transforms anonymous classes to the name `_class` + if (!name || name === '_class') { + name = ''; + } + options.truncate -= name.length; + return `${name}${inspectObject$1(value, options)}`; +} + +function inspectArguments(args, options) { + if (args.length === 0) + return 'Arguments[]'; + options.truncate -= 13; + return `Arguments[ ${inspectList(args, options)} ]`; +} + +const errorKeys = [ + 'stack', + 'line', + 'column', + 'name', + 'message', + 'fileName', + 'lineNumber', + 'columnNumber', + 'number', + 'description', + 'cause', +]; +function inspectObject(error, options) { + const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1); + const name = error.name; + options.truncate -= name.length; + let message = ''; + if (typeof error.message === 'string') { + message = truncate(error.message, options.truncate); + } + else { + properties.unshift('message'); + } + message = message ? `: ${message}` : ''; + options.truncate -= message.length + 5; + options.seen = options.seen || []; + if (options.seen.includes(error)) { + return '[Circular]'; + } + options.seen.push(error); + const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty); + return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`; +} + +function inspectAttribute([key, value], options) { + options.truncate -= 3; + if (!value) { + return `${options.stylize(String(key), 'yellow')}`; + } + return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`; +} +function inspectNodeCollection(collection, options) { + return inspectList(collection, options, inspectNode, '\n'); +} +function inspectNode(node, options) { + switch (node.nodeType) { + case 1: + return inspectHTML(node, options); + case 3: + return options.inspect(node.data, options); + default: + return options.inspect(node, options); + } +} +// @ts-ignore (Deno doesn't have Element) +function inspectHTML(element, options) { + const properties = element.getAttributeNames(); + const name = element.tagName.toLowerCase(); + const head = options.stylize(`<${name}`, 'special'); + const headClose = options.stylize(`>`, 'special'); + const tail = options.stylize(``, 'special'); + options.truncate -= name.length * 2 + 5; + let propertyContents = ''; + if (properties.length > 0) { + propertyContents += ' '; + propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' '); + } + options.truncate -= propertyContents.length; + const truncate = options.truncate; + let children = inspectNodeCollection(element.children, options); + if (children && children.length > truncate) { + children = `${truncator}(${element.children.length})`; + } + return `${head}${propertyContents}${headClose}${children}${tail}`; +} + +/* ! + * loupe + * Copyright(c) 2013 Jake Luer + * MIT Licensed + */ +const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; +const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; +const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); +const constructorMap = new WeakMap(); +const stringTagMap = {}; +const baseTypesMap = { + undefined: (value, options) => options.stylize('undefined', 'undefined'), + null: (value, options) => options.stylize('null', 'null'), + boolean: (value, options) => options.stylize(String(value), 'boolean'), + Boolean: (value, options) => options.stylize(String(value), 'boolean'), + number: inspectNumber, + Number: inspectNumber, + bigint: inspectBigInt, + BigInt: inspectBigInt, + string: inspectString, + String: inspectString, + function: inspectFunction, + Function: inspectFunction, + symbol: inspectSymbol, + // A Symbol polyfill will return `Symbol` not `symbol` from typedetect + Symbol: inspectSymbol, + Array: inspectArray, + Date: inspectDate, + Map: inspectMap, + Set: inspectSet, + RegExp: inspectRegExp, + Promise: getPromiseValue, + // WeakSet, WeakMap are totally opaque to us + WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'), + WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'), + Arguments: inspectArguments, + Int8Array: inspectTypedArray, + Uint8Array: inspectTypedArray, + Uint8ClampedArray: inspectTypedArray, + Int16Array: inspectTypedArray, + Uint16Array: inspectTypedArray, + Int32Array: inspectTypedArray, + Uint32Array: inspectTypedArray, + Float32Array: inspectTypedArray, + Float64Array: inspectTypedArray, + Generator: () => '', + DataView: () => '', + ArrayBuffer: () => '', + Error: inspectObject, + HTMLCollection: inspectNodeCollection, + NodeList: inspectNodeCollection, +}; +// eslint-disable-next-line complexity +const inspectCustom = (value, options, type, inspectFn) => { + if (chaiInspect in value && typeof value[chaiInspect] === 'function') { + return value[chaiInspect](options); + } + if (nodeInspect in value && typeof value[nodeInspect] === 'function') { + return value[nodeInspect](options.depth, options, inspectFn); + } + if ('inspect' in value && typeof value.inspect === 'function') { + return value.inspect(options.depth, options); + } + if ('constructor' in value && constructorMap.has(value.constructor)) { + return constructorMap.get(value.constructor)(value, options); + } + if (stringTagMap[type]) { + return stringTagMap[type](value, options); + } + return ''; +}; +const toString = Object.prototype.toString; +// eslint-disable-next-line complexity +function inspect$1(value, opts = {}) { + const options = normaliseOptions(opts, inspect$1); + const { customInspect } = options; + let type = value === null ? 'null' : typeof value; + if (type === 'object') { + type = toString.call(value).slice(8, -1); + } + // If it is a base value that we already support, then use Loupe's inspector + if (type in baseTypesMap) { + return baseTypesMap[type](value, options); + } + // If `options.customInspect` is set to true then try to use the custom inspector + if (customInspect && value) { + const output = inspectCustom(value, options, type, inspect$1); + if (output) { + if (typeof output === 'string') + return output; + return inspect$1(output, options); + } + } + const proto = value ? Object.getPrototypeOf(value) : false; + // If it's a plain Object then use Loupe's inspector + if (proto === Object.prototype || proto === null) { + return inspectObject$1(value, options); + } + // Specifically account for HTMLElements + // @ts-ignore + if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { + return inspectHTML(value, options); + } + if ('constructor' in value) { + // If it is a class, inspect it like an object but add the constructor name + if (value.constructor !== Object) { + return inspectClass(value, options); + } + // If it is an object with an anonymous prototype, display it as an object. + return inspectObject$1(value, options); + } + // last chance to check if it's an object + if (value === Object(value)) { + return inspectObject$1(value, options); + } + // We have run out of options! Just stringify the value + return options.stylize(String(value), type); +} + +const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +function stringify(object, maxDepth = 10, { maxLength, filterNode, ...options } = {}) { + const MAX_LENGTH = maxLength ?? 1e4; + let result; + // Convert string selector to filter function + const filterFn = typeof filterNode === "string" ? createNodeFilterFromSelector(filterNode) : filterNode; + const plugins = filterFn ? [ + ReactTestComponent, + ReactElement, + createDOMElementFilter(filterFn), + DOMCollection, + Immutable, + AsymmetricMatcher + ] : PLUGINS; + try { + result = format$1(object, { + maxDepth, + escapeString: false, + plugins, + ...options + }); + } catch { + result = format$1(object, { + callToJSON: false, + maxDepth, + escapeString: false, + plugins, + ...options + }); + } + // Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249 + return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), { + maxLength, + filterNode, + ...options + }) : result; +} +function createNodeFilterFromSelector(selector) { + const ELEMENT_NODE = 1; + const COMMENT_NODE = 8; + return (node) => { + // Filter out comments + if (node.nodeType === COMMENT_NODE) { + return false; + } + // Filter out elements matching the selector + if (node.nodeType === ELEMENT_NODE && node.matches) { + try { + return !node.matches(selector); + } catch { + return true; + } + } + return true; + }; +} +const formatRegExp = /%[sdjifoOc%]/g; +function baseFormat(args, options = {}) { + const formatArg = (item, inspecOptions) => { + if (options.prettifyObject) { + return stringify(item, undefined, { + printBasicPrototype: false, + escapeString: false + }); + } + return inspect(item, inspecOptions); + }; + if (typeof args[0] !== "string") { + const objects = []; + for (let i = 0; i < args.length; i++) { + objects.push(formatArg(args[i], { + depth: 0, + colors: false + })); + } + return objects.join(" "); + } + const len = args.length; + let i = 1; + const template = args[0]; + let str = String(template).replace(formatRegExp, (x) => { + if (x === "%%") { + return "%"; + } + if (i >= len) { + return x; + } + switch (x) { + case "%s": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + if (typeof value === "number" && value === 0 && 1 / value < 0) { + return "-0"; + } + if (typeof value === "object" && value !== null) { + if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) { + return value.toString(); + } + return formatArg(value, { + depth: 0, + colors: false + }); + } + return String(value); + } + case "%d": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + if (typeof value === "symbol") { + return "NaN"; + } + return Number(value).toString(); + } + case "%i": { + const value = args[i++]; + if (typeof value === "bigint") { + return `${value.toString()}n`; + } + return Number.parseInt(String(value)).toString(); + } + case "%f": return Number.parseFloat(String(args[i++])).toString(); + case "%o": return formatArg(args[i++], { + showHidden: true, + showProxy: true + }); + case "%O": return formatArg(args[i++]); + case "%c": { + i++; + return ""; + } + case "%j": try { + return JSON.stringify(args[i++]); + } catch (err) { + const m = err.message; + if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) { + return "[Circular]"; + } + throw err; + } + default: return x; + } + }); + for (let x = args[i]; i < len; x = args[++i]) { + if (x === null || typeof x !== "object") { + str += ` ${typeof x === "symbol" ? x.toString() : x}`; + } else { + str += ` ${formatArg(x)}`; + } + } + return str; +} +function format(...args) { + return baseFormat(args); +} +function browserFormat(...args) { + return baseFormat(args, { prettifyObject: true }); +} +function inspect(obj, options = {}) { + if (options.truncate === 0) { + options.truncate = Number.POSITIVE_INFINITY; + } + return inspect$1(obj, options); +} +function objDisplay(obj, options = {}) { + if (typeof options.truncate === "undefined") { + options.truncate = 40; + } + const str = inspect(obj, options); + const type = Object.prototype.toString.call(obj); + if (options.truncate && str.length >= options.truncate) { + if (type === "[object Function]") { + const fn = obj; + return !fn.name ? "[Function]" : `[Function: ${fn.name}]`; + } else if (type === "[object Array]") { + return `[ Array(${obj.length}) ]`; + } else if (type === "[object Object]") { + const keys = Object.keys(obj); + const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", "); + return `{ Object (${kstr}) }`; + } else { + return str; + } + } + return str; +} + +export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; diff --git a/node_modules/@vitest/utils/dist/error.d.ts b/node_modules/@vitest/utils/dist/error.d.ts new file mode 100644 index 000000000..92158c1b2 --- /dev/null +++ b/node_modules/@vitest/utils/dist/error.d.ts @@ -0,0 +1,8 @@ +import { D as DiffOptions } from './types.d-BCElaP-c.js'; +import { TestError } from './types.js'; +export { serializeValue as serializeError } from './serialize.js'; +import '@vitest/pretty-format'; + +declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet): TestError; + +export { processError }; diff --git a/node_modules/@vitest/utils/dist/error.js b/node_modules/@vitest/utils/dist/error.js new file mode 100644 index 000000000..fbcf9182f --- /dev/null +++ b/node_modules/@vitest/utils/dist/error.js @@ -0,0 +1,41 @@ +import { printDiffOrStringify } from './diff.js'; +import { stringify } from './display.js'; +import { serializeValue } from './serialize.js'; +import '@vitest/pretty-format'; +import 'tinyrainbow'; +import './helpers.js'; +import './constants.js'; + +function processError(_err, diffOptions, seen = new WeakSet()) { + if (!_err || typeof _err !== "object") { + return { message: String(_err) }; + } + const err = _err; + if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) { + err.diff = printDiffOrStringify(err.actual, err.expected, { + ...diffOptions, + ...err.diffOptions + }); + } + if ("expected" in err && typeof err.expected !== "string") { + err.expected = stringify(err.expected, 10); + } + if ("actual" in err && typeof err.actual !== "string") { + err.actual = stringify(err.actual, 10); + } + // some Error implementations may not allow rewriting cause + // in most cases, the assignment will lead to "err.cause = err.cause" + try { + if (!seen.has(err) && typeof err.cause === "object") { + seen.add(err); + err.cause = processError(err.cause, diffOptions, seen); + } + } catch {} + try { + return serializeValue(err); + } catch (e) { + return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`)); + } +} + +export { processError, serializeValue as serializeError }; diff --git a/node_modules/@vitest/utils/dist/helpers.d.ts b/node_modules/@vitest/utils/dist/helpers.d.ts new file mode 100644 index 000000000..48a70a69e --- /dev/null +++ b/node_modules/@vitest/utils/dist/helpers.d.ts @@ -0,0 +1,80 @@ +import { Nullable, Arrayable } from './types.js'; + +declare function nanoid(size?: number): string; + +declare function shuffle(array: T[], seed?: number): T[]; + +interface CloneOptions { + forceWritable?: boolean; +} +interface ErrorOptions { + message?: string; + stackTraceLimit?: number; +} + +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +declare function createSimpleStackTrace(options?: ErrorOptions): string; +declare function notNullish(v: T | null | undefined): v is NonNullable; +declare function assertTypes(value: unknown, name: string, types: string[]): void; +declare function isPrimitive(value: unknown): boolean; +declare function slash(path: string): string; +declare function cleanUrl(url: string): string; +declare function splitFileAndPostfix(path: string): { + file: string; + postfix: string; +}; +declare const isExternalUrl: (url: string) => boolean; +/** +* Prepend `/@id/` and replace null byte so the id is URL-safe. +* This is prepended to resolved ids that are not valid browser +* import specifiers by the importAnalysis plugin. +*/ +declare function wrapId(id: string): string; +/** +* Undo {@link wrapId}'s `/@id/` and null byte replacements. +*/ +declare function unwrapId(id: string): string; +declare function withTrailingSlash(path: string): string; +declare function filterOutComments(s: string): string; +declare function isBareImport(id: string): boolean; +declare function toArray(array?: Nullable>): Array; +declare function isObject(item: unknown): boolean; +declare function getType(value: unknown): string; +declare function getOwnProperties(obj: any): (string | symbol)[]; +declare function deepClone(val: T, options?: CloneOptions): T; +declare function clone(val: T, seen: WeakMap, options?: CloneOptions): T; +declare function noop(): void; +declare function objectAttr(source: any, path: string, defaultValue?: undefined): any; +type DeferPromise = Promise & { + resolve: (value: T | PromiseLike) => void; + reject: (reason?: any) => void; +}; +declare function createDefer(): DeferPromise; +/** +* If code starts with a function call, will return its last index, respecting arguments. +* This will return 25 - last ending character of toMatch ")" +* Also works with callbacks +* ``` +* toMatch({ test: '123' }); +* toBeAliased('123') +* ``` +*/ +declare function getCallLastIndex(code: string): number | null; +declare function isNegativeNaN(val: number): boolean; +declare function ordinal(i: number): string; +/** +* Deep merge :P +* +* Will merge objects only if they are plain +* +* Do not merge types - it is very expensive and usually it's better to case a type here +*/ +declare function deepMerge(target: T, ...sources: any[]): T; +declare function unique(array: T[]): T[]; + +export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId }; +export type { DeferPromise }; diff --git a/node_modules/@vitest/utils/dist/helpers.js b/node_modules/@vitest/utils/dist/helpers.js new file mode 100644 index 000000000..c62b1fbeb --- /dev/null +++ b/node_modules/@vitest/utils/dist/helpers.js @@ -0,0 +1,344 @@ +import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js'; + +// port from nanoid +// https://github.com/ai/nanoid +const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; +function nanoid(size = 21) { + let id = ""; + let i = size; + while (i--) { + id += urlAlphabet[Math.random() * 64 | 0]; + } + return id; +} + +const RealDate = Date; +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; +} + +/** +* Get original stacktrace without source map support the most performant way. +* - Create only 1 stack frame. +* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). +*/ +function createSimpleStackTrace(options) { + const { message = "$$stack trace 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; +} +function notNullish(v) { + return v != null; +} +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 isPrimitive(value) { + return value === null || typeof value !== "function" && typeof value !== "object"; +} +function slash(path) { + return path.replace(/\\/g, "/"); +} +const postfixRE = /[?#].*$/; +function cleanUrl(url) { + return url.replace(postfixRE, ""); +} +function splitFileAndPostfix(path) { + const file = cleanUrl(path); + return { + file, + postfix: path.slice(file.length) + }; +} +const externalRE = /^(?:[a-z]+:)?\/\//; +const isExternalUrl = (url) => externalRE.test(url); +/** +* Prepend `/@id/` and replace null byte so the id is URL-safe. +* This is prepended to resolved ids that are not valid browser +* import specifiers by the importAnalysis plugin. +*/ +function wrapId(id) { + return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); +} +/** +* Undo {@link wrapId}'s `/@id/` and null byte replacements. +*/ +function unwrapId(id) { + return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; +} +function withTrailingSlash(path) { + if (path.at(-1) !== "/") { + return `${path}/`; + } + return path; +} +function filterOutComments(s) { + const result = []; + let commentState = "none"; + for (let i = 0; i < s.length; ++i) { + if (commentState === "singleline") { + if (s[i] === "\n") { + commentState = "none"; + } + } else if (commentState === "multiline") { + if (s[i - 1] === "*" && s[i] === "/") { + commentState = "none"; + } + } else if (commentState === "none") { + if (s[i] === "/" && s[i + 1] === "/") { + commentState = "singleline"; + } else if (s[i] === "/" && s[i + 1] === "*") { + commentState = "multiline"; + i += 2; + } else { + result.push(s[i]); + } + } + } + return result.join(""); +} +const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i; +function isBareImport(id) { + return bareImportRE.test(id); +} +function toArray(array) { + if (array === null || array === undefined) { + array = []; + } + if (Array.isArray(array)) { + return array; + } + return [array]; +} +function isObject(item) { + return item != null && typeof item === "object" && !Array.isArray(item); +} +function isFinalObj(obj) { + return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype; +} +function getType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +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 getOwnProperties(obj) { + const ownProps = new Set(); + if (isFinalObj(obj)) { + return []; + } + collectOwnProperties(obj, ownProps); + return Array.from(ownProps); +} +const defaultCloneOptions = { forceWritable: false }; +function deepClone(val, options = defaultCloneOptions) { + const seen = new WeakMap(); + return clone(val, seen, options); +} +function clone(val, seen, options = defaultCloneOptions) { + let k, out; + if (seen.has(val)) { + return seen.get(val); + } + if (Array.isArray(val)) { + out = Array.from({ length: k = val.length }); + seen.set(val, out); + while (k--) { + out[k] = clone(val[k], seen, options); + } + return out; + } + if (Object.prototype.toString.call(val) === "[object Object]") { + out = Object.create(Object.getPrototypeOf(val)); + seen.set(val, out); + // we don't need properties from prototype + const props = getOwnProperties(val); + for (const k of props) { + const descriptor = Object.getOwnPropertyDescriptor(val, k); + if (!descriptor) { + continue; + } + const cloned = clone(val[k], seen, options); + if (options.forceWritable) { + Object.defineProperty(out, k, { + enumerable: descriptor.enumerable, + configurable: true, + writable: true, + value: cloned + }); + } else if ("get" in descriptor) { + Object.defineProperty(out, k, { + ...descriptor, + get() { + return cloned; + } + }); + } else { + Object.defineProperty(out, k, { + ...descriptor, + value: cloned + }); + } + } + return out; + } + return val; +} +function noop() {} +function objectAttr(source, path, defaultValue = undefined) { + // a[3].b -> a.3.b + const paths = path.replace(/\[(\d+)\]/g, ".$1").split("."); + let result = source; + for (const p of paths) { + result = new Object(result)[p]; + if (result === undefined) { + return defaultValue; + } + } + return result; +} +function createDefer() { + let resolve = null; + let reject = null; + const p = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + p.resolve = resolve; + p.reject = reject; + return p; +} +/** +* If code starts with a function call, will return its last index, respecting arguments. +* This will return 25 - last ending character of toMatch ")" +* Also works with callbacks +* ``` +* toMatch({ test: '123' }); +* toBeAliased('123') +* ``` +*/ +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; +} +function isNegativeNaN(val) { + if (!Number.isNaN(val)) { + return false; + } + const f64 = new Float64Array(1); + f64[0] = val; + const u32 = new Uint32Array(f64.buffer); + const isNegative = u32[1] >>> 31 === 1; + return isNegative; +} +function toString(v) { + return Object.prototype.toString.call(v); +} +function isPlainObject(val) { + return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object"); +} +function isMergeableObject(item) { + return isPlainObject(item) && !Array.isArray(item); +} +function ordinal(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`; +} +/** +* Deep merge :P +* +* Will merge objects only if they are plain +* +* Do not merge types - it is very expensive and usually it's better to case a type here +*/ +function deepMerge(target, ...sources) { + if (!sources.length) { + return target; + } + const source = sources.shift(); + if (source === undefined) { + return target; + } + if (isMergeableObject(target) && isMergeableObject(source)) { + Object.keys(source).forEach((key) => { + const _source = source; + if (isMergeableObject(_source[key])) { + if (!target[key]) { + target[key] = {}; + } + deepMerge(target[key], _source[key]); + } else { + target[key] = _source[key]; + } + }); + } + return deepMerge(target, ...sources); +} +function unique(array) { + return Array.from(new Set(array)); +} + +export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, splitFileAndPostfix, toArray, unique, unwrapId, withTrailingSlash, wrapId }; diff --git a/node_modules/@vitest/utils/dist/index.d.ts b/node_modules/@vitest/utils/dist/index.d.ts new file mode 100644 index 000000000..d4435cc6f --- /dev/null +++ b/node_modules/@vitest/utils/dist/index.d.ts @@ -0,0 +1,5 @@ +export { LoupeOptions, StringifyOptions } from './display.js'; +export { DeferPromise } from './helpers.js'; +export { SafeTimers } from './timers.js'; +export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js'; +import '@vitest/pretty-format'; diff --git a/node_modules/@vitest/utils/dist/index.js b/node_modules/@vitest/utils/dist/index.js new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/node_modules/@vitest/utils/dist/index.js @@ -0,0 +1 @@ + diff --git a/node_modules/@vitest/utils/dist/offset.d.ts b/node_modules/@vitest/utils/dist/offset.d.ts new file mode 100644 index 000000000..ae65386fb --- /dev/null +++ b/node_modules/@vitest/utils/dist/offset.d.ts @@ -0,0 +1,5 @@ +declare const lineSplitRE: RegExp; +declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number; +declare function offsetToLineNumber(source: string, offset: number): number; + +export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/node_modules/@vitest/utils/dist/offset.js b/node_modules/@vitest/utils/dist/offset.js new file mode 100644 index 000000000..d8cb08db0 --- /dev/null +++ b/node_modules/@vitest/utils/dist/offset.js @@ -0,0 +1,32 @@ +const lineSplitRE = /\r?\n/; +function positionToOffset(source, lineNumber, columnNumber) { + const lines = source.split(lineSplitRE); + const nl = /\r\n/.test(source) ? 2 : 1; + let start = 0; + if (lineNumber > lines.length) { + return source.length; + } + for (let i = 0; i < lineNumber - 1; i++) { + start += lines[i].length + nl; + } + 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); + const nl = /\r\n/.test(source) ? 2 : 1; + let counted = 0; + let line = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + nl; + if (counted + lineLength >= offset) { + break; + } + counted += lineLength; + } + return line + 1; +} + +export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/node_modules/@vitest/utils/dist/resolver.d.ts b/node_modules/@vitest/utils/dist/resolver.d.ts new file mode 100644 index 000000000..71ebc639e --- /dev/null +++ b/node_modules/@vitest/utils/dist/resolver.d.ts @@ -0,0 +1,7 @@ +declare function findNearestPackageData(basedir: string): { + type?: "module" | "commonjs"; +}; +declare function getCachedData(cache: Map, basedir: string, originalBasedir: string): NonNullable | undefined; +declare function setCacheData(cache: Map, data: T, basedir: string, originalBasedir: string): void; + +export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/node_modules/@vitest/utils/dist/resolver.js b/node_modules/@vitest/utils/dist/resolver.js new file mode 100644 index 000000000..12ef66d5c --- /dev/null +++ b/node_modules/@vitest/utils/dist/resolver.js @@ -0,0 +1,70 @@ +import fs from 'node:fs'; +import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js'; + +const packageCache = new Map(); +function findNearestPackageData(basedir) { + const originalBasedir = basedir; + while (basedir) { + const cached = getCachedData(packageCache, basedir, originalBasedir); + if (cached) { + return cached; + } + const pkgPath = join(basedir, "package.json"); + if (tryStatSync(pkgPath)?.isFile()) { + const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8"))); + if (packageCache) { + setCacheData(packageCache, pkgData, basedir, originalBasedir); + } + return pkgData; + } + const nextBasedir = dirname(basedir); + if (nextBasedir === basedir) { + break; + } + basedir = nextBasedir; + } + return {}; +} +function stripBomTag(content) { + if (content.charCodeAt(0) === 65279) { + return content.slice(1); + } + return content; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs.statSync(file, { throwIfNoEntry: false }); + } catch {} +} +function getCachedData(cache, basedir, originalBasedir) { + const pkgData = cache.get(getFnpdCacheKey(basedir)); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setCacheData(cache, data, basedir, originalBasedir) { + cache.set(getFnpdCacheKey(basedir), data); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + cache.set(getFnpdCacheKey(dir), data); + }); +} +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +/** +* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. +* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` +* @param shorterDir Shorter dir path, e.g. `/User/foo` +*/ +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = dirname(longerDir); + } +} + +export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/node_modules/@vitest/utils/dist/serialize.d.ts b/node_modules/@vitest/utils/dist/serialize.d.ts new file mode 100644 index 000000000..dd8ee7d8b --- /dev/null +++ b/node_modules/@vitest/utils/dist/serialize.d.ts @@ -0,0 +1,3 @@ +declare function serializeValue(val: any, seen?: WeakMap): any; + +export { serializeValue }; diff --git a/node_modules/@vitest/utils/dist/serialize.js b/node_modules/@vitest/utils/dist/serialize.js new file mode 100644 index 000000000..22bf79855 --- /dev/null +++ b/node_modules/@vitest/utils/dist/serialize.js @@ -0,0 +1,118 @@ +const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; +const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@"; +function isImmutable(v) { + return 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 ""; +} +// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm +function serializeValue(val, seen = new WeakMap()) { + if (!val || typeof val === "string") { + return val; + } + if (val instanceof Error && "toJSON" in val && typeof val.toJSON === "function") { + const jsonValue = val.toJSON(); + if (jsonValue && jsonValue !== val && typeof jsonValue === "object") { + if (typeof val.message === "string") { + safe(() => jsonValue.message ??= normalizeErrorMessage(val.message)); + } + if (typeof val.stack === "string") { + safe(() => jsonValue.stack ??= val.stack); + } + if (typeof val.name === "string") { + safe(() => jsonValue.name ??= val.name); + } + if (val.cause != null) { + safe(() => jsonValue.cause ??= serializeValue(val.cause, seen)); + } + } + return serializeValue(jsonValue, seen); + } + if (typeof val === "function") { + return `Function<${val.name || "anonymous"}>`; + } + if (typeof val === "symbol") { + return val.toString(); + } + if (typeof val !== "object") { + return val; + } + if (typeof Buffer !== "undefined" && val instanceof Buffer) { + return ``; + } + if (typeof Uint8Array !== "undefined" && val instanceof Uint8Array) { + return ``; + } + // cannot serialize immutables as immutables + if (isImmutable(val)) { + return serializeValue(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.toJSON === "function") { + return serializeValue(val.toJSON(), seen); + } + if (seen.has(val)) { + return seen.get(val); + } + if (Array.isArray(val)) { + // eslint-disable-next-line unicorn/no-new-array -- we need to keep sparse arrays ([1,,3]) + const clone = new Array(val.length); + seen.set(val, clone); + val.forEach((e, i) => { + try { + clone[i] = serializeValue(e, seen); + } catch (err) { + clone[i] = getUnserializableMessage(err); + } + }); + return clone; + } else { + // Objects with `Error` constructors appear to cause problems during worker communication + // using `MessagePort`, so the serialized error object is being recreated as plain object. + const clone = 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] = serializeValue(val[key], seen); + } catch (err) { + // delete in case it has a setter from prototype that might throw + delete clone[key]; + clone[key] = getUnserializableMessage(err); + } + }); + obj = Object.getPrototypeOf(obj); + } + if (val instanceof Error) { + safe(() => clone.message = normalizeErrorMessage(val.message)); + } + return clone; + } +} +function safe(fn) { + try { + return fn(); + } catch {} +} +function normalizeErrorMessage(message) { + return message.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/getByTestId('__vitest_\d+__')/g, "page"); +} + +export { serializeValue }; diff --git a/node_modules/@vitest/utils/dist/source-map.d.ts b/node_modules/@vitest/utils/dist/source-map.d.ts new file mode 100644 index 000000000..582d24f81 --- /dev/null +++ b/node_modules/@vitest/utils/dist/source-map.d.ts @@ -0,0 +1,55 @@ +import { TestError, ParsedStack } from './types.js'; + +type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; + +interface StackTraceParserOptions { + ignoreStackEntries?: (RegExp | string)[]; + getSourceMap?: (file: string) => unknown; + getUrlId?: (id: string) => string; + frameFilter?: (error: TestError, frame: ParsedStack) => boolean | void; +} +declare const stackIgnorePatterns: (string | RegExp)[]; + +declare function parseSingleFFOrSafariStack(raw: string): ParsedStack | null; +declare function parseSingleStack(raw: string): ParsedStack | null; +declare function parseSingleV8Stack(raw: string): ParsedStack | null; +declare function createStackString(stacks: ParsedStack[]): string; +declare function parseStacktrace(stack: string, options?: StackTraceParserOptions): ParsedStack[]; +declare function parseErrorStacktrace(e: TestError | Error, options?: StackTraceParserOptions): ParsedStack[]; +interface SourceMapLike { + version: number; + mappings?: string; + names?: string[]; + sources?: string[]; + sourcesContent?: string[]; + sourceRoot?: string; +} +interface Needle { + line: number; + column: number; +} +declare class DecodedMap { + map: SourceMapLike; + _encoded: string; + _decoded: undefined | number[][][]; + _decodedMemo: Stats; + url: string; + version: number; + names: string[]; + resolvedSources: string[]; + constructor(map: SourceMapLike, from: string); +} +interface Stats { + lastKey: number; + lastNeedle: number; + lastIndex: number; +} +declare function getOriginalPosition(map: DecodedMap, needle: Needle): OriginalMapping | null; + +export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; +export type { StackTraceParserOptions }; diff --git a/node_modules/@vitest/utils/dist/source-map.js b/node_modules/@vitest/utils/dist/source-map.js new file mode 100644 index 000000000..c5cc45f42 --- /dev/null +++ b/node_modules/@vitest/utils/dist/source-map.js @@ -0,0 +1,488 @@ +import { isPrimitive, notNullish } from './helpers.js'; +import { r as resolve } from './chunk-pathe.M-eThtNZ.js'; +import './constants.js'; + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader, relative) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -2147483648 | -value; + } + return relative + value; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn = decodeInteger(reader, genColumn); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex = decodeInteger(reader, sourcesIndex); + sourceLine = decodeInteger(reader, sourceLine); + sourceColumn = decodeInteger(reader, sourceColumn); + if (hasMoreVlq(reader, semi)) { + namesIndex = decodeInteger(reader, namesIndex); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} + +// src/trace-mapping.ts + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +function cast(map) { + return map; +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} + +const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; +const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; +const stackIgnorePatterns = [ + "node:internal", + /\/packages\/\w+\/dist\//, + /\/@vitest\/\w+\/dist\//, + "/vitest/dist/", + "/vitest/src/", + "/node_modules/chai/", + "/node_modules/tinyspy/", + "/vite/dist/node/module-runner", + "/rolldown-vite/dist/node/module-runner", + "/deps/chunk-", + "/deps/@vitest", + "/deps/loupe", + "/deps/chai", + "/browser-playwright/dist/locators.js", + "/browser-webdriverio/dist/locators.js", + "/browser-preview/dist/locators.js", + /node:\w+/, + /__vitest_test__/, + /__vitest_browser__/, + "/@id/__x00__vitest/browser", + /\/deps\/vitest_/ +]; +const NOW_LENGTH = Date.now().toString().length; +const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`); +function extractLocation(urlLike) { + // Fail-fast but return locations like "(native)" + if (!urlLike.includes(":")) { + return [urlLike]; + } + const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; + const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); + if (!parts) { + return [urlLike]; + } + let url = parts[1]; + if (url.startsWith("async ")) { + url = url.slice(6); + } + if (url.startsWith("http:") || url.startsWith("https:")) { + const urlObj = new URL(url); + urlObj.searchParams.delete("import"); + urlObj.searchParams.delete("browserv"); + url = urlObj.pathname + urlObj.hash + urlObj.search; + } + if (url.startsWith("/@fs/")) { + const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); + url = url.slice(isWindows ? 5 : 4); + } + if (url.includes("vitest=")) { + url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, ""); + } + return [ + url, + parts[2] || undefined, + parts[3] || undefined + ]; +} +function parseSingleFFOrSafariStack(raw) { + let line = raw.trim(); + if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { + return null; + } + if (line.includes(" > eval")) { + line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); + } + // Early return for lines that don't look like Firefox/Safari stack traces + // Firefox/Safari stack traces must contain '@' and should have location info after it + if (!line.includes("@")) { + return null; + } + // Find the correct @ that separates function name from location + // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' + // we need to find the first @ that precedes a valid location (containing :) + let atIndex = -1; + let locationPart = ""; + let functionName; + // Try each @ from left to right to find the one that gives us a valid location + for (let i = 0; i < line.length; i++) { + if (line[i] === "@") { + const candidateLocation = line.slice(i + 1); + // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") + if (candidateLocation.includes(":") && candidateLocation.length >= 3) { + atIndex = i; + locationPart = candidateLocation; + functionName = i > 0 ? line.slice(0, i) : undefined; + break; + } + } + } + // Validate we found a valid location with minimum length (filename:line format) + if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { + return null; + } + const [url, lineNumber, columnNumber] = extractLocation(locationPart); + if (!url || !lineNumber || !columnNumber) { + return null; + } + return { + file: url, + method: functionName || "", + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function parseSingleStack(raw) { + const line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return parseSingleFFOrSafariStack(line); + } + return parseSingleV8Stack(line); +} +// Based on https://github.com/stacktracejs/error-stack-parser +// Credit to stacktracejs +function parseSingleV8Stack(raw) { + let line = raw.trim(); + if (!CHROME_IE_STACK_REGEXP.test(line)) { + return null; + } + 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+/, ""); + // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in + // case it has spaces in it, as the string is split on \s+ later on + const location = sanitizedLine.match(/ (\(.+\)$)/); + // remove the parenthesized location from the line, if it was matched + sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; + // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine + // because this line doesn't have function name + const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); + let method = location && sanitizedLine || ""; + let file = url && ["eval", ""].includes(url) ? undefined : url; + if (!file || !lineNumber || !columnNumber) { + return null; + } + if (method.startsWith("async ")) { + method = method.slice(6); + } + if (file.startsWith("file://")) { + file = file.slice(7); + } + // normalize Windows path (\ -> /) + file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); + if (method) { + method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); + } + return { + method, + file, + line: Number.parseInt(lineNumber), + column: Number.parseInt(columnNumber) + }; +} +function createStackString(stacks) { + return stacks.map((stack) => { + const line = `${stack.file}:${stack.line}:${stack.column}`; + if (stack.method) { + return ` at ${stack.method}(${line})`; + } + return ` at ${line}`; + }).join("\n"); +} +function parseStacktrace(stack, options = {}) { + const { ignoreStackEntries = stackIgnorePatterns } = options; + let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); + // remove vi.defineHelper's internal stacks + const helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__")); + if (helperIndex >= 0) { + stacks = stacks.slice(helperIndex + 1); + } + return stacks.map((stack) => { + if (options.getUrlId) { + stack.file = options.getUrlId(stack.file); + } + const map = options.getSourceMap?.(stack.file); + if (!map || typeof map !== "object" || !map.version) { + return shouldFilter(ignoreStackEntries, stack.file) ? null : stack; + } + const traceMap = new DecodedMap(map, stack.file); + const position = getOriginalPosition(traceMap, stack); + if (!position) { + return stack; + } + const { line, column, source, name } = position; + let file = source || stack.file; + if (file.match(/\/\w:\//)) { + file = file.slice(1); + } + if (shouldFilter(ignoreStackEntries, file)) { + return null; + } + if (line != null && column != null) { + return { + line, + column, + file, + method: name || stack.method + }; + } + return stack; + }).filter((s) => s != null); +} +function shouldFilter(ignoreStackEntries, file) { + return ignoreStackEntries.some((p) => file.match(p)); +} +function parseFFOrSafariStackTrace(stack) { + return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); +} +function parseV8Stacktrace(stack) { + return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); +} +function parseErrorStacktrace(e, options = {}) { + if (!e || isPrimitive(e)) { + return []; + } + if ("stacks" in e && e.stacks) { + return e.stacks; + } + const stackStr = e.stack || ""; + // if "stack" property was overwritten at runtime to be something else, + // ignore the value because we don't know how to process it + let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : []; + if (!stackFrames.length) { + const e_ = e; + if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) { + stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options); + } + if (e_.sourceURL != null && e_.line != null && e_._column != null) { + stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options); + } + } + if (options.frameFilter) { + stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); + } + e.stacks = stackFrames; + return stackFrames; +} +class DecodedMap { + _encoded; + _decoded; + _decodedMemo; + url; + version; + names = []; + resolvedSources; + constructor(map, from) { + this.map = map; + const { mappings, names, sources } = map; + this.version = map.version; + this.names = names || []; + this._encoded = mappings || ""; + this._decodedMemo = memoizedState(); + this.url = from; + this.resolvedSources = (sources || []).map((s) => resolve(from, "..", s || "")); + } +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function getOriginalPosition(map, needle) { + const result = originalPositionFor(map, needle); + if (result.column == null) { + return null; + } + return result; +} + +export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; diff --git a/node_modules/@vitest/utils/dist/source-map/node.d.ts b/node_modules/@vitest/utils/dist/source-map/node.d.ts new file mode 100644 index 000000000..aa81c3ca7 --- /dev/null +++ b/node_modules/@vitest/utils/dist/source-map/node.d.ts @@ -0,0 +1,6 @@ +interface ExtractedSourceMap { + map: any; +} +declare function extractSourcemapFromFile(code: string, filePath: string): ExtractedSourceMap | undefined; + +export { extractSourcemapFromFile }; diff --git a/node_modules/@vitest/utils/dist/source-map/node.js b/node_modules/@vitest/utils/dist/source-map/node.js new file mode 100644 index 000000000..b1e322a10 --- /dev/null +++ b/node_modules/@vitest/utils/dist/source-map/node.js @@ -0,0 +1,23 @@ +import { existsSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import convertSourceMap from 'convert-source-map'; + +// based on vite +// https://github.com/vitejs/vite/blob/84079a84ad94de4c1ef4f1bdb2ab448ff2c01196/packages/vite/src/node/server/sourcemap.ts#L149 +function extractSourcemapFromFile(code, filePath) { + const map = (convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, createConvertSourceMapReadMap(filePath)))?.toObject(); + return map ? { map } : undefined; +} +function createConvertSourceMapReadMap(originalFileName) { + return (filename) => { + // convertSourceMap can detect invalid filename from comments. + // fallback to empty source map to avoid errors. + const targetPath = path.resolve(path.dirname(originalFileName), filename); + if (existsSync(targetPath)) { + return readFileSync(targetPath, "utf-8"); + } + return "{}"; + }; +} + +export { extractSourcemapFromFile }; diff --git a/node_modules/@vitest/utils/dist/timers.d.ts b/node_modules/@vitest/utils/dist/timers.d.ts new file mode 100644 index 000000000..8dd6025e6 --- /dev/null +++ b/node_modules/@vitest/utils/dist/timers.d.ts @@ -0,0 +1,33 @@ +interface SafeTimers { + nextTick?: (cb: () => void) => void; + setImmediate?: { + (callback: (...args: TArgs) => void, ...args: TArgs): any; + __promisify__: (value?: T, options?: any) => Promise; + }; + clearImmediate?: (immediateId: any) => void; + setTimeout: typeof setTimeout; + setInterval: typeof setInterval; + clearInterval: typeof clearInterval; + clearTimeout: typeof clearTimeout; + queueMicrotask: typeof queueMicrotask; +} +declare function getSafeTimers(): SafeTimers; +declare function setSafeTimers(): void; +/** +* Returns a promise that resolves after the specified duration. +* +* @param timeout - Delay in milliseconds +* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. +* +* @example +* await delay(100) +* +* @example +* // With mocked timers +* const { setTimeout } = getSafeTimers() +* await delay(100, setTimeout) +*/ +declare function delay(timeout: number, scheduler?: typeof setTimeout): Promise; + +export { delay, getSafeTimers, setSafeTimers }; +export type { SafeTimers }; diff --git a/node_modules/@vitest/utils/dist/timers.js b/node_modules/@vitest/utils/dist/timers.js new file mode 100644 index 000000000..29229e5af --- /dev/null +++ b/node_modules/@vitest/utils/dist/timers.js @@ -0,0 +1,49 @@ +const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS"); +function getSafeTimers() { + const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis; + const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {}; + return { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate, + queueMicrotask: safeQueueMicrotask + }; +} +function setSafeTimers() { + const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis; + const { nextTick: safeNextTick } = globalThis.process || {}; + const timers = { + nextTick: safeNextTick, + setTimeout: safeSetTimeout, + setInterval: safeSetInterval, + clearInterval: safeClearInterval, + clearTimeout: safeClearTimeout, + setImmediate: safeSetImmediate, + clearImmediate: safeClearImmediate, + queueMicrotask: safeQueueMicrotask + }; + globalThis[SAFE_TIMERS_SYMBOL] = timers; +} +/** +* Returns a promise that resolves after the specified duration. +* +* @param timeout - Delay in milliseconds +* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. +* +* @example +* await delay(100) +* +* @example +* // With mocked timers +* const { setTimeout } = getSafeTimers() +* await delay(100, setTimeout) +*/ +function delay(timeout, scheduler = setTimeout) { + return new Promise((resolve) => scheduler(resolve, timeout)); +} + +export { delay, getSafeTimers, setSafeTimers }; diff --git a/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts b/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts new file mode 100644 index 000000000..cba06c6c3 --- /dev/null +++ b/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts @@ -0,0 +1,53 @@ +import { CompareKeys } from '@vitest/pretty-format'; + +/** +* Copyright (c) Meta Platforms, Inc. and affiliates. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +type DiffOptionsColor = (arg: string) => string; +interface DiffOptions { + aAnnotation?: string; + aColor?: DiffOptionsColor; + aIndicator?: string; + bAnnotation?: string; + bColor?: DiffOptionsColor; + bIndicator?: string; + changeColor?: DiffOptionsColor; + changeLineTrailingSpaceColor?: DiffOptionsColor; + commonColor?: DiffOptionsColor; + commonIndicator?: string; + commonLineTrailingSpaceColor?: DiffOptionsColor; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: DiffOptionsColor; + printBasicPrototype?: boolean; + maxDepth?: number; + compareKeys?: CompareKeys; + truncateThreshold?: number; + truncateAnnotation?: string; + truncateAnnotationColor?: DiffOptionsColor; +} +interface SerializedDiffOptions { + aAnnotation?: string; + aIndicator?: string; + bAnnotation?: string; + bIndicator?: string; + commonIndicator?: string; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + printBasicPrototype?: boolean; + maxDepth?: number; + truncateThreshold?: number; + truncateAnnotation?: string; +} + +export type { DiffOptions as D, SerializedDiffOptions as S, DiffOptionsColor as a }; diff --git a/node_modules/@vitest/utils/dist/types.d.ts b/node_modules/@vitest/utils/dist/types.d.ts new file mode 100644 index 000000000..4e6d810d9 --- /dev/null +++ b/node_modules/@vitest/utils/dist/types.d.ts @@ -0,0 +1,34 @@ +type Awaitable = T | PromiseLike; +type Nullable = T | null | undefined; +type Arrayable = T | Array; +type ArgumentsType = T extends (...args: infer U) => any ? U : never; +type MergeInsertions = T extends object ? { [K in keyof T] : MergeInsertions } : T; +type DeepMerge< + F, + S +> = 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 }>; +interface Constructable { + new (...args: any[]): any; +} +interface ParsedStack { + method: string; + file: string; + line: number; + column: number; +} +interface SerializedError { + message: string; + stacks?: ParsedStack[]; + stack?: string; + name?: string; + cause?: SerializedError; + [key: string]: unknown; +} +interface TestError extends SerializedError { + cause?: TestError; + diff?: string; + actual?: string; + expected?: string; +} + +export type { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError }; diff --git a/node_modules/@vitest/utils/dist/types.js b/node_modules/@vitest/utils/dist/types.js new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/node_modules/@vitest/utils/dist/types.js @@ -0,0 +1 @@ + diff --git a/node_modules/@vitest/utils/error.d.ts b/node_modules/@vitest/utils/error.d.ts new file mode 100644 index 000000000..9329baa87 --- /dev/null +++ b/node_modules/@vitest/utils/error.d.ts @@ -0,0 +1 @@ +export * from './dist/error.js' diff --git a/node_modules/@vitest/utils/helpers.d.ts b/node_modules/@vitest/utils/helpers.d.ts new file mode 100644 index 000000000..0add1d0f2 --- /dev/null +++ b/node_modules/@vitest/utils/helpers.d.ts @@ -0,0 +1 @@ +export * from './dist/helpers.js' diff --git a/node_modules/@vitest/utils/package.json b/node_modules/@vitest/utils/package.json new file mode 100644 index 000000000..f1471532e --- /dev/null +++ b/node_modules/@vitest/utils/package.json @@ -0,0 +1,102 @@ +{ + "name": "@vitest/utils", + "type": "module", + "version": "4.1.5", + "description": "Shared Vitest utility functions", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/utils" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./diff": { + "types": "./dist/diff.d.ts", + "default": "./dist/diff.js" + }, + "./resolver": { + "types": "./dist/resolver.d.ts", + "default": "./dist/resolver.js" + }, + "./error": { + "types": "./dist/error.d.ts", + "default": "./dist/error.js" + }, + "./helpers": { + "types": "./dist/helpers.d.ts", + "default": "./dist/helpers.js" + }, + "./offset": { + "types": "./dist/offset.d.ts", + "default": "./dist/offset.js" + }, + "./constants": { + "types": "./dist/constants.d.ts", + "default": "./dist/constants.js" + }, + "./timers": { + "types": "./dist/timers.d.ts", + "default": "./dist/timers.js" + }, + "./display": { + "types": "./dist/display.d.ts", + "default": "./dist/display.js" + }, + "./source-map": { + "types": "./dist/source-map.d.ts", + "default": "./dist/source-map.js" + }, + "./source-map/node": { + "types": "./dist/source-map/node.d.ts", + "default": "./dist/source-map/node.js" + }, + "./serialize": { + "types": "./dist/serialize.d.ts", + "default": "./dist/serialize.js" + }, + "./*": "./*" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "typesVersions": { + "*": { + "source-map": [ + "dist/source-map.d.ts" + ], + "source-map/node": [ + "dist/source-map/node.d.ts" + ] + } + }, + "files": [ + "*.d.ts", + "dist" + ], + "dependencies": { + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0", + "@vitest/pretty-format": "4.1.5" + }, + "devDependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@types/convert-source-map": "^2.0.3", + "@types/estree": "^1.0.8", + "diff-sequences": "^29.6.3", + "loupe": "^3.2.1" + }, + "scripts": { + "build": "premove dist && rollup -c", + "dev": "rollup -c --watch" + } +} \ No newline at end of file diff --git a/node_modules/ansi-styles/index.d.ts b/node_modules/ansi-styles/index.d.ts new file mode 100644 index 000000000..44a907e58 --- /dev/null +++ b/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,345 @@ +declare type CSSColor = + | 'aliceblue' + | 'antiquewhite' + | 'aqua' + | 'aquamarine' + | 'azure' + | 'beige' + | 'bisque' + | 'black' + | 'blanchedalmond' + | 'blue' + | 'blueviolet' + | 'brown' + | 'burlywood' + | 'cadetblue' + | 'chartreuse' + | 'chocolate' + | 'coral' + | 'cornflowerblue' + | 'cornsilk' + | 'crimson' + | 'cyan' + | 'darkblue' + | 'darkcyan' + | 'darkgoldenrod' + | 'darkgray' + | 'darkgreen' + | 'darkgrey' + | 'darkkhaki' + | 'darkmagenta' + | 'darkolivegreen' + | 'darkorange' + | 'darkorchid' + | 'darkred' + | 'darksalmon' + | 'darkseagreen' + | 'darkslateblue' + | 'darkslategray' + | 'darkslategrey' + | 'darkturquoise' + | 'darkviolet' + | 'deeppink' + | 'deepskyblue' + | 'dimgray' + | 'dimgrey' + | 'dodgerblue' + | 'firebrick' + | 'floralwhite' + | 'forestgreen' + | 'fuchsia' + | 'gainsboro' + | 'ghostwhite' + | 'gold' + | 'goldenrod' + | 'gray' + | 'green' + | 'greenyellow' + | 'grey' + | 'honeydew' + | 'hotpink' + | 'indianred' + | 'indigo' + | 'ivory' + | 'khaki' + | 'lavender' + | 'lavenderblush' + | 'lawngreen' + | 'lemonchiffon' + | 'lightblue' + | 'lightcoral' + | 'lightcyan' + | 'lightgoldenrodyellow' + | 'lightgray' + | 'lightgreen' + | 'lightgrey' + | 'lightpink' + | 'lightsalmon' + | 'lightseagreen' + | 'lightskyblue' + | 'lightslategray' + | 'lightslategrey' + | 'lightsteelblue' + | 'lightyellow' + | 'lime' + | 'limegreen' + | 'linen' + | 'magenta' + | 'maroon' + | 'mediumaquamarine' + | 'mediumblue' + | 'mediumorchid' + | 'mediumpurple' + | 'mediumseagreen' + | 'mediumslateblue' + | 'mediumspringgreen' + | 'mediumturquoise' + | 'mediumvioletred' + | 'midnightblue' + | 'mintcream' + | 'mistyrose' + | 'moccasin' + | 'navajowhite' + | 'navy' + | 'oldlace' + | 'olive' + | 'olivedrab' + | 'orange' + | 'orangered' + | 'orchid' + | 'palegoldenrod' + | 'palegreen' + | 'paleturquoise' + | 'palevioletred' + | 'papayawhip' + | 'peachpuff' + | 'peru' + | 'pink' + | 'plum' + | 'powderblue' + | 'purple' + | 'rebeccapurple' + | 'red' + | 'rosybrown' + | 'royalblue' + | 'saddlebrown' + | 'salmon' + | 'sandybrown' + | 'seagreen' + | 'seashell' + | 'sienna' + | 'silver' + | 'skyblue' + | 'slateblue' + | 'slategray' + | 'slategrey' + | 'snow' + | 'springgreen' + | 'steelblue' + | 'tan' + | 'teal' + | 'thistle' + | 'tomato' + | 'turquoise' + | 'violet' + | 'wheat' + | 'white' + | 'whitesmoke' + | 'yellow' + | 'yellowgreen'; + +declare namespace ansiStyles { + interface ColorConvert { + /** + The RGB color space. + + @param red - (`0`-`255`) + @param green - (`0`-`255`) + @param blue - (`0`-`255`) + */ + rgb(red: number, green: number, blue: number): string; + + /** + The RGB HEX color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hex(hex: string): string; + + /** + @param keyword - A CSS color name. + */ + keyword(keyword: CSSColor): string; + + /** + The HSL color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param lightness - (`0`-`100`) + */ + hsl(hue: number, saturation: number, lightness: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param value - (`0`-`100`) + */ + hsv(hue: number, saturation: number, value: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param whiteness - (`0`-`100`) + @param blackness - (`0`-`100`) + */ + hwb(hue: number, whiteness: number, blackness: number): string; + + /** + Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. + */ + ansi(ansi: number): string; + + /** + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(ansi: number): string; + } + + 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 { + readonly ansi: ColorConvert; + readonly ansi256: ColorConvert; + readonly ansi16m: ColorConvert; + + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: 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; + + /** + 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; + } +} + +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; + +export = ansiStyles; diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 000000000..5d82581a1 --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,163 @@ +'use strict'; + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = require('color-convert'); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +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], + + // 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'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license new file mode 100644 index 000000000..e7af2f771 --- /dev/null +++ b/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/ansi-styles/package.json b/node_modules/ansi-styles/package.json new file mode 100644 index 000000000..75393284d --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,56 @@ +{ + "name": "ansi-styles", + "version": "4.3.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": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "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" + ], + "dependencies": { + "color-convert": "^2.0.1" + }, + "devDependencies": { + "@types/color-convert": "^1.9.0", + "ava": "^2.3.0", + "svg-term-cli": "^2.1.1", + "tsd": "^0.11.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 000000000..24883de80 --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,152 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/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 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` +- `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` 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. + +The following color spaces from `color-convert` are supported: + +- `rgb` +- `hex` +- `keyword` +- `hsl` +- `hsv` +- `hwb` +- `ansi` +- `ansi256` + +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-) + +## 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/assertion-error/LICENSE b/node_modules/assertion-error/LICENSE new file mode 100644 index 000000000..5e9f3ac63 --- /dev/null +++ b/node_modules/assertion-error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Jake Luer jake@qualiancy.com (http://qualiancy.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/assertion-error/README.md b/node_modules/assertion-error/README.md new file mode 100644 index 000000000..37c392879 --- /dev/null +++ b/node_modules/assertion-error/README.md @@ -0,0 +1,68 @@ +

+ AssertionError and AssertionResult classes. +

+ +

+ + build:? + + downloads:? + + devDependencies:none + +

+ +## What is AssertionError? + +Assertion Error is a module that contains two classes: `AssertionError`, which +is an instance of an `Error`, and `AssertionResult` which is not an instance of +Error. + +These can be useful for returning from a function - if the function "succeeds" +return an `AssertionResult` and if the function fails return (or throw) an +`AssertionError`. + +Both `AssertionError` and `AssertionResult` implement the `Result` interface: + +```typescript +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} +``` + +So if a function returns `AssertionResult | AssertionError` it is easy to check +_which_ one is returned by checking either `.name` or `.ok`, or check +`instanceof Error`. + +## Installation + +### Node.js + +`assertion-error` is available on [npm](http://npmjs.org). + +``` +$ npm install --save assertion-error +``` + +### Deno + +`assertion_error` is available on +[Deno.land](https://deno.land/x/assertion_error) + +```typescript +import { + AssertionError, + AssertionResult, +} from "https://deno.land/x/assertion_error@2.0.0/mod.ts"; +``` diff --git a/node_modules/assertion-error/index.d.ts b/node_modules/assertion-error/index.d.ts new file mode 100644 index 000000000..d8fda2c78 --- /dev/null +++ b/node_modules/assertion-error/index.d.ts @@ -0,0 +1,27 @@ +interface Result { + name: "AssertionError" | "AssertionResult"; + ok: boolean; + toJSON(...args: unknown[]): Record; +} + +declare class AssertionError extends Error implements Result { + [key: string]: unknown + name: "AssertionError"; + ok: false; + message: string; + // deno-lint-ignore ban-types + constructor(message: string, props?: T, ssf?: Function); + stack: string; + toJSON(stack?: boolean): Record; +} + +declare class AssertionResult implements Result { + [key: string]: unknown + name: "AssertionResult"; + ok: true; + message: string; + constructor(props?: T); + toJSON(): Record; +} + +export { AssertionError, AssertionResult, Result }; diff --git a/node_modules/assertion-error/index.js b/node_modules/assertion-error/index.js new file mode 100644 index 000000000..2bfcb81ed --- /dev/null +++ b/node_modules/assertion-error/index.js @@ -0,0 +1,60 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually + +const canElideFrames = "captureStackTrace" in Error; +class AssertionError extends Error { + message; + get name() { + return "AssertionError"; + } + get ok() { + return false; + } + constructor(message = "Unspecified AssertionError", props, ssf){ + super(message); + this.message = message; + if (canElideFrames) { + Error.captureStackTrace(this, ssf || AssertionError); + } + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON(stack) { + return { + ...this, + name: this.name, + message: this.message, + ok: false, + stack: stack !== false ? this.stack : undefined + }; + } +} +class AssertionResult { + get name() { + return "AssertionResult"; + } + get ok() { + return true; + } + constructor(props){ + for(const key in props){ + if (!(key in this)) { + this[key] = props[key]; + } + } + } + toJSON() { + return { + ...this, + name: this.name, + ok: this.ok + }; + } +} +export { AssertionError as AssertionError }; +export { AssertionResult as AssertionResult }; + diff --git a/node_modules/assertion-error/package.json b/node_modules/assertion-error/package.json new file mode 100644 index 000000000..02dc0f5b6 --- /dev/null +++ b/node_modules/assertion-error/package.json @@ -0,0 +1,32 @@ +{ + "name": "assertion-error", + "version": "2.0.1", + "description": "Error constructor for test and validation frameworks that implements standardized AssertionError specification.", + "author": "Jake Luer (http://qualiancy.com)", + "license": "MIT", + "types": "./index.d.ts", + "keywords": [ + "test", + "assertion", + "assertion-error" + ], + "repository": { + "type": "git", + "url": "git@github.com:chaijs/assertion-error.git" + }, + "engines": { + "node": ">=12" + }, + "files": [ + "index.d.ts" + ], + "type": "module", + "module": "index.js", + "main": "index.js", + "scripts": { + "build": "deno bundle mod.ts > index.js", + "pretest": "rm -rf coverage/", + "test": "deno test --coverage=coverage", + "posttest": "deno coverage coverage --lcov > coverage/lcov.info && lcov --summary coverage/lcov.info" + } +} diff --git a/node_modules/async/CHANGELOG.md b/node_modules/async/CHANGELOG.md new file mode 100644 index 000000000..ce990a51c --- /dev/null +++ b/node_modules/async/CHANGELOG.md @@ -0,0 +1,351 @@ +# v3.2.5 +- Ensure `Error` objects such as `AggregateError` are propagated without modification (#1920) + +# v3.2.4 +- Fix a bug in `priorityQueue` where it didn't wait for the result. (#1725) +- Fix a bug where `unshiftAsync` was included in `priorityQueue`. (#1790) + +# v3.2.3 +- Fix bugs in comment parsing in `autoInject`. (#1767, #1780) + +# v3.2.2 +- Fix potential prototype pollution exploit + +# v3.2.1 +- Use `queueMicrotask` if available to the environment (#1761) +- Minor perf improvement in `priorityQueue` (#1727) +- More examples in documentation (#1726) +- Various doc fixes (#1708, #1712, #1717, #1740, #1739, #1749, #1756) +- Improved test coverage (#1754) + +# v3.2.0 +- Fix a bug in Safari related to overwriting `func.name` +- Remove built-in browserify configuration (#1653) +- Varios doc fixes (#1688, #1703, #1704) + +# v3.1.1 +- Allow redefining `name` property on wrapped functions. + +# v3.1.0 + +- Added `q.pushAsync` and `q.unshiftAsync`, analagous to `q.push` and `q.unshift`, except they always do not accept a callback, and reject if processing the task errors. (#1659) +- Promises returned from `q.push` and `q.unshift` when a callback is not passed now resolve even if an error ocurred. (#1659) +- Fixed a parsing bug in `autoInject` with complicated function bodies (#1663) +- Added ES6+ configuration for Browserify bundlers (#1653) +- Various doc fixes (#1664, #1658, #1665, #1652) + +# v3.0.1 + +## Bug fixes +- Fixed a regression where arrays passed to `queue` and `cargo` would be completely flattened. (#1645) +- Clarified Async's browser support (#1643) + + +# v3.0.0 + +The `async`/`await` release! + +There are a lot of new features and subtle breaking changes in this major version, but the biggest feature is that most Async methods return a Promise if you omit the callback, meaning you can `await` them from within an `async` function. + +```js +const results = await async.mapLimit(urls, 5, async url => { + const resp = await fetch(url) + return resp.body +}) +``` + +## Breaking Changes +- Most Async methods return a Promise when the final callback is omitted, making them `await`-able! (#1572) +- We are now making heavy use of ES2015 features, this means we have dropped out-of-the-box support for Node 4 and earlier, and many old versions of browsers. (#1541, #1553) +- In `queue`, `priorityQueue`, `cargo` and `cargoQueue`, the "event"-style methods, like `q.drain` and `q.saturated` are now methods that register a callback, rather than properties you assign a callback to. They are now of the form `q.drain(callback)`. If you do not pass a callback a Promise will be returned for the next occurrence of the event, making them `await`-able, e.g. `await q.drain()`. (#1586, #1641) +- Calling `callback(false)` will cancel an async method, preventing further iteration and callback calls. This is useful for preventing memory leaks when you break out of an async flow by calling an outer callback. (#1064, #1542) +- `during` and `doDuring` have been removed, and instead `whilst`, `doWhilst`, `until` and `doUntil` now have asynchronous `test` functions. (#850, #1557) +- `limits` of less than 1 now cause an error to be thrown in queues and collection methods. (#1249, #1552) +- `memoize` no longer memoizes errors (#1465, #1466) +- `applyEach`/`applyEachSeries` have a simpler interface, to make them more easily type-able. It always returns a function that takes in a single callback argument. If that callback is omitted, a promise is returned, making it awaitable. (#1228, #1640) + +## New Features +- Async generators are now supported in all the Collection methods. (#1560) +- Added `cargoQueue`, a queue with both `concurrency` and `payload` size parameters. (#1567) +- Queue objects returned from `queue` now have a `Symbol.iterator` method, meaning they can be iterated over to inspect the current list of items in the queue. (#1459, #1556) +- A ESM-flavored `async.mjs` is included in the `async` package. This is described in the `package.json` `"module"` field, meaning it should be automatically used by Webpack and other compatible bundlers. + +## Bug fixes +- Better handle arbitrary error objects in `asyncify` (#1568, #1569) + +## Other +- Removed Lodash as a dependency (#1283, #1528) +- Miscellaneous docs fixes (#1393, #1501, #1540, #1543, #1558, #1563, #1564, #1579, #1581) +- Miscellaneous test fixes (#1538) + +------- + +# v2.6.1 +- Updated lodash to prevent `npm audit` warnings. (#1532, #1533) +- Made `async-es` more optimized for webpack users (#1517) +- Fixed a stack overflow with large collections and a synchronous iterator (#1514) +- Various small fixes/chores (#1505, #1511, #1527, #1530) + +# v2.6.0 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) +- Improved `queue` performance. (#1448, #1454) +- Add missing sourcemap (#1452, #1453) +- Various doc updates (#1448, #1471, #1483) + +# v2.5.0 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) + +# v2.4.1 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) + +# v2.4.0 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) + +# v2.3.0 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) + +# v2.2.0 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) + +# v2.1.5 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) +- Avoid stack overflow case in queue +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. +- Cleanup implementations of `some`, `every` and `find` + +# v2.1.3 +- Make bundle size smaller +- Create optimized hotpath for `filter` in array case. + +# v2.1.2 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). + +# v2.1.0 + +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) + +# v2.0.1 + +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). + +# v2.0.0 + +Lots of changes here! + +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. + +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. + +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. + +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. + +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: + +1. Takes a variable number of arguments +2. The last argument is always a callback +3. The callback can accept any number of arguments +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy +5. Any number of result arguments can be passed after the "error" argument +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. + +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`. + +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. + +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). + +## New Features + +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) + +## Breaking changes + +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) + +## Bug Fixes + +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). + +## Other + +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) + +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. + +------------------------------------------ + +# v1.5.2 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) + +# v1.4.2 + +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) + +# v1.4.1 + +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) + +# v1.4.0 + +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE new file mode 100644 index 000000000..b18aed692 --- /dev/null +++ b/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2018 Caolan McMahon + +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/async/README.md b/node_modules/async/README.md new file mode 100644 index 000000000..55a0626de --- /dev/null +++ b/node_modules/async/README.md @@ -0,0 +1,59 @@ +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) + +![Github Actions CI status](https://github.com/caolan/async/actions/workflows/ci.yml/badge.svg) +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) + + + +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/v3/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm i async`, it can also be used directly in the browser. An ESM/MJS version is included in the main `async` package that should automatically be used with compatible bundlers such as Webpack and Rollup. + +A pure ESM version of Async is available as [`async-es`](https://www.npmjs.com/package/async-es). + +For Documentation, visit + +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* + + +```javascript +// for use with Node-style callbacks... +var async = require("async"); + +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, (value, key, callback) => { + fs.readFile(__dirname + value, "utf8", (err, data) => { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }); +}, err => { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}); +``` + +```javascript +var async = require("async"); + +// ...or ES2017 async functions +async.mapLimit(urls, 5, async function(url) { + const response = await fetch(url) + return response.body +}, (err, results) => { + if (err) throw err + // results is now an array of the response bodies + console.log(results) +}) +``` diff --git a/node_modules/async/all.js b/node_modules/async/all.js new file mode 100644 index 000000000..622b30194 --- /dev/null +++ b/node_modules/async/all.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allLimit.js b/node_modules/async/allLimit.js new file mode 100644 index 000000000..375e12602 --- /dev/null +++ b/node_modules/async/allLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allSeries.js b/node_modules/async/allSeries.js new file mode 100644 index 000000000..9a6bf7d46 --- /dev/null +++ b/node_modules/async/allSeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/any.js b/node_modules/async/any.js new file mode 100644 index 000000000..a5bd328ab --- /dev/null +++ b/node_modules/async/any.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anyLimit.js b/node_modules/async/anyLimit.js new file mode 100644 index 000000000..3a8096fda --- /dev/null +++ b/node_modules/async/anyLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anySeries.js b/node_modules/async/anySeries.js new file mode 100644 index 000000000..51aad19bd --- /dev/null +++ b/node_modules/async/anySeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/apply.js b/node_modules/async/apply.js new file mode 100644 index 000000000..d40784f30 --- /dev/null +++ b/node_modules/async/apply.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn, ...args) { + return (...callArgs) => fn(...args, ...callArgs); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEach.js b/node_modules/async/applyEach.js new file mode 100644 index 000000000..841842c8b --- /dev/null +++ b/node_modules/async/applyEach.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +exports.default = (0, _applyEach2.default)(_map2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEachSeries.js b/node_modules/async/applyEachSeries.js new file mode 100644 index 000000000..f5267f67f --- /dev/null +++ b/node_modules/async/applyEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach.js'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _mapSeries = require('./mapSeries.js'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +exports.default = (0, _applyEach2.default)(_mapSeries2.default); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/asyncify.js b/node_modules/async/asyncify.js new file mode 100644 index 000000000..ddc3f02ff --- /dev/null +++ b/node_modules/async/asyncify.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/auto.js b/node_modules/async/auto.js new file mode 100644 index 000000000..163c4f278 --- /dev/null +++ b/node_modules/async/auto.js @@ -0,0 +1,333 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = auto; + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return; + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = (0, _onlyOnce2.default)((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return; + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return; + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/autoInject.js b/node_modules/async/autoInject.js new file mode 100644 index 000000000..5db2653ae --- /dev/null +++ b/node_modules/async/autoInject.js @@ -0,0 +1,182 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = autoInject; + +var _auto = require('./auto.js'); + +var _auto2 = _interopRequireDefault(_auto); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index + 1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = endIndex === -1 ? string.length : endIndex; + } else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src); + let [, args] = match; + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + (0, _wrapAsync2.default)(taskFn)(...newArgs); + } + }); + + return (0, _auto2.default)(newTasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/bower.json b/node_modules/async/bower.json new file mode 100644 index 000000000..390c6502f --- /dev/null +++ b/node_modules/async/bower.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "main": "dist/async.js", + "ignore": [ + "bower_components", + "lib", + "test", + "node_modules", + "perf", + "support", + "**/.*", + "*.config.js", + "*.json", + "index.js", + "Makefile" + ] +} diff --git a/node_modules/async/cargo.js b/node_modules/async/cargo.js new file mode 100644 index 000000000..d4abd214d --- /dev/null +++ b/node_modules/async/cargo.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = cargo; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatLimit.js b/node_modules/async/concatLimit.js new file mode 100644 index 000000000..a27cc7d45 --- /dev/null +++ b/node_modules/async/concatLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatSeries.js b/node_modules/async/concatSeries.js new file mode 100644 index 000000000..332de3f3e --- /dev/null +++ b/node_modules/async/concatSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/constant.js b/node_modules/async/constant.js new file mode 100644 index 000000000..ea406f655 --- /dev/null +++ b/node_modules/async/constant.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (...args) { + return function (...ignoredArgs /*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detect.js b/node_modules/async/detect.js new file mode 100644 index 000000000..d5896ef64 --- /dev/null +++ b/node_modules/async/detect.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectLimit.js b/node_modules/async/detectLimit.js new file mode 100644 index 000000000..c59843b62 --- /dev/null +++ b/node_modules/async/detectLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectSeries.js b/node_modules/async/detectSeries.js new file mode 100644 index 000000000..b48689967 --- /dev/null +++ b/node_modules/async/detectSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dir.js b/node_modules/async/dir.js new file mode 100644 index 000000000..8e9fafd78 --- /dev/null +++ b/node_modules/async/dir.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +exports.default = (0, _consoleFunc2.default)('dir'); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dist/async.js b/node_modules/async/dist/async.js new file mode 100644 index 000000000..d7b791898 --- /dev/null +++ b/node_modules/async/dist/async.js @@ -0,0 +1,6061 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.async = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer$1; + + if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else if (hasNextTick) { + _defer$1 = process.nextTick; + } else { + _defer$1 = fallback; + } + + var setImmediate$1 = wrap(_defer$1); + + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$1 = awaitify(eachOfLimit, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); + } + + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); + + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach = applyEach$1(map$1); + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach$1(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback + } + + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] + } + + var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; + } + + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } + + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } + + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } + + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } + + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; + } + + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } + + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } + + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) + } + + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); + + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit$2, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$1 = awaitify(eachLimit, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } + + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); + } + + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /* istanbul ignore file */ + + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer; + + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; + } + + var nextTick = wrap(_defer); + + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); + + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } + + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } + } + + function leftChi(i) { + return (i<<1)+1; + } + + function parent(i) { + return ((i+1)>>1)-1; + } + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; + } + + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } + + function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) + } + var reject$1 = awaitify(reject, 3); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant(value) { + return function () { + return value; + } + } + + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; + + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] + } + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } + + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); + + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); + + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } + + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } + + var tryEach$1 = awaitify(tryEach); + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); + + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js new file mode 100644 index 000000000..f0b7fdf5f --- /dev/null +++ b/node_modules/async/dist/async.min.js @@ -0,0 +1 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e="undefined"==typeof globalThis?e||self:globalThis,t(e.async={}))})(this,function(e){"use strict";function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return d(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&(e instanceof Error||e.message)?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){_e(t=>{throw t},e)}}function d(e){return"AsyncFunction"===e[Symbol.toStringTag]}function u(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function c(e){if("function"!=typeof e)throw new Error("expected a function");return d(e)?r(e):e}function o(e,t){function n(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1{c(e).apply(i,n.concat(t))},a)});return i}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=c(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function a(){return++t=t||u||l||(u=!0,e.next().then(({value:e,done:t})=>{if(!(d||l))return u=!1,t?(l=!0,void(0>=p&&a(null))):void(p++,n(e,c,r),c++,i())}).catch(s))}function r(e,t){return p-=1,d?void 0:e?s(e):!1===e?(l=!0,void(d=!0)):t===be||l&&0>=p?(l=!0,a(null)):void i()}function s(e){d||(u=!1,l=!0,a(e))}let l=!1,d=!1,u=!1,p=0,c=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===be)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i{t=e,n=a}),e}function A(e,t,n){function a(e,t){k.push(()=>l(e,t))}function i(){if(!f){if(0===k.length&&0===h)return n(null,o);for(;k.length&&he()),i()}function l(e,t){if(!y){var a=L((t,...a)=>{if(h--,!1===t)return void(f=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(o).forEach(e=>{i[e]=o[e]}),i[e]=a,y=!0,g=Object.create(null),f)return;n(t,i)}else o[e]=a,s(e)});h++;var i=c(t[t.length-1]);1{0==--S[e]&&v.push(e)});if(t!==p)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function u(t){var n=[];return Object.keys(e).forEach(a=>{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||b());var p=Object.keys(e).length;if(!p)return n(null);t||(t=p);var o={},h=0,f=!1,y=!1,g=Object.create(null),k=[],v=[],S={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void v.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void v.push(t)):void(S[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),d(),i(),n[Ce]}function I(e){let t="",n=0,a=e.indexOf("*/");for(;ne.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),c(r)(...n)}var i,r=e[t],s=d(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l=k._createTaskItem(e,n?i:a||i);if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,_e(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function d(e){return function(t,...n){o-=1;for(var a=0,r=e.length;as("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=c(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,_createTaskItem(e,t){return{data:e,callback:t}},*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const d=c(i);n(a,(n,a,i)=>{d(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>c(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=c(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return d(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?_e(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,c(n),a)}function G(e,t,n){return dt(e,1/0,t,n)}function W(e,t,n){return dt(e,1,t,n)}function H(e,t,n){return pt(e,1/0,t,n)}function J(e,t,n){return pt(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=c(e),l=n((e,n)=>{var d=t(...e);d in a?_e(()=>n(null,...a[d])):d in r?r[d].push(n):(r[d]=[n],s(...e,(e,...t)=>{e||(a[d]=t);var n=r[d];delete r[d];for(var s=0,u=n.length;s{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount({data:e,priority:t})):{data:e,priority:t}}var a=$(e,t),{push:i,pushAsync:r}=a;return a._tasks=new ht,a._createTaskItem=({data:e,priority:t},n)=>({data:e,priority:t,callback:n}),a.push=function(e,t=0,a){return i(n(e,t),a)},a.pushAsync=function(e,t=0,a){return r(n(e,t),a)},delete a.unshift,delete a.unshiftAsync,a}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=c(e);return n(function a(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=c(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function de(e){return function(){return e}}function ue(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(n=t||b(),t=e):(pe(i,e),n=n||b()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=c(t),s=1;return a(),n[Ce]}function pe(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:de(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function ce(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;d(t)&&(a+=1);var i=c(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length{function s(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),d=!0,r(n)}var l,d=!1;n.push((...e)=>{d||(r(...e),clearTimeout(l))}),l=setTimeout(s,t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=c(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||b());var i=c(n);return Me(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=c(e);return _t(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var _e=i(xe);const be={};var Ae=e=>(t,n,a)=>{function i(e,t){if(!d)if(c-=1,e)l=!0,a(e);else if(!1===e)l=!0,d=!0;else{if(t===be||l&&0>=c)return l=!0,a(null);o||r()}}function r(){for(o=!0;c=c&&a(null));c+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(u(t))return E(t,e,n,a);if(p(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,d=!1,c=0,o=!1;r()},Ie=o(function i(e,t,n,a){return Ae(t)(e,c(n),a)},4),Me=o(function a(e,t,n){var i=y(e)?O:_;return i(e,c(t),n)},3),je=o(function a(e,t,n){return f(Me,e,t,n)},3),we=h(je),Be=o(function a(e,t,n){return Ie(e,1,t,n)},3),Te=o(function a(e,t,n){return f(Be,e,t,n)},3),Fe=h(Te);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/,Re=/^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function i(e,t,n,a){a=m(a);var r=c(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function i(e,t,n,a){return f(Ae(t),e,n,a)},4),Qe=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;re,(e,t)=>t)(Me,e,t,n)},3),He=o(function i(e,t,n,a){return z(e=>e,(e,t)=>t)(Ae(t),e,n,a)},4),Je=o(function a(e,t,n){return z(e=>e,(e,t)=>t)(Ae(1),e,t,n)},3),Ke=N("dir"),Xe=o(function a(e,t,n){function i(e,...t){return e?n(e):void(!1===e||(s=t,d(...t,r)))}function r(e,t){return e?n(e):!1===e?void 0:t?void l(i):n(null,...s)}n=L(n);var s,l=c(e),d=c(t);return r(null,!0)},3),Ze=o(function a(e,t,n){return Me(e,Y(c(t)),n)},3),$e=o(function i(e,t,n,a){return Ae(t)(e,Y(c(n)),a)},4),et=o(function a(e,t,n){return $e(e,1,t,n)},3),tt=o(function a(e,t,n){return z(e=>!e,e=>!e)(Me,e,t,n)},3),nt=o(function i(e,t,n,a){return z(e=>!e,e=>!e)(Ae(t),e,n,a)},4),at=o(function a(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function a(e,t,n){return U(Me,e,t,n)},3),rt=o(function i(e,t,n,a){return U(Ae(t),e,n,a)},4),st=o(function a(e,t,n){return U(Be,e,t,n)},3),lt=o(function n(e,t){function a(e){return e?i(e):void(!1===e||r(a))}var i=L(t),r=c(q(e));return a()},2),dt=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s{s(e,t,(e,a)=>e?n(e):void(r[t]=a,n(e)))},e=>a(e,r))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var ct=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{c(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0e)(Me,e,t,n)},3),xt=o(function i(e,t,n,a){return z(Boolean,e=>e)(Ae(t),e,n,a)},4),Lt=o(function a(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function a(e,t,n){function i(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var r=c(t);return je(e,(e,t)=>{r(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(i).map(e=>e.value)))},3),Ot=o(function n(e,t){var a,i=null;return et(e,(e,t)=>{c(e)((e,...n)=>!1===e?t(e):void(2>n.length?[a]=n:a=n,i=e,t(e?null:{})))},()=>t(i,a))}),_t=o(function a(e,t,n){function i(e,...t){if(e)return n(e);d=t;!1===e||l(r)}function r(e,t){return e?n(e):!1===e?void 0:t?void s(i):n(null,...d)}n=L(n);var s=c(t),l=c(e),d=[];return l(r)},3),bt=o(function n(e,t){function a(t){var n=c(e[r++]);n(...t,L(i))}function i(n,...i){return!1===n?void 0:n||r===e.length?t(n,...i):void a(i)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;a([])});e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.apply=t,e.applyEach=we,e.applyEachSeries=Fe,e.asyncify=r,e.auto=A,e.autoInject=j,e.cargo=T,e.cargoQueue=F,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.default={apply:t,applyEach:we,applyEachSeries:Fe,asyncify:r,auto:A,autoInject:j,cargo:T,cargoQueue:F,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Me,eachOfLimit:Ie,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:dt,groupBySeries:W,log:ut,map:je,mapLimit:De,mapSeries:Te,mapValues:H,mapValuesLimit:pt,mapValuesSeries:J,memoize:K,nextTick:ct,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:ue,retryable:ce,seq:C,series:oe,setImmediate:_e,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:bt,whilst:_t,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Me,forEachOfSeries:Be,forEachOfLimit:Ie,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:_t,doDuring:Xe},e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doDuring=Xe,e.doUntil=V,e.doWhilst=Xe,e.during=_t,e.each=Ze,e.eachLimit=$e,e.eachOf=Me,e.eachOfLimit=Ie,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.foldl=qe,e.foldr=ie,e.forEach=Ze,e.forEachLimit=$e,e.forEachOf=Me,e.forEachOfLimit=Ie,e.forEachOfSeries=Be,e.forEachSeries=et,e.forever=lt,e.groupBy=G,e.groupByLimit=dt,e.groupBySeries=W,e.inject=qe,e.log=ut,e.map=je,e.mapLimit=De,e.mapSeries=Te,e.mapValues=H,e.mapValuesLimit=pt,e.mapValuesSeries=J,e.memoize=K,e.nextTick=ct,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=ue,e.retryable=ce,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.seq=C,e.series=oe,e.setImmediate=_e,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=bt,e.whilst=_t,e.wrapSync=r,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/node_modules/async/dist/async.mjs b/node_modules/async/dist/async.mjs new file mode 100644 index 000000000..2c5996533 --- /dev/null +++ b/node_modules/async/dist/async.mjs @@ -0,0 +1,5948 @@ +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); +} + +function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +} + +/* istanbul ignore file */ + +var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer$1; + +if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else if (hasNextTick) { + _defer$1 = process.nextTick; +} else { + _defer$1 = fallback; +} + +var setImmediate$1 = wrap(_defer$1); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } +} + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable +} + +function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} + +function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; + +function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper +} + +function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; +} + +function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} + +var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); +} + +var eachOfLimit$1 = awaitify(eachOfLimit, 4); + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); +} + +var eachOf$1 = awaitify(eachOf, 3); + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) +} +var map$1 = awaitify(map, 3); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ +var applyEach = applyEach$1(map$1); + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) +} +var eachOfSeries$1 = awaitify(eachOfSeries, 3); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) +} +var mapSeries$1 = awaitify(mapSeries, 3); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ +var applyEachSeries = applyEach$1(mapSeries$1); + +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] +} + +var FN_ARGS = /^(?:async\s)?(?:function)?\s*(?:\w+\s*)?\(([^)]+)\)(?:\s*{)/; +var ARROW_FN_ARGS = /^(?:async\s)?\s*(?:\(\s*)?((?:[^)=\s]\s*)*)(?:\)\s*)?=>/; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; + +function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; +} + +function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; +} + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +var reduce$1 = awaitify(reduce, 4); + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; +} + +/** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ +function compose(...args) { + return seq(...args.reverse()); +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) +} +var mapLimit$1 = awaitify(mapLimit, 4); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +var concatLimit$1 = awaitify(concatLimit, 4); + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) +} +var concat$1 = awaitify(concat, 3); + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) +} +var concatSeries$1 = awaitify(concatSeries, 3); + +/** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ +function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; +} + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) +} +var detect$1 = awaitify(detect, 3); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var detectLimit$1 = awaitify(detectLimit, 4); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) +} + +var detectSeries$1 = awaitify(detectSeries, 3); + +function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +var doWhilst$1 = awaitify(doWhilst, 3); + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); +} + +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +var each = awaitify(eachLimit$2, 3); + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} +var eachLimit$1 = awaitify(eachLimit, 4); + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) +} +var eachSeries$1 = awaitify(eachSeries, 3); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) +} +var every$1 = awaitify(every, 3); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var everyLimit$1 = awaitify(everyLimit, 4); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) +} +var everySeries$1 = awaitify(everySeries, 3); + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) +} +var filter$1 = awaitify(filter, 3); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) +} +var filterLimit$1 = awaitify(filterLimit, 4); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) +} +var filterSeries$1 = awaitify(filterSeries, 3); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +var forever$1 = awaitify(forever, 2); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +var groupByLimit$1 = awaitify(groupByLimit, 4); + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) +} + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) +} + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/* istanbul ignore file */ + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; + +if (hasNextTick) { + _defer = process.nextTick; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = fallback; +} + +var nextTick = wrap(_defer); + +var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +} + +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +function leftChi(i) { + return (i<<1)+1; +} + +function parent(i) { + return ((i+1)>>1)-1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } +} + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ +function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +} + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +var race$1 = awaitify(race, 2); + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; +} + +function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) +} +var reject$1 = awaitify(reject, 3); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) +} +var rejectLimit$1 = awaitify(rejectLimit, 4); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) +} +var rejectSeries$1 = awaitify(rejectSeries, 3); + +function constant(value) { + return function () { + return value; + } +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); +} + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) +} +var some$1 = awaitify(some, 3); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) +} +var someLimit$1 = awaitify(someLimit, 4); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) +} +var someSeries$1 = awaitify(someSeries, 3); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +var sortBy$1 = awaitify(sortBy, 3); + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} + +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) +} + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +var tryEach$1 = awaitify(tryEach); + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +var whilst$1 = awaitify(whilst, 3); + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +var waterfall$1 = awaitify(waterfall); + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + +var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 +}; + +export { every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo$1 as cargo, cargo as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant$1 as constant, index as default, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doWhilst$1 as doDuring, doUntil, doWhilst$1 as doWhilst, whilst$1 as during, each, eachLimit$1 as eachLimit, eachOf$1 as eachOf, eachOfLimit$1 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, reduce$1 as foldl, reduceRight as foldr, each as forEach, eachLimit$1 as forEachLimit, eachOf$1 as forEachOf, eachOfLimit$1 as forEachOfLimit, eachOfSeries$1 as forEachOfSeries, eachSeries$1 as forEachSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, reduce$1 as inject, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$1 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, asyncify as wrapSync }; diff --git a/node_modules/async/doDuring.js b/node_modules/async/doDuring.js new file mode 100644 index 000000000..c72766d0a --- /dev/null +++ b/node_modules/async/doDuring.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doUntil.js b/node_modules/async/doUntil.js new file mode 100644 index 000000000..519900ee9 --- /dev/null +++ b/node_modules/async/doUntil.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doUntil; + +var _doWhilst = require('./doWhilst.js'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doUntil(iteratee, test, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _doWhilst2.default)(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb(err, !truth)); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doWhilst.js b/node_modules/async/doWhilst.js new file mode 100644 index 000000000..c72766d0a --- /dev/null +++ b/node_modules/async/doWhilst.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ +function doWhilst(iteratee, test, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); +} + +exports.default = (0, _awaitify2.default)(doWhilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/during.js b/node_modules/async/during.js new file mode 100644 index 000000000..4165543f8 --- /dev/null +++ b/node_modules/async/during.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/each.js b/node_modules/async/each.js new file mode 100644 index 000000000..fdfcbd882 --- /dev/null +++ b/node_modules/async/each.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachLimit.js b/node_modules/async/eachLimit.js new file mode 100644 index 000000000..7f5928c61 --- /dev/null +++ b/node_modules/async/eachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOf.js b/node_modules/async/eachOf.js new file mode 100644 index 000000000..9ed20f669 --- /dev/null +++ b/node_modules/async/eachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfLimit.js b/node_modules/async/eachOfLimit.js new file mode 100644 index 000000000..a596e5ac0 --- /dev/null +++ b/node_modules/async/eachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfSeries.js b/node_modules/async/eachOfSeries.js new file mode 100644 index 000000000..04243ada0 --- /dev/null +++ b/node_modules/async/eachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachSeries.js b/node_modules/async/eachSeries.js new file mode 100644 index 000000000..b04896e39 --- /dev/null +++ b/node_modules/async/eachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/ensureAsync.js b/node_modules/async/ensureAsync.js new file mode 100644 index 000000000..749c5dac7 --- /dev/null +++ b/node_modules/async/ensureAsync.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ensureAsync; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if ((0, _wrapAsync.isAsync)(fn)) return fn; + return function (...args /*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + (0, _setImmediate2.default)(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/every.js b/node_modules/async/every.js new file mode 100644 index 000000000..622b30194 --- /dev/null +++ b/node_modules/async/every.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function every(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(every, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everyLimit.js b/node_modules/async/everyLimit.js new file mode 100644 index 000000000..375e12602 --- /dev/null +++ b/node_modules/async/everyLimit.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everyLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everyLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everySeries.js b/node_modules/async/everySeries.js new file mode 100644 index 000000000..9a6bf7d46 --- /dev/null +++ b/node_modules/async/everySeries.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function everySeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(everySeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filter.js b/node_modules/async/filter.js new file mode 100644 index 000000000..2c9a63de5 --- /dev/null +++ b/node_modules/async/filter.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterLimit.js b/node_modules/async/filterLimit.js new file mode 100644 index 000000000..d3b3f50c6 --- /dev/null +++ b/node_modules/async/filterLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterSeries.js b/node_modules/async/filterSeries.js new file mode 100644 index 000000000..019a2d0a9 --- /dev/null +++ b/node_modules/async/filterSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/find.js b/node_modules/async/find.js new file mode 100644 index 000000000..d5896ef64 --- /dev/null +++ b/node_modules/async/find.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function detect(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detect, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findLimit.js b/node_modules/async/findLimit.js new file mode 100644 index 000000000..c59843b62 --- /dev/null +++ b/node_modules/async/findLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(detectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findSeries.js b/node_modules/async/findSeries.js new file mode 100644 index 000000000..b48689967 --- /dev/null +++ b/node_modules/async/findSeries.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ +function detectSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); +} + +exports.default = (0, _awaitify2.default)(detectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMap.js b/node_modules/async/flatMap.js new file mode 100644 index 000000000..4540a79cf --- /dev/null +++ b/node_modules/async/flatMap.js @@ -0,0 +1,115 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ +function concat(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concat, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapLimit.js b/node_modules/async/flatMapLimit.js new file mode 100644 index 000000000..a27cc7d45 --- /dev/null +++ b/node_modules/async/flatMapLimit.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); +} +exports.default = (0, _awaitify2.default)(concatLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapSeries.js b/node_modules/async/flatMapSeries.js new file mode 100644 index 000000000..332de3f3e --- /dev/null +++ b/node_modules/async/flatMapSeries.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _concatLimit = require('./concatLimit.js'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ +function concatSeries(coll, iteratee, callback) { + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(concatSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldl.js b/node_modules/async/foldl.js new file mode 100644 index 000000000..8a69548a6 --- /dev/null +++ b/node_modules/async/foldl.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldr.js b/node_modules/async/foldr.js new file mode 100644 index 000000000..5be1b68dc --- /dev/null +++ b/node_modules/async/foldr.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEach.js b/node_modules/async/forEach.js new file mode 100644 index 000000000..fdfcbd882 --- /dev/null +++ b/node_modules/async/forEach.js @@ -0,0 +1,129 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ +function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} + +exports.default = (0, _awaitify2.default)(eachLimit, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachLimit.js b/node_modules/async/forEachLimit.js new file mode 100644 index 000000000..7f5928c61 --- /dev/null +++ b/node_modules/async/forEachLimit.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex.js'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +exports.default = (0, _awaitify2.default)(eachLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOf.js b/node_modules/async/forEachOf.js new file mode 100644 index 000000000..9ed20f669 --- /dev/null +++ b/node_modules/async/forEachOf.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./internal/isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index = 0, + completed = 0, + { length } = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); +} + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ +function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOf, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfLimit.js b/node_modules/async/forEachOfLimit.js new file mode 100644 index 000000000..a596e5ac0 --- /dev/null +++ b/node_modules/async/forEachOfLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit2 = require('./internal/eachOfLimit.js'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} + +exports.default = (0, _awaitify2.default)(eachOfLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfSeries.js b/node_modules/async/forEachOfSeries.js new file mode 100644 index 000000000..04243ada0 --- /dev/null +++ b/node_modules/async/forEachOfSeries.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachOfSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachSeries.js b/node_modules/async/forEachSeries.js new file mode 100644 index 000000000..b04896e39 --- /dev/null +++ b/node_modules/async/forEachSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit.js'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ +function eachSeries(coll, iteratee, callback) { + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(eachSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forever.js b/node_modules/async/forever.js new file mode 100644 index 000000000..22925185e --- /dev/null +++ b/node_modules/async/forever.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _ensureAsync = require('./ensureAsync.js'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = (0, _onlyOnce2.default)(errback); + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); +} +exports.default = (0, _awaitify2.default)(forever, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBy.js b/node_modules/async/groupBy.js new file mode 100644 index 000000000..f29576302 --- /dev/null +++ b/node_modules/async/groupBy.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBy; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function groupBy(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupByLimit.js b/node_modules/async/groupByLimit.js new file mode 100644 index 000000000..30fd290af --- /dev/null +++ b/node_modules/async/groupByLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, { key, val }); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var { hasOwnProperty } = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var { key } = mapResults[i]; + var { val } = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +} + +exports.default = (0, _awaitify2.default)(groupByLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBySeries.js b/node_modules/async/groupBySeries.js new file mode 100644 index 000000000..e2a528749 --- /dev/null +++ b/node_modules/async/groupBySeries.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = groupBySeries; + +var _groupByLimit = require('./groupByLimit.js'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ +function groupBySeries(coll, iteratee, callback) { + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/index.js b/node_modules/async/index.js new file mode 100644 index 000000000..6154647d6 --- /dev/null +++ b/node_modules/async/index.js @@ -0,0 +1,588 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.doDuring = exports.during = exports.wrapSync = undefined; +exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; + +var _apply = require('./apply'); + +var _apply2 = _interopRequireDefault(_apply); + +var _applyEach = require('./applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _applyEachSeries = require('./applyEachSeries'); + +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); + +var _asyncify = require('./asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _autoInject = require('./autoInject'); + +var _autoInject2 = _interopRequireDefault(_autoInject); + +var _cargo = require('./cargo'); + +var _cargo2 = _interopRequireDefault(_cargo); + +var _cargoQueue = require('./cargoQueue'); + +var _cargoQueue2 = _interopRequireDefault(_cargoQueue); + +var _compose = require('./compose'); + +var _compose2 = _interopRequireDefault(_compose); + +var _concat = require('./concat'); + +var _concat2 = _interopRequireDefault(_concat); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _concatSeries = require('./concatSeries'); + +var _concatSeries2 = _interopRequireDefault(_concatSeries); + +var _constant = require('./constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _detect = require('./detect'); + +var _detect2 = _interopRequireDefault(_detect); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _detectSeries = require('./detectSeries'); + +var _detectSeries2 = _interopRequireDefault(_detectSeries); + +var _dir = require('./dir'); + +var _dir2 = _interopRequireDefault(_dir); + +var _doUntil = require('./doUntil'); + +var _doUntil2 = _interopRequireDefault(_doUntil); + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _each = require('./each'); + +var _each2 = _interopRequireDefault(_each); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _every = require('./every'); + +var _every2 = _interopRequireDefault(_every); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _everySeries = require('./everySeries'); + +var _everySeries2 = _interopRequireDefault(_everySeries); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _filterSeries = require('./filterSeries'); + +var _filterSeries2 = _interopRequireDefault(_filterSeries); + +var _forever = require('./forever'); + +var _forever2 = _interopRequireDefault(_forever); + +var _groupBy = require('./groupBy'); + +var _groupBy2 = _interopRequireDefault(_groupBy); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +var _groupBySeries = require('./groupBySeries'); + +var _groupBySeries2 = _interopRequireDefault(_groupBySeries); + +var _log = require('./log'); + +var _log2 = _interopRequireDefault(_log); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +var _mapValues = require('./mapValues'); + +var _mapValues2 = _interopRequireDefault(_mapValues); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _mapValuesSeries = require('./mapValuesSeries'); + +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); + +var _memoize = require('./memoize'); + +var _memoize2 = _interopRequireDefault(_memoize); + +var _nextTick = require('./nextTick'); + +var _nextTick2 = _interopRequireDefault(_nextTick); + +var _parallel = require('./parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _parallelLimit = require('./parallelLimit'); + +var _parallelLimit2 = _interopRequireDefault(_parallelLimit); + +var _priorityQueue = require('./priorityQueue'); + +var _priorityQueue2 = _interopRequireDefault(_priorityQueue); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _race = require('./race'); + +var _race2 = _interopRequireDefault(_race); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _reduceRight = require('./reduceRight'); + +var _reduceRight2 = _interopRequireDefault(_reduceRight); + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _reflectAll = require('./reflectAll'); + +var _reflectAll2 = _interopRequireDefault(_reflectAll); + +var _reject = require('./reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _rejectSeries = require('./rejectSeries'); + +var _rejectSeries2 = _interopRequireDefault(_rejectSeries); + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _retryable = require('./retryable'); + +var _retryable2 = _interopRequireDefault(_retryable); + +var _seq = require('./seq'); + +var _seq2 = _interopRequireDefault(_seq); + +var _series = require('./series'); + +var _series2 = _interopRequireDefault(_series); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _some = require('./some'); + +var _some2 = _interopRequireDefault(_some); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _someSeries = require('./someSeries'); + +var _someSeries2 = _interopRequireDefault(_someSeries); + +var _sortBy = require('./sortBy'); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +var _timeout = require('./timeout'); + +var _timeout2 = _interopRequireDefault(_timeout); + +var _times = require('./times'); + +var _times2 = _interopRequireDefault(_times); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _timesSeries = require('./timesSeries'); + +var _timesSeries2 = _interopRequireDefault(_timesSeries); + +var _transform = require('./transform'); + +var _transform2 = _interopRequireDefault(_transform); + +var _tryEach = require('./tryEach'); + +var _tryEach2 = _interopRequireDefault(_tryEach); + +var _unmemoize = require('./unmemoize'); + +var _unmemoize2 = _interopRequireDefault(_unmemoize); + +var _until = require('./until'); + +var _until2 = _interopRequireDefault(_until); + +var _waterfall = require('./waterfall'); + +var _waterfall2 = _interopRequireDefault(_waterfall); + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +exports.default = { + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + cargoQueue: _cargoQueue2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + flatMap: _concat2.default, + flatMapLimit: _concatLimit2.default, + flatMapSeries: _concatSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default, + during: _whilst2.default, + doDuring: _doWhilst2.default +}; +exports.apply = _apply2.default; +exports.applyEach = _applyEach2.default; +exports.applyEachSeries = _applyEachSeries2.default; +exports.asyncify = _asyncify2.default; +exports.auto = _auto2.default; +exports.autoInject = _autoInject2.default; +exports.cargo = _cargo2.default; +exports.cargoQueue = _cargoQueue2.default; +exports.compose = _compose2.default; +exports.concat = _concat2.default; +exports.concatLimit = _concatLimit2.default; +exports.concatSeries = _concatSeries2.default; +exports.constant = _constant2.default; +exports.detect = _detect2.default; +exports.detectLimit = _detectLimit2.default; +exports.detectSeries = _detectSeries2.default; +exports.dir = _dir2.default; +exports.doUntil = _doUntil2.default; +exports.doWhilst = _doWhilst2.default; +exports.each = _each2.default; +exports.eachLimit = _eachLimit2.default; +exports.eachOf = _eachOf2.default; +exports.eachOfLimit = _eachOfLimit2.default; +exports.eachOfSeries = _eachOfSeries2.default; +exports.eachSeries = _eachSeries2.default; +exports.ensureAsync = _ensureAsync2.default; +exports.every = _every2.default; +exports.everyLimit = _everyLimit2.default; +exports.everySeries = _everySeries2.default; +exports.filter = _filter2.default; +exports.filterLimit = _filterLimit2.default; +exports.filterSeries = _filterSeries2.default; +exports.forever = _forever2.default; +exports.groupBy = _groupBy2.default; +exports.groupByLimit = _groupByLimit2.default; +exports.groupBySeries = _groupBySeries2.default; +exports.log = _log2.default; +exports.map = _map2.default; +exports.mapLimit = _mapLimit2.default; +exports.mapSeries = _mapSeries2.default; +exports.mapValues = _mapValues2.default; +exports.mapValuesLimit = _mapValuesLimit2.default; +exports.mapValuesSeries = _mapValuesSeries2.default; +exports.memoize = _memoize2.default; +exports.nextTick = _nextTick2.default; +exports.parallel = _parallel2.default; +exports.parallelLimit = _parallelLimit2.default; +exports.priorityQueue = _priorityQueue2.default; +exports.queue = _queue2.default; +exports.race = _race2.default; +exports.reduce = _reduce2.default; +exports.reduceRight = _reduceRight2.default; +exports.reflect = _reflect2.default; +exports.reflectAll = _reflectAll2.default; +exports.reject = _reject2.default; +exports.rejectLimit = _rejectLimit2.default; +exports.rejectSeries = _rejectSeries2.default; +exports.retry = _retry2.default; +exports.retryable = _retryable2.default; +exports.seq = _seq2.default; +exports.series = _series2.default; +exports.setImmediate = _setImmediate2.default; +exports.some = _some2.default; +exports.someLimit = _someLimit2.default; +exports.someSeries = _someSeries2.default; +exports.sortBy = _sortBy2.default; +exports.timeout = _timeout2.default; +exports.times = _times2.default; +exports.timesLimit = _timesLimit2.default; +exports.timesSeries = _timesSeries2.default; +exports.transform = _transform2.default; +exports.tryEach = _tryEach2.default; +exports.unmemoize = _unmemoize2.default; +exports.until = _until2.default; +exports.waterfall = _waterfall2.default; +exports.whilst = _whilst2.default; +exports.all = _every2.default; +exports.allLimit = _everyLimit2.default; +exports.allSeries = _everySeries2.default; +exports.any = _some2.default; +exports.anyLimit = _someLimit2.default; +exports.anySeries = _someSeries2.default; +exports.find = _detect2.default; +exports.findLimit = _detectLimit2.default; +exports.findSeries = _detectSeries2.default; +exports.flatMap = _concat2.default; +exports.flatMapLimit = _concatLimit2.default; +exports.flatMapSeries = _concatSeries2.default; +exports.forEach = _each2.default; +exports.forEachSeries = _eachSeries2.default; +exports.forEachLimit = _eachLimit2.default; +exports.forEachOf = _eachOf2.default; +exports.forEachOfSeries = _eachOfSeries2.default; +exports.forEachOfLimit = _eachOfLimit2.default; +exports.inject = _reduce2.default; +exports.foldl = _reduce2.default; +exports.foldr = _reduceRight2.default; +exports.select = _filter2.default; +exports.selectLimit = _filterLimit2.default; +exports.selectSeries = _filterSeries2.default; +exports.wrapSync = _asyncify2.default; +exports.during = _whilst2.default; +exports.doDuring = _doWhilst2.default; \ No newline at end of file diff --git a/node_modules/async/inject.js b/node_modules/async/inject.js new file mode 100644 index 000000000..8a69548a6 --- /dev/null +++ b/node_modules/async/inject.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/DoublyLinkedList.js b/node_modules/async/internal/DoublyLinkedList.js new file mode 100644 index 000000000..419ce44bd --- /dev/null +++ b/node_modules/async/internal/DoublyLinkedList.js @@ -0,0 +1,92 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty() { + while (this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove(testFn) { + var curr = this.head; + while (curr) { + var { next } = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } +} + +exports.default = DLL; +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/Heap.js b/node_modules/async/internal/Heap.js new file mode 100644 index 000000000..7867c9281 --- /dev/null +++ b/node_modules/async/internal/Heap.js @@ -0,0 +1,120 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// Binary min-heap implementation used for priority queue. +// Implementation is stable, i.e. push time is considered for equal priorities +class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty() { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l = leftChi(index)) < this.heap.length) { + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) { + l = l + 1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length - 1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length - 1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator]() { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove(testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length - 1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } +} + +exports.default = Heap; +function leftChi(i) { + return (i << 1) + 1; +} + +function parent(i) { + return (i + 1 >> 1) - 1; +} + +function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } else { + return x.pushCount < y.pushCount; + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/applyEach.js b/node_modules/async/internal/applyEach.js new file mode 100644 index 000000000..544491267 --- /dev/null +++ b/node_modules/async/internal/applyEach.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = (0, _awaitify2.default)(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + (0, _wrapAsync2.default)(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; +}; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/asyncEachOfLimit.js b/node_modules/async/internal/asyncEachOfLimit.js new file mode 100644 index 000000000..34dd82bf6 --- /dev/null +++ b/node_modules/async/internal/asyncEachOfLimit.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncEachOfLimit; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// for async generators +function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return; + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + //console.log('got value', value) + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return; + if (err) return handleError(err); + + if (err === false) { + done = true; + canceled = true; + return; + } + + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); + } + + replenish(); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/awaitify.js b/node_modules/async/internal/awaitify.js new file mode 100644 index 000000000..bb7a609ad --- /dev/null +++ b/node_modules/async/internal/awaitify.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = awaitify; +// conditionally promisify a function. +// only return a promise if a callback is omitted +function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined'); + function awaitable(...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args); + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); + } + + return awaitable; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/breakLoop.js b/node_modules/async/internal/breakLoop.js new file mode 100644 index 000000000..87413dd0d --- /dev/null +++ b/node_modules/async/internal/breakLoop.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +const breakLoop = {}; +exports.default = breakLoop; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/consoleFunc.js b/node_modules/async/internal/consoleFunc.js new file mode 100644 index 000000000..748d54b74 --- /dev/null +++ b/node_modules/async/internal/consoleFunc.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = consoleFunc; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function consoleFunc(name) { + return (fn, ...args) => (0, _wrapAsync2.default)(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { + /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/createTester.js b/node_modules/async/internal/createTester.js new file mode 100644 index 000000000..cafdf62eb --- /dev/null +++ b/node_modules/async/internal/createTester.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createTester; + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = (0, _wrapAsync2.default)(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, _breakLoop2.default); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/eachOfLimit.js b/node_modules/async/internal/eachOfLimit.js new file mode 100644 index 000000000..ceed60f47 --- /dev/null +++ b/node_modules/async/internal/eachOfLimit.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator.js'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./wrapAsync.js'); + +var _asyncEachOfLimit = require('./asyncEachOfLimit.js'); + +var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + +var _breakLoop = require('./breakLoop.js'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = limit => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1'); + } + if (!obj) { + return callback(null); + } + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } + + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/filter.js b/node_modules/async/internal/filter.js new file mode 100644 index 000000000..065c211ec --- /dev/null +++ b/node_modules/async/internal/filter.js @@ -0,0 +1,55 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _filter; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({ index, value: x }); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results.sort((a, b) => a.index - b.index).map(v => v.value)); + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/getIterator.js b/node_modules/async/internal/getIterator.js new file mode 100644 index 000000000..f518fce8c --- /dev/null +++ b/node_modules/async/internal/getIterator.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/initialParams.js b/node_modules/async/internal/initialParams.js new file mode 100644 index 000000000..04c0eff79 --- /dev/null +++ b/node_modules/async/internal/initialParams.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn) { + return function (...args /*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; +}; + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/isArrayLike.js b/node_modules/async/internal/isArrayLike.js new file mode 100644 index 000000000..a4c4c8a59 --- /dev/null +++ b/node_modules/async/internal/isArrayLike.js @@ -0,0 +1,10 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isArrayLike; +function isArrayLike(value) { + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/iterator.js b/node_modules/async/internal/iterator.js new file mode 100644 index 000000000..5778b1e83 --- /dev/null +++ b/node_modules/async/internal/iterator.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createIterator; + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator.js'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? { value: obj[key], key } : null; + }; +} + +function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/map.js b/node_modules/async/internal/map.js new file mode 100644 index 000000000..acab1e725 --- /dev/null +++ b/node_modules/async/internal/map.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncMap; + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/once.js b/node_modules/async/internal/once.js new file mode 100644 index 000000000..a8b579266 --- /dev/null +++ b/node_modules/async/internal/once.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + function wrapper(...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/onlyOnce.js b/node_modules/async/internal/onlyOnce.js new file mode 100644 index 000000000..c95a92d40 --- /dev/null +++ b/node_modules/async/internal/onlyOnce.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/parallel.js b/node_modules/async/internal/parallel.js new file mode 100644 index 000000000..57fbd0d01 --- /dev/null +++ b/node_modules/async/internal/parallel.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _isArrayLike = require('./isArrayLike.js'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); +}, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/promiseCallback.js b/node_modules/async/internal/promiseCallback.js new file mode 100644 index 000000000..17a83016c --- /dev/null +++ b/node_modules/async/internal/promiseCallback.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +const PROMISE_SYMBOL = Symbol('promiseCallback'); + +function promiseCallback() { + let resolve, reject; + function callback(err, ...args) { + if (err) return reject(err); + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, reject = rej; + }); + + return callback; +} + +exports.promiseCallback = promiseCallback; +exports.PROMISE_SYMBOL = PROMISE_SYMBOL; \ No newline at end of file diff --git a/node_modules/async/internal/queue.js b/node_modules/async/internal/queue.js new file mode 100644 index 000000000..7414e03bd --- /dev/null +++ b/node_modules/async/internal/queue.js @@ -0,0 +1,294 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _onlyOnce = require('./onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList.js'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = (0, _wrapAsync2.default)(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on(event, handler) { + events[event].push(handler); + } + + function once(event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off(event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []); + if (!handler) return events[event] = []; + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger(event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback(err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res(); + if (args.length <= 1) return res(args[0]); + res(args); + } + + var item = q._createTaskItem(data, rejectOnError ? promiseCallback : callback || promiseCallback); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + (0, _setImmediate2.default)(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= q.concurrency - q.buffer) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + (0, _setImmediate2.default)(() => trigger('drain')); + return true; + } + return false; + } + + const eventMethod = name => handler => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); + } + off(name); + on(name, handler); + }; + + var isProcessing = false; + var q = { + _tasks: new _DoublyLinkedList2.default(), + _createTaskItem(data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator]() { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, false, callback)); + } + return _insert(data, false, false, callback); + }, + pushAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, false, true, callback)); + } + return _insert(data, false, true, callback); + }, + kill() { + off(); + q._tasks.empty(); + }, + unshift(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, false, callback)); + } + return _insert(data, true, false, callback); + }, + unshiftAsync(data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return; + return data.map(datum => _insert(datum, true, true, callback)); + } + return _insert(data, true, true, callback); + }, + remove(testFn) { + q._tasks.remove(testFn); + }, + process() { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = (0, _onlyOnce2.default)(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length() { + return q._tasks.length; + }, + running() { + return numRunning; + }, + workersList() { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause() { + q.paused = true; + }, + resume() { + if (q.paused === false) { + return; + } + q.paused = false; + (0, _setImmediate2.default)(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + } + }); + return q; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/range.js b/node_modules/async/internal/range.js new file mode 100644 index 000000000..cc7b3a9cd --- /dev/null +++ b/node_modules/async/internal/range.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = range; +function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/reject.js b/node_modules/async/internal/reject.js new file mode 100644 index 000000000..9d9bc80bc --- /dev/null +++ b/node_modules/async/internal/reject.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reject; + +var _filter = require('./filter.js'); + +var _filter2 = _interopRequireDefault(_filter); + +var _wrapAsync = require('./wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reject(eachfn, arr, _iteratee, callback) { + const iteratee = (0, _wrapAsync2.default)(_iteratee); + return (0, _filter2.default)(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/setImmediate.js b/node_modules/async/internal/setImmediate.js new file mode 100644 index 000000000..513efd13c --- /dev/null +++ b/node_modules/async/internal/setImmediate.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fallback = fallback; +exports.wrap = wrap; +/* istanbul ignore file */ + +var hasQueueMicrotask = exports.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); +} + +var _defer; + +if (hasQueueMicrotask) { + _defer = queueMicrotask; +} else if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); \ No newline at end of file diff --git a/node_modules/async/internal/withoutIndex.js b/node_modules/async/internal/withoutIndex.js new file mode 100644 index 000000000..fa91c2d5d --- /dev/null +++ b/node_modules/async/internal/withoutIndex.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/wrapAsync.js b/node_modules/async/internal/wrapAsync.js new file mode 100644 index 000000000..ad4d61986 --- /dev/null +++ b/node_modules/async/internal/wrapAsync.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined; + +var _asyncify = require('../asyncify.js'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; +} + +function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; +} + +function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function'); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; +} + +exports.default = wrapAsync; +exports.isAsync = isAsync; +exports.isAsyncGenerator = isAsyncGenerator; +exports.isAsyncIterable = isAsyncIterable; \ No newline at end of file diff --git a/node_modules/async/log.js b/node_modules/async/log.js new file mode 100644 index 000000000..332b9da79 --- /dev/null +++ b/node_modules/async/log.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc.js'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +exports.default = (0, _consoleFunc2.default)('log'); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/map.js b/node_modules/async/map.js new file mode 100644 index 000000000..c4b7a5ac5 --- /dev/null +++ b/node_modules/async/map.js @@ -0,0 +1,142 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function map(coll, iteratee, callback) { + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(map, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapLimit.js b/node_modules/async/mapLimit.js new file mode 100644 index 000000000..6ad35724e --- /dev/null +++ b/node_modules/async/mapLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapLimit(coll, limit, iteratee, callback) { + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapSeries.js b/node_modules/async/mapSeries.js new file mode 100644 index 000000000..8dfdd8aae --- /dev/null +++ b/node_modules/async/mapSeries.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map2 = require('./internal/map.js'); + +var _map3 = _interopRequireDefault(_map2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function mapSeries(coll, iteratee, callback) { + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(mapSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValues.js b/node_modules/async/mapValues.js new file mode 100644 index 000000000..3d0470e31 --- /dev/null +++ b/node_modules/async/mapValues.js @@ -0,0 +1,152 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValues; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function mapValues(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesLimit.js b/node_modules/async/mapValuesLimit.js new file mode 100644 index 000000000..f59e36f2f --- /dev/null +++ b/node_modules/async/mapValuesLimit.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = (0, _once2.default)(callback); + var newObj = {}; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); +} + +exports.default = (0, _awaitify2.default)(mapValuesLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesSeries.js b/node_modules/async/mapValuesSeries.js new file mode 100644 index 000000000..5f05bf218 --- /dev/null +++ b/node_modules/async/mapValuesSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValuesSeries; + +var _mapValuesLimit = require('./mapValuesLimit.js'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function mapValuesSeries(obj, iteratee, callback) { + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/memoize.js b/node_modules/async/memoize.js new file mode 100644 index 000000000..6535d4e46 --- /dev/null +++ b/node_modules/async/memoize.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize; + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = (0, _wrapAsync2.default)(fn); + var memoized = (0, _initialParams2.default)((args, callback) => { + var key = hasher(...args); + if (key in memo) { + (0, _setImmediate2.default)(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/nextTick.js b/node_modules/async/nextTick.js new file mode 100644 index 000000000..8ebfda9e6 --- /dev/null +++ b/node_modules/async/nextTick.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; /* istanbul ignore file */ + + +if (_setImmediate.hasNextTick) { + _defer = process.nextTick; +} else if (_setImmediate.hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = _setImmediate.fallback; +} + +exports.default = (0, _setImmediate.wrap)(_defer); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/package.json b/node_modules/async/package.json new file mode 100644 index 000000000..bcf4c41b4 --- /dev/null +++ b/node_modules/async/package.json @@ -0,0 +1,75 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "3.2.6", + "main": "dist/async.js", + "author": "Caolan McMahon", + "homepage": "https://caolan.github.io/async/", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "keywords": [ + "async", + "callback", + "module", + "utility" + ], + "devDependencies": { + "@babel/eslint-parser": "^7.16.5", + "@babel/core": "7.25.2", + "babel-minify": "^0.5.0", + "babel-plugin-add-module-exports": "^1.0.4", + "babel-plugin-istanbul": "^7.0.0", + "babel-plugin-syntax-async-generators": "^6.13.0", + "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", + "babel-preset-es2015": "^6.3.13", + "babel-preset-es2017": "^6.22.0", + "babel-register": "^6.26.0", + "babelify": "^10.0.0", + "benchmark": "^2.1.1", + "bluebird": "^3.4.6", + "browserify": "^17.0.0", + "chai": "^4.2.0", + "cheerio": "^0.22.0", + "es6-promise": "^4.2.8", + "eslint": "^8.6.0", + "eslint-plugin-prefer-arrow": "^1.2.3", + "fs-extra": "^11.1.1", + "jsdoc": "^4.0.3", + "karma": "^6.3.12", + "karma-browserify": "^8.1.0", + "karma-firefox-launcher": "^2.1.2", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.0", + "karma-safari-launcher": "^1.0.0", + "mocha": "^6.1.4", + "native-promise-only": "^0.8.0-a", + "nyc": "^17.0.0", + "rollup": "^4.2.0", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-npm": "^2.0.0", + "rsvp": "^4.8.5", + "semver": "^7.3.5", + "yargs": "^17.3.1" + }, + "scripts": { + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", + "lint": "eslint --fix .", + "mocha-browser-test": "karma start", + "mocha-node-test": "mocha", + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", + "test": "npm run lint && npm run mocha-node-test" + }, + "license": "MIT", + "nyc": { + "exclude": [ + "test" + ] + }, + "module": "dist/async.mjs" +} \ No newline at end of file diff --git a/node_modules/async/parallel.js b/node_modules/async/parallel.js new file mode 100644 index 000000000..2c7976fed --- /dev/null +++ b/node_modules/async/parallel.js @@ -0,0 +1,180 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallel; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function parallel(tasks, callback) { + return (0, _parallel3.default)(_eachOf2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/parallelLimit.js b/node_modules/async/parallelLimit.js new file mode 100644 index 000000000..43379572d --- /dev/null +++ b/node_modules/async/parallelLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _parallel = require('./internal/parallel.js'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ +function parallelLimit(tasks, limit, callback) { + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/priorityQueue.js b/node_modules/async/priorityQueue.js new file mode 100644 index 000000000..16c4daa0b --- /dev/null +++ b/node_modules/async/priorityQueue.js @@ -0,0 +1,60 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + // Start with a normal queue + var q = (0, _queue2.default)(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new _Heap2.default(); + q._createTaskItem = ({ data, priority }, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return { data: tasks, priority }; + } + return tasks.map(data => { + return { data, priority }; + }); + } + + // Override push to accept second parameter representing priority + q.push = function (data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function (data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; +}; + +var _queue = require('./queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _Heap = require('./internal/Heap.js'); + +var _Heap2 = _interopRequireDefault(_Heap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/queue.js b/node_modules/async/queue.js new file mode 100644 index 000000000..c01340dc2 --- /dev/null +++ b/node_modules/async/queue.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue.js'); + +var _queue2 = _interopRequireDefault(_queue); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/race.js b/node_modules/async/race.js new file mode 100644 index 000000000..aa167be3f --- /dev/null +++ b/node_modules/async/race.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + (0, _wrapAsync2.default)(tasks[i])(callback); + } +} + +exports.default = (0, _awaitify2.default)(race, 2); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduce.js b/node_modules/async/reduce.js new file mode 100644 index 000000000..8a69548a6 --- /dev/null +++ b/node_modules/async/reduce.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); +} +exports.default = (0, _awaitify2.default)(reduce, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduceRight.js b/node_modules/async/reduceRight.js new file mode 100644 index 000000000..5be1b68dc --- /dev/null +++ b/node_modules/async/reduceRight.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflect.js b/node_modules/async/reflect.js new file mode 100644 index 000000000..39544956b --- /dev/null +++ b/node_modules/async/reflect.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflect; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = (0, _wrapAsync2.default)(fn); + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0) { + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflectAll.js b/node_modules/async/reflectAll.js new file mode 100644 index 000000000..b78d598bf --- /dev/null +++ b/node_modules/async/reflectAll.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflectAll; + +var _reflect = require('./reflect.js'); + +var _reflect2 = _interopRequireDefault(_reflect); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(_reflect2.default); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = _reflect2.default.call(this, tasks[key]); + }); + } + return results; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reject.js b/node_modules/async/reject.js new file mode 100644 index 000000000..895949bd8 --- /dev/null +++ b/node_modules/async/reject.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function reject(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(reject, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectLimit.js b/node_modules/async/rejectLimit.js new file mode 100644 index 000000000..ce10edf57 --- /dev/null +++ b/node_modules/async/rejectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectLimit(coll, limit, iteratee, callback) { + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectSeries.js b/node_modules/async/rejectSeries.js new file mode 100644 index 000000000..c08e413f9 --- /dev/null +++ b/node_modules/async/rejectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject2 = require('./internal/reject.js'); + +var _reject3 = _interopRequireDefault(_reject2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ +function rejectSeries(coll, iteratee, callback) { + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(rejectSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retry.js b/node_modules/async/retry.js new file mode 100644 index 000000000..a4b02356f --- /dev/null +++ b/node_modules/async/retry.js @@ -0,0 +1,159 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retry; + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function constant(value) { + return function () { + return value; + }; +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +const DEFAULT_TIMES = 5; +const DEFAULT_INTERVAL = 0; + +function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || (0, _promiseCallback.promiseCallback)(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || (0, _promiseCallback.promiseCallback)(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = (0, _wrapAsync2.default)(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return; + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} + +function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retryable.js b/node_modules/async/retryable.js new file mode 100644 index 000000000..68256c316 --- /dev/null +++ b/node_modules/async/retryable.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retryable; + +var _retry = require('./retry.js'); + +var _retry2 = _interopRequireDefault(_retry); + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +function retryable(opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = opts && opts.arity || task.length; + if ((0, _wrapAsync.isAsync)(task)) { + arity += 1; + } + var _task = (0, _wrapAsync2.default)(task); + return (0, _initialParams2.default)((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = (0, _promiseCallback.promiseCallback)(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); + + return callback[_promiseCallback.PROMISE_SYMBOL]; + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/select.js b/node_modules/async/select.js new file mode 100644 index 000000000..2c9a63de5 --- /dev/null +++ b/node_modules/async/select.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function filter(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filter, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectLimit.js b/node_modules/async/selectLimit.js new file mode 100644 index 000000000..d3b3f50c6 --- /dev/null +++ b/node_modules/async/selectLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ +function filterLimit(coll, limit, iteratee, callback) { + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectSeries.js b/node_modules/async/selectSeries.js new file mode 100644 index 000000000..019a2d0a9 --- /dev/null +++ b/node_modules/async/selectSeries.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter2 = require('./internal/filter.js'); + +var _filter3 = _interopRequireDefault(_filter2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ +function filterSeries(coll, iteratee, callback) { + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(filterSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/seq.js b/node_modules/async/seq.js new file mode 100644 index 000000000..e7881cd01 --- /dev/null +++ b/node_modules/async/seq.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = seq; + +var _reduce = require('./reduce.js'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq(...functions) { + var _functions = functions.map(_wrapAsync2.default); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = (0, _promiseCallback.promiseCallback)(); + } + + (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, (err, results) => cb(err, ...results)); + + return cb[_promiseCallback.PROMISE_SYMBOL]; + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/series.js b/node_modules/async/series.js new file mode 100644 index 000000000..60c17ed65 --- /dev/null +++ b/node_modules/async/series.js @@ -0,0 +1,186 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = series; + +var _parallel2 = require('./internal/parallel.js'); + +var _parallel3 = _interopRequireDefault(_parallel2); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/setImmediate.js b/node_modules/async/setImmediate.js new file mode 100644 index 000000000..eea867717 --- /dev/null +++ b/node_modules/async/setImmediate.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `setImmediate`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name setImmediate + * @static + * @memberOf module:Utils + * @method + * @see [async.nextTick]{@link module:Utils.nextTick} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +exports.default = _setImmediate2.default; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/some.js b/node_modules/async/some.js new file mode 100644 index 000000000..a5bd328ab --- /dev/null +++ b/node_modules/async/some.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function some(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(some, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someLimit.js b/node_modules/async/someLimit.js new file mode 100644 index 000000000..3a8096fda --- /dev/null +++ b/node_modules/async/someLimit.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfLimit = require('./internal/eachOfLimit.js'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someLimit(coll, limit, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someLimit, 4); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someSeries.js b/node_modules/async/someSeries.js new file mode 100644 index 000000000..51aad19bd --- /dev/null +++ b/node_modules/async/someSeries.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester.js'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _eachOfSeries = require('./eachOfSeries.js'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ +function someSeries(coll, iteratee, callback) { + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); +} +exports.default = (0, _awaitify2.default)(someSeries, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/sortBy.js b/node_modules/async/sortBy.js new file mode 100644 index 000000000..0988b6120 --- /dev/null +++ b/node_modules/async/sortBy.js @@ -0,0 +1,190 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _map = require('./map.js'); + +var _map2 = _interopRequireDefault(_map); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ +function sortBy(coll, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _map2.default)(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, { value: x, criteria }); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +exports.default = (0, _awaitify2.default)(sortBy, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timeout.js b/node_modules/async/timeout.js new file mode 100644 index 000000000..46bb233af --- /dev/null +++ b/node_modules/async/timeout.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeout; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = (0, _wrapAsync2.default)(asyncFn); + + return (0, _initialParams2.default)((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/times.js b/node_modules/async/times.js new file mode 100644 index 000000000..ca7df517b --- /dev/null +++ b/node_modules/async/times.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = times; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +function times(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesLimit.js b/node_modules/async/timesLimit.js new file mode 100644 index 000000000..f76de250c --- /dev/null +++ b/node_modules/async/timesLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesLimit; + +var _mapLimit = require('./mapLimit.js'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _range = require('./internal/range.js'); + +var _range2 = _interopRequireDefault(_range); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesLimit(count, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesSeries.js b/node_modules/async/timesSeries.js new file mode 100644 index 000000000..776b4f3af --- /dev/null +++ b/node_modules/async/timesSeries.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timesSeries; + +var _timesLimit = require('./timesLimit.js'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ +function timesSeries(n, iteratee, callback) { + return (0, _timesLimit2.default)(n, 1, iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/transform.js b/node_modules/async/transform.js new file mode 100644 index 000000000..75dadea87 --- /dev/null +++ b/node_modules/async/transform.js @@ -0,0 +1,173 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = transform; + +var _eachOf = require('./eachOf.js'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _promiseCallback = require('./internal/promiseCallback.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ +function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)()); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + (0, _eachOf2.default)(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[_promiseCallback.PROMISE_SYMBOL]; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/tryEach.js b/node_modules/async/tryEach.js new file mode 100644 index 000000000..7e63f9d5a --- /dev/null +++ b/node_modules/async/tryEach.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachSeries = require('./eachSeries.js'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + return (0, _eachSeries2.default)(tasks, (task, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); +} + +exports.default = (0, _awaitify2.default)(tryEach); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/unmemoize.js b/node_modules/async/unmemoize.js new file mode 100644 index 000000000..badd7aecd --- /dev/null +++ b/node_modules/async/unmemoize.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unmemoize; +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/until.js b/node_modules/async/until.js new file mode 100644 index 000000000..4b69b9723 --- /dev/null +++ b/node_modules/async/until.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = until; + +var _whilst = require('./whilst.js'); + +var _whilst2 = _interopRequireDefault(_whilst); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ +function until(test, iteratee, callback) { + const _test = (0, _wrapAsync2.default)(test); + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/waterfall.js b/node_modules/async/waterfall.js new file mode 100644 index 000000000..c3242f797 --- /dev/null +++ b/node_modules/async/waterfall.js @@ -0,0 +1,105 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _once = require('./internal/once.js'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +function waterfall(tasks, callback) { + callback = (0, _once2.default)(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); + task(...args, (0, _onlyOnce2.default)(next)); + } + + function next(err, ...args) { + if (err === false) return; + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); +} + +exports.default = (0, _awaitify2.default)(waterfall); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/whilst.js b/node_modules/async/whilst.js new file mode 100644 index 000000000..4165543f8 --- /dev/null +++ b/node_modules/async/whilst.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _onlyOnce = require('./internal/onlyOnce.js'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _awaitify = require('./internal/awaitify.js'); + +var _awaitify2 = _interopRequireDefault(_awaitify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback); + var _fn = (0, _wrapAsync2.default)(iteratee); + var _test = (0, _wrapAsync2.default)(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); +} +exports.default = (0, _awaitify2.default)(whilst, 3); +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/wrapSync.js b/node_modules/async/wrapSync.js new file mode 100644 index 000000000..ddc3f02ff --- /dev/null +++ b/node_modules/async/wrapSync.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _initialParams = require('./internal/initialParams.js'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate.js'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _wrapAsync = require('./internal/wrapAsync.js'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function (...args /*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); +} + +function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate2.default)(e => { + throw e; + }, err); + } +} +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/axe-core/LICENSE b/node_modules/axe-core/LICENSE new file mode 100644 index 000000000..be2cc4dfb --- /dev/null +++ b/node_modules/axe-core/LICENSE @@ -0,0 +1,362 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. "Contributor" + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. "Contributor Version" + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the terms of + a Secondary License. + +1.6. "Executable Form" + + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + + means a work that combines Covered Software with other material, in a + separate file or files, that is not Covered Software. + +1.8. "License" + + means this document. + +1.9. "Licensable" + + means having the right to grant, to the maximum extent possible, whether + at the time of the initial grant or subsequently, any and all of the + rights conveyed by this License. + +1.10. "Modifications" + + means any of the following: + + a. any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. "Patent Claims" of a Contributor + + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the License, + by the making, using, selling, offering for sale, having made, import, + or transfer of either its Contributions or its Contributor Version. + +1.12. "Secondary License" + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. "Source Code Form" + + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, "control" means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution + become effective for each Contribution on the date the Contributor first + distributes such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under + this License. No additional rights or licenses will be implied from the + distribution or licensing of Covered Software under this License. + Notwithstanding Section 2.1(b) above, no patent license is granted by a + Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of + its Contributions. + + This License does not grant any rights in the trademarks, service marks, + or logos of any Contributor (except as may be necessary to comply with + the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this + License (see Section 10.2) or under the terms of a Secondary License (if + permitted under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its + Contributions are its original creation(s) or it has sufficient rights to + grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under + applicable copyright doctrines of fair use, fair dealing, or other + equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under + the terms of this License. You must inform recipients that the Source + Code Form of the Covered Software is governed by the terms of this + License, and how they can obtain a copy of this License. You may not + attempt to alter or restrict the recipients' rights in the Source Code + Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter the + recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for + the Covered Software. If the Larger Work is a combination of Covered + Software with a work governed by one or more Secondary Licenses, and the + Covered Software is not Incompatible With Secondary Licenses, this + License permits You to additionally distribute such Covered Software + under the terms of such Secondary License(s), so that the recipient of + the Larger Work may, at their option, further distribute the Covered + Software under the terms of either this License or such Secondary + License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices + (including copyright notices, patent notices, disclaimers of warranty, or + limitations of liability) contained within the Source Code Form of the + Covered Software, except that You may alter any license notices to the + extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on + behalf of any Contributor. You must make it absolutely clear that any + such warranty, support, indemnity, or liability obligation is offered by + You alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, + judicial order, or regulation then You must: (a) comply with the terms of + this License to the maximum extent possible; and (b) describe the + limitations and the code they affect. Such description must be placed in a + text file included with all distributions of the Covered Software under + this License. Except to the extent prohibited by statute or regulation, + such description must be sufficiently detailed for a recipient of ordinary + skill to be able to understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing + basis, if such Contributor fails to notify You of the non-compliance by + some reasonable means prior to 60 days after You have come back into + compliance. Moreover, Your grants from a particular Contributor are + reinstated on an ongoing basis if such Contributor notifies You of the + non-compliance by some reasonable means, this is the first time You have + received notice of non-compliance with this License from such + Contributor, and You become compliant prior to 30 days after Your receipt + of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, + counter-claims, and cross-claims) alleging that a Contributor Version + directly or indirectly infringes any patent, then the rights granted to + You by any and all Contributors for the Covered Software under Section + 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an "as is" basis, + without warranty of any kind, either expressed, implied, or statutory, + including, without limitation, warranties that the Covered Software is free + of defects, merchantable, fit for a particular purpose or non-infringing. + The entire risk as to the quality and performance of the Covered Software + is with You. Should any Covered Software prove defective in any respect, + You (not any Contributor) assume the cost of any necessary servicing, + repair, or correction. This disclaimer of warranty constitutes an essential + part of this License. No use of any Covered Software is authorized under + this License except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from + such party's negligence to the extent applicable law prohibits such + limitation. Some jurisdictions do not allow the exclusion or limitation of + incidental or consequential damages, so this exclusion and limitation may + not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts + of a jurisdiction where the defendant maintains its principal place of + business and such litigation shall be governed by laws of that + jurisdiction, without reference to its conflict-of-law provisions. Nothing + in this Section shall prevent a party's ability to bring cross-claims or + counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. Any law or regulation which provides that + the language of a contract shall be construed against the drafter shall not + be used to construe this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version + of the License under which You originally received the Covered Software, + or under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a + modified version of this License if you rename the license and remove + any references to the name of the license steward (except to note that + such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary + Licenses If You choose to distribute Source Code Form that is + Incompatible With Secondary Licenses under the terms of this version of + the License, the notice described in Exhibit B of this License must be + attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, +then You may include the notice in a location (such as a LICENSE file in a +relevant directory) where a recipient would be likely to look for such a +notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice + + This Source Code Form is "Incompatible + With Secondary Licenses", as defined by + the Mozilla Public License, v. 2.0. diff --git a/node_modules/axe-core/LICENSE-3RD-PARTY.txt b/node_modules/axe-core/LICENSE-3RD-PARTY.txt new file mode 100644 index 000000000..368c293be --- /dev/null +++ b/node_modules/axe-core/LICENSE-3RD-PARTY.txt @@ -0,0 +1,66 @@ +----------------------------------------------------------------------------- + MIT License + Applies to: + - colorjs.io; Copyright (c) 2021 Lea Verou, Chris Lilley + - core-js-pure; Copyright (c) 2014-2023 Denis Pushkarev + - css-selector-parser; Copyright (c) 2013 Dulin Marat + - doT.js; Copyright (c) 2011 Laura Doktorova + Software includes portions from jQote2 Copyright (c) 2010 aefxx, + http://aefxx.com/ licensed under the MIT license. + - emoji-regex; Copyright (c) Mathias Bynens + - es6-iterator; Copyright (c) 2013-2017 Mariusz Nowak (www.medikoo.com) + - es6-promise; + Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors + - event-emitter; Copyright (C) 2012-2015 Mariusz Nowak (www.medikoo.com) + - is-promise; Copyright (c) 2014 Forbes Lindesay + - lru-queue; Copyright (C) 2014 Mariusz Nowak (www.medikoo.com) + - typedarray; + Copyright (c) 2010, Linden Research, Inc. + Copyright (c) 2012, Joshua Bell + - weakmap-polyfill; Copyright (c) 2015-2021 polygonplanet +----------------------------------------------------------------------------- + +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. + + +----------------------------------------------------------------------------- + ISC License + Applies to: + - d; Copyright (c) 2013-2019, Mariusz Nowak, @medikoo, medikoo.com + - es5-ext; Copyright (c) 2011-2022, Mariusz Nowak, @medikoo, medikoo.com + - es6-symbol; Copyright (c) 2013-2019, Mariusz Nowak, @medikoo, medikoo.com + - es6-weak-map; Copyright (c) 2013-2018, Mariusz Nowak, @medikoo, medikoo.com + - ext; Copyright (c) 2011-2022, Mariusz Nowak, @medikoo, medikoo.com + - memoizee; Copyright (c) 2012-2018, Mariusz Nowak, @medikoo, medikoo.com + - next-tick; Copyright (c) 2012-2020, Mariusz Nowak, @medikoo, medikoo.com + - timers-ext; Copyright (c) 2013-2018, Mariusz Nowak, @medikoo, medikoo.com + - type; Copyright (c) 2019, Mariusz Nowak, @medikoo, medikoo.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. diff --git a/node_modules/axe-core/README.md b/node_modules/axe-core/README.md new file mode 100644 index 000000000..9be7bd46e --- /dev/null +++ b/node_modules/axe-core/README.md @@ -0,0 +1,190 @@ +# axe-core + +[![License](https://img.shields.io/npm/l/axe-core.svg?color=c41)](LICENSE) +[![Version](https://img.shields.io/npm/v/axe-core.svg)](https://www.npmjs.com/package/axe-core) +[![NPM downloads](https://img.shields.io/npm/dw/axe-core.svg?color=080)![](https://img.shields.io/npm/dy/axe-core.svg?color=080&label=)](https://npm-stat.com/charts.html?package=axe-core&from=2017-01-01) +[![Commits](https://img.shields.io/github/commit-activity/y/dequelabs/axe-core.svg)](https://github.com/dequelabs/axe-core/commits/develop) +[![GitHub contributors](https://img.shields.io/github/contributors/dequelabs/axe-core.svg?color=080)](https://github.com/dequelabs/axe-core/graphs/contributors) +[![Join our Slack chat](https://img.shields.io/badge/slack-chat-purple.svg?logo=slack)](https://accessibility.deque.com/axe-community) +[![Package Quality](https://npm.packagequality.com/shield/axe-core.svg)](https://packagequality.com/#?package=axe-core) + +Axe is an accessibility testing engine for websites and other HTML-based user interfaces. It's fast, secure, lightweight, and was built to seamlessly integrate with any existing test environment so you can automate accessibility testing alongside your regular functional testing. + +[Sign up for axe news](https://hubs.ly/H0fsN0b0) to get the latest on axe features, future releases, and events. + +## The Accessibility Rules + +Axe-core has different types of rules, for WCAG 2.0, 2.1, 2.2 on level A, AA and AAA as well as a number of best practices that help you identify common accessibility practices like ensuring every page has an `h1` heading, and to help you avoid "gotchas" in ARIA like where an ARIA attribute you used will get ignored. The complete list of rules, grouped WCAG level and best practice, can be found in [doc/rule-descriptions.md](./doc/rule-descriptions.md). + +With axe-core, you can find **on average 57% of WCAG issues automatically**. Additionally, axe-core will return elements as "incomplete" where axe-core could not be certain, and manual review is needed. + +To catch bugs earlier in the development cycle we recommend using the [axe-linter vscode extension](https://marketplace.visualstudio.com/items?itemName=deque-systems.vscode-axe-linter). To improve test coverage even further we recommend the [intelligent guided tests](https://www.youtube.com/watch?v=AtsX0dPCG_4&feature=youtu.be&ab_channel=DequeSystems) in the [axe Extension](https://www.deque.com/axe/browser-extensions/). + +## Getting started + +First download the package: + +```console +npm install axe-core --save-dev +``` + +Now include the javascript file in each of your iframes in your fixtures or test systems: + +```html + +``` + +Now insert calls at each point in your tests where a new piece of UI becomes visible or exposed: + +```js +axe + .run() + .then(results => { + if (results.violations.length) { + throw new Error('Accessibility issues found'); + } + }) + .catch(err => { + console.error('Something bad happened:', err.message); + }); +``` + +## Philosophy + +The web can only become an accessible, inclusive space if developers are empowered to take responsibility for accessibility testing and accessible coding practices. + +Automated accessibility testing is a huge timesaver, it doesn't require special expertise, and it allows teams to focus expert resources on the accessibility issues that really need them. Unfortunately, most accessibility tools are meant to be run on sites and applications that have reached the end of the development process and often don't give clear or consistent results, causing frustration and delays just when you thought your product was ready to ship. + +Axe was built to reflect how web development actually works. It works with all modern browsers, tools, and testing environments a dev team might use. With axe, accessibility testing can be performed as part of your unit testing, integration testing, browser testing, and any other functional testing your team already performs on a day-to-day basis. Building accessibility testing into the early development process saves time, resources, and all kinds of frustration. + +## About axe - our Manifesto + +- Axe is open source. +- It returns zero false positives (bugs notwithstanding). +- It's designed to work on all modern browsers and with whatever tools, frameworks, libraries and environments you use today. +- It's actively supported by [Deque Systems](https://www.deque.com), a major accessibility vendor. +- It integrates with your existing functional/acceptance automated tests. +- It automatically determines which rules to run based on the evaluation context. +- Axe supports in-memory fixtures, static fixtures, integration tests, and iframes of infinite depth. +- Axe is highly configurable. + +## Supported Browsers + +The [axe-core API](doc/API.md) fully supports the following browsers: + +- Microsoft Edge v40 and above +- Google Chrome v42 and above +- Mozilla Firefox v38 and above +- Apple Safari v7 and above +- Internet Explorer v11 (DEPRECATED) + +Support means that we will fix bugs and attempt to test each browser regularly. Only Chrome and Firefox are currently tested on every pull request. + +There is limited support for JSDOM. We will attempt to make all rules compatible with JSDOM but where this is not possible, we recommend turning those rules off. Currently the `color-contrast` rule is known not to work with JSDOM. + +We can only support environments where features are either natively supported or polyfilled correctly. We do not support the deprecated v0 Shadow DOM implementation. + +## Contents of the API Package + +The [axe-core API](doc/API.md) package consists of: + +- `axe.js` - the JavaScript file that should be included in your web site under test (API) +- `axe.min.js` - a minified version of the above file + +## Localization + +Axe can be built using your local language. To do so, a localization file must be added to the `./locales` directory. This file must be named in the following manner: `.json`. To build axe using this locale, instead of the default, run axe with the `--lang` flag, like so: + +`grunt build --lang=nl` + +or equivalently: + +`npm run build -- --lang=nl` + +This will create a new build for axe, called `axe..js` and `axe..min.js`. If you want to build all localized versions, simply pass in `--all-lang` instead. If you want to build multiple localized versions (but not all of them), you can pass in a comma-separated list of languages to the `--lang` flag, like `--lang=nl,ja`. + +To create a new translation for axe, start by running `grunt translate --lang=`. This will create a json file in the `./locales` directory, with the default English text in it for you to translate. Alternatively, you could copy `./locales/_template.json`. We welcome any localization for axe-core. For details on how to contribute, see the Contributing section below. For details on the message syntax, see [Check Message Template](/doc/check-message-template.md). + +To update an existing translation file, re-run `grunt translate --lang=`. This will add new messages used in English and remove messages which were not used in English. + +Additionally, locale can be applied at runtime by passing a `locale` object to `axe.configure()`. The locale object must be of the same shape as existing locales in the `./locales` directory. For example: + +```js +axe.configure({ + locale: { + lang: 'de', + rules: { + accesskeys: { + help: 'Der Wert des accesskey-Attributes muss einzigartig sein.' + } + // ... + }, + checks: { + abstractrole: { + fail: 'Abstrakte ARIA-Rollen dürfen nicht direkt verwendet werden.' + }, + 'aria-errormessage': { + // Note: doT (https://github.com/olado/dot) templates are supported here. + fail: 'Der Wert der aria-errormessage ${data.values}` muss eine Technik verwenden, um die Message anzukündigen (z. B., aria-live, aria-describedby, role=alert, etc.).' + } + // ... + } + } +}); +``` + +### Supported Locales + +Axe-core supports the following locales. Do note that since locales are contributed by our community, they are not guaranteed to include all translations needed in a release. + +- Basque +- Chinese (Simplified) +- Chinese (Traditional) +- Danish +- Dutch +- French +- German +- Greek +- Hebrew +- Italian +- Japanese +- Korean +- Norwegian (Bokmål) +- Polish +- Portuguese (Brazilian) +- Spanish + +## Updates & Security + +Axe-core has a new minor release every 3 to 5 months, which usually introduces new rules and features. We recommend scheduling time to upgrade to these versions. Security updates will be made available for minor version lines up to **18 months old**. + +- See [release and support](doc/release-and-support.md) for details on the frequency of releases, long-term support and recommendations on upgrading axe-core. +- See [backward compatibility](doc/backwards-compatibility-doc.md) for details on the types of changes different releases may introduce. + +## Deque Trademarks Policy + +DEQUE, DEQUELABS, AXE®, and AXE-CORE® are trademarks of Deque Systems, Inc. Use of the Deque trademarks must be in accordance with [Deque's trademark policy](https://www.deque.com/legal/trademarks/). + +## Supported ARIA Roles and Attributes. + +Refer [axe-core ARIA support](./doc/aria-supported.md) for a complete list of ARIA supported roles and attributes by axe. + +## Contributing + +Read the [Proposing Axe-core Rules guide](./doc/rule-proposal.md) + +Read the [documentation on the architecture](./doc/developer-guide.md) + +Read the [documentation on contributing](CONTRIBUTING.md) + +## Projects using axe-core + +[List of projects using axe-core](doc/projects.md) + +## Acknowledgements + +Thanks to Marat Dulin for his [css-selector-parser](https://www.npmjs.com/package/css-selector-parser) implementation which is included for shadow DOM support. Another thank you to the [Slick Parser](https://github.com/mootools/slick/blob/master/Source/Slick.Parser.js) implementers for their contribution, we have used some of their algorithms in our shadow DOM support code. Thanks to Lea Verou and Chris Lilley for their [colorjs.io](https://colorjs.io/) library which we have used for converting between color formats. + +## Licenses + +Axe-core is distributed under the [Mozilla Public License, version 2.0](LICENSE). It comes bundled with several dependencies which are distributed under their own terms. (See [LICENSE-3RD-PARTY.txt](LICENSE-3RD-PARTY.txt)) diff --git a/node_modules/axe-core/axe.d.ts b/node_modules/axe-core/axe.d.ts new file mode 100644 index 000000000..03cd835b3 --- /dev/null +++ b/node_modules/axe-core/axe.d.ts @@ -0,0 +1,698 @@ +// Type definitions for axe-core +// Project: https://github.com/dequelabs/axe-core + +declare namespace axe { + type ImpactValue = 'minor' | 'moderate' | 'serious' | 'critical' | null; + + type TagValue = string; + + type ReporterVersion = 'v1' | 'v2' | 'raw' | 'rawEnv' | 'no-passes'; + + type RunOnlyType = 'rule' | 'rules' | 'tag' | 'tags'; + + type resultGroups = 'inapplicable' | 'passes' | 'incomplete' | 'violations'; + + type AriaAttrsType = + | 'boolean' + | 'nmtoken' + | 'mntokens' + | 'idref' + | 'idrefs' + | 'string' + | 'decimal' + | 'int'; + + type AriaRolesType = 'abstract' | 'widget' | 'structure' | 'landmark'; + + type DpubRolesType = + | 'section' + | 'landmark' + | 'link' + | 'listitem' + | 'img' + | 'navigation' + | 'note' + | 'separator' + | 'none' + | 'sectionhead'; + + type HtmlContentTypes = + | 'flow' + | 'sectioning' + | 'heading' + | 'phrasing' + | 'embedded' + | 'interactive'; + + // Array of length 2 or greater + type MultiArray = [T, T, ...T[]]; + + // Selectors within a frame + type BaseSelector = string; + + type ShadowDomSelector = MultiArray; + type CrossTreeSelector = BaseSelector | ShadowDomSelector; + type LabelledShadowDomSelector = { fromShadowDom: ShadowDomSelector }; + + // Cross-frame selectors + type FramesSelector = Array; + type UnlabelledFrameSelector = CrossTreeSelector[]; + type LabelledFramesSelector = { fromFrames: MultiArray }; + /** + * @deprecated Use UnlabelledFrameSelector instead + */ + type CrossFrameSelector = UnlabelledFrameSelector; + + // Context options + type Selector = + | Node + | BaseSelector + | LabelledShadowDomSelector + | LabelledFramesSelector; + type SelectorList = Array | NodeList; + type ContextProp = Selector | SelectorList; + type ContextObject = + | { + include: ContextProp; + exclude?: ContextProp; + } + | { + exclude: ContextProp; + include?: ContextProp; + }; + type ContextSpec = ContextProp | ContextObject; + /** Synonym to ContextSpec */ + type ElementContext = ContextSpec; + + type SerialSelector = + | BaseSelector + | LabelledShadowDomSelector + | LabelledFramesSelector; + type SerialFrameSelector = SerialSelector | FramesSelector; + type SerialSelectorList = Array; + + type SerialContextObject = + | { + include: SerialSelector | SerialSelectorList; + exclude?: SerialSelector | SerialSelectorList; + } + | { + exclude: SerialSelector | SerialSelectorList; + include?: SerialSelector | SerialSelectorList; + }; + + interface FrameContextObject { + include: UnlabelledFrameSelector[]; + exclude: UnlabelledFrameSelector[]; + } + + type RunCallback = (error: Error, results: T) => void; + + interface TestEngine { + name: string; + version: string; + } + interface TestRunner { + name: string; + } + interface TestEnvironment { + userAgent: string; + windowWidth: number; + windowHeight: number; + orientationAngle?: number; + orientationType?: string; + } + interface RunOnly { + type: RunOnlyType; + values: TagValue[] | string[]; + } + interface RuleObject { + [key: string]: { + enabled: boolean; + }; + } + interface RunOptions { + runOnly?: RunOnly | TagValue[] | string[] | string; + rules?: RuleObject; + reporter?: ReporterVersion | string; + resultTypes?: resultGroups[]; + selectors?: boolean; + ancestry?: boolean; + xpath?: boolean; + absolutePaths?: boolean; + iframes?: boolean; + elementRef?: boolean; + frameWaitTime?: number; + preload?: boolean | PreloadOptions; + performanceTimer?: boolean; + pingWaitTime?: number; + } + interface PreloadOptions { + assets: string[]; + timeout?: number; + } + interface AxeResults extends EnvironmentData { + toolOptions: RunOptions; + passes: Result[]; + violations: Result[]; + incomplete: IncompleteResult[]; + inapplicable: Result[]; + } + interface Result { + description: string; + help: string; + helpUrl: string; + id: string; + impact?: ImpactValue; + tags: TagValue[]; + nodes: NodeResult[]; + } + interface IncompleteResult extends Result { + error?: Omit; + } + interface NodeResult { + html: string; + impact?: ImpactValue; + target: UnlabelledFrameSelector; + xpath?: string[]; + ancestry?: UnlabelledFrameSelector; + any: CheckResult[]; + all: CheckResult[]; + none: CheckResult[]; + failureSummary?: string; + element?: HTMLElement; + } + interface CheckResult { + id: string; + impact: string; + message: string; + data: any; + relatedNodes?: RelatedNode[]; + } + interface RelatedNode { + html: string; + target: UnlabelledFrameSelector; + xpath?: string[]; + ancestry?: UnlabelledFrameSelector; + element?: HTMLElement; + } + interface RuleLocale { + [key: string]: { + description: string; + help: string; + }; + } + interface CheckMessages { + pass: string | { [key: string]: string }; + fail: string | { [key: string]: string }; + incomplete?: string | { [key: string]: string }; + } + interface RuleError { + name: string; + message: string; + stack: string; + ruleId?: string; + method?: string; + cause?: SerialError; + errorNode?: SerialDqElement; + } + interface SerialError { + message: string; + stack: string; + name: string; + cause?: SerialError; + } + interface CheckLocale { + [key: string]: CheckMessages; + } + interface Locale { + lang?: string; + rules?: RuleLocale; + checks?: CheckLocale; + } + interface AriaAttrs { + type: AriaAttrsType; + values?: string[]; + allowEmpty?: boolean; + global?: boolean; + unsupported?: boolean; + } + interface AriaRoles { + type: AriaRolesType | DpubRolesType; + requiredContext?: string[]; + requiredOwned?: string[]; + requiredAttrs?: string[]; + allowedAttrs?: string[]; + nameFromContent?: boolean; + unsupported?: boolean; + } + interface HtmlElmsVariant { + contentTypes?: HtmlContentTypes[]; + allowedRoles: boolean | string[]; + noAriaAttrs?: boolean; + shadowRoot?: boolean; + implicitAttrs?: { [key: string]: string }; + namingMethods?: string[]; + } + interface HtmlElms extends HtmlElmsVariant { + variant?: { [key: string]: HtmlElmsVariant }; + } + interface Standards { + ariaAttrs?: { [key: string]: AriaAttrs }; + ariaRoles?: { [key: string]: AriaRoles }; + htmlElms?: { [key: string]: HtmlElms }; + cssColors?: { [key: string]: number[] }; + } + interface Spec { + branding?: string | Branding; + reporter?: ReporterVersion | string | AxeReporter; + checks?: Check[]; + rules?: Rule[]; + standards?: Standards; + locale?: Locale; + disableOtherRules?: boolean; + axeVersion?: string; + noHtml?: boolean; + allowedOrigins?: string[]; + // Deprecated - do not use. + ver?: string; + } + /** + * @deprecated Use branding: string instead to set the application key in help URLs + */ + interface Branding { + brand?: string; + application?: string; + } + interface CheckHelper { + async: () => (result: boolean | undefined | Error) => void; + data: (data: unknown) => void; + relatedNodes: (nodes: Element[]) => void; + } + interface AfterResult { + id: string; + data?: unknown; + relatedNodes: SerialDqElement[]; + result: boolean | undefined; + node: SerialDqElement; + } + interface Check { + id: string; + evaluate?: + | string + | (( + this: CheckHelper, + node: Element, + options: unknown, + virtualNode: VirtualNode + ) => boolean | undefined | void); + after?: + | string + | ((results: AfterResult[], options: unknown) => AfterResult[]); + options?: any; + matches?: string; + enabled?: boolean; + metadata?: { + impact?: ImpactValue; + messages?: CheckMessages; + }; + } + interface Rule { + id: string; + selector?: string; + impact?: ImpactValue; + excludeHidden?: boolean; + enabled?: boolean; + pageLevel?: boolean; + any?: string[]; + all?: string[]; + none?: string[]; + tags?: string[]; + matches?: string | ((node: Element, virtualNode: VirtualNode) => boolean); + reviewOnFail?: boolean; + actIds?: string[]; + metadata?: Omit; + } + interface AxePlugin { + id: string; + run(...args: any[]): any; + commands: { + id: string; + callback(...args: any[]): void; + }[]; + cleanup?(callback: Function): void; + } + interface RuleMetadata { + ruleId: string; + description: string; + help: string; + helpUrl: string; + tags: string[]; + actIds?: string[]; + } + interface SerialDqElement { + source: string; + nodeIndexes: number[]; + selector: UnlabelledFrameSelector; + xpath: string[]; + ancestry: UnlabelledFrameSelector; + } + interface DqElement extends SerialDqElement { + element: Element; + toJSON(): SerialDqElement; + } + interface DqElementConstructor { + new (elm: Element, options?: { absolutePaths?: boolean }): DqElement; + mergeSpecs( + childSpec: SerialDqElement, + parentSpec: SerialDqElement + ): SerialDqElement; + } + interface PartialRuleResult { + id: string; + result: 'inapplicable'; + pageLevel: boolean; + impact: null; + nodes: Array>; + } + interface PartialResult { + frames: SerialDqElement[]; + results: PartialRuleResult[]; + environmentData?: EnvironmentData; + } + type PartialResults = Array; + interface FrameContext { + frameSelector: CrossTreeSelector; + frameContext: FrameContextObject; + } + + interface RawCheckResult extends Omit< + CheckResult, + 'relatedNodes' | 'impact' + > { + relatedNodes?: Array; + impact?: ImpactValue; + } + + interface RawNodeResult { + node: SerialDqElement | DqElement; + any: RawCheckResult[]; + all: RawCheckResult[]; + none: RawCheckResult[]; + impact: ImpactValue | undefined; + result: T; + } + + interface RawResult extends Omit { + inapplicable: Array; + passes: RawNodeResult<'passed'>[]; + incomplete: RawNodeResult<'cantTell'>[]; + violations: RawNodeResult<'failed'>[]; + pageLevel: boolean; + result: 'failed' | 'passed' | 'incomplete' | 'inapplicable'; + } + + type AxeReporter = ( + rawResults: RawResult[], + option: RunOptions, + resolve: (report: T) => void, + reject: (error: Error) => void + ) => void; + + interface VirtualNode { + actualNode?: Node; + shadowId?: string; + children?: VirtualNode[]; + parent?: VirtualNode; + attr(attr: string): string | null; + hasAttr(attr: string): boolean; + props: { [key: string]: unknown }; + boundingClientRect: DOMRect; + } + + type GridCell = VirtualNode[]; + + interface Grid { + container: VirtualNode | null; + cells: unknown; // opaque implementation detail + boundaries?: DOMRect; + toGridIndex(num: number): number; + getCellFromPoint(point: { x: number; y: number }): GridCell; + loopGridPosition( + gridPosition: DOMRect, + callback: (gridCell: GridCell, pos: { row: number; col: number }) => void + ): void; + getGridPositionOfRect( + rect: { top: number; right: number; bottom: number; left: number }, + margin?: number + ): DOMRect; + } + + interface CustomNodeSerializer { + toSpec: (dqElm: DqElement) => T; + mergeSpecs: (nodeSpec: T, parentFrameSpec: T) => T; + } + + interface NodeSerializer { + update: (serializer: CustomNodeSerializer) => void; + toSpec: (node: Element | VirtualNode) => SerialDqElement; + dqElmToSpec: ( + dqElm: DqElement | SerialDqElement, + options?: RunOptions + ) => SerialDqElement; + mergeSpecs: ( + nodeSpec: SerialDqElement, + parentFrameSpec: SerialDqElement + ) => SerialDqElement; + } + + interface Utils { + getElementSource: ( + element: Node | null | undefined, + options?: { maxLength?: number; attrLimit?: number } + ) => string; + getFrameContexts: ( + context?: ElementContext, + options?: RunOptions + ) => FrameContext[]; + shadowSelect: (selector: CrossTreeSelector) => Element | null; + shadowSelectAll: (selector: CrossTreeSelector) => Element[]; + getStandards(): Required; + isContextSpec: (context: unknown) => context is ContextSpec; + isContextObject: (context: unknown) => context is ContextObject; + isContextProp: (context: unknown) => context is ContextProp; + isLabelledFramesSelector: ( + selector: unknown + ) => selector is LabelledFramesSelector; + isLabelledShadowDomSelector: ( + selector: unknown + ) => selector is LabelledShadowDomSelector; + RuleError: new (options: { + error: Error; + ruleId?: string; + method?: string; + errorNode?: SerialDqElement; + }) => RuleError; + serializeError: (error: Error) => SerialError; + DqElement: DqElementConstructor; + uuid: ( + options?: { random?: Uint8Array | Array }, + buf?: Uint8Array | Array, + offset?: number + ) => string | Uint8Array | Array; + nodeSerializer: NodeSerializer; + } + + interface Aria { + getRoleType: (role: string | Element | VirtualNode | null) => string | null; + } + + interface Dom { + isFocusable: (node: Element | VirtualNode) => boolean; + isNativelyFocusable: (node: Element | VirtualNode) => boolean; + getNodeGrid: (node: Node | VirtualNode) => Grid; + } + + type AccessibleTextOptions = { + inControlContext?: boolean; + inLabelledByContext?: boolean; + }; + + interface Text { + accessibleText: ( + element: Element, + options?: AccessibleTextOptions + ) => string; + } + + interface Commons { + aria: Aria; + dom: Dom; + text: Text; + } + + interface EnvironmentData { + testEngine: TestEngine; + testRunner: TestRunner; + testEnvironment: TestEnvironment; + url: string; + timestamp: string; + } + + let version: string; + let plugins: any; + let utils: Utils; + let commons: Commons; + + /** + * Source string to use as an injected script in Selenium + */ + let source: string; + + /** + * Object for axe Results + */ + var AxeResults: AxeResults; + + /** + * Runs a number of rules against the provided HTML page and returns the resulting issue list + * + * @param {ElementContext} context Optional The `Context` specification object @see Context + * @param {RunOptions} options Optional Options passed into rules or checks, temporarily modifying them. + * @param {RunCallback} callback Optional The function to invoke when analysis is complete. + * @returns {Promise|void} If the callback was not defined, axe will return a Promise. + */ + function run(context?: ElementContext): Promise; + function run(options: RunOptions): Promise; + function run( + callback: (error: Error, results: T) => void + ): void; + function run( + context: ElementContext, + callback: RunCallback + ): void; + function run( + options: RunOptions, + callback: RunCallback + ): void; + function run( + context: ElementContext, + options: RunOptions + ): Promise; + function run( + context: ElementContext, + options: RunOptions, + callback: RunCallback + ): void; + + /** + * Method for configuring the data format used by axe. Helpful for adding new + * rules, which must be registered with the library to execute. + * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data + */ + function configure(spec: Spec): void; + + /** + * Run axe in the current window only + * @param {ElementContext} context Optional The `Context` specification object @see Context + * @param {RunOptions} options Optional Options passed into rules or checks, temporarily modifying them. + * @returns {Promise} Partial result, for use in axe.finishRun. + */ + function runPartial( + context: ElementContext, + options: RunOptions + ): Promise; + + /** + * Create a report from axe.runPartial results + * @param {PartialResult[]} partialResults Results from axe.runPartial, calls in different frames on the page. + * @param {RunOptions} options Optional Options passed into rules or checks, temporarily modifying them. + */ + function finishRun( + partialResults: PartialResults, + options: RunOptions + ): Promise; + + /** + * Searches and returns rules that contain a tag in the list of tags. + * @param {Array} tags Optional array of tags + * @return {Array} Array of rules + */ + function getRules(tags?: string[]): RuleMetadata[]; + + /** + * Restores the default axe configuration + */ + function reset(): void; + + /** + * Function to register a plugin configuration in document and its subframes + * @param {Object} plugin A plugin configuration object + */ + function registerPlugin(plugin: AxePlugin): void; + + /** + * Function to clean up plugin configuration in document and its subframes + */ + function cleanup(): void; + + /** + * Set up alternative frame communication + */ + function frameMessenger(frameMessenger: FrameMessenger): void; + + /** + * Setup axe-core so axe.common functions can work properly. + */ + function setup(node?: Element | Document): VirtualNode; + + /** + * Clean up axe-core tree and caches. `axe.run` will call this function at the end of the run so there's no need to call it yourself afterwards. + */ + function teardown(): void; + + /** + * Check if a reporter is registered + */ + function hasReporter(reporterName: string): boolean; + + /** + * Get a reporter based the name it is registered with + */ + function getReporter(reporterName: string): AxeReporter; + + /** + * Register a new reporter, optionally setting it as the default + */ + function addReporter( + reporterName: string, + reporter: AxeReporter, + isDefault?: boolean + ): void; + + // axe.frameMessenger + type FrameMessenger = { + open: (topicHandler: TopicHandler) => Close | void; + post: ( + frameWindow: Window, + data: TopicData, + replyHandler: ReplyHandler + ) => boolean | void; + }; + type Close = Function; + type TopicHandler = (data: TopicData, responder: Responder) => void; + type ReplyHandler = ( + message: any | Error, + keepalive: boolean, + responder: Responder + ) => void; + type Responder = ( + message: any | Error, + keepalive?: boolean, + replyHandler?: ReplyHandler + ) => void; + type TopicData = { topic: string } & ReplyData; + type ReplyData = { channelId: string; message: any; keepalive: boolean }; +} + +export = axe; diff --git a/node_modules/axe-core/axe.js b/node_modules/axe-core/axe.js new file mode 100644 index 000000000..a61793f77 --- /dev/null +++ b/node_modules/axe-core/axe.js @@ -0,0 +1,33176 @@ +/*! axe v4.11.4 + * Copyright (c) 2015 - 2026 Deque Systems, Inc. + * + * Your use of this Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This entire copyright notice must appear in every copy of this file you + * distribute or in any file that contains substantial portions of this source + * code. + */ +(function axeFunction(window) { + var global = window; + var document = window.document; + 'use strict'; + function _typeof(o) { + '@babel/helpers - typeof'; + return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function(o) { + return typeof o; + } : function(o) { + return o && 'function' == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? 'symbol' : typeof o; + }, _typeof(o); + } + var axe = axe || {}; + axe.version = '4.11.4'; + if (typeof define === 'function' && define.amd) { + define('axe-core', [], function() { + return axe; + }); + } + if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object' && module.exports && typeof axeFunction.toString === 'function') { + axe.source = '(' + axeFunction.toString() + ')(typeof window === "object" ? window : this);'; + module.exports = axe; + } + if (typeof window.getComputedStyle === 'function') { + window.axe = axe; + } + var commons; + 'use strict'; + var _excluded = [ 'precision', 'format', 'inGamut' ], _excluded2 = [ 'space' ], _excluded3 = [ 'algorithm' ], _excluded4 = [ 'method' ], _excluded5 = [ 'maxDeltaE', 'deltaEMethod', 'steps', 'maxSteps' ], _excluded6 = [ 'node' ], _excluded7 = [ 'relatedNodes' ], _excluded8 = [ 'node' ], _excluded9 = [ 'variant' ], _excluded0 = [ 'matches' ], _excluded1 = [ 'chromium' ], _excluded10 = [ 'noImplicit' ], _excluded11 = [ 'noPresentational' ], _excluded12 = [ 'node' ], _excluded13 = [ 'environmentData' ], _excluded14 = [ 'environmentData' ], _excluded15 = [ 'environmentData' ], _excluded16 = [ 'environmentData' ], _excluded17 = [ 'environmentData' ]; + function _toArray(r) { + return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest(); + } + function _wrapNativeSuper(t) { + var r = 'function' == typeof Map ? new Map() : void 0; + return _wrapNativeSuper = function _wrapNativeSuper(t) { + if (null === t || !_isNativeFunction(t)) { + return t; + } + if ('function' != typeof t) { + throw new TypeError('Super expression must either be null or a function'); + } + if (void 0 !== r) { + if (r.has(t)) { + return r.get(t); + } + r.set(t, Wrapper); + } + function Wrapper() { + return _construct(t, arguments, _getPrototypeOf(this).constructor); + } + return Wrapper.prototype = Object.create(t.prototype, { + constructor: { + value: Wrapper, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), _setPrototypeOf(Wrapper, t); + }, _wrapNativeSuper(t); + } + function _isNativeFunction(t) { + try { + return -1 !== Function.toString.call(t).indexOf('[native code]'); + } catch (n) { + return 'function' == typeof t; + } + } + function _defineProperty(e, r, t) { + return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { + value: t, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[r] = t, e; + } + function _construct(t, e, r) { + if (_isNativeReflectConstruct()) { + return Reflect.construct.apply(null, arguments); + } + var o = [ null ]; + o.push.apply(o, e); + var p = new (t.bind.apply(t, o))(); + return r && _setPrototypeOf(p, r.prototype), p; + } + function _objectWithoutProperties(e, t) { + if (null == e) { + return {}; + } + var o, r, i = _objectWithoutPropertiesLoose(e, t); + if (Object.getOwnPropertySymbols) { + var n = Object.getOwnPropertySymbols(e); + for (r = 0; r < n.length; r++) { + o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); + } + } + return i; + } + function _objectWithoutPropertiesLoose(r, e) { + if (null == r) { + return {}; + } + var t = {}; + for (var n in r) { + if ({}.hasOwnProperty.call(r, n)) { + if (-1 !== e.indexOf(n)) { + continue; + } + t[n] = r[n]; + } + } + return t; + } + function _callSuper(t, o, e) { + return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); + } + function _possibleConstructorReturn(t, e) { + if (e && ('object' == _typeof(e) || 'function' == typeof e)) { + return e; + } + if (void 0 !== e) { + throw new TypeError('Derived constructors may only return object or undefined'); + } + return _assertThisInitialized(t); + } + function _assertThisInitialized(e) { + if (void 0 === e) { + throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called'); + } + return e; + } + function _isNativeReflectConstruct() { + try { + var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); + } catch (t) {} + return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { + return !!t; + })(); + } + function _getPrototypeOf(t) { + return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t) { + return t.__proto__ || Object.getPrototypeOf(t); + }, _getPrototypeOf(t); + } + function _inherits(t, e) { + if ('function' != typeof e && null !== e) { + throw new TypeError('Super expression must either be null or a function'); + } + t.prototype = Object.create(e && e.prototype, { + constructor: { + value: t, + writable: !0, + configurable: !0 + } + }), Object.defineProperty(t, 'prototype', { + writable: !1 + }), e && _setPrototypeOf(t, e); + } + function _setPrototypeOf(t, e) { + return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t, e) { + return t.__proto__ = e, t; + }, _setPrototypeOf(t, e); + } + function _extends() { + return _extends = Object.assign ? Object.assign.bind() : function(n) { + for (var e = 1; e < arguments.length; e++) { + var t = arguments[e]; + for (var r in t) { + ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); + } + } + return n; + }, _extends.apply(null, arguments); + } + function _toConsumableArray(r) { + return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); + } + function _nonIterableSpread() { + throw new TypeError('Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.'); + } + function _iterableToArray(r) { + if ('undefined' != typeof Symbol && null != r[Symbol.iterator] || null != r['@@iterator']) { + return Array.from(r); + } + } + function _arrayWithoutHoles(r) { + if (Array.isArray(r)) { + return _arrayLikeToArray(r); + } + } + function _classPrivateFieldInitSpec(e, t, a) { + _checkPrivateRedeclaration(e, t), t.set(e, a); + } + function _classPrivateMethodInitSpec(e, a) { + _checkPrivateRedeclaration(e, a), a.add(e); + } + function _checkPrivateRedeclaration(e, t) { + if (t.has(e)) { + throw new TypeError('Cannot initialize the same private elements twice on an object'); + } + } + function _classPrivateFieldGet(s, a) { + return s.get(_assertClassBrand(s, a)); + } + function _classPrivateFieldSet(s, a, r) { + return s.set(_assertClassBrand(s, a), r), r; + } + function _assertClassBrand(e, t, n) { + if ('function' == typeof e ? e === t : e.has(t)) { + return arguments.length < 3 ? t : n; + } + throw new TypeError('Private element is not present on this object'); + } + function _slicedToArray(r, e) { + return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); + } + function _nonIterableRest() { + throw new TypeError('Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.'); + } + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : 'undefined' != typeof Symbol && r[Symbol.iterator] || r['@@iterator']; + if (null != t) { + var e, n, i, u, a = [], f = !0, o = !1; + try { + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) { + return; + } + f = !1; + } else { + for (;!(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) {} + } + } catch (r) { + o = !0, n = r; + } finally { + try { + if (!f && null != t['return'] && (u = t['return'](), Object(u) !== u)) { + return; + } + } finally { + if (o) { + throw n; + } + } + } + return a; + } + } + function _arrayWithHoles(r) { + if (Array.isArray(r)) { + return r; + } + } + function _classCallCheck(a, n) { + if (!(a instanceof n)) { + throw new TypeError('Cannot call a class as a function'); + } + } + function _defineProperties(e, r) { + for (var t = 0; t < r.length; t++) { + var o = r[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, 'value' in o && (o.writable = !0), + Object.defineProperty(e, _toPropertyKey(o.key), o); + } + } + function _createClass(e, r, t) { + return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), + Object.defineProperty(e, 'prototype', { + writable: !1 + }), e; + } + function _toPropertyKey(t) { + var i = _toPrimitive(t, 'string'); + return 'symbol' == _typeof(i) ? i : i + ''; + } + function _toPrimitive(t, r) { + if ('object' != _typeof(t) || !t) { + return t; + } + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || 'default'); + if ('object' != _typeof(i)) { + return i; + } + throw new TypeError('@@toPrimitive must return a primitive value.'); + } + return ('string' === r ? String : Number)(t); + } + function _createForOfIteratorHelper(r, e) { + var t = 'undefined' != typeof Symbol && r[Symbol.iterator] || r['@@iterator']; + if (!t) { + if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && 'number' == typeof r.length) { + t && (r = t); + var _n = 0, F = function F() {}; + return { + s: F, + n: function n() { + return _n >= r.length ? { + done: !0 + } : { + done: !1, + value: r[_n++] + }; + }, + e: function e(r) { + throw r; + }, + 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 o, a = !0, u = !1; + return { + s: function s() { + t = t.call(r); + }, + n: function n() { + var r = t.next(); + return a = r.done, r; + }, + e: function e(r) { + u = !0, o = r; + }, + f: function f() { + try { + a || null == t['return'] || t['return'](); + } finally { + if (u) { + throw o; + } + } + } + }; + } + function _unsupportedIterableToArray(r, a) { + if (r) { + if ('string' == typeof r) { + return _arrayLikeToArray(r, a); + } + var t = {}.toString.call(r).slice(8, -1); + return 'Object' === t && r.constructor && (t = r.constructor.name), 'Map' === t || 'Set' === t ? Array.from(r) : 'Arguments' === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; + } + } + function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) { + n[e] = r[e]; + } + return n; + } + function _typeof(o) { + '@babel/helpers - typeof'; + return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function(o) { + return typeof o; + } : function(o) { + return o && 'function' == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? 'symbol' : typeof o; + }, _typeof(o); + } + (function(_Class_brand, _path, _CSS, _space, _r, _g, _b, _red, _green, _blue, _Class3_brand) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __defNormalProp = function __defNormalProp(obj, key, value) { + return key in obj ? __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value: value + }) : obj[key] = value; + }; + var __markAsModule = function __markAsModule(target) { + return __defProp(target, '__esModule', { + value: true + }); + }; + var __commonJS = function __commonJS(cb, mod) { + return function() { + return mod || cb((mod = { + exports: {} + }).exports, mod), mod.exports; + }; + }; + var __export = function __export(target, all) { + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + }; + var __exportStar = function __exportStar(target, module, desc) { + if (module && _typeof(module) === 'object' || typeof module === 'function') { + var _iterator = _createForOfIteratorHelper(__getOwnPropNames(module)), _step; + try { + var _loop = function _loop() { + var key = _step.value; + if (!__hasOwnProp.call(target, key) && key !== 'default') { + __defProp(target, key, { + get: function get() { + return module[key]; + }, + enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable + }); + } + }; + for (_iterator.s(); !(_step = _iterator.n()).done; ) { + _loop(); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + return target; + }; + var __toModule = function __toModule(module) { + return __exportStar(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, 'default', module && module.__esModule && 'default' in module ? { + get: function get() { + return module['default']; + }, + enumerable: true + } : { + value: module, + enumerable: true + })), module); + }; + var __publicField = function __publicField(obj, key, value) { + __defNormalProp(obj, _typeof(key) !== 'symbol' ? key + '' : key, value); + return value; + }; + var require_es6_promise = __commonJS(function(exports, module) { + (function(global2, factory) { + _typeof(exports) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global2.ES6Promise = factory(); + })(exports, function() { + 'use strict'; + function objectOrFunction(x) { + var type2 = _typeof(x); + return x !== null && (type2 === 'object' || type2 === 'function'); + } + function isFunction(x) { + return typeof x === 'function'; + } + var _isArray = void 0; + if (Array.isArray) { + _isArray = Array.isArray; + } else { + _isArray = function _isArray(x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } + var isArray = _isArray; + var len = 0; + var vertxNext = void 0; + var customSchedulerFn = void 0; + var asap = function asap2(callback, arg) { + queue2[len] = callback; + queue2[len + 1] = arg; + len += 2; + if (len === 2) { + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } + }; + function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; + } + function setAsap(asapFn) { + asap = asapFn; + } + var browserWindow = typeof window !== 'undefined' ? window : void 0; + var browserGlobal = browserWindow || {}; + var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; + var isNode2 = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + function useNextTick() { + return function() { + return process.nextTick(flush); + }; + } + function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function() { + vertxNext(flush); + }; + } + return useSetTimeout(); + } + function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { + characterData: true + }); + return function() { + node.data = iterations = ++iterations % 2; + }; + } + function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function() { + return channel.port2.postMessage(0); + }; + } + function useSetTimeout() { + var globalSetTimeout = setTimeout; + return function() { + return globalSetTimeout(flush, 1); + }; + } + var queue2 = new Array(1e3); + function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue2[i]; + var arg = queue2[i + 1]; + callback(arg); + queue2[i] = void 0; + queue2[i + 1] = void 0; + } + len = 0; + } + function attemptVertx() { + try { + var vertx = Function('return this')().require('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } + } + var scheduleFlush = void 0; + if (isNode2) { + scheduleFlush = useNextTick(); + } else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); + } else if (isWorker) { + scheduleFlush = useMessageChannel(); + } else if (browserWindow === void 0 && true) { + scheduleFlush = attemptVertx(); + } else { + scheduleFlush = useSetTimeout(); + } + function then(onFulfillment, onRejection) { + var parent = this; + var child = new this.constructor(noop3); + if (child[PROMISE_ID] === void 0) { + makePromise(child); + } + var _state = parent._state; + if (_state) { + var callback = arguments[_state - 1]; + asap(function() { + return invokeCallback(_state, child, callback, parent._result); + }); + } else { + subscribe2(parent, child, onFulfillment, onRejection); + } + return child; + } + function resolve$1(object) { + var Constructor = this; + if (object && _typeof(object) === 'object' && object.constructor === Constructor) { + return object; + } + var promise = new Constructor(noop3); + resolve(promise, object); + return promise; + } + var PROMISE_ID = Math.random().toString(36).substring(2); + function noop3() {} + var PENDING = void 0; + var FULFILLED = 1; + var REJECTED = 2; + function selfFulfillment() { + return new TypeError('You cannot resolve a promise with itself'); + } + function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } + } + function handleForeignThenable(promise, thenable, then$$1) { + asap(function(promise2) { + var sealed = false; + var error = tryThen(then$$1, thenable, function(value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise2, value); + } else { + fulfill(promise2, value); + } + }, function(reason) { + if (sealed) { + return; + } + sealed = true; + reject(promise2, reason); + }, 'Settle: ' + (promise2._label || ' unknown promise')); + if (!sealed && error) { + sealed = true; + reject(promise2, error); + } + }, promise); + } + function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe2(thenable, void 0, function(value) { + return resolve(promise, value); + }, function(reason) { + return reject(promise, reason); + }); + } + } + function handleMaybeThenable(promise, maybeThenable, then$$1) { + if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$1 === void 0) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } + } + } + function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + var then$$1 = void 0; + try { + then$$1 = value.then; + } catch (error) { + reject(promise, error); + return; + } + handleMaybeThenable(promise, value, then$$1); + } else { + fulfill(promise, value); + } + } + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + publish(promise); + } + function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + promise._result = value; + promise._state = FULFILLED; + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } + } + function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + asap(publishRejection, promise); + } + function subscribe2(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + parent._onerror = null; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + if (length === 0 && parent._state) { + asap(publish, parent); + } + } + function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + if (subscribers.length === 0) { + return; + } + var child = void 0, callback = void 0, detail = promise._result; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + promise._subscribers.length = 0; + } + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), value = void 0, error = void 0, succeeded = true; + if (hasCallback) { + try { + value = callback(detail); + } catch (e) { + succeeded = false; + error = e; + } + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + } + if (promise._state !== PENDING) {} else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (succeeded === false) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } + } + var id = 0; + function nextId() { + return id++; + } + function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = void 0; + promise._result = void 0; + promise._subscribers = []; + } + function validationError() { + return new Error('Array Methods must be provided an Array'); + } + var Enumerator = function() { + function Enumerator2(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop3); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; + this._result = new Array(this.length); + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } + } + Enumerator2.prototype._enumerate = function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + }; + Enumerator2.prototype._eachEntry = function _eachEntry(entry, i) { + var c4 = this._instanceConstructor; + var resolve$$1 = c4.resolve; + if (resolve$$1 === resolve$1) { + var _then = void 0; + var error = void 0; + var didError = false; + try { + _then = entry.then; + } catch (e) { + didError = true; + error = e; + } + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c4 === Promise$1) { + var promise = new c4(noop3); + if (didError) { + reject(promise, error); + } else { + handleMaybeThenable(promise, entry, _then); + } + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c4(function(resolve$$12) { + return resolve$$12(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + }; + Enumerator2.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; + if (promise._state === PENDING) { + this._remaining--; + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; + Enumerator2.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; + subscribe2(promise, void 0, function(value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function(reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + return Enumerator2; + }(); + function all(entries) { + return new Enumerator(this, entries).promise; + } + function race(entries) { + var Constructor = this; + if (!isArray(entries)) { + return new Constructor(function(_, reject2) { + return reject2(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve2, reject2) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve2, reject2); + } + }); + } + } + function reject$1(reason) { + var Constructor = this; + var promise = new Constructor(noop3); + reject(promise, reason); + return promise; + } + function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + function needsNew() { + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); + } + var Promise$1 = function() { + function Promise2(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = void 0; + this._subscribers = []; + if (noop3 !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise2 ? initializePromise(this, resolver) : needsNew(); + } + } + Promise2.prototype['catch'] = function _catch(onRejection) { + return this.then(null, onRejection); + }; + Promise2.prototype['finally'] = function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + if (isFunction(callback)) { + return promise.then(function(value) { + return constructor.resolve(callback()).then(function() { + return value; + }); + }, function(reason) { + return constructor.resolve(callback()).then(function() { + throw reason; + }); + }); + } + return promise.then(callback, callback); + }; + return Promise2; + }(); + Promise$1.prototype.then = then; + Promise$1.all = all; + Promise$1.race = race; + Promise$1.resolve = resolve$1; + Promise$1.reject = reject$1; + Promise$1._setScheduler = setScheduler; + Promise$1._setAsap = setAsap; + Promise$1._asap = asap; + function polyfill() { + var local = void 0; + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + var P = local.Promise; + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) {} + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + local.Promise = Promise$1; + } + Promise$1.polyfill = polyfill; + Promise$1.Promise = Promise$1; + return Promise$1; + }); + }); + var require_typedarray = __commonJS(function(exports) { + var MAX_ARRAY_LENGTH = 1e5; + var ECMAScript = function() { + var opts = Object.prototype.toString; + var ophop = Object.prototype.hasOwnProperty; + return { + Class: function Class(v) { + return opts.call(v).replace(/^\[object *|\]$/g, ''); + }, + HasProperty: function HasProperty(o, p2) { + return p2 in o; + }, + HasOwnProperty: function HasOwnProperty(o, p2) { + return ophop.call(o, p2); + }, + IsCallable: function IsCallable(o) { + return typeof o === 'function'; + }, + ToInt32: function ToInt32(v) { + return v >> 0; + }, + ToUint32: function ToUint32(v) { + return v >>> 0; + } + }; + }(); + var LN2 = Math.LN2; + var abs = Math.abs; + var floor = Math.floor; + var log2 = Math.log; + var min = Math.min; + var pow = Math.pow; + var round = Math.round; + function clamp3(v, minimum, max2) { + return v < minimum ? minimum : v > max2 ? max2 : v; + } + var getOwnPropNames = Object.getOwnPropertyNames || function(o) { + if (o !== Object(o)) { + throw new TypeError('Object.getOwnPropertyNames called on non-object'); + } + var props = [], p2; + for (p2 in o) { + if (ECMAScript.HasOwnProperty(o, p2)) { + props.push(p2); + } + } + return props; + }; + var defineProp; + if (Object.defineProperty && function() { + try { + Object.defineProperty({}, 'x', {}); + return true; + } catch (e) { + return false; + } + }()) { + defineProp = Object.defineProperty; + } else { + defineProp = function defineProp(o, p2, desc) { + if (!o === Object(o)) { + throw new TypeError('Object.defineProperty called on non-object'); + } + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { + Object.prototype.__defineGetter__.call(o, p2, desc.get); + } + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { + Object.prototype.__defineSetter__.call(o, p2, desc.set); + } + if (ECMAScript.HasProperty(desc, 'value')) { + o[p2] = desc.value; + } + return o; + }; + } + function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i; + for (i = 0; i < props.length; i += 1) { + defineProp(obj, props[i], { + value: obj[props[i]], + writable: false, + enumerable: false, + configurable: false + }); + } + } + } + function makeArrayAccessors(obj) { + if (!defineProp) { + return; + } + if (obj.length > MAX_ARRAY_LENGTH) { + throw new RangeError('Array too large for polyfill'); + } + function makeArrayAccessor(index) { + defineProp(obj, index, { + get: function get() { + return obj._getter(index); + }, + set: function set(v) { + obj._setter(index, v); + }, + enumerable: true, + configurable: false + }); + } + var i; + for (i = 0; i < obj.length; i += 1) { + makeArrayAccessor(i); + } + } + function as_signed(value, bits) { + var s = 32 - bits; + return value << s >> s; + } + function as_unsigned(value, bits) { + var s = 32 - bits; + return value << s >>> s; + } + function packI8(n2) { + return [ n2 & 255 ]; + } + function unpackI8(bytes) { + return as_signed(bytes[0], 8); + } + function packU8(n2) { + return [ n2 & 255 ]; + } + function unpackU8(bytes) { + return as_unsigned(bytes[0], 8); + } + function packU8Clamped(n2) { + n2 = round(Number(n2)); + return [ n2 < 0 ? 0 : n2 > 255 ? 255 : n2 & 255 ]; + } + function packI16(n2) { + return [ n2 >> 8 & 255, n2 & 255 ]; + } + function unpackI16(bytes) { + return as_signed(bytes[0] << 8 | bytes[1], 16); + } + function packU16(n2) { + return [ n2 >> 8 & 255, n2 & 255 ]; + } + function unpackU16(bytes) { + return as_unsigned(bytes[0] << 8 | bytes[1], 16); + } + function packI32(n2) { + return [ n2 >> 24 & 255, n2 >> 16 & 255, n2 >> 8 & 255, n2 & 255 ]; + } + function unpackI32(bytes) { + return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); + } + function packU32(n2) { + return [ n2 >> 24 & 255, n2 >> 16 & 255, n2 >> 8 & 255, n2 & 255 ]; + } + function unpackU32(bytes) { + return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); + } + function packIEEE754(v, ebits, fbits) { + var bias = (1 << ebits - 1) - 1; + var s, e, f, i, bits, str, bytes; + function roundToEven(n2) { + var w = floor(n2); + var fl = n2 - w; + if (fl < .5) { + return w; + } + if (fl > .5) { + return w + 1; + } + return w % 2 ? w + 1 : w; + } + if (v !== v) { + e = (1 << ebits) - 1; + f = pow(2, fbits - 1); + s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; + f = 0; + s = v < 0 ? 1 : 0; + } else if (v === 0) { + e = 0; + f = 0; + s = 1 / v === -Infinity ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + if (v >= pow(2, 1 - bias)) { + e = min(floor(log2(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + e = (1 << ebits) - 1; + f = 0; + } else { + e = e + bias; + f = f - pow(2, fbits); + } + } else { + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; + } + function unpackIEEE754(bytes, ebits, fbits) { + var bits = [], i, j, b2, str, bias, s, e, f; + for (i = bytes.length; i; i -= 1) { + b2 = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b2 % 2 ? 1 : 0); + b2 = b2 >> 1; + } + } + bits.reverse(); + str = bits.join(''); + bias = (1 << ebits - 1) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + if (e === (1 << ebits) - 1) { + return f === 0 ? s * Infinity : NaN; + } else if (e > 0) { + return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + } else if (f !== 0) { + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + } + return s < 0 ? -0 : 0; + } + function unpackF64(b2) { + return unpackIEEE754(b2, 11, 52); + } + function packF64(v) { + return packIEEE754(v, 11, 52); + } + function unpackF32(b2) { + return unpackIEEE754(b2, 8, 23); + } + function packF32(v) { + return packIEEE754(v, 8, 23); + } + (function() { + function ArrayBuffer(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) { + throw new RangeError('ArrayBuffer size is not a small enough positive integer'); + } + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; + var i; + for (i = 0; i < this.byteLength; i += 1) { + this._bytes[i] = 0; + } + configureProperties(this); + } + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer; + function ArrayBufferView() {} + function makeConstructor(bytesPerElement, pack, unpack) { + var _ctor; + _ctor = function ctor(buffer, byteOffset, length) { + var array, sequence, i, s; + if (!arguments.length || typeof arguments[0] === 'number') { + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) { + throw new RangeError('ArrayBufferView size is not a small enough positive integer'); + } + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + } else if (_typeof(arguments[0]) === 'object' && arguments[0].constructor === _ctor) { + array = arguments[0]; + this.length = array.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + for (i = 0; i < this.length; i += 1) { + this._setter(i, array._getter(i)); + } + } else if (_typeof(arguments[0]) === 'object' && !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + sequence = arguments[0]; + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer(this.byteLength); + this.byteOffset = 0; + for (i = 0; i < this.length; i += 1) { + s = sequence[i]; + this._setter(i, Number(s)); + } + } else if (_typeof(arguments[0]) === 'object' && (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { + this.buffer = buffer; + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError('byteOffset out of range'); + } + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + throw new RangeError('ArrayBuffer length minus the byteOffset is not a multiple of the element size.'); + } + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError('length of buffer minus byteOffset not a multiple of the element size'); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + if (this.byteOffset + this.byteLength > this.buffer.byteLength) { + throw new RangeError('byteOffset and length reference an area beyond the end of the buffer'); + } + } else { + throw new TypeError('Unexpected argument type(s)'); + } + this.constructor = _ctor; + configureProperties(this); + makeArrayAccessors(this); + }; + _ctor.prototype = new ArrayBufferView(); + _ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + _ctor.prototype._pack = pack; + _ctor.prototype._unpack = unpack; + _ctor.BYTES_PER_ELEMENT = bytesPerElement; + _ctor.prototype._getter = function(index) { + if (arguments.length < 1) { + throw new SyntaxError('Not enough arguments'); + } + index = ECMAScript.ToUint32(index); + if (index >= this.length) { + return void 0; + } + var bytes = []; + for (var i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, + o += 1) { + bytes.push(this.buffer._bytes[o]); + } + return this._unpack(bytes); + }; + _ctor.prototype.get = _ctor.prototype._getter; + _ctor.prototype._setter = function(index, value) { + if (arguments.length < 2) { + throw new SyntaxError('Not enough arguments'); + } + index = ECMAScript.ToUint32(index); + if (index < this.length) { + var bytes = this._pack(value); + var i; + var o; + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, + o += 1) { + this.buffer._bytes[o] = bytes[i]; + } + } + }; + _ctor.prototype.set = function(index, value) { + if (arguments.length < 1) { + throw new SyntaxError('Not enough arguments'); + } + var array, sequence, offset, len, i, s, d2, byteOffset, byteLength, tmp; + if (_typeof(arguments[0]) === 'object' && arguments[0].constructor === this.constructor) { + array = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); + if (offset + array.length > this.length) { + throw new RangeError('Offset plus length of array is out of range'); + } + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array.length * this.BYTES_PER_ELEMENT; + if (array.buffer === this.buffer) { + tmp = []; + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { + tmp[i] = array.buffer._bytes[s]; + } + for (i = 0, d2 = byteOffset; i < byteLength; i += 1, d2 += 1) { + this.buffer._bytes[d2] = tmp[i]; + } + } else { + for (i = 0, s = array.byteOffset, d2 = byteOffset; i < byteLength; i += 1, + s += 1, d2 += 1) { + this.buffer._bytes[d2] = array.buffer._bytes[s]; + } + } + } else if (_typeof(arguments[0]) === 'object' && typeof arguments[0].length !== 'undefined') { + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); + if (offset + len > this.length) { + throw new RangeError('Offset plus length of array is out of range'); + } + for (i = 0; i < len; i += 1) { + s = sequence[i]; + this._setter(offset + i, Number(s)); + } + } else { + throw new TypeError('Unexpected argument type(s)'); + } + }; + _ctor.prototype.subarray = function(start, end) { + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); + if (arguments.length < 1) { + start = 0; + } + if (arguments.length < 2) { + end = this.length; + } + if (start < 0) { + start = this.length + start; + } + if (end < 0) { + end = this.length + end; + } + start = clamp3(start, 0, this.length); + end = clamp3(end, 0, this.length); + var len = end - start; + if (len < 0) { + len = 0; + } + return new this.constructor(this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); + }; + return _ctor; + } + var Int8Array = makeConstructor(1, packI8, unpackI8); + var Uint8Array2 = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray2 = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array = makeConstructor(2, packI16, unpackI16); + var Uint16Array = makeConstructor(2, packU16, unpackU16); + var Int32Array = makeConstructor(4, packI32, unpackI32); + var Uint32Array3 = makeConstructor(4, packU32, unpackU32); + var Float32Array = makeConstructor(4, packF32, unpackF32); + var Float64Array = makeConstructor(8, packF64, unpackF64); + exports.Int8Array = exports.Int8Array || Int8Array; + exports.Uint8Array = exports.Uint8Array || Uint8Array2; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray2; + exports.Int16Array = exports.Int16Array || Int16Array; + exports.Uint16Array = exports.Uint16Array || Uint16Array; + exports.Int32Array = exports.Int32Array || Int32Array; + exports.Uint32Array = exports.Uint32Array || Uint32Array3; + exports.Float32Array = exports.Float32Array || Float32Array; + exports.Float64Array = exports.Float64Array || Float64Array; + })(); + (function() { + function r(array, index) { + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; + } + var IS_BIG_ENDIAN = function() { + var u16array = new exports.Uint16Array([ 4660 ]), u8array = new exports.Uint8Array(u16array.buffer); + return r(u8array, 0) === 18; + }(); + function DataView(buffer, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer = new exports.ArrayBuffer(0); + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) { + throw new TypeError('TypeError'); + } + this.buffer = buffer || new exports.ArrayBuffer(0); + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError('byteOffset out of range'); + } + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + } else { + this.byteLength = ECMAScript.ToUint32(byteLength); + } + if (this.byteOffset + this.byteLength > this.buffer.byteLength) { + throw new RangeError('byteOffset and length reference an area beyond the end of the buffer'); + } + configureProperties(this); + } + function makeGetter(arrayType) { + return function(byteOffset, littleEndian) { + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError('Array index out of range'); + } + byteOffset += this.byteOffset; + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), bytes = [], i; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(uint8Array, i)); + } + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0); + }; + } + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array); + function makeSetter(arrayType) { + return function(byteOffset, value, littleEndian) { + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError('Array index out of range'); + } + var typeArray = new arrayType([ value ]), byteArray = new exports.Uint8Array(typeArray.buffer), bytes = [], i, byteView; + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { + bytes.push(r(byteArray, i)); + } + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array); + exports.DataView = exports.DataView || DataView; + })(); + }); + var require_weakmap_polyfill = __commonJS(function(exports) { + (function(self2) { + 'use strict'; + if (self2.WeakMap) { + return; + } + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + var hasDefine = Object.defineProperty && function() { + try { + return Object.defineProperty({}, 'x', { + value: 1 + }).x === 1; + } catch (e) {} + }(); + var defineProperty = function defineProperty(object, name, value) { + if (hasDefine) { + Object.defineProperty(object, name, { + configurable: true, + writable: true, + value: value + }); + } else { + object[name] = value; + } + }; + self2.WeakMap = function() { + function WeakMap2() { + if (this === void 0) { + throw new TypeError('Constructor WeakMap requires \'new\''); + } + defineProperty(this, '_id', genId('_WeakMap')); + if (arguments.length > 0) { + throw new TypeError('WeakMap iterable is not supported'); + } + } + defineProperty(WeakMap2.prototype, 'delete', function(key) { + checkInstance(this, 'delete'); + if (!isObject(key)) { + return false; + } + var entry = key[this._id]; + if (entry && entry[0] === key) { + delete key[this._id]; + return true; + } + return false; + }); + defineProperty(WeakMap2.prototype, 'get', function(key) { + checkInstance(this, 'get'); + if (!isObject(key)) { + return void 0; + } + var entry = key[this._id]; + if (entry && entry[0] === key) { + return entry[1]; + } + return void 0; + }); + defineProperty(WeakMap2.prototype, 'has', function(key) { + checkInstance(this, 'has'); + if (!isObject(key)) { + return false; + } + var entry = key[this._id]; + if (entry && entry[0] === key) { + return true; + } + return false; + }); + defineProperty(WeakMap2.prototype, 'set', function(key, value) { + checkInstance(this, 'set'); + if (!isObject(key)) { + throw new TypeError('Invalid value used as weak map key'); + } + var entry = key[this._id]; + if (entry && entry[0] === key) { + entry[1] = value; + return this; + } + defineProperty(key, this._id, [ key, value ]); + return this; + }); + function checkInstance(x, methodName) { + if (!isObject(x) || !hasOwnProperty2.call(x, '_id')) { + throw new TypeError(methodName + ' method called on incompatible receiver ' + _typeof(x)); + } + } + function genId(prefix) { + return prefix + '_' + rand() + '.' + rand(); + } + function rand() { + return Math.random().toString().substring(2); + } + defineProperty(WeakMap2, '_polyfill', true); + return WeakMap2; + }(); + function isObject(x) { + return Object(x) === x; + } + })(typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : exports); + }); + var require_global_this = __commonJS(function(exports, module) { + 'use strict'; + var check = function check(it) { + return it && it.Math === Math && it; + }; + module.exports = check((typeof globalThis === 'undefined' ? 'undefined' : _typeof(globalThis)) == 'object' && globalThis) || check((typeof window === 'undefined' ? 'undefined' : _typeof(window)) == 'object' && window) || check((typeof self === 'undefined' ? 'undefined' : _typeof(self)) == 'object' && self) || check((typeof global === 'undefined' ? 'undefined' : _typeof(global)) == 'object' && global) || check(_typeof(exports) == 'object' && exports) || function() { + return this; + }() || Function('return this')(); + }); + var require_fails = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(exec) { + try { + return !!exec(); + } catch (error) { + return true; + } + }; + }); + var require_function_bind_native = __commonJS(function(exports, module) { + 'use strict'; + var fails = require_fails(); + module.exports = !fails(function() { + var test = function() {}.bind(); + return typeof test != 'function' || test.hasOwnProperty('prototype'); + }); + }); + var require_function_apply = __commonJS(function(exports, module) { + 'use strict'; + var NATIVE_BIND = require_function_bind_native(); + var FunctionPrototype = Function.prototype; + var apply = FunctionPrototype.apply; + var call = FunctionPrototype.call; + module.exports = (typeof Reflect === 'undefined' ? 'undefined' : _typeof(Reflect)) == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function() { + return call.apply(apply, arguments); + }); + }); + var require_function_uncurry_this = __commonJS(function(exports, module) { + 'use strict'; + var NATIVE_BIND = require_function_bind_native(); + var FunctionPrototype = Function.prototype; + var call = FunctionPrototype.call; + var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); + module.exports = NATIVE_BIND ? uncurryThisWithBind : function(fn) { + return function() { + return call.apply(fn, arguments); + }; + }; + }); + var require_classof_raw = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var toString = uncurryThis({}.toString); + var stringSlice = uncurryThis(''.slice); + module.exports = function(it) { + return stringSlice(toString(it), 8, -1); + }; + }); + var require_function_uncurry_this_clause = __commonJS(function(exports, module) { + 'use strict'; + var classofRaw = require_classof_raw(); + var uncurryThis = require_function_uncurry_this(); + module.exports = function(fn) { + if (classofRaw(fn) === 'Function') { + return uncurryThis(fn); + } + }; + }); + var require_is_callable = __commonJS(function(exports, module) { + 'use strict'; + var documentAll = (typeof document === 'undefined' ? 'undefined' : _typeof(document)) == 'object' && document.all; + module.exports = typeof documentAll == 'undefined' && documentAll !== void 0 ? function(argument) { + return typeof argument == 'function' || argument === documentAll; + } : function(argument) { + return typeof argument == 'function'; + }; + }); + var require_descriptors = __commonJS(function(exports, module) { + 'use strict'; + var fails = require_fails(); + module.exports = !fails(function() { + return Object.defineProperty({}, 1, { + get: function get() { + return 7; + } + })[1] !== 7; + }); + }); + var require_function_call = __commonJS(function(exports, module) { + 'use strict'; + var NATIVE_BIND = require_function_bind_native(); + var call = Function.prototype.call; + module.exports = NATIVE_BIND ? call.bind(call) : function() { + return call.apply(call, arguments); + }; + }); + var require_object_property_is_enumerable = __commonJS(function(exports) { + 'use strict'; + var $propertyIsEnumerable = {}.propertyIsEnumerable; + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ + 1: 2 + }, 1); + exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { + var descriptor = getOwnPropertyDescriptor(this, V); + return !!descriptor && descriptor.enumerable; + } : $propertyIsEnumerable; + }); + var require_create_property_descriptor = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + }); + var require_indexed_object = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var fails = require_fails(); + var classof = require_classof_raw(); + var $Object = Object; + var split = uncurryThis(''.split); + module.exports = fails(function() { + return !$Object('z').propertyIsEnumerable(0); + }) ? function(it) { + return classof(it) === 'String' ? split(it, '') : $Object(it); + } : $Object; + }); + var require_is_null_or_undefined = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(it) { + return it === null || it === void 0; + }; + }); + var require_require_object_coercible = __commonJS(function(exports, module) { + 'use strict'; + var isNullOrUndefined = require_is_null_or_undefined(); + var $TypeError = TypeError; + module.exports = function(it) { + if (isNullOrUndefined(it)) { + throw new $TypeError('Can\'t call method on ' + it); + } + return it; + }; + }); + var require_to_indexed_object = __commonJS(function(exports, module) { + 'use strict'; + var IndexedObject = require_indexed_object(); + var requireObjectCoercible = require_require_object_coercible(); + module.exports = function(it) { + return IndexedObject(requireObjectCoercible(it)); + }; + }); + var require_is_object = __commonJS(function(exports, module) { + 'use strict'; + var isCallable = require_is_callable(); + module.exports = function(it) { + return _typeof(it) == 'object' ? it !== null : isCallable(it); + }; + }); + var require_path = __commonJS(function(exports, module) { + 'use strict'; + module.exports = {}; + }); + var require_get_built_in = __commonJS(function(exports, module) { + 'use strict'; + var path = require_path(); + var globalThis2 = require_global_this(); + var isCallable = require_is_callable(); + var aFunction = function aFunction(variable) { + return isCallable(variable) ? variable : void 0; + }; + module.exports = function(namespace, method) { + return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(globalThis2[namespace]) : path[namespace] && path[namespace][method] || globalThis2[namespace] && globalThis2[namespace][method]; + }; + }); + var require_object_is_prototype_of = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + module.exports = uncurryThis({}.isPrototypeOf); + }); + var require_environment_user_agent = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var navigator = globalThis2.navigator; + var userAgent = navigator && navigator.userAgent; + module.exports = userAgent ? String(userAgent) : ''; + }); + var require_environment_v8_version = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var userAgent = require_environment_user_agent(); + var process2 = globalThis2.process; + var Deno = globalThis2.Deno; + var versions = process2 && process2.versions || Deno && Deno.version; + var v8 = versions && versions.v8; + var match; + var version; + if (v8) { + match = v8.split('.'); + version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); + } + if (!version && userAgent) { + match = userAgent.match(/Edge\/(\d+)/); + if (!match || match[1] >= 74) { + match = userAgent.match(/Chrome\/(\d+)/); + if (match) { + version = +match[1]; + } + } + } + module.exports = version; + }); + var require_symbol_constructor_detection = __commonJS(function(exports, module) { + 'use strict'; + var V8_VERSION = require_environment_v8_version(); + var fails = require_fails(); + var globalThis2 = require_global_this(); + var $String = globalThis2.String; + module.exports = !!Object.getOwnPropertySymbols && !fails(function() { + var symbol = Symbol('symbol detection'); + return !$String(symbol) || !(Object(symbol) instanceof Symbol) || !Symbol.sham && V8_VERSION && V8_VERSION < 41; + }); + }); + var require_use_symbol_as_uid = __commonJS(function(exports, module) { + 'use strict'; + var NATIVE_SYMBOL = require_symbol_constructor_detection(); + module.exports = NATIVE_SYMBOL && !Symbol.sham && _typeof(Symbol.iterator) == 'symbol'; + }); + var require_is_symbol = __commonJS(function(exports, module) { + 'use strict'; + var getBuiltIn = require_get_built_in(); + var isCallable = require_is_callable(); + var isPrototypeOf = require_object_is_prototype_of(); + var USE_SYMBOL_AS_UID = require_use_symbol_as_uid(); + var $Object = Object; + module.exports = USE_SYMBOL_AS_UID ? function(it) { + return _typeof(it) == 'symbol'; + } : function(it) { + var $Symbol = getBuiltIn('Symbol'); + return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); + }; + }); + var require_try_to_string = __commonJS(function(exports, module) { + 'use strict'; + var $String = String; + module.exports = function(argument) { + try { + return $String(argument); + } catch (error) { + return 'Object'; + } + }; + }); + var require_a_callable = __commonJS(function(exports, module) { + 'use strict'; + var isCallable = require_is_callable(); + var tryToString = require_try_to_string(); + var $TypeError = TypeError; + module.exports = function(argument) { + if (isCallable(argument)) { + return argument; + } + throw new $TypeError(tryToString(argument) + ' is not a function'); + }; + }); + var require_get_method = __commonJS(function(exports, module) { + 'use strict'; + var aCallable = require_a_callable(); + var isNullOrUndefined = require_is_null_or_undefined(); + module.exports = function(V, P) { + var func = V[P]; + return isNullOrUndefined(func) ? void 0 : aCallable(func); + }; + }); + var require_ordinary_to_primitive = __commonJS(function(exports, module) { + 'use strict'; + var call = require_function_call(); + var isCallable = require_is_callable(); + var isObject = require_is_object(); + var $TypeError = TypeError; + module.exports = function(input, pref) { + var fn, val; + if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) { + return val; + } + if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) { + return val; + } + if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) { + return val; + } + throw new $TypeError('Can\'t convert object to primitive value'); + }; + }); + var require_is_pure = __commonJS(function(exports, module) { + 'use strict'; + module.exports = true; + }); + var require_define_global_property = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var defineProperty = Object.defineProperty; + module.exports = function(key, value) { + try { + defineProperty(globalThis2, key, { + value: value, + configurable: true, + writable: true + }); + } catch (error) { + globalThis2[key] = value; + } + return value; + }; + }); + var require_shared_store = __commonJS(function(exports, module) { + 'use strict'; + var IS_PURE = require_is_pure(); + var globalThis2 = require_global_this(); + var defineGlobalProperty = require_define_global_property(); + var SHARED = '__core-js_shared__'; + var store = module.exports = globalThis2[SHARED] || defineGlobalProperty(SHARED, {}); + (store.versions || (store.versions = [])).push({ + version: '3.48.0', + mode: IS_PURE ? 'pure' : 'global', + copyright: '\xa9 2013\u20132025 Denis Pushkarev (zloirock.ru), 2025\u20132026 CoreJS Company (core-js.io). All rights reserved.', + license: 'https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE', + source: 'https://github.com/zloirock/core-js' + }); + }); + var require_shared = __commonJS(function(exports, module) { + 'use strict'; + var store = require_shared_store(); + module.exports = function(key, value) { + return store[key] || (store[key] = value || {}); + }; + }); + var require_to_object = __commonJS(function(exports, module) { + 'use strict'; + var requireObjectCoercible = require_require_object_coercible(); + var $Object = Object; + module.exports = function(argument) { + return $Object(requireObjectCoercible(argument)); + }; + }); + var require_has_own_property = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var toObject = require_to_object(); + var hasOwnProperty2 = uncurryThis({}.hasOwnProperty); + module.exports = Object.hasOwn || function hasOwn2(it, key) { + return hasOwnProperty2(toObject(it), key); + }; + }); + var require_uid = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var id = 0; + var postfix = Math.random(); + var toString = uncurryThis(1.1.toString); + module.exports = function(key) { + return 'Symbol(' + (key === void 0 ? '' : key) + ')_' + toString(++id + postfix, 36); + }; + }); + var require_well_known_symbol = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var shared = require_shared(); + var hasOwn2 = require_has_own_property(); + var uid = require_uid(); + var NATIVE_SYMBOL = require_symbol_constructor_detection(); + var USE_SYMBOL_AS_UID = require_use_symbol_as_uid(); + var Symbol2 = globalThis2.Symbol; + var WellKnownSymbolsStore = shared('wks'); + var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol2['for'] || Symbol2 : Symbol2 && Symbol2.withoutSetter || uid; + module.exports = function(name) { + if (!hasOwn2(WellKnownSymbolsStore, name)) { + WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn2(Symbol2, name) ? Symbol2[name] : createWellKnownSymbol('Symbol.' + name); + } + return WellKnownSymbolsStore[name]; + }; + }); + var require_to_primitive = __commonJS(function(exports, module) { + 'use strict'; + var call = require_function_call(); + var isObject = require_is_object(); + var isSymbol = require_is_symbol(); + var getMethod = require_get_method(); + var ordinaryToPrimitive = require_ordinary_to_primitive(); + var wellKnownSymbol = require_well_known_symbol(); + var $TypeError = TypeError; + var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); + module.exports = function(input, pref) { + if (!isObject(input) || isSymbol(input)) { + return input; + } + var exoticToPrim = getMethod(input, TO_PRIMITIVE); + var result; + if (exoticToPrim) { + if (pref === void 0) { + pref = 'default'; + } + result = call(exoticToPrim, input, pref); + if (!isObject(result) || isSymbol(result)) { + return result; + } + throw new $TypeError('Can\'t convert object to primitive value'); + } + if (pref === void 0) { + pref = 'number'; + } + return ordinaryToPrimitive(input, pref); + }; + }); + var require_to_property_key = __commonJS(function(exports, module) { + 'use strict'; + var toPrimitive = require_to_primitive(); + var isSymbol = require_is_symbol(); + module.exports = function(argument) { + var key = toPrimitive(argument, 'string'); + return isSymbol(key) ? key : key + ''; + }; + }); + var require_document_create_element = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var isObject = require_is_object(); + var document2 = globalThis2.document; + var EXISTS = isObject(document2) && isObject(document2.createElement); + module.exports = function(it) { + return EXISTS ? document2.createElement(it) : {}; + }; + }); + var require_ie8_dom_define = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var fails = require_fails(); + var createElement = require_document_create_element(); + module.exports = !DESCRIPTORS && !fails(function() { + return Object.defineProperty(createElement('div'), 'a', { + get: function get() { + return 7; + } + }).a !== 7; + }); + }); + var require_object_get_own_property_descriptor = __commonJS(function(exports) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var call = require_function_call(); + var propertyIsEnumerableModule = require_object_property_is_enumerable(); + var createPropertyDescriptor = require_create_property_descriptor(); + var toIndexedObject = require_to_indexed_object(); + var toPropertyKey = require_to_property_key(); + var hasOwn2 = require_has_own_property(); + var IE8_DOM_DEFINE = require_ie8_dom_define(); + var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { + O = toIndexedObject(O); + P = toPropertyKey(P); + if (IE8_DOM_DEFINE) { + try { + return $getOwnPropertyDescriptor(O, P); + } catch (error) {} + } + if (hasOwn2(O, P)) { + return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); + } + }; + }); + var require_is_forced = __commonJS(function(exports, module) { + 'use strict'; + var fails = require_fails(); + var isCallable = require_is_callable(); + var replacement = /#|\.prototype\./; + var isForced = function isForced(feature, detection) { + var value = data[normalize(feature)]; + return value === POLYFILL ? true : value === NATIVE ? false : isCallable(detection) ? fails(detection) : !!detection; + }; + var normalize = isForced.normalize = function(string) { + return String(string).replace(replacement, '.').toLowerCase(); + }; + var data = isForced.data = {}; + var NATIVE = isForced.NATIVE = 'N'; + var POLYFILL = isForced.POLYFILL = 'P'; + module.exports = isForced; + }); + var require_function_bind_context = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this_clause(); + var aCallable = require_a_callable(); + var NATIVE_BIND = require_function_bind_native(); + var bind = uncurryThis(uncurryThis.bind); + module.exports = function(fn, that) { + aCallable(fn); + return that === void 0 ? fn : NATIVE_BIND ? bind(fn, that) : function() { + return fn.apply(that, arguments); + }; + }; + }); + var require_v8_prototype_define_bug = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var fails = require_fails(); + module.exports = DESCRIPTORS && fails(function() { + return Object.defineProperty(function() {}, 'prototype', { + value: 42, + writable: false + }).prototype !== 42; + }); + }); + var require_an_object = __commonJS(function(exports, module) { + 'use strict'; + var isObject = require_is_object(); + var $String = String; + var $TypeError = TypeError; + module.exports = function(argument) { + if (isObject(argument)) { + return argument; + } + throw new $TypeError($String(argument) + ' is not an object'); + }; + }); + var require_object_define_property = __commonJS(function(exports) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var IE8_DOM_DEFINE = require_ie8_dom_define(); + var V8_PROTOTYPE_DEFINE_BUG = require_v8_prototype_define_bug(); + var anObject = require_an_object(); + var toPropertyKey = require_to_property_key(); + var $TypeError = TypeError; + var $defineProperty = Object.defineProperty; + var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var ENUMERABLE = 'enumerable'; + var CONFIGURABLE = 'configurable'; + var WRITABLE = 'writable'; + exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { + anObject(O); + P = toPropertyKey(P); + anObject(Attributes); + if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { + var current = $getOwnPropertyDescriptor(O, P); + if (current && current[WRITABLE]) { + O[P] = Attributes.value; + Attributes = { + configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], + enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], + writable: false + }; + } + } + return $defineProperty(O, P, Attributes); + } : $defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPropertyKey(P); + anObject(Attributes); + if (IE8_DOM_DEFINE) { + try { + return $defineProperty(O, P, Attributes); + } catch (error) {} + } + if ('get' in Attributes || 'set' in Attributes) { + throw new $TypeError('Accessors not supported'); + } + if ('value' in Attributes) { + O[P] = Attributes.value; + } + return O; + }; + }); + var require_create_non_enumerable_property = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var definePropertyModule = require_object_define_property(); + var createPropertyDescriptor = require_create_property_descriptor(); + module.exports = DESCRIPTORS ? function(object, key, value) { + return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); + } : function(object, key, value) { + object[key] = value; + return object; + }; + }); + var require_export = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var apply = require_function_apply(); + var uncurryThis = require_function_uncurry_this_clause(); + var isCallable = require_is_callable(); + var getOwnPropertyDescriptor = require_object_get_own_property_descriptor().f; + var isForced = require_is_forced(); + var path = require_path(); + var bind = require_function_bind_context(); + var createNonEnumerableProperty = require_create_non_enumerable_property(); + var hasOwn2 = require_has_own_property(); + require_shared_store(); + var wrapConstructor = function wrapConstructor(NativeConstructor) { + var _Wrapper = function Wrapper(a2, b2, c4) { + if (this instanceof _Wrapper) { + switch (arguments.length) { + case 0: + return new NativeConstructor(); + + case 1: + return new NativeConstructor(a2); + + case 2: + return new NativeConstructor(a2, b2); + } + return new NativeConstructor(a2, b2, c4); + } + return apply(NativeConstructor, this, arguments); + }; + _Wrapper.prototype = NativeConstructor.prototype; + return _Wrapper; + }; + module.exports = function(options, source) { + var TARGET = options.target; + var GLOBAL = options.global; + var STATIC = options.stat; + var PROTO = options.proto; + var nativeSource = GLOBAL ? globalThis2 : STATIC ? globalThis2[TARGET] : globalThis2[TARGET] && globalThis2[TARGET].prototype; + var target = GLOBAL ? path : path[TARGET] || createNonEnumerableProperty(path, TARGET, {})[TARGET]; + var targetPrototype = target.prototype; + var FORCED, USE_NATIVE, VIRTUAL_PROTOTYPE; + var key, sourceProperty, targetProperty, nativeProperty, resultProperty, descriptor; + for (key in source) { + FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); + USE_NATIVE = !FORCED && nativeSource && hasOwn2(nativeSource, key); + targetProperty = target[key]; + if (USE_NATIVE) { + if (options.dontCallGetSet) { + descriptor = getOwnPropertyDescriptor(nativeSource, key); + nativeProperty = descriptor && descriptor.value; + } else { + nativeProperty = nativeSource[key]; + } + } + sourceProperty = USE_NATIVE && nativeProperty ? nativeProperty : source[key]; + if (!FORCED && !PROTO && _typeof(targetProperty) == _typeof(sourceProperty)) { + continue; + } + if (options.bind && USE_NATIVE) { + resultProperty = bind(sourceProperty, globalThis2); + } else if (options.wrap && USE_NATIVE) { + resultProperty = wrapConstructor(sourceProperty); + } else if (PROTO && isCallable(sourceProperty)) { + resultProperty = uncurryThis(sourceProperty); + } else { + resultProperty = sourceProperty; + } + if (options.sham || sourceProperty && sourceProperty.sham || targetProperty && targetProperty.sham) { + createNonEnumerableProperty(resultProperty, 'sham', true); + } + createNonEnumerableProperty(target, key, resultProperty); + if (PROTO) { + VIRTUAL_PROTOTYPE = TARGET + 'Prototype'; + if (!hasOwn2(path, VIRTUAL_PROTOTYPE)) { + createNonEnumerableProperty(path, VIRTUAL_PROTOTYPE, {}); + } + createNonEnumerableProperty(path[VIRTUAL_PROTOTYPE], key, sourceProperty); + if (options.real && targetPrototype && (FORCED || !targetPrototype[key])) { + createNonEnumerableProperty(targetPrototype, key, sourceProperty); + } + } + } + }; + }); + var require_es_object_has_own = __commonJS(function() { + 'use strict'; + var $ = require_export(); + var hasOwn2 = require_has_own_property(); + $({ + target: 'Object', + stat: true + }, { + hasOwn: hasOwn2 + }); + }); + var require_has_own = __commonJS(function(exports, module) { + 'use strict'; + require_es_object_has_own(); + var path = require_path(); + module.exports = path.Object.hasOwn; + }); + var require_has_own2 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_has_own(); + module.exports = parent; + }); + var require_has_own3 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_has_own2(); + module.exports = parent; + }); + var require_shared_key = __commonJS(function(exports, module) { + 'use strict'; + var shared = require_shared(); + var uid = require_uid(); + var keys = shared('keys'); + module.exports = function(key) { + return keys[key] || (keys[key] = uid(key)); + }; + }); + var require_correct_prototype_getter = __commonJS(function(exports, module) { + 'use strict'; + var fails = require_fails(); + module.exports = !fails(function() { + function F() {} + F.prototype.constructor = null; + return Object.getPrototypeOf(new F()) !== F.prototype; + }); + }); + var require_object_get_prototype_of = __commonJS(function(exports, module) { + 'use strict'; + var hasOwn2 = require_has_own_property(); + var isCallable = require_is_callable(); + var toObject = require_to_object(); + var sharedKey = require_shared_key(); + var CORRECT_PROTOTYPE_GETTER = require_correct_prototype_getter(); + var IE_PROTO = sharedKey('IE_PROTO'); + var $Object = Object; + var ObjectPrototype = $Object.prototype; + module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function(O) { + var object = toObject(O); + if (hasOwn2(object, IE_PROTO)) { + return object[IE_PROTO]; + } + var constructor = object.constructor; + if (isCallable(constructor) && object instanceof constructor) { + return constructor.prototype; + } + return object instanceof $Object ? ObjectPrototype : null; + }; + }); + var require_math_trunc = __commonJS(function(exports, module) { + 'use strict'; + var ceil = Math.ceil; + var floor = Math.floor; + module.exports = Math.trunc || function trunc(x) { + var n2 = +x; + return (n2 > 0 ? floor : ceil)(n2); + }; + }); + var require_to_integer_or_infinity = __commonJS(function(exports, module) { + 'use strict'; + var trunc = require_math_trunc(); + module.exports = function(argument) { + var number = +argument; + return number !== number || number === 0 ? 0 : trunc(number); + }; + }); + var require_to_absolute_index = __commonJS(function(exports, module) { + 'use strict'; + var toIntegerOrInfinity = require_to_integer_or_infinity(); + var max2 = Math.max; + var min = Math.min; + module.exports = function(index, length) { + var integer = toIntegerOrInfinity(index); + return integer < 0 ? max2(integer + length, 0) : min(integer, length); + }; + }); + var require_to_length = __commonJS(function(exports, module) { + 'use strict'; + var toIntegerOrInfinity = require_to_integer_or_infinity(); + var min = Math.min; + module.exports = function(argument) { + var len = toIntegerOrInfinity(argument); + return len > 0 ? min(len, 9007199254740991) : 0; + }; + }); + var require_length_of_array_like = __commonJS(function(exports, module) { + 'use strict'; + var toLength = require_to_length(); + module.exports = function(obj) { + return toLength(obj.length); + }; + }); + var require_array_includes = __commonJS(function(exports, module) { + 'use strict'; + var toIndexedObject = require_to_indexed_object(); + var toAbsoluteIndex = require_to_absolute_index(); + var lengthOfArrayLike = require_length_of_array_like(); + var createMethod = function createMethod(IS_INCLUDES) { + return function($this, el, fromIndex) { + var O = toIndexedObject($this); + var length = lengthOfArrayLike(O); + if (length === 0) { + return !IS_INCLUDES && -1; + } + var index = toAbsoluteIndex(fromIndex, length); + var value; + if (IS_INCLUDES && el !== el) { + while (length > index) { + value = O[index++]; + if (value !== value) { + return true; + } + } + } else { + for (;length > index; index++) { + if ((IS_INCLUDES || index in O) && O[index] === el) { + return IS_INCLUDES || index || 0; + } + } + } + return !IS_INCLUDES && -1; + }; + }; + module.exports = { + includes: createMethod(true), + indexOf: createMethod(false) + }; + }); + var require_hidden_keys = __commonJS(function(exports, module) { + 'use strict'; + module.exports = {}; + }); + var require_object_keys_internal = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var hasOwn2 = require_has_own_property(); + var toIndexedObject = require_to_indexed_object(); + var indexOf = require_array_includes().indexOf; + var hiddenKeys = require_hidden_keys(); + var push = uncurryThis([].push); + module.exports = function(object, names) { + var O = toIndexedObject(object); + var i = 0; + var result = []; + var key; + for (key in O) { + !hasOwn2(hiddenKeys, key) && hasOwn2(O, key) && push(result, key); + } + while (names.length > i) { + if (hasOwn2(O, key = names[i++])) { + ~indexOf(result, key) || push(result, key); + } + } + return result; + }; + }); + var require_enum_bug_keys = __commonJS(function(exports, module) { + 'use strict'; + module.exports = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; + }); + var require_object_keys = __commonJS(function(exports, module) { + 'use strict'; + var internalObjectKeys = require_object_keys_internal(); + var enumBugKeys = require_enum_bug_keys(); + module.exports = Object.keys || function keys(O) { + return internalObjectKeys(O, enumBugKeys); + }; + }); + var require_object_to_array = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var fails = require_fails(); + var uncurryThis = require_function_uncurry_this(); + var objectGetPrototypeOf = require_object_get_prototype_of(); + var objectKeys = require_object_keys(); + var toIndexedObject = require_to_indexed_object(); + var $propertyIsEnumerable = require_object_property_is_enumerable().f; + var propertyIsEnumerable = uncurryThis($propertyIsEnumerable); + var push = uncurryThis([].push); + var IE_BUG = DESCRIPTORS && fails(function() { + var O = Object.create(null); + O[2] = 2; + return !propertyIsEnumerable(O, 2); + }); + var createMethod = function createMethod(TO_ENTRIES) { + return function(it) { + var O = toIndexedObject(it); + var keys = objectKeys(O); + var IE_WORKAROUND = IE_BUG && objectGetPrototypeOf(O) === null; + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) { + key = keys[i++]; + if (!DESCRIPTORS || (IE_WORKAROUND ? key in O : propertyIsEnumerable(O, key))) { + push(result, TO_ENTRIES ? [ key, O[key] ] : O[key]); + } + } + return result; + }; + }; + module.exports = { + entries: createMethod(true), + values: createMethod(false) + }; + }); + var require_es_object_values = __commonJS(function() { + 'use strict'; + var $ = require_export(); + var $values = require_object_to_array().values; + $({ + target: 'Object', + stat: true + }, { + values: function values2(O) { + return $values(O); + } + }); + }); + var require_values = __commonJS(function(exports, module) { + 'use strict'; + require_es_object_values(); + var path = require_path(); + module.exports = path.Object.values; + }); + var require_values2 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_values(); + module.exports = parent; + }); + var require_values3 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_values2(); + module.exports = parent; + }); + var require_to_string_tag_support = __commonJS(function(exports, module) { + 'use strict'; + var wellKnownSymbol = require_well_known_symbol(); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + var test = {}; + test[TO_STRING_TAG] = 'z'; + module.exports = String(test) === '[object z]'; + }); + var require_classof = __commonJS(function(exports, module) { + 'use strict'; + var TO_STRING_TAG_SUPPORT = require_to_string_tag_support(); + var isCallable = require_is_callable(); + var classofRaw = require_classof_raw(); + var wellKnownSymbol = require_well_known_symbol(); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + var $Object = Object; + var CORRECT_ARGUMENTS = classofRaw(function() { + return arguments; + }()) === 'Arguments'; + var tryGet = function tryGet(it, key) { + try { + return it[key]; + } catch (error) {} + }; + module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function(it) { + var O, tag, result; + return it === void 0 ? 'Undefined' : it === null ? 'Null' : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag : CORRECT_ARGUMENTS ? classofRaw(O) : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; + }; + }); + var require_to_string = __commonJS(function(exports, module) { + 'use strict'; + var classof = require_classof(); + var $String = String; + module.exports = function(argument) { + if (classof(argument) === 'Symbol') { + throw new TypeError('Cannot convert a Symbol value to a string'); + } + return $String(argument); + }; + }); + var require_string_multibyte = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var toIntegerOrInfinity = require_to_integer_or_infinity(); + var toString = require_to_string(); + var requireObjectCoercible = require_require_object_coercible(); + var charAt = uncurryThis(''.charAt); + var charCodeAt = uncurryThis(''.charCodeAt); + var stringSlice = uncurryThis(''.slice); + var createMethod = function createMethod(CONVERT_TO_STRING) { + return function($this, pos) { + var S = toString(requireObjectCoercible($this)); + var position = toIntegerOrInfinity(pos); + var size = S.length; + var first, second; + if (position < 0 || position >= size) { + return CONVERT_TO_STRING ? '' : void 0; + } + first = charCodeAt(S, position); + return first < 55296 || first > 56319 || position + 1 === size || (second = charCodeAt(S, position + 1)) < 56320 || second > 57343 ? CONVERT_TO_STRING ? charAt(S, position) : first : CONVERT_TO_STRING ? stringSlice(S, position, position + 2) : (first - 55296 << 10) + (second - 56320) + 65536; + }; + }; + module.exports = { + codeAt: createMethod(false), + charAt: createMethod(true) + }; + }); + var require_weak_map_basic_detection = __commonJS(function(exports, module) { + 'use strict'; + var globalThis2 = require_global_this(); + var isCallable = require_is_callable(); + var WeakMap2 = globalThis2.WeakMap; + module.exports = isCallable(WeakMap2) && /native code/.test(String(WeakMap2)); + }); + var require_internal_state = __commonJS(function(exports, module) { + 'use strict'; + var NATIVE_WEAK_MAP = require_weak_map_basic_detection(); + var globalThis2 = require_global_this(); + var isObject = require_is_object(); + var createNonEnumerableProperty = require_create_non_enumerable_property(); + var hasOwn2 = require_has_own_property(); + var shared = require_shared_store(); + var sharedKey = require_shared_key(); + var hiddenKeys = require_hidden_keys(); + var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; + var TypeError2 = globalThis2.TypeError; + var WeakMap2 = globalThis2.WeakMap; + var set2; + var get2; + var has; + var enforce = function enforce(it) { + return has(it) ? get2(it) : set2(it, {}); + }; + var getterFor = function getterFor(TYPE) { + return function(it) { + var state; + if (!isObject(it) || (state = get2(it)).type !== TYPE) { + throw new TypeError2('Incompatible receiver, ' + TYPE + ' required'); + } + return state; + }; + }; + if (NATIVE_WEAK_MAP || shared.state) { + store = shared.state || (shared.state = new WeakMap2()); + store.get = store.get; + store.has = store.has; + store.set = store.set; + set2 = function set2(it, metadata) { + if (store.has(it)) { + throw new TypeError2(OBJECT_ALREADY_INITIALIZED); + } + metadata.facade = it; + store.set(it, metadata); + return metadata; + }; + get2 = function get2(it) { + return store.get(it) || {}; + }; + has = function has(it) { + return store.has(it); + }; + } else { + STATE = sharedKey('state'); + hiddenKeys[STATE] = true; + set2 = function set2(it, metadata) { + if (hasOwn2(it, STATE)) { + throw new TypeError2(OBJECT_ALREADY_INITIALIZED); + } + metadata.facade = it; + createNonEnumerableProperty(it, STATE, metadata); + return metadata; + }; + get2 = function get2(it) { + return hasOwn2(it, STATE) ? it[STATE] : {}; + }; + has = function has(it) { + return hasOwn2(it, STATE); + }; + } + var store; + var STATE; + module.exports = { + set: set2, + get: get2, + has: has, + enforce: enforce, + getterFor: getterFor + }; + }); + var require_function_name = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var hasOwn2 = require_has_own_property(); + var FunctionPrototype = Function.prototype; + var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; + var EXISTS = hasOwn2(FunctionPrototype, 'name'); + var PROPER = EXISTS && function something() {}.name === 'something'; + var CONFIGURABLE = EXISTS && (!DESCRIPTORS || DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable); + module.exports = { + EXISTS: EXISTS, + PROPER: PROPER, + CONFIGURABLE: CONFIGURABLE + }; + }); + var require_object_define_properties = __commonJS(function(exports) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var V8_PROTOTYPE_DEFINE_BUG = require_v8_prototype_define_bug(); + var definePropertyModule = require_object_define_property(); + var anObject = require_an_object(); + var toIndexedObject = require_to_indexed_object(); + var objectKeys = require_object_keys(); + exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var props = toIndexedObject(Properties); + var keys = objectKeys(Properties); + var length = keys.length; + var index = 0; + var key; + while (length > index) { + definePropertyModule.f(O, key = keys[index++], props[key]); + } + return O; + }; + }); + var require_html = __commonJS(function(exports, module) { + 'use strict'; + var getBuiltIn = require_get_built_in(); + module.exports = getBuiltIn('document', 'documentElement'); + }); + var require_object_create = __commonJS(function(exports, module) { + 'use strict'; + var anObject = require_an_object(); + var definePropertiesModule = require_object_define_properties(); + var enumBugKeys = require_enum_bug_keys(); + var hiddenKeys = require_hidden_keys(); + var html = require_html(); + var documentCreateElement = require_document_create_element(); + var sharedKey = require_shared_key(); + var GT = '>'; + var LT = '<'; + var PROTOTYPE = 'prototype'; + var SCRIPT = 'script'; + var IE_PROTO = sharedKey('IE_PROTO'); + var EmptyConstructor = function EmptyConstructor() {}; + var scriptTag = function scriptTag(content) { + return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; + }; + var NullProtoObjectViaActiveX = function NullProtoObjectViaActiveX(activeXDocument2) { + activeXDocument2.write(scriptTag('')); + activeXDocument2.close(); + var temp = activeXDocument2.parentWindow.Object; + activeXDocument2 = null; + return temp; + }; + var NullProtoObjectViaIFrame = function NullProtoObjectViaIFrame() { + var iframe = documentCreateElement('iframe'); + var JS = 'java' + SCRIPT + ':'; + var iframeDocument; + iframe.style.display = 'none'; + html.appendChild(iframe); + iframe.src = String(JS); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(scriptTag('document.F=Object')); + iframeDocument.close(); + return iframeDocument.F; + }; + var activeXDocument; + var _NullProtoObject = function NullProtoObject() { + try { + activeXDocument = new ActiveXObject('htmlfile'); + } catch (error) {} + _NullProtoObject = typeof document != 'undefined' ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument); + var length = enumBugKeys.length; + while (length--) { + delete _NullProtoObject[PROTOTYPE][enumBugKeys[length]]; + } + return _NullProtoObject(); + }; + hiddenKeys[IE_PROTO] = true; + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + EmptyConstructor[PROTOTYPE] = anObject(O); + result = new EmptyConstructor(); + EmptyConstructor[PROTOTYPE] = null; + result[IE_PROTO] = O; + } else { + result = _NullProtoObject(); + } + return Properties === void 0 ? result : definePropertiesModule.f(result, Properties); + }; + }); + var require_define_built_in = __commonJS(function(exports, module) { + 'use strict'; + var createNonEnumerableProperty = require_create_non_enumerable_property(); + module.exports = function(target, key, value, options) { + if (options && options.enumerable) { + target[key] = value; + } else { + createNonEnumerableProperty(target, key, value); + } + return target; + }; + }); + var require_iterators_core = __commonJS(function(exports, module) { + 'use strict'; + var fails = require_fails(); + var isCallable = require_is_callable(); + var isObject = require_is_object(); + var create = require_object_create(); + var getPrototypeOf = require_object_get_prototype_of(); + var defineBuiltIn = require_define_built_in(); + var wellKnownSymbol = require_well_known_symbol(); + var IS_PURE = require_is_pure(); + var ITERATOR = wellKnownSymbol('iterator'); + var BUGGY_SAFARI_ITERATORS = false; + var IteratorPrototype; + var PrototypeOfArrayIteratorPrototype; + var arrayIterator; + if ([].keys) { + arrayIterator = [].keys(); + if (!('next' in arrayIterator)) { + BUGGY_SAFARI_ITERATORS = true; + } else { + PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); + if (PrototypeOfArrayIteratorPrototype !== Object.prototype) { + IteratorPrototype = PrototypeOfArrayIteratorPrototype; + } + } + } + var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function() { + var test = {}; + return IteratorPrototype[ITERATOR].call(test) !== test; + }); + if (NEW_ITERATOR_PROTOTYPE) { + IteratorPrototype = {}; + } else if (IS_PURE) { + IteratorPrototype = create(IteratorPrototype); + } + if (!isCallable(IteratorPrototype[ITERATOR])) { + defineBuiltIn(IteratorPrototype, ITERATOR, function() { + return this; + }); + } + module.exports = { + IteratorPrototype: IteratorPrototype, + BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS + }; + }); + var require_object_to_string = __commonJS(function(exports, module) { + 'use strict'; + var TO_STRING_TAG_SUPPORT = require_to_string_tag_support(); + var classof = require_classof(); + module.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() { + return '[object ' + classof(this) + ']'; + }; + }); + var require_set_to_string_tag = __commonJS(function(exports, module) { + 'use strict'; + var TO_STRING_TAG_SUPPORT = require_to_string_tag_support(); + var defineProperty = require_object_define_property().f; + var createNonEnumerableProperty = require_create_non_enumerable_property(); + var hasOwn2 = require_has_own_property(); + var toString = require_object_to_string(); + var wellKnownSymbol = require_well_known_symbol(); + var TO_STRING_TAG = wellKnownSymbol('toStringTag'); + module.exports = function(it, TAG, STATIC, SET_METHOD) { + var target = STATIC ? it : it && it.prototype; + if (target) { + if (!hasOwn2(target, TO_STRING_TAG)) { + defineProperty(target, TO_STRING_TAG, { + configurable: true, + value: TAG + }); + } + if (SET_METHOD && !TO_STRING_TAG_SUPPORT) { + createNonEnumerableProperty(target, 'toString', toString); + } + } + }; + }); + var require_iterators = __commonJS(function(exports, module) { + 'use strict'; + module.exports = {}; + }); + var require_iterator_create_constructor = __commonJS(function(exports, module) { + 'use strict'; + var IteratorPrototype = require_iterators_core().IteratorPrototype; + var create = require_object_create(); + var createPropertyDescriptor = require_create_property_descriptor(); + var setToStringTag = require_set_to_string_tag(); + var Iterators = require_iterators(); + var returnThis = function returnThis() { + return this; + }; + module.exports = function(IteratorConstructor, NAME, next, ENUMERABLE_NEXT) { + var TO_STRING_TAG = NAME + ' Iterator'; + IteratorConstructor.prototype = create(IteratorPrototype, { + next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) + }); + setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); + Iterators[TO_STRING_TAG] = returnThis; + return IteratorConstructor; + }; + }); + var require_function_uncurry_this_accessor = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var aCallable = require_a_callable(); + module.exports = function(object, key, method) { + try { + return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); + } catch (error) {} + }; + }); + var require_is_possible_prototype = __commonJS(function(exports, module) { + 'use strict'; + var isObject = require_is_object(); + module.exports = function(argument) { + return isObject(argument) || argument === null; + }; + }); + var require_a_possible_prototype = __commonJS(function(exports, module) { + 'use strict'; + var isPossiblePrototype = require_is_possible_prototype(); + var $String = String; + var $TypeError = TypeError; + module.exports = function(argument) { + if (isPossiblePrototype(argument)) { + return argument; + } + throw new $TypeError('Can\'t set ' + $String(argument) + ' as a prototype'); + }; + }); + var require_object_set_prototype_of = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThisAccessor = require_function_uncurry_this_accessor(); + var isObject = require_is_object(); + var requireObjectCoercible = require_require_object_coercible(); + var aPossiblePrototype = require_a_possible_prototype(); + module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function() { + var CORRECT_SETTER = false; + var test = {}; + var setter; + try { + setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); + setter(test, []); + CORRECT_SETTER = test instanceof Array; + } catch (error) {} + return function setPrototypeOf(O, proto) { + requireObjectCoercible(O); + aPossiblePrototype(proto); + if (!isObject(O)) { + return O; + } + if (CORRECT_SETTER) { + setter(O, proto); + } else { + O.__proto__ = proto; + } + return O; + }; + }() : void 0); + }); + var require_iterator_define = __commonJS(function(exports, module) { + 'use strict'; + var $ = require_export(); + var call = require_function_call(); + var IS_PURE = require_is_pure(); + var FunctionName = require_function_name(); + var isCallable = require_is_callable(); + var createIteratorConstructor = require_iterator_create_constructor(); + var getPrototypeOf = require_object_get_prototype_of(); + var setPrototypeOf = require_object_set_prototype_of(); + var setToStringTag = require_set_to_string_tag(); + var createNonEnumerableProperty = require_create_non_enumerable_property(); + var defineBuiltIn = require_define_built_in(); + var wellKnownSymbol = require_well_known_symbol(); + var Iterators = require_iterators(); + var IteratorsCore = require_iterators_core(); + var PROPER_FUNCTION_NAME = FunctionName.PROPER; + var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE; + var IteratorPrototype = IteratorsCore.IteratorPrototype; + var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; + var ITERATOR = wellKnownSymbol('iterator'); + var KEYS = 'keys'; + var VALUES = 'values'; + var ENTRIES = 'entries'; + var returnThis = function returnThis() { + return this; + }; + module.exports = function(Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { + createIteratorConstructor(IteratorConstructor, NAME, next); + var getIterationMethod = function getIterationMethod(KIND) { + if (KIND === DEFAULT && defaultIterator) { + return defaultIterator; + } + if (!BUGGY_SAFARI_ITERATORS && KIND && KIND in IterablePrototype) { + return IterablePrototype[KIND]; + } + switch (KIND) { + case KEYS: + return function keys() { + return new IteratorConstructor(this, KIND); + }; + + case VALUES: + return function values2() { + return new IteratorConstructor(this, KIND); + }; + + case ENTRIES: + return function entries() { + return new IteratorConstructor(this, KIND); + }; + } + return function() { + return new IteratorConstructor(this); + }; + }; + var TO_STRING_TAG = NAME + ' Iterator'; + var INCORRECT_VALUES_NAME = false; + var IterablePrototype = Iterable.prototype; + var nativeIterator = IterablePrototype[ITERATOR] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; + var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); + var anyNativeIterator = NAME === 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; + var CurrentIteratorPrototype, methods, KEY; + if (anyNativeIterator) { + CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); + if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { + if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { + if (setPrototypeOf) { + setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); + } else if (!isCallable(CurrentIteratorPrototype[ITERATOR])) { + defineBuiltIn(CurrentIteratorPrototype, ITERATOR, returnThis); + } + } + setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); + if (IS_PURE) { + Iterators[TO_STRING_TAG] = returnThis; + } + } + } + if (PROPER_FUNCTION_NAME && DEFAULT === VALUES && nativeIterator && nativeIterator.name !== VALUES) { + if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) { + createNonEnumerableProperty(IterablePrototype, 'name', VALUES); + } else { + INCORRECT_VALUES_NAME = true; + defaultIterator = function values2() { + return call(nativeIterator, this); + }; + } + } + if (DEFAULT) { + methods = { + values: getIterationMethod(VALUES), + keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), + entries: getIterationMethod(ENTRIES) + }; + if (FORCED) { + for (KEY in methods) { + if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { + defineBuiltIn(IterablePrototype, KEY, methods[KEY]); + } + } + } else { + $({ + target: NAME, + proto: true, + forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME + }, methods); + } + } + if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { + defineBuiltIn(IterablePrototype, ITERATOR, defaultIterator, { + name: DEFAULT + }); + } + Iterators[NAME] = defaultIterator; + return methods; + }; + }); + var require_create_iter_result_object = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(value, done) { + return { + value: value, + done: done + }; + }; + }); + var require_es_string_iterator = __commonJS(function() { + 'use strict'; + var charAt = require_string_multibyte().charAt; + var toString = require_to_string(); + var InternalStateModule = require_internal_state(); + var defineIterator = require_iterator_define(); + var createIterResultObject = require_create_iter_result_object(); + var STRING_ITERATOR = 'String Iterator'; + var setInternalState = InternalStateModule.set; + var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); + defineIterator(String, 'String', function(iterated) { + setInternalState(this, { + type: STRING_ITERATOR, + string: toString(iterated), + index: 0 + }); + }, function next() { + var state = getInternalState(this); + var string = state.string; + var index = state.index; + var point; + if (index >= string.length) { + return createIterResultObject(void 0, true); + } + point = charAt(string, index); + state.index += point.length; + return createIterResultObject(point, false); + }); + }); + var require_iterator_close = __commonJS(function(exports, module) { + 'use strict'; + var call = require_function_call(); + var anObject = require_an_object(); + var getMethod = require_get_method(); + module.exports = function(iterator, kind, value) { + var innerResult, innerError; + anObject(iterator); + try { + innerResult = getMethod(iterator, 'return'); + if (!innerResult) { + if (kind === 'throw') { + throw value; + } + return value; + } + innerResult = call(innerResult, iterator); + } catch (error) { + innerError = true; + innerResult = error; + } + if (kind === 'throw') { + throw value; + } + if (innerError) { + throw innerResult; + } + anObject(innerResult); + return value; + }; + }); + var require_call_with_safe_iteration_closing = __commonJS(function(exports, module) { + 'use strict'; + var anObject = require_an_object(); + var iteratorClose = require_iterator_close(); + module.exports = function(iterator, fn, value, ENTRIES) { + try { + return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); + } catch (error) { + iteratorClose(iterator, 'throw', error); + } + }; + }); + var require_is_array_iterator_method = __commonJS(function(exports, module) { + 'use strict'; + var wellKnownSymbol = require_well_known_symbol(); + var Iterators = require_iterators(); + var ITERATOR = wellKnownSymbol('iterator'); + var ArrayPrototype = Array.prototype; + module.exports = function(it) { + return it !== void 0 && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); + }; + }); + var require_inspect_source = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var isCallable = require_is_callable(); + var store = require_shared_store(); + var functionToString = uncurryThis(Function.toString); + if (!isCallable(store.inspectSource)) { + store.inspectSource = function(it) { + return functionToString(it); + }; + } + module.exports = store.inspectSource; + }); + var require_is_constructor = __commonJS(function(exports, module) { + 'use strict'; + var uncurryThis = require_function_uncurry_this(); + var fails = require_fails(); + var isCallable = require_is_callable(); + var classof = require_classof(); + var getBuiltIn = require_get_built_in(); + var inspectSource = require_inspect_source(); + var noop3 = function noop3() {}; + var construct = getBuiltIn('Reflect', 'construct'); + var constructorRegExp = /^\s*(?:class|function)\b/; + var exec = uncurryThis(constructorRegExp.exec); + var INCORRECT_TO_STRING = !constructorRegExp.test(noop3); + var isConstructorModern = function isConstructor(argument) { + if (!isCallable(argument)) { + return false; + } + try { + construct(noop3, [], argument); + return true; + } catch (error) { + return false; + } + }; + var isConstructorLegacy = function isConstructor(argument) { + if (!isCallable(argument)) { + return false; + } + switch (classof(argument)) { + case 'AsyncFunction': + case 'GeneratorFunction': + case 'AsyncGeneratorFunction': + return false; + } + try { + return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument)); + } catch (error) { + return true; + } + }; + isConstructorLegacy.sham = true; + module.exports = !construct || fails(function() { + var called; + return isConstructorModern(isConstructorModern.call) || !isConstructorModern(Object) || !isConstructorModern(function() { + called = true; + }) || called; + }) ? isConstructorLegacy : isConstructorModern; + }); + var require_create_property = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var definePropertyModule = require_object_define_property(); + var createPropertyDescriptor = require_create_property_descriptor(); + module.exports = function(object, key, value) { + if (DESCRIPTORS) { + definePropertyModule.f(object, key, createPropertyDescriptor(0, value)); + } else { + object[key] = value; + } + }; + }); + var require_is_array = __commonJS(function(exports, module) { + 'use strict'; + var classof = require_classof_raw(); + module.exports = Array.isArray || function isArray(argument) { + return classof(argument) === 'Array'; + }; + }); + var require_array_set_length = __commonJS(function(exports, module) { + 'use strict'; + var DESCRIPTORS = require_descriptors(); + var isArray = require_is_array(); + var $TypeError = TypeError; + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function() { + if (this !== void 0) { + return true; + } + try { + Object.defineProperty([], 'length', { + writable: false + }).length = 1; + } catch (error) { + return error instanceof TypeError; + } + }(); + module.exports = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function(O, length) { + if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) { + throw new $TypeError('Cannot set read only .length'); + } + return O.length = length; + } : function(O, length) { + return O.length = length; + }; + }); + var require_get_iterator_method = __commonJS(function(exports, module) { + 'use strict'; + var classof = require_classof(); + var getMethod = require_get_method(); + var isNullOrUndefined = require_is_null_or_undefined(); + var Iterators = require_iterators(); + var wellKnownSymbol = require_well_known_symbol(); + var ITERATOR = wellKnownSymbol('iterator'); + module.exports = function(it) { + if (!isNullOrUndefined(it)) { + return getMethod(it, ITERATOR) || getMethod(it, '@@iterator') || Iterators[classof(it)]; + } + }; + }); + var require_get_iterator = __commonJS(function(exports, module) { + 'use strict'; + var call = require_function_call(); + var aCallable = require_a_callable(); + var anObject = require_an_object(); + var tryToString = require_try_to_string(); + var getIteratorMethod = require_get_iterator_method(); + var $TypeError = TypeError; + module.exports = function(argument, usingIterator) { + var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator; + if (aCallable(iteratorMethod)) { + return anObject(call(iteratorMethod, argument)); + } + throw new $TypeError(tryToString(argument) + ' is not iterable'); + }; + }); + var require_array_from = __commonJS(function(exports, module) { + 'use strict'; + var bind = require_function_bind_context(); + var call = require_function_call(); + var toObject = require_to_object(); + var callWithSafeIterationClosing = require_call_with_safe_iteration_closing(); + var isArrayIteratorMethod = require_is_array_iterator_method(); + var isConstructor = require_is_constructor(); + var lengthOfArrayLike = require_length_of_array_like(); + var createProperty = require_create_property(); + var setArrayLength = require_array_set_length(); + var getIterator = require_get_iterator(); + var getIteratorMethod = require_get_iterator_method(); + var $Array = Array; + module.exports = function from(arrayLike) { + var O = toObject(arrayLike); + var IS_CONSTRUCTOR = isConstructor(this); + var argumentsLength = arguments.length; + var mapfn = argumentsLength > 1 ? arguments[1] : void 0; + var mapping = mapfn !== void 0; + if (mapping) { + mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : void 0); + } + var iteratorMethod = getIteratorMethod(O); + var index = 0; + var length, result, step, iterator, next, value; + if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) { + result = IS_CONSTRUCTOR ? new this() : []; + iterator = getIterator(O, iteratorMethod); + next = iterator.next; + for (;!(step = call(next, iterator)).done; index++) { + value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [ step.value, index ], true) : step.value; + createProperty(result, index, value); + } + } else { + length = lengthOfArrayLike(O); + result = IS_CONSTRUCTOR ? new this(length) : $Array(length); + for (;length > index; index++) { + value = mapping ? mapfn(O[index], index) : O[index]; + createProperty(result, index, value); + } + } + setArrayLength(result, index); + return result; + }; + }); + var require_check_correctness_of_iteration = __commonJS(function(exports, module) { + 'use strict'; + var wellKnownSymbol = require_well_known_symbol(); + var ITERATOR = wellKnownSymbol('iterator'); + var SAFE_CLOSING = false; + try { + called = 0; + iteratorWithReturn = { + next: function next() { + return { + done: !!called++ + }; + }, + return: function _return() { + SAFE_CLOSING = true; + } + }; + iteratorWithReturn[ITERATOR] = function() { + return this; + }; + Array.from(iteratorWithReturn, function() { + throw 2; + }); + } catch (error) {} + var called; + var iteratorWithReturn; + module.exports = function(exec, SKIP_CLOSING) { + try { + if (!SKIP_CLOSING && !SAFE_CLOSING) { + return false; + } + } catch (error) { + return false; + } + var ITERATION_SUPPORT = false; + try { + var object = {}; + object[ITERATOR] = function() { + return { + next: function next() { + return { + done: ITERATION_SUPPORT = true + }; + } + }; + }; + exec(object); + } catch (error) {} + return ITERATION_SUPPORT; + }; + }); + var require_es_array_from = __commonJS(function() { + 'use strict'; + var $ = require_export(); + var from = require_array_from(); + var checkCorrectnessOfIteration = require_check_correctness_of_iteration(); + var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function(iterable) { + Array.from(iterable); + }); + $({ + target: 'Array', + stat: true, + forced: INCORRECT_ITERATION + }, { + from: from + }); + }); + var require_from = __commonJS(function(exports, module) { + 'use strict'; + require_es_string_iterator(); + require_es_array_from(); + var path = require_path(); + module.exports = path.Array.from; + }); + var require_from2 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_from(); + module.exports = parent; + }); + var require_from3 = __commonJS(function(exports, module) { + 'use strict'; + var parent = require_from2(); + module.exports = parent; + }); + var require_utils = __commonJS(function(exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + function isIdentStart(c4) { + return c4 >= 'a' && c4 <= 'z' || c4 >= 'A' && c4 <= 'Z' || c4 === '-' || c4 === '_'; + } + exports.isIdentStart = isIdentStart; + function isIdent(c4) { + return c4 >= 'a' && c4 <= 'z' || c4 >= 'A' && c4 <= 'Z' || c4 >= '0' && c4 <= '9' || c4 === '-' || c4 === '_'; + } + exports.isIdent = isIdent; + function isHex(c4) { + return c4 >= 'a' && c4 <= 'f' || c4 >= 'A' && c4 <= 'F' || c4 >= '0' && c4 <= '9'; + } + exports.isHex = isHex; + function escapeIdentifier(s) { + var len = s.length; + var result = ''; + var i = 0; + while (i < len) { + var chr = s.charAt(i); + if (exports.identSpecialChars[chr]) { + result += '\\' + chr; + } else { + if (!(chr === '_' || chr === '-' || chr >= 'A' && chr <= 'Z' || chr >= 'a' && chr <= 'z' || i !== 0 && chr >= '0' && chr <= '9')) { + var charCode = chr.charCodeAt(0); + if ((charCode & 63488) === 55296) { + var extraCharCode = s.charCodeAt(i++); + if ((charCode & 64512) !== 55296 || (extraCharCode & 64512) !== 56320) { + throw Error('UCS-2(decode): illegal sequence'); + } + charCode = ((charCode & 1023) << 10) + (extraCharCode & 1023) + 65536; + } + result += '\\' + charCode.toString(16) + ' '; + } else { + result += chr; + } + } + i++; + } + return result; + } + exports.escapeIdentifier = escapeIdentifier; + function escapeStr(s) { + var len = s.length; + var result = ''; + var i = 0; + var replacement; + while (i < len) { + var chr = s.charAt(i); + if (chr === '"') { + chr = '\\"'; + } else if (chr === '\\') { + chr = '\\\\'; + } else if ((replacement = exports.strReplacementsRev[chr]) !== void 0) { + chr = replacement; + } + result += chr; + i++; + } + return '"' + result + '"'; + } + exports.escapeStr = escapeStr; + exports.identSpecialChars = { + '!': true, + '"': true, + '#': true, + $: true, + '%': true, + '&': true, + '\'': true, + '(': true, + ')': true, + '*': true, + '+': true, + ',': true, + '.': true, + '/': true, + ';': true, + '<': true, + '=': true, + '>': true, + '?': true, + '@': true, + '[': true, + '\\': true, + ']': true, + '^': true, + '`': true, + '{': true, + '|': true, + '}': true, + '~': true + }; + exports.strReplacementsRev = { + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\f': '\\f', + '\v': '\\v' + }; + exports.singleQuoteEscapeChars = { + n: '\n', + r: '\r', + t: '\t', + f: '\f', + '\\': '\\', + '\'': '\'' + }; + exports.doubleQuotesEscapeChars = { + n: '\n', + r: '\r', + t: '\t', + f: '\f', + '\\': '\\', + '"': '"' + }; + }); + var require_parser_context = __commonJS(function(exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + var utils_1 = require_utils(); + function parseCssSelector(str, pos, pseudos, attrEqualityMods, ruleNestingOperators, substitutesEnabled) { + var l = str.length; + var chr = ''; + function getStr(quote, escapeTable) { + var result = ''; + pos++; + chr = str.charAt(pos); + while (pos < l) { + if (chr === quote) { + pos++; + return result; + } else if (chr === '\\') { + pos++; + chr = str.charAt(pos); + var esc = void 0; + if (chr === quote) { + result += quote; + } else if ((esc = escapeTable[chr]) !== void 0) { + result += esc; + } else if (utils_1.isHex(chr)) { + var hex = chr; + pos++; + chr = str.charAt(pos); + while (utils_1.isHex(chr)) { + hex += chr; + pos++; + chr = str.charAt(pos); + } + if (chr === ' ') { + pos++; + chr = str.charAt(pos); + } + result += String.fromCharCode(parseInt(hex, 16)); + continue; + } else { + result += chr; + } + } else { + result += chr; + } + pos++; + chr = str.charAt(pos); + } + return result; + } + function getIdent() { + var result = ''; + chr = str.charAt(pos); + while (pos < l) { + if (utils_1.isIdent(chr)) { + result += chr; + } else if (chr === '\\') { + pos++; + if (pos >= l) { + throw Error('Expected symbol but end of file reached.'); + } + chr = str.charAt(pos); + if (utils_1.identSpecialChars[chr]) { + result += chr; + } else if (utils_1.isHex(chr)) { + var hex = chr; + pos++; + chr = str.charAt(pos); + while (utils_1.isHex(chr)) { + hex += chr; + pos++; + chr = str.charAt(pos); + } + if (chr === ' ') { + pos++; + chr = str.charAt(pos); + } + result += String.fromCharCode(parseInt(hex, 16)); + continue; + } else { + result += chr; + } + } else { + return result; + } + pos++; + chr = str.charAt(pos); + } + return result; + } + function skipWhitespace() { + chr = str.charAt(pos); + var result = false; + while (chr === ' ' || chr === '\t' || chr === '\n' || chr === '\r' || chr === '\f') { + result = true; + pos++; + chr = str.charAt(pos); + } + return result; + } + function parse3() { + var res = parseSelector(); + if (pos < l) { + throw Error('Rule expected but "' + str.charAt(pos) + '" found.'); + } + return res; + } + function parseSelector() { + var selector = parseSingleSelector(); + if (!selector) { + return null; + } + var res = selector; + chr = str.charAt(pos); + while (chr === ',') { + pos++; + skipWhitespace(); + if (res.type !== 'selectors') { + res = { + type: 'selectors', + selectors: [ selector ] + }; + } + selector = parseSingleSelector(); + if (!selector) { + throw Error('Rule expected after ",".'); + } + res.selectors.push(selector); + } + return res; + } + function parseSingleSelector() { + skipWhitespace(); + var selector = { + type: 'ruleSet' + }; + var rule = parseRule(); + if (!rule) { + return null; + } + var currentRule = selector; + while (rule) { + rule.type = 'rule'; + currentRule.rule = rule; + currentRule = rule; + skipWhitespace(); + chr = str.charAt(pos); + if (pos >= l || chr === ',' || chr === ')') { + break; + } + if (ruleNestingOperators[chr]) { + var op = chr; + pos++; + skipWhitespace(); + rule = parseRule(); + if (!rule) { + throw Error('Rule expected after "' + op + '".'); + } + rule.nestingOperator = op; + } else { + rule = parseRule(); + if (rule) { + rule.nestingOperator = null; + } + } + } + return selector; + } + function parseRule() { + var rule = null; + while (pos < l) { + chr = str.charAt(pos); + if (chr === '*') { + pos++; + (rule = rule || {}).tagName = '*'; + } else if (utils_1.isIdentStart(chr) || chr === '\\') { + (rule = rule || {}).tagName = getIdent(); + } else if (chr === '.') { + pos++; + rule = rule || {}; + (rule.classNames = rule.classNames || []).push(getIdent()); + } else if (chr === '#') { + pos++; + (rule = rule || {}).id = getIdent(); + } else if (chr === '[') { + pos++; + skipWhitespace(); + var attr = { + name: getIdent() + }; + skipWhitespace(); + if (chr === ']') { + pos++; + } else { + var operator = ''; + if (attrEqualityMods[chr]) { + operator = chr; + pos++; + chr = str.charAt(pos); + } + if (pos >= l) { + throw Error('Expected "=" but end of file reached.'); + } + if (chr !== '=') { + throw Error('Expected "=" but "' + chr + '" found.'); + } + attr.operator = operator + '='; + pos++; + skipWhitespace(); + var attrValue = ''; + attr.valueType = 'string'; + if (chr === '"') { + attrValue = getStr('"', utils_1.doubleQuotesEscapeChars); + } else if (chr === '\'') { + attrValue = getStr('\'', utils_1.singleQuoteEscapeChars); + } else if (substitutesEnabled && chr === '$') { + pos++; + attrValue = getIdent(); + attr.valueType = 'substitute'; + } else { + while (pos < l) { + if (chr === ']') { + break; + } + attrValue += chr; + pos++; + chr = str.charAt(pos); + } + attrValue = attrValue.trim(); + } + skipWhitespace(); + if (pos >= l) { + throw Error('Expected "]" but end of file reached.'); + } + if (chr !== ']') { + throw Error('Expected "]" but "' + chr + '" found.'); + } + pos++; + attr.value = attrValue; + } + rule = rule || {}; + (rule.attrs = rule.attrs || []).push(attr); + } else if (chr === ':') { + pos++; + var pseudoName = getIdent(); + var pseudo = { + name: pseudoName + }; + if (chr === '(') { + pos++; + var value = ''; + skipWhitespace(); + if (pseudos[pseudoName] === 'selector') { + pseudo.valueType = 'selector'; + value = parseSelector(); + } else { + pseudo.valueType = pseudos[pseudoName] || 'string'; + if (chr === '"') { + value = getStr('"', utils_1.doubleQuotesEscapeChars); + } else if (chr === '\'') { + value = getStr('\'', utils_1.singleQuoteEscapeChars); + } else if (substitutesEnabled && chr === '$') { + pos++; + value = getIdent(); + pseudo.valueType = 'substitute'; + } else { + while (pos < l) { + if (chr === ')') { + break; + } + value += chr; + pos++; + chr = str.charAt(pos); + } + value = value.trim(); + } + skipWhitespace(); + } + if (pos >= l) { + throw Error('Expected ")" but end of file reached.'); + } + if (chr !== ')') { + throw Error('Expected ")" but "' + chr + '" found.'); + } + pos++; + pseudo.value = value; + } + rule = rule || {}; + (rule.pseudos = rule.pseudos || []).push(pseudo); + } else { + break; + } + } + return rule; + } + return parse3(); + } + exports.parseCssSelector = parseCssSelector; + }); + var require_render = __commonJS(function(exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + var utils_1 = require_utils(); + function renderEntity(entity) { + var res = ''; + switch (entity.type) { + case 'ruleSet': + var currentEntity = entity.rule; + var parts = []; + while (currentEntity) { + if (currentEntity.nestingOperator) { + parts.push(currentEntity.nestingOperator); + } + parts.push(renderEntity(currentEntity)); + currentEntity = currentEntity.rule; + } + res = parts.join(' '); + break; + + case 'selectors': + res = entity.selectors.map(renderEntity).join(', '); + break; + + case 'rule': + if (entity.tagName) { + if (entity.tagName === '*') { + res = '*'; + } else { + res = utils_1.escapeIdentifier(entity.tagName); + } + } + if (entity.id) { + res += '#' + utils_1.escapeIdentifier(entity.id); + } + if (entity.classNames) { + res += entity.classNames.map(function(cn) { + return '.' + utils_1.escapeIdentifier(cn); + }).join(''); + } + if (entity.attrs) { + res += entity.attrs.map(function(attr) { + if ('operator' in attr) { + if (attr.valueType === 'substitute') { + return '[' + utils_1.escapeIdentifier(attr.name) + attr.operator + '$' + attr.value + ']'; + } else { + return '[' + utils_1.escapeIdentifier(attr.name) + attr.operator + utils_1.escapeStr(attr.value) + ']'; + } + } else { + return '[' + utils_1.escapeIdentifier(attr.name) + ']'; + } + }).join(''); + } + if (entity.pseudos) { + res += entity.pseudos.map(function(pseudo) { + if (pseudo.valueType) { + if (pseudo.valueType === 'selector') { + return ':' + utils_1.escapeIdentifier(pseudo.name) + '(' + renderEntity(pseudo.value) + ')'; + } else if (pseudo.valueType === 'substitute') { + return ':' + utils_1.escapeIdentifier(pseudo.name) + '($' + pseudo.value + ')'; + } else if (pseudo.valueType === 'numeric') { + return ':' + utils_1.escapeIdentifier(pseudo.name) + '(' + pseudo.value + ')'; + } else { + return ':' + utils_1.escapeIdentifier(pseudo.name) + '(' + utils_1.escapeIdentifier(pseudo.value) + ')'; + } + } else { + return ':' + utils_1.escapeIdentifier(pseudo.name); + } + }).join(''); + } + break; + + default: + throw Error('Unknown entity type: "' + entity.type + '".'); + } + return res; + } + exports.renderEntity = renderEntity; + }); + var require_lib = __commonJS(function(exports) { + 'use strict'; + Object.defineProperty(exports, '__esModule', { + value: true + }); + var parser_context_1 = require_parser_context(); + var render_1 = require_render(); + var CssSelectorParser2 = function() { + function CssSelectorParser3() { + this.pseudos = {}; + this.attrEqualityMods = {}; + this.ruleNestingOperators = {}; + this.substitutesEnabled = false; + } + CssSelectorParser3.prototype.registerSelectorPseudos = function() { + var pseudos = []; + for (var _i = 0; _i < arguments.length; _i++) { + pseudos[_i] = arguments[_i]; + } + for (var _a = 0, pseudos_1 = pseudos; _a < pseudos_1.length; _a++) { + var pseudo = pseudos_1[_a]; + this.pseudos[pseudo] = 'selector'; + } + return this; + }; + CssSelectorParser3.prototype.unregisterSelectorPseudos = function() { + var pseudos = []; + for (var _i = 0; _i < arguments.length; _i++) { + pseudos[_i] = arguments[_i]; + } + for (var _a = 0, pseudos_2 = pseudos; _a < pseudos_2.length; _a++) { + var pseudo = pseudos_2[_a]; + delete this.pseudos[pseudo]; + } + return this; + }; + CssSelectorParser3.prototype.registerNumericPseudos = function() { + var pseudos = []; + for (var _i = 0; _i < arguments.length; _i++) { + pseudos[_i] = arguments[_i]; + } + for (var _a = 0, pseudos_3 = pseudos; _a < pseudos_3.length; _a++) { + var pseudo = pseudos_3[_a]; + this.pseudos[pseudo] = 'numeric'; + } + return this; + }; + CssSelectorParser3.prototype.unregisterNumericPseudos = function() { + var pseudos = []; + for (var _i = 0; _i < arguments.length; _i++) { + pseudos[_i] = arguments[_i]; + } + for (var _a = 0, pseudos_4 = pseudos; _a < pseudos_4.length; _a++) { + var pseudo = pseudos_4[_a]; + delete this.pseudos[pseudo]; + } + return this; + }; + CssSelectorParser3.prototype.registerNestingOperators = function() { + var operators = []; + for (var _i = 0; _i < arguments.length; _i++) { + operators[_i] = arguments[_i]; + } + for (var _a = 0, operators_1 = operators; _a < operators_1.length; _a++) { + var operator = operators_1[_a]; + this.ruleNestingOperators[operator] = true; + } + return this; + }; + CssSelectorParser3.prototype.unregisterNestingOperators = function() { + var operators = []; + for (var _i = 0; _i < arguments.length; _i++) { + operators[_i] = arguments[_i]; + } + for (var _a = 0, operators_2 = operators; _a < operators_2.length; _a++) { + var operator = operators_2[_a]; + delete this.ruleNestingOperators[operator]; + } + return this; + }; + CssSelectorParser3.prototype.registerAttrEqualityMods = function() { + var mods = []; + for (var _i = 0; _i < arguments.length; _i++) { + mods[_i] = arguments[_i]; + } + for (var _a = 0, mods_1 = mods; _a < mods_1.length; _a++) { + var mod = mods_1[_a]; + this.attrEqualityMods[mod] = true; + } + return this; + }; + CssSelectorParser3.prototype.unregisterAttrEqualityMods = function() { + var mods = []; + for (var _i = 0; _i < arguments.length; _i++) { + mods[_i] = arguments[_i]; + } + for (var _a = 0, mods_2 = mods; _a < mods_2.length; _a++) { + var mod = mods_2[_a]; + delete this.attrEqualityMods[mod]; + } + return this; + }; + CssSelectorParser3.prototype.enableSubstitutes = function() { + this.substitutesEnabled = true; + return this; + }; + CssSelectorParser3.prototype.disableSubstitutes = function() { + this.substitutesEnabled = false; + return this; + }; + CssSelectorParser3.prototype.parse = function(str) { + return parser_context_1.parseCssSelector(str, 0, this.pseudos, this.attrEqualityMods, this.ruleNestingOperators, this.substitutesEnabled); + }; + CssSelectorParser3.prototype.render = function(path) { + return render_1.renderEntity(path).trim(); + }; + return CssSelectorParser3; + }(); + exports.CssSelectorParser = CssSelectorParser2; + }); + var require_doT = __commonJS(function(exports, module) { + (function() { + 'use strict'; + var doT2 = { + name: 'doT', + version: '1.1.1', + templateSettings: { + evaluate: /\{\{([\s\S]+?(\}?)+)\}\}/g, + interpolate: /\{\{=([\s\S]+?)\}\}/g, + encode: /\{\{!([\s\S]+?)\}\}/g, + use: /\{\{#([\s\S]+?)\}\}/g, + useParams: /(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g, + define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g, + defineParams: /^\s*([\w$]+):([\s\S]+)/, + conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g, + iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g, + varname: 'it', + strip: true, + append: true, + selfcontained: false, + doNotSkipEncoded: false + }, + template: void 0, + compile: void 0, + log: true + }; + (function() { + if ((typeof globalThis === 'undefined' ? 'undefined' : _typeof(globalThis)) === 'object') { + return; + } + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function get() { + return this; + }, + configurable: true + }); + __magic__.globalThis = __magic__; + delete Object.prototype.__magic__; + } catch (e) { + window.globalThis = function() { + if (typeof self !== 'undefined') { + return self; + } + if (typeof window !== 'undefined') { + return window; + } + if (typeof global !== 'undefined') { + return global; + } + if (typeof this !== 'undefined') { + return this; + } + throw new Error('Unable to locate global `this`'); + }(); + } + })(); + doT2.encodeHTMLSource = function(doNotSkipEncoded) { + var encodeHTMLRules = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + '\'': ''', + '/': '/' + }, matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g; + return function(code) { + return code ? code.toString().replace(matchHTML, function(m3) { + return encodeHTMLRules[m3] || m3; + }) : ''; + }; + }; + if (typeof module !== 'undefined' && module.exports) { + module.exports = doT2; + } else if (typeof define === 'function' && define.amd) { + define(function() { + return doT2; + }); + } else { + globalThis.doT = doT2; + } + var startend = { + append: { + start: '\'+(', + end: ')+\'', + startencode: '\'+encodeHTML(' + }, + split: { + start: '\';out+=(', + end: ');out+=\'', + startencode: '\';out+=encodeHTML(' + } + }, skip = /$^/; + function resolveDefs(c4, block, def) { + return (typeof block === 'string' ? block : block.toString()).replace(c4.define || skip, function(m3, code, assign, value) { + if (code.indexOf('def.') === 0) { + code = code.substring(4); + } + if (!(code in def)) { + if (assign === ':') { + if (c4.defineParams) { + value.replace(c4.defineParams, function(m4, param, v) { + def[code] = { + arg: param, + text: v + }; + }); + } + if (!(code in def)) { + def[code] = value; + } + } else { + new Function('def', 'def[\'' + code + '\']=' + value)(def); + } + } + return ''; + }).replace(c4.use || skip, function(m3, code) { + if (c4.useParams) { + code = code.replace(c4.useParams, function(m4, s, d2, param) { + if (def[d2] && def[d2].arg && param) { + var rw = (d2 + ':' + param).replace(/'|\\/g, '_'); + def.__exp = def.__exp || {}; + def.__exp[rw] = def[d2].text.replace(new RegExp('(^|[^\\w$])' + def[d2].arg + '([^\\w$])', 'g'), '$1' + param + '$2'); + return s + 'def.__exp[\'' + rw + '\']'; + } + }); + } + var v = new Function('def', 'return ' + code)(def); + return v ? resolveDefs(c4, v, def) : v; + }); + } + function unescape(code) { + return code.replace(/\\('|\\)/g, '$1').replace(/[\r\t\n]/g, ' '); + } + doT2.template = function(tmpl, c4, def) { + c4 = c4 || doT2.templateSettings; + var cse = c4.append ? startend.append : startend.split, needhtmlencode, sid = 0, indv, str = c4.use || c4.define ? resolveDefs(c4, tmpl, def || {}) : tmpl; + str = ('var out=\'' + (c4.strip ? str.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g, ' ').replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g, '') : str).replace(/'|\\/g, '\\$&').replace(c4.interpolate || skip, function(m3, code) { + return cse.start + unescape(code) + cse.end; + }).replace(c4.encode || skip, function(m3, code) { + needhtmlencode = true; + return cse.startencode + unescape(code) + cse.end; + }).replace(c4.conditional || skip, function(m3, elsecase, code) { + return elsecase ? code ? '\';}else if(' + unescape(code) + '){out+=\'' : '\';}else{out+=\'' : code ? '\';if(' + unescape(code) + '){out+=\'' : '\';}out+=\''; + }).replace(c4.iterate || skip, function(m3, iterate, vname, iname) { + if (!iterate) { + return '\';} } out+=\''; + } + sid += 1; + indv = iname || 'i' + sid; + iterate = unescape(iterate); + return '\';var arr' + sid + '=' + iterate + ';if(arr' + sid + '){var ' + vname + ',' + indv + '=-1,l' + sid + '=arr' + sid + '.length-1;while(' + indv + ' 0 ? 1 : -1; + }; + }); + var require_sign = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented()() ? Math.sign : require_shim(); + }); + var require_to_integer = __commonJS(function(exports, module) { + 'use strict'; + var sign = require_sign(); + var abs = Math.abs; + var floor = Math.floor; + module.exports = function(value) { + if (isNaN(value)) { + return 0; + } + value = Number(value); + if (value === 0 || !isFinite(value)) { + return value; + } + return sign(value) * floor(abs(value)); + }; + }); + var require_to_pos_integer = __commonJS(function(exports, module) { + 'use strict'; + var toInteger = require_to_integer(); + var max2 = Math.max; + module.exports = function(value) { + return max2(0, toInteger(value)); + }; + }); + var require_resolve_length = __commonJS(function(exports, module) { + 'use strict'; + var toPosInt = require_to_pos_integer(); + module.exports = function(optsLength, fnLength, isAsync) { + var length; + if (isNaN(optsLength)) { + length = fnLength; + if (!(length >= 0)) { + return 1; + } + if (isAsync && length) { + return length - 1; + } + return length; + } + if (optsLength === false) { + return false; + } + return toPosInt(optsLength); + }; + }); + var require_valid_callable = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError(fn + ' is not a function'); + } + return fn; + }; + }); + var require_valid_value = __commonJS(function(exports, module) { + 'use strict'; + var isValue = require_is_value(); + module.exports = function(value) { + if (!isValue(value)) { + throw new TypeError('Cannot use null or undefined'); + } + return value; + }; + }); + var require_iterate = __commonJS(function(exports, module) { + 'use strict'; + var callable = require_valid_callable(); + var value = require_valid_value(); + var bind = Function.prototype.bind; + var call = Function.prototype.call; + var keys = Object.keys; + var objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; + module.exports = function(method, defVal) { + return function(obj, cb) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable(cb); + list = keys(obj); + if (compareFn) { + list.sort(typeof compareFn === 'function' ? bind.call(compareFn, obj) : void 0); + } + if (typeof method !== 'function') { + method = list[method]; + } + return call.call(method, list, function(key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) { + return defVal; + } + return call.call(cb, thisArg, obj[key], key, obj, index); + }); + }; + }; + }); + var require_for_each = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_iterate()('forEach'); + }); + var require_registered_extensions = __commonJS(function() { + 'use strict'; + }); + var require_is_implemented2 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function() { + var assign = Object.assign, obj; + if (typeof assign !== 'function') { + return false; + } + obj = { + foo: 'raz' + }; + assign(obj, { + bar: 'dwa' + }, { + trzy: 'trzy' + }); + return obj.foo + obj.bar + obj.trzy === 'razdwatrzy'; + }; + }); + var require_is_implemented3 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function() { + try { + Object.keys('primitive'); + return true; + } catch (e) { + return false; + } + }; + }); + var require_shim2 = __commonJS(function(exports, module) { + 'use strict'; + var isValue = require_is_value(); + var keys = Object.keys; + module.exports = function(object) { + return keys(isValue(object) ? Object(object) : object); + }; + }); + var require_keys = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented3()() ? Object.keys : require_shim2(); + }); + var require_shim3 = __commonJS(function(exports, module) { + 'use strict'; + var keys = require_keys(); + var value = require_valid_value(); + var max2 = Math.max; + module.exports = function(dest, src) { + var error, i, length = max2(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function assign(key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) { + error = e; + } + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== void 0) { + throw error; + } + return dest; + }; + }); + var require_assign = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented2()() ? Object.assign : require_shim3(); + }); + var require_is_object2 = __commonJS(function(exports, module) { + 'use strict'; + var isValue = require_is_value(); + var map = { + function: true, + object: true + }; + module.exports = function(value) { + return isValue(value) && map[_typeof(value)] || false; + }; + }); + var require_custom = __commonJS(function(exports, module) { + 'use strict'; + var assign = require_assign(); + var isObject = require_is_object2(); + var isValue = require_is_value(); + var captureStackTrace = Error.captureStackTrace; + module.exports = function(message) { + var err2 = new Error(message), code = arguments[1], ext = arguments[2]; + if (!isValue(ext)) { + if (isObject(code)) { + ext = code; + code = null; + } + } + if (isValue(ext)) { + assign(err2, ext); + } + if (isValue(code)) { + err2.code = code; + } + if (captureStackTrace) { + captureStackTrace(err2, module.exports); + } + return err2; + }; + }); + var require_mixin = __commonJS(function(exports, module) { + 'use strict'; + var value = require_valid_value(); + var defineProperty = Object.defineProperty; + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var getOwnPropertyNames = Object.getOwnPropertyNames; + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + module.exports = function(target, source) { + var error, sourceObject = Object(value(source)); + target = Object(value(target)); + getOwnPropertyNames(sourceObject).forEach(function(name) { + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { + error = e; + } + }); + if (typeof getOwnPropertySymbols === 'function') { + getOwnPropertySymbols(sourceObject).forEach(function(symbol) { + try { + defineProperty(target, symbol, getOwnPropertyDescriptor(source, symbol)); + } catch (e) { + error = e; + } + }); + } + if (error !== void 0) { + throw error; + } + return target; + }; + }); + var require_define_length = __commonJS(function(exports, module) { + 'use strict'; + var toPosInt = require_to_pos_integer(); + var test = function test(arg1, arg2) { + return arg2; + }; + var desc; + var defineProperty; + var generate; + var mixin; + try { + Object.defineProperty(test, 'length', { + configurable: true, + writable: false, + enumerable: false, + value: 1 + }); + } catch (ignore) {} + if (test.length === 1) { + desc = { + configurable: true, + writable: false, + enumerable: false + }; + defineProperty = Object.defineProperty; + module.exports = function(fn, length) { + length = toPosInt(length); + if (fn.length === length) { + return fn; + } + desc.value = length; + return defineProperty(fn, 'length', desc); + }; + } else { + mixin = require_mixin(); + generate = function() { + var cache2 = []; + return function(length) { + var args, i = 0; + if (cache2[length]) { + return cache2[length]; + } + args = []; + while (length--) { + args.push('a' + (++i).toString(36)); + } + return new Function('fn', 'return function (' + args.join(', ') + ') { return fn.apply(this, arguments); };'); + }; + }(); + module.exports = function(src, length) { + var target; + length = toPosInt(length); + if (src.length === length) { + return src; + } + target = generate(length)(src); + try { + mixin(target, src); + } catch (ignore) {} + return target; + }; + } + }); + var require_is = __commonJS(function(exports, module) { + 'use strict'; + var _undefined = void 0; + module.exports = function(value) { + return value !== _undefined && value !== null; + }; + }); + var require_is2 = __commonJS(function(exports, module) { + 'use strict'; + var isValue = require_is(); + var possibleTypes = { + object: true, + function: true, + undefined: true + }; + module.exports = function(value) { + if (!isValue(value)) { + return false; + } + return hasOwnProperty.call(possibleTypes, _typeof(value)); + }; + }); + var require_is3 = __commonJS(function(exports, module) { + 'use strict'; + var isObject = require_is2(); + module.exports = function(value) { + if (!isObject(value)) { + return false; + } + try { + if (!value.constructor) { + return false; + } + return value.constructor.prototype === value; + } catch (error) { + return false; + } + }; + }); + var require_is4 = __commonJS(function(exports, module) { + 'use strict'; + var isPrototype = require_is3(); + module.exports = function(value) { + if (typeof value !== 'function') { + return false; + } + if (!hasOwnProperty.call(value, 'length')) { + return false; + } + try { + if (typeof value.length !== 'number') { + return false; + } + if (typeof value.call !== 'function') { + return false; + } + if (typeof value.apply !== 'function') { + return false; + } + } catch (error) { + return false; + } + return !isPrototype(value); + }; + }); + var require_is5 = __commonJS(function(exports, module) { + 'use strict'; + var isFunction = require_is4(); + var classRe = /^\s*class[\s{/}]/; + var functionToString = Function.prototype.toString; + module.exports = function(value) { + if (!isFunction(value)) { + return false; + } + if (classRe.test(functionToString.call(value))) { + return false; + } + return true; + }; + }); + var require_is_implemented4 = __commonJS(function(exports, module) { + 'use strict'; + var str = 'razdwatrzy'; + module.exports = function() { + if (typeof str.contains !== 'function') { + return false; + } + return str.contains('dwa') === true && str.contains('foo') === false; + }; + }); + var require_shim4 = __commonJS(function(exports, module) { + 'use strict'; + var indexOf = String.prototype.indexOf; + module.exports = function(searchString) { + return indexOf.call(this, searchString, arguments[1]) > -1; + }; + }); + var require_contains = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented4()() ? String.prototype.contains : require_shim4(); + }); + var require_d = __commonJS(function(exports, module) { + 'use strict'; + var isValue = require_is(); + var isPlainFunction = require_is5(); + var assign = require_assign(); + var normalizeOpts = require_normalize_options(); + var contains3 = require_contains(); + var d2 = module.exports = function(dscr, value) { + var c4, e, w, options, desc; + if (arguments.length < 2 || typeof dscr !== 'string') { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (isValue(dscr)) { + c4 = contains3.call(dscr, 'c'); + e = contains3.call(dscr, 'e'); + w = contains3.call(dscr, 'w'); + } else { + c4 = w = true; + e = false; + } + desc = { + value: value, + configurable: c4, + enumerable: e, + writable: w + }; + return !options ? desc : assign(normalizeOpts(options), desc); + }; + d2.gs = function(dscr, get2, set2) { + var c4, e, options, desc; + if (typeof dscr !== 'string') { + options = set2; + set2 = get2; + get2 = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (!isValue(get2)) { + get2 = void 0; + } else if (!isPlainFunction(get2)) { + options = get2; + get2 = set2 = void 0; + } else if (!isValue(set2)) { + set2 = void 0; + } else if (!isPlainFunction(set2)) { + options = set2; + set2 = void 0; + } + if (isValue(dscr)) { + c4 = contains3.call(dscr, 'c'); + e = contains3.call(dscr, 'e'); + } else { + c4 = true; + e = false; + } + desc = { + get: get2, + set: set2, + configurable: c4, + enumerable: e + }; + return !options ? desc : assign(normalizeOpts(options), desc); + }; + }); + var require_event_emitter = __commonJS(function(exports, module) { + 'use strict'; + var d2 = require_d(); + var callable = require_valid_callable(); + var apply = Function.prototype.apply; + var call = Function.prototype.call; + var create = Object.create; + var defineProperty = Object.defineProperty; + var defineProperties = Object.defineProperties; + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + var descriptor = { + configurable: true, + enumerable: false, + writable: true + }; + var on; + var once; + var off; + var emit; + var methods; + var descriptors; + var base; + on = function on(type2, listener) { + var data; + callable(listener); + if (!hasOwnProperty2.call(this, '__ee__')) { + data = descriptor.value = create(null); + defineProperty(this, '__ee__', descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type2]) { + data[type2] = listener; + } else if (_typeof(data[type2]) === 'object') { + data[type2].push(listener); + } else { + data[type2] = [ data[type2], listener ]; + } + return this; + }; + once = function once(type2, listener) { + var _once, self2; + callable(listener); + self2 = this; + on.call(this, type2, _once = function once2() { + off.call(self2, type2, _once); + apply.call(listener, this, arguments); + }); + _once.__eeOnceListener__ = listener; + return this; + }; + off = function off(type2, listener) { + var data, listeners, candidate, i; + callable(listener); + if (!hasOwnProperty2.call(this, '__ee__')) { + return this; + } + data = this.__ee__; + if (!data[type2]) { + return this; + } + listeners = data[type2]; + if (_typeof(listeners) === 'object') { + for (i = 0; candidate = listeners[i]; ++i) { + if (candidate === listener || candidate.__eeOnceListener__ === listener) { + if (listeners.length === 2) { + data[type2] = listeners[i ? 0 : 1]; + } else { + listeners.splice(i, 1); + } + } + } + } else { + if (listeners === listener || listeners.__eeOnceListener__ === listener) { + delete data[type2]; + } + } + return this; + }; + emit = function emit(type2) { + var i, l, listener, listeners, args; + if (!hasOwnProperty2.call(this, '__ee__')) { + return; + } + listeners = this.__ee__[type2]; + if (!listeners) { + return; + } + if (_typeof(listeners) === 'object') { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + listeners = listeners.slice(); + for (i = 0; listener = listeners[i]; ++i) { + apply.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call.call(listeners, this); + break; + + case 2: + call.call(listeners, this, arguments[1]); + break; + + case 3: + call.call(listeners, this, arguments[1], arguments[2]); + break; + + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply.call(listeners, this, args); + } + } + }; + methods = { + on: on, + once: once, + off: off, + emit: emit + }; + descriptors = { + on: d2(on), + once: d2(once), + off: d2(off), + emit: d2(emit) + }; + base = defineProperties({}, descriptors); + module.exports = exports = function exports(o) { + return o == null ? create(base) : defineProperties(Object(o), descriptors); + }; + exports.methods = methods; + }); + var require_is_implemented5 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function() { + var from = Array.from, arr, result; + if (typeof from !== 'function') { + return false; + } + arr = [ 'raz', 'dwa' ]; + result = from(arr); + return Boolean(result && result !== arr && result[1] === 'dwa'); + }; + }); + var require_is_implemented6 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function() { + if ((typeof globalThis === 'undefined' ? 'undefined' : _typeof(globalThis)) !== 'object') { + return false; + } + if (!globalThis) { + return false; + } + return globalThis.Array === Array; + }; + }); + var require_implementation = __commonJS(function(exports, module) { + var naiveFallback = function naiveFallback() { + if ((typeof self === 'undefined' ? 'undefined' : _typeof(self)) === 'object' && self) { + return self; + } + if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window) { + return window; + } + throw new Error('Unable to resolve global `this`'); + }; + module.exports = function() { + if (this) { + return this; + } + try { + Object.defineProperty(Object.prototype, '__global__', { + get: function get() { + return this; + }, + configurable: true + }); + } catch (error) { + return naiveFallback(); + } + try { + if (!__global__) { + return naiveFallback(); + } + return __global__; + } finally { + delete Object.prototype.__global__; + } + }(); + }); + var require_global_this2 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented6()() ? globalThis : require_implementation(); + }); + var require_is_implemented7 = __commonJS(function(exports, module) { + 'use strict'; + var global2 = require_global_this2(); + var validTypes = { + object: true, + symbol: true + }; + module.exports = function() { + var Symbol2 = global2.Symbol; + var symbol; + if (typeof Symbol2 !== 'function') { + return false; + } + symbol = Symbol2('test symbol'); + try { + String(symbol); + } catch (e) { + return false; + } + if (!validTypes[_typeof(Symbol2.iterator)]) { + return false; + } + if (!validTypes[_typeof(Symbol2.toPrimitive)]) { + return false; + } + if (!validTypes[_typeof(Symbol2.toStringTag)]) { + return false; + } + return true; + }; + }); + var require_is_symbol2 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(value) { + if (!value) { + return false; + } + if (_typeof(value) === 'symbol') { + return true; + } + if (!value.constructor) { + return false; + } + if (value.constructor.name !== 'Symbol') { + return false; + } + return value[value.constructor.toStringTag] === 'Symbol'; + }; + }); + var require_validate_symbol = __commonJS(function(exports, module) { + 'use strict'; + var isSymbol = require_is_symbol2(); + module.exports = function(value) { + if (!isSymbol(value)) { + throw new TypeError(value + ' is not a symbol'); + } + return value; + }; + }); + var require_generate_name = __commonJS(function(exports, module) { + 'use strict'; + var d2 = require_d(); + var create = Object.create; + var defineProperty = Object.defineProperty; + var objPrototype = Object.prototype; + var created = create(null); + module.exports = function(desc) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc + (postfix || '')]) { + ++postfix; + } + desc += postfix || ''; + created[desc] = true; + name = '@@' + desc; + defineProperty(objPrototype, name, d2.gs(null, function(value) { + if (ie11BugWorkaround) { + return; + } + ie11BugWorkaround = true; + defineProperty(this, name, d2(value)); + ie11BugWorkaround = false; + })); + return name; + }; + }); + var require_standard_symbols = __commonJS(function(exports, module) { + 'use strict'; + var d2 = require_d(); + var NativeSymbol = require_global_this2().Symbol; + module.exports = function(SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + hasInstance: d2('', NativeSymbol && NativeSymbol.hasInstance || SymbolPolyfill('hasInstance')), + isConcatSpreadable: d2('', NativeSymbol && NativeSymbol.isConcatSpreadable || SymbolPolyfill('isConcatSpreadable')), + iterator: d2('', NativeSymbol && NativeSymbol.iterator || SymbolPolyfill('iterator')), + match: d2('', NativeSymbol && NativeSymbol.match || SymbolPolyfill('match')), + replace: d2('', NativeSymbol && NativeSymbol.replace || SymbolPolyfill('replace')), + search: d2('', NativeSymbol && NativeSymbol.search || SymbolPolyfill('search')), + species: d2('', NativeSymbol && NativeSymbol.species || SymbolPolyfill('species')), + split: d2('', NativeSymbol && NativeSymbol.split || SymbolPolyfill('split')), + toPrimitive: d2('', NativeSymbol && NativeSymbol.toPrimitive || SymbolPolyfill('toPrimitive')), + toStringTag: d2('', NativeSymbol && NativeSymbol.toStringTag || SymbolPolyfill('toStringTag')), + unscopables: d2('', NativeSymbol && NativeSymbol.unscopables || SymbolPolyfill('unscopables')) + }); + }; + }); + var require_symbol_registry = __commonJS(function(exports, module) { + 'use strict'; + var d2 = require_d(); + var validateSymbol = require_validate_symbol(); + var registry = Object.create(null); + module.exports = function(SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + for: d2(function(key) { + if (registry[key]) { + return registry[key]; + } + return registry[key] = SymbolPolyfill(String(key)); + }), + keyFor: d2(function(symbol) { + var key; + validateSymbol(symbol); + for (key in registry) { + if (registry[key] === symbol) { + return key; + } + } + return void 0; + }) + }); + }; + }); + var require_polyfill = __commonJS(function(exports, module) { + 'use strict'; + var d2 = require_d(); + var validateSymbol = require_validate_symbol(); + var NativeSymbol = require_global_this2().Symbol; + var generateName = require_generate_name(); + var setupStandardSymbols = require_standard_symbols(); + var setupSymbolRegistry = require_symbol_registry(); + var create = Object.create; + var defineProperties = Object.defineProperties; + var defineProperty = Object.defineProperty; + var SymbolPolyfill; + var HiddenSymbol; + var isNativeSafe; + if (typeof NativeSymbol === 'function') { + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) {} + } else { + NativeSymbol = null; + } + HiddenSymbol = function Symbol2(description) { + if (this instanceof HiddenSymbol) { + throw new TypeError('Symbol is not a constructor'); + } + return SymbolPolyfill(description); + }; + module.exports = SymbolPolyfill = function Symbol2(description) { + var symbol; + if (this instanceof Symbol2) { + throw new TypeError('Symbol is not a constructor'); + } + if (isNativeSafe) { + return NativeSymbol(description); + } + symbol = create(HiddenSymbol.prototype); + description = description === void 0 ? '' : String(description); + return defineProperties(symbol, { + __description__: d2('', description), + __name__: d2('', generateName(description)) + }); + }; + setupStandardSymbols(SymbolPolyfill); + setupSymbolRegistry(SymbolPolyfill); + defineProperties(HiddenSymbol.prototype, { + constructor: d2(SymbolPolyfill), + toString: d2('', function() { + return this.__name__; + }) + }); + defineProperties(SymbolPolyfill.prototype, { + toString: d2(function() { + return 'Symbol (' + validateSymbol(this).__description__ + ')'; + }), + valueOf: d2(function() { + return validateSymbol(this); + }) + }); + defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d2('', function() { + var symbol = validateSymbol(this); + if (_typeof(symbol) === 'symbol') { + return symbol; + } + return symbol.toString(); + })); + defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d2('c', 'Symbol')); + defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d2('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); + defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d2('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); + }); + var require_es6_symbol = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented7()() ? require_global_this2().Symbol : require_polyfill(); + }); + var require_is_arguments = __commonJS(function(exports, module) { + 'use strict'; + var objToString = Object.prototype.toString; + var id = objToString.call(function() { + return arguments; + }()); + module.exports = function(value) { + return objToString.call(value) === id; + }; + }); + var require_is_function = __commonJS(function(exports, module) { + 'use strict'; + var objToString = Object.prototype.toString; + var isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); + module.exports = function(value) { + return typeof value === 'function' && isFunctionStringTag(objToString.call(value)); + }; + }); + var require_is_string = __commonJS(function(exports, module) { + 'use strict'; + var objToString = Object.prototype.toString; + var id = objToString.call(''); + module.exports = function(value) { + return typeof value === 'string' || value && _typeof(value) === 'object' && (value instanceof String || objToString.call(value) === id) || false; + }; + }); + var require_shim5 = __commonJS(function(exports, module) { + 'use strict'; + var iteratorSymbol = require_es6_symbol().iterator; + var isArguments = require_is_arguments(); + var isFunction = require_is_function(); + var toPosInt = require_to_pos_integer(); + var callable = require_valid_callable(); + var validValue = require_valid_value(); + var isValue = require_is_value(); + var isString2 = require_is_string(); + var isArray = Array.isArray; + var call = Function.prototype.call; + var desc = { + configurable: true, + enumerable: true, + writable: true, + value: null + }; + var defineProperty = Object.defineProperty; + module.exports = function(arrayLike) { + var mapFn = arguments[1], thisArg = arguments[2], Context2, i, j, arr, length, code, iterator, result, getIterator, value; + arrayLike = Object(validValue(arrayLike)); + if (isValue(mapFn)) { + callable(mapFn); + } + if (!this || this === Array || !isFunction(this)) { + if (!mapFn) { + if (isArguments(arrayLike)) { + length = arrayLike.length; + if (length !== 1) { + return Array.apply(null, arrayLike); + } + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (isArray(arrayLike)) { + arr = new Array(length = arrayLike.length); + for (i = 0; i < length; ++i) { + arr[i] = arrayLike[i]; + } + return arr; + } + } + arr = []; + } else { + Context2 = this; + } + if (!isArray(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== void 0) { + iterator = callable(getIterator).call(arrayLike); + if (Context2) { + arr = new Context2(); + } + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (Context2) { + desc.value = value; + defineProperty(arr, i, desc); + } else { + arr[i] = value; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (isString2(arrayLike)) { + length = arrayLike.length; + if (Context2) { + arr = new Context2(); + } + for (i = 0, j = 0; i < length; ++i) { + value = arrayLike[i]; + if (i + 1 < length) { + code = value.charCodeAt(0); + if (code >= 55296 && code <= 56319) { + value += arrayLike[++i]; + } + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (Context2) { + desc.value = value; + defineProperty(arr, j, desc); + } else { + arr[j] = value; + } + ++j; + } + length = j; + } + } + if (length === void 0) { + length = toPosInt(arrayLike.length); + if (Context2) { + arr = new Context2(length); + } + for (i = 0; i < length; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context2) { + desc.value = value; + defineProperty(arr, i, desc); + } else { + arr[i] = value; + } + } + } + if (Context2) { + desc.value = null; + arr.length = length; + } + return arr; + }; + }); + var require_from4 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented5()() ? Array.from : require_shim5(); + }); + var require_to_array = __commonJS(function(exports, module) { + 'use strict'; + var from = require_from4(); + var isArray = Array.isArray; + module.exports = function(arrayLike) { + return isArray(arrayLike) ? arrayLike : from(arrayLike); + }; + }); + var require_resolve_resolve = __commonJS(function(exports, module) { + 'use strict'; + var toArray2 = require_to_array(); + var isValue = require_is_value(); + var callable = require_valid_callable(); + var slice = Array.prototype.slice; + var resolveArgs; + resolveArgs = function resolveArgs(args) { + return this.map(function(resolve, i) { + return resolve ? resolve(args[i]) : args[i]; + }).concat(slice.call(args, this.length)); + }; + module.exports = function(resolvers) { + resolvers = toArray2(resolvers); + resolvers.forEach(function(resolve) { + if (isValue(resolve)) { + callable(resolve); + } + }); + return resolveArgs.bind(resolvers); + }; + }); + var require_resolve_normalize = __commonJS(function(exports, module) { + 'use strict'; + var callable = require_valid_callable(); + module.exports = function(userNormalizer) { + var normalizer; + if (typeof userNormalizer === 'function') { + return { + set: userNormalizer, + get: userNormalizer + }; + } + normalizer = { + get: callable(userNormalizer.get) + }; + if (userNormalizer.set !== void 0) { + normalizer.set = callable(userNormalizer.set); + if (userNormalizer['delete']) { + normalizer['delete'] = callable(userNormalizer['delete']); + } + if (userNormalizer.clear) { + normalizer.clear = callable(userNormalizer.clear); + } + return normalizer; + } + normalizer.set = normalizer.get; + return normalizer; + }; + }); + var require_configure_map = __commonJS(function(exports, module) { + 'use strict'; + var customError = require_custom(); + var defineLength = require_define_length(); + var d2 = require_d(); + var ee = require_event_emitter().methods; + var resolveResolve = require_resolve_resolve(); + var resolveNormalize = require_resolve_normalize(); + var apply = Function.prototype.apply; + var call = Function.prototype.call; + var create = Object.create; + var defineProperties = Object.defineProperties; + var _on = ee.on; + var emit = ee.emit; + module.exports = function(original, length, options) { + var cache2 = create(null), conf, memLength, get2, set2, del, _clear, extDel, extGet, extHas, normalizer, getListeners, setListeners, deleteListeners, memoized, resolve; + if (length !== false) { + memLength = length; + } else if (isNaN(original.length)) { + memLength = 1; + } else { + memLength = original.length; + } + if (options.normalizer) { + normalizer = resolveNormalize(options.normalizer); + get2 = normalizer.get; + set2 = normalizer.set; + del = normalizer['delete']; + _clear = normalizer.clear; + } + if (options.resolvers != null) { + resolve = resolveResolve(options.resolvers); + } + if (get2) { + memoized = defineLength(function(arg) { + var id, result, args = arguments; + if (resolve) { + args = resolve(args); + } + id = get2(args); + if (id !== null) { + if (hasOwnProperty.call(cache2, id)) { + if (getListeners) { + conf.emit('get', id, args, this); + } + return cache2[id]; + } + } + if (args.length === 1) { + result = call.call(original, this, args[0]); + } else { + result = apply.call(original, this, args); + } + if (id === null) { + id = get2(args); + if (id !== null) { + throw customError('Circular invocation', 'CIRCULAR_INVOCATION'); + } + id = set2(args); + } else if (hasOwnProperty.call(cache2, id)) { + throw customError('Circular invocation', 'CIRCULAR_INVOCATION'); + } + cache2[id] = result; + if (setListeners) { + conf.emit('set', id, null, result); + } + return result; + }, memLength); + } else if (length === 0) { + memoized = function memoized() { + var result; + if (hasOwnProperty.call(cache2, 'data')) { + if (getListeners) { + conf.emit('get', 'data', arguments, this); + } + return cache2.data; + } + if (arguments.length) { + result = apply.call(original, this, arguments); + } else { + result = call.call(original, this); + } + if (hasOwnProperty.call(cache2, 'data')) { + throw customError('Circular invocation', 'CIRCULAR_INVOCATION'); + } + cache2.data = result; + if (setListeners) { + conf.emit('set', 'data', null, result); + } + return result; + }; + } else { + memoized = function memoized(arg) { + var result, args = arguments, id; + if (resolve) { + args = resolve(arguments); + } + id = String(args[0]); + if (hasOwnProperty.call(cache2, id)) { + if (getListeners) { + conf.emit('get', id, args, this); + } + return cache2[id]; + } + if (args.length === 1) { + result = call.call(original, this, args[0]); + } else { + result = apply.call(original, this, args); + } + if (hasOwnProperty.call(cache2, id)) { + throw customError('Circular invocation', 'CIRCULAR_INVOCATION'); + } + cache2[id] = result; + if (setListeners) { + conf.emit('set', id, null, result); + } + return result; + }; + } + conf = { + original: original, + memoized: memoized, + profileName: options.profileName, + get: function get(args) { + if (resolve) { + args = resolve(args); + } + if (get2) { + return get2(args); + } + return String(args[0]); + }, + has: function has(id) { + return hasOwnProperty.call(cache2, id); + }, + delete: function _delete(id) { + var result; + if (!hasOwnProperty.call(cache2, id)) { + return; + } + if (del) { + del(id); + } + result = cache2[id]; + delete cache2[id]; + if (deleteListeners) { + conf.emit('delete', id, result); + } + }, + clear: function clear() { + var oldCache = cache2; + if (_clear) { + _clear(); + } + cache2 = create(null); + conf.emit('clear', oldCache); + }, + on: function on(type2, listener) { + if (type2 === 'get') { + getListeners = true; + } else if (type2 === 'set') { + setListeners = true; + } else if (type2 === 'delete') { + deleteListeners = true; + } + return _on.call(this, type2, listener); + }, + emit: emit, + updateEnv: function updateEnv() { + original = conf.original; + } + }; + if (get2) { + extDel = defineLength(function(arg) { + var id, args = arguments; + if (resolve) { + args = resolve(args); + } + id = get2(args); + if (id === null) { + return; + } + conf['delete'](id); + }, memLength); + } else if (length === 0) { + extDel = function extDel() { + return conf['delete']('data'); + }; + } else { + extDel = function extDel(arg) { + if (resolve) { + arg = resolve(arguments)[0]; + } + return conf['delete'](arg); + }; + } + extGet = defineLength(function() { + var id, args = arguments; + if (length === 0) { + return cache2.data; + } + if (resolve) { + args = resolve(args); + } + if (get2) { + id = get2(args); + } else { + id = String(args[0]); + } + return cache2[id]; + }); + extHas = defineLength(function() { + var id, args = arguments; + if (length === 0) { + return conf.has('data'); + } + if (resolve) { + args = resolve(args); + } + if (get2) { + id = get2(args); + } else { + id = String(args[0]); + } + if (id === null) { + return false; + } + return conf.has(id); + }); + defineProperties(memoized, { + __memoized__: d2(true), + delete: d2(extDel), + clear: d2(conf.clear), + _get: d2(extGet), + _has: d2(extHas) + }); + return conf; + }; + }); + var require_plain = __commonJS(function(exports, module) { + 'use strict'; + var callable = require_valid_callable(); + var forEach = require_for_each(); + var extensions = require_registered_extensions(); + var configure4 = require_configure_map(); + var resolveLength = require_resolve_length(); + module.exports = function self2(fn) { + var options, length, conf; + callable(fn); + options = Object(arguments[1]); + if (options.async && options.promise) { + throw new Error('Options \'async\' and \'promise\' cannot be used together'); + } + if (hasOwnProperty.call(fn, '__memoized__') && !options.force) { + return fn; + } + length = resolveLength(options.length, fn.length, options.async && extensions.async); + conf = configure4(fn, length, options); + forEach(extensions, function(extFn, name) { + if (options[name]) { + extFn(options[name], conf, options); + } + }); + if (self2.__profiler__) { + self2.__profiler__(conf); + } + conf.updateEnv(); + return conf.memoized; + }; + }); + var require_primitive = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(args) { + var id, i, length = args.length; + if (!length) { + return '\x02'; + } + id = String(args[i = 0]); + while (--length) { + id += '\x01' + args[++i]; + } + return id; + }; + }); + var require_get_primitive_fixed = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(length) { + if (!length) { + return function() { + return ''; + }; + } + return function(args) { + var id = String(args[0]), i = 0, currentLength = length; + while (--currentLength) { + id += '\x01' + args[++i]; + } + return id; + }; + }; + }); + var require_is_implemented8 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function() { + var numberIsNaN = Number.isNaN; + if (typeof numberIsNaN !== 'function') { + return false; + } + return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); + }; + }); + var require_shim6 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(value) { + return value !== value; + }; + }); + var require_is_nan = __commonJS(function(exports, module) { + 'use strict'; + module.exports = require_is_implemented8()() ? Number.isNaN : require_shim6(); + }); + var require_e_index_of = __commonJS(function(exports, module) { + 'use strict'; + var numberIsNaN = require_is_nan(); + var toPosInt = require_to_pos_integer(); + var value = require_valid_value(); + var indexOf = Array.prototype.indexOf; + var objHasOwnProperty = Object.prototype.hasOwnProperty; + var abs = Math.abs; + var floor = Math.floor; + module.exports = function(searchElement) { + var i, length, fromIndex, val; + if (!numberIsNaN(searchElement)) { + return indexOf.apply(this, arguments); + } + length = toPosInt(value(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) { + fromIndex = 0; + } else if (fromIndex >= 0) { + fromIndex = floor(fromIndex); + } else { + fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + } + for (i = fromIndex; i < length; ++i) { + if (objHasOwnProperty.call(this, i)) { + val = this[i]; + if (numberIsNaN(val)) { + return i; + } + } + } + return -1; + }; + }); + var require_get = __commonJS(function(exports, module) { + 'use strict'; + var indexOf = require_e_index_of(); + var create = Object.create; + module.exports = function() { + var lastId = 0, map = [], cache2 = create(null); + return { + get: function get(args) { + var index = 0, set2 = map, i, length = args.length; + if (length === 0) { + return set2[length] || null; + } + if (set2 = set2[length]) { + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return null; + } + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return null; + } + return set2[1][i] || null; + } + return null; + }, + set: function set(args) { + var index = 0, set2 = map, i, length = args.length; + if (length === 0) { + set2[length] = ++lastId; + } else { + if (!set2[length]) { + set2[length] = [ [], [] ]; + } + set2 = set2[length]; + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + i = set2[0].push(args[index]) - 1; + set2[1].push([ [], [] ]); + } + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + i = set2[0].push(args[index]) - 1; + } + set2[1][i] = ++lastId; + } + cache2[lastId] = args; + return lastId; + }, + delete: function _delete(id) { + var index = 0, set2 = map, i, args = cache2[id], length = args.length, path = []; + if (length === 0) { + delete set2[length]; + } else if (set2 = set2[length]) { + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return; + } + path.push(set2, i); + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return; + } + id = set2[1][i]; + set2[0].splice(i, 1); + set2[1].splice(i, 1); + while (!set2[0].length && path.length) { + i = path.pop(); + set2 = path.pop(); + set2[0].splice(i, 1); + set2[1].splice(i, 1); + } + } + delete cache2[id]; + }, + clear: function clear() { + map = []; + cache2 = create(null); + } + }; + }; + }); + var require_get_1 = __commonJS(function(exports, module) { + 'use strict'; + var indexOf = require_e_index_of(); + module.exports = function() { + var lastId = 0, argsMap = [], cache2 = []; + return { + get: function get(args) { + var index = indexOf.call(argsMap, args[0]); + return index === -1 ? null : cache2[index]; + }, + set: function set(args) { + argsMap.push(args[0]); + cache2.push(++lastId); + return lastId; + }, + delete: function _delete(id) { + var index = indexOf.call(cache2, id); + if (index !== -1) { + argsMap.splice(index, 1); + cache2.splice(index, 1); + } + }, + clear: function clear() { + argsMap = []; + cache2 = []; + } + }; + }; + }); + var require_get_fixed = __commonJS(function(exports, module) { + 'use strict'; + var indexOf = require_e_index_of(); + var create = Object.create; + module.exports = function(length) { + var lastId = 0, map = [ [], [] ], cache2 = create(null); + return { + get: function get(args) { + var index = 0, set2 = map, i; + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return null; + } + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return null; + } + return set2[1][i] || null; + }, + set: function set(args) { + var index = 0, set2 = map, i; + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + i = set2[0].push(args[index]) - 1; + set2[1].push([ [], [] ]); + } + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + i = set2[0].push(args[index]) - 1; + } + set2[1][i] = ++lastId; + cache2[lastId] = args; + return lastId; + }, + delete: function _delete(id) { + var index = 0, set2 = map, i, path = [], args = cache2[id]; + while (index < length - 1) { + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return; + } + path.push(set2, i); + set2 = set2[1][i]; + ++index; + } + i = indexOf.call(set2[0], args[index]); + if (i === -1) { + return; + } + id = set2[1][i]; + set2[0].splice(i, 1); + set2[1].splice(i, 1); + while (!set2[0].length && path.length) { + i = path.pop(); + set2 = path.pop(); + set2[0].splice(i, 1); + set2[1].splice(i, 1); + } + delete cache2[id]; + }, + clear: function clear() { + map = [ [], [] ]; + cache2 = create(null); + } + }; + }; + }); + var require_map = __commonJS(function(exports, module) { + 'use strict'; + var callable = require_valid_callable(); + var forEach = require_for_each(); + var call = Function.prototype.call; + module.exports = function(obj, cb) { + var result = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function(value, key, targetObj, index) { + result[key] = call.call(cb, thisArg, value, key, targetObj, index); + }); + return result; + }; + }); + var require_next_tick = __commonJS(function(exports, module) { + 'use strict'; + var ensureCallable = function ensureCallable(fn) { + if (typeof fn !== 'function') { + throw new TypeError(fn + ' is not a function'); + } + return fn; + }; + var byObserver = function byObserver(Observer) { + var node = document.createTextNode(''), queue2, currentQueue, i = 0; + new Observer(function() { + var callback; + if (!queue2) { + if (!currentQueue) { + return; + } + queue2 = currentQueue; + } else if (currentQueue) { + queue2 = currentQueue.concat(queue2); + } + currentQueue = queue2; + queue2 = null; + if (typeof currentQueue === 'function') { + callback = currentQueue; + currentQueue = null; + callback(); + return; + } + node.data = i = ++i % 2; + while (currentQueue) { + callback = currentQueue.shift(); + if (!currentQueue.length) { + currentQueue = null; + } + callback(); + } + }).observe(node, { + characterData: true + }); + return function(fn) { + ensureCallable(fn); + if (queue2) { + if (typeof queue2 === 'function') { + queue2 = [ queue2, fn ]; + } else { + queue2.push(fn); + } + return; + } + queue2 = fn; + node.data = i = ++i % 2; + }; + }; + module.exports = function() { + if ((typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && process && typeof process.nextTick === 'function') { + return process.nextTick; + } + if (typeof queueMicrotask === 'function') { + return function(cb) { + queueMicrotask(ensureCallable(cb)); + }; + } + if ((typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object' && document) { + if (typeof MutationObserver === 'function') { + return byObserver(MutationObserver); + } + if (typeof WebKitMutationObserver === 'function') { + return byObserver(WebKitMutationObserver); + } + } + if (typeof setImmediate === 'function') { + return function(cb) { + setImmediate(ensureCallable(cb)); + }; + } + if (typeof setTimeout === 'function' || (typeof setTimeout === 'undefined' ? 'undefined' : _typeof(setTimeout)) === 'object') { + return function(cb) { + setTimeout(ensureCallable(cb), 0); + }; + } + return null; + }(); + }); + var require_async = __commonJS(function() { + 'use strict'; + var aFrom = require_from4(); + var objectMap = require_map(); + var mixin = require_mixin(); + var defineLength = require_define_length(); + var nextTick = require_next_tick(); + var slice = Array.prototype.slice; + var apply = Function.prototype.apply; + var create = Object.create; + require_registered_extensions().async = function(tbi, conf) { + var waiting = create(null), cache2 = create(null), base = conf.memoized, original = conf.original, currentCallback, currentContext, currentArgs; + conf.memoized = defineLength(function(arg) { + var args = arguments, last2 = args[args.length - 1]; + if (typeof last2 === 'function') { + currentCallback = last2; + args = slice.call(args, 0, -1); + } + return base.apply(currentContext = this, currentArgs = args); + }, base); + try { + mixin(conf.memoized, base); + } catch (ignore) {} + conf.on('get', function(id) { + var cb, context, args; + if (!currentCallback) { + return; + } + if (waiting[id]) { + if (typeof waiting[id] === 'function') { + waiting[id] = [ waiting[id], currentCallback ]; + } else { + waiting[id].push(currentCallback); + } + currentCallback = null; + return; + } + cb = currentCallback; + context = currentContext; + args = currentArgs; + currentCallback = currentContext = currentArgs = null; + nextTick(function() { + var data; + if (hasOwnProperty.call(cache2, id)) { + data = cache2[id]; + conf.emit('getasync', id, args, context); + apply.call(cb, data.context, data.args); + } else { + currentCallback = cb; + currentContext = context; + currentArgs = args; + base.apply(context, args); + } + }); + }); + conf.original = function() { + var args, cb, origCb, result; + if (!currentCallback) { + return apply.call(original, this, arguments); + } + args = aFrom(arguments); + cb = function self2(err2) { + var cb2, args2, id = self2.id; + if (id == null) { + nextTick(apply.bind(self2, this, arguments)); + return void 0; + } + delete self2.id; + cb2 = waiting[id]; + delete waiting[id]; + if (!cb2) { + return void 0; + } + args2 = aFrom(arguments); + if (conf.has(id)) { + if (err2) { + conf['delete'](id); + } else { + cache2[id] = { + context: this, + args: args2 + }; + conf.emit('setasync', id, typeof cb2 === 'function' ? 1 : cb2.length); + } + } + if (typeof cb2 === 'function') { + result = apply.call(cb2, this, args2); + } else { + cb2.forEach(function(cb3) { + result = apply.call(cb3, this, args2); + }, this); + } + return result; + }; + origCb = currentCallback; + currentCallback = currentContext = currentArgs = null; + args.push(cb); + result = apply.call(original, this, args); + cb.cb = origCb; + currentCallback = cb; + return result; + }; + conf.on('set', function(id) { + if (!currentCallback) { + conf['delete'](id); + return; + } + if (waiting[id]) { + if (typeof waiting[id] === 'function') { + waiting[id] = [ waiting[id], currentCallback.cb ]; + } else { + waiting[id].push(currentCallback.cb); + } + } else { + waiting[id] = currentCallback.cb; + } + delete currentCallback.cb; + currentCallback.id = id; + currentCallback = null; + }); + conf.on('delete', function(id) { + var result; + if (hasOwnProperty.call(waiting, id)) { + return; + } + if (!cache2[id]) { + return; + } + result = cache2[id]; + delete cache2[id]; + conf.emit('deleteasync', id, slice.call(result.args, 1)); + }); + conf.on('clear', function() { + var oldCache = cache2; + cache2 = create(null); + conf.emit('clearasync', objectMap(oldCache, function(data) { + return slice.call(data.args, 1); + })); + }); + }; + }); + var require_primitive_set = __commonJS(function(exports, module) { + 'use strict'; + var forEach = Array.prototype.forEach; + var create = Object.create; + module.exports = function(arg) { + var set2 = create(null); + forEach.call(arguments, function(name) { + set2[name] = true; + }); + return set2; + }; + }); + var require_is_callable2 = __commonJS(function(exports, module) { + 'use strict'; + module.exports = function(obj) { + return typeof obj === 'function'; + }; + }); + var require_validate_stringifiable = __commonJS(function(exports, module) { + 'use strict'; + var isCallable = require_is_callable2(); + module.exports = function(stringifiable) { + try { + if (stringifiable && isCallable(stringifiable.toString)) { + return stringifiable.toString(); + } + return String(stringifiable); + } catch (e) { + throw new TypeError('Passed argument cannot be stringifed'); + } + }; + }); + var require_validate_stringifiable_value = __commonJS(function(exports, module) { + 'use strict'; + var ensureValue = require_valid_value(); + var stringifiable = require_validate_stringifiable(); + module.exports = function(value) { + return stringifiable(ensureValue(value)); + }; + }); + var require_safe_to_string = __commonJS(function(exports, module) { + 'use strict'; + var isCallable = require_is_callable2(); + module.exports = function(value) { + try { + if (value && isCallable(value.toString)) { + return value.toString(); + } + return String(value); + } catch (e) { + return ''; + } + }; + }); + var require_to_short_string_representation = __commonJS(function(exports, module) { + 'use strict'; + var safeToString = require_safe_to_string(); + var reNewLine = /[\n\r\u2028\u2029]/g; + module.exports = function(value) { + var string = safeToString(value); + if (string.length > 100) { + string = string.slice(0, 99) + '\u2026'; + } + string = string.replace(reNewLine, function(_char) { + return JSON.stringify(_char).slice(1, -1); + }); + return string; + }; + }); + var require_is_promise = __commonJS(function(exports, module) { + module.exports = isPromise; + module.exports['default'] = isPromise; + function isPromise(obj) { + return !!obj && (_typeof(obj) === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; + } + }); + var require_promise = __commonJS(function() { + 'use strict'; + var objectMap = require_map(); + var primitiveSet = require_primitive_set(); + var ensureString = require_validate_stringifiable_value(); + var toShortString = require_to_short_string_representation(); + var isPromise = require_is_promise(); + var nextTick = require_next_tick(); + var create = Object.create; + var supportedModes = primitiveSet('then', 'then:finally', 'done', 'done:finally'); + require_registered_extensions().promise = function(mode, conf) { + var waiting = create(null), cache2 = create(null), promises = create(null); + if (mode === true) { + mode = null; + } else { + mode = ensureString(mode); + if (!supportedModes[mode]) { + throw new TypeError('\'' + toShortString(mode) + '\' is not valid promise mode'); + } + } + conf.on('set', function(id, ignore, promise) { + var isFailed = false; + if (!isPromise(promise)) { + cache2[id] = promise; + conf.emit('setasync', id, 1); + return; + } + waiting[id] = 1; + promises[id] = promise; + var onSuccess = function onSuccess(result) { + var count = waiting[id]; + if (isFailed) { + throw new Error('Memoizee error: Detected unordered then|done & finally resolution, which in turn makes proper detection of success/failure impossible (when in \'done:finally\' mode)\nConsider to rely on \'then\' or \'done\' mode instead.'); + } + if (!count) { + return; + } + delete waiting[id]; + cache2[id] = result; + conf.emit('setasync', id, count); + }; + var onFailure = function onFailure() { + isFailed = true; + if (!waiting[id]) { + return; + } + delete waiting[id]; + delete promises[id]; + conf['delete'](id); + }; + var resolvedMode = mode; + if (!resolvedMode) { + resolvedMode = 'then'; + } + if (resolvedMode === 'then') { + var nextTickFailure = function nextTickFailure() { + nextTick(onFailure); + }; + promise = promise.then(function(result) { + nextTick(onSuccess.bind(this, result)); + }, nextTickFailure); + if (typeof promise['finally'] === 'function') { + promise['finally'](nextTickFailure); + } + } else if (resolvedMode === 'done') { + if (typeof promise.done !== 'function') { + throw new Error('Memoizee error: Retrieved promise does not implement \'done\' in \'done\' mode'); + } + promise.done(onSuccess, onFailure); + } else if (resolvedMode === 'done:finally') { + if (typeof promise.done !== 'function') { + throw new Error('Memoizee error: Retrieved promise does not implement \'done\' in \'done:finally\' mode'); + } + if (typeof promise['finally'] !== 'function') { + throw new Error('Memoizee error: Retrieved promise does not implement \'finally\' in \'done:finally\' mode'); + } + promise.done(onSuccess); + promise['finally'](onFailure); + } + }); + conf.on('get', function(id, args, context) { + var promise; + if (waiting[id]) { + ++waiting[id]; + return; + } + promise = promises[id]; + var emit = function emit() { + conf.emit('getasync', id, args, context); + }; + if (isPromise(promise)) { + if (typeof promise.done === 'function') { + promise.done(emit); + } else { + promise.then(function() { + nextTick(emit); + }); + } + } else { + emit(); + } + }); + conf.on('delete', function(id) { + delete promises[id]; + if (waiting[id]) { + delete waiting[id]; + return; + } + if (!hasOwnProperty.call(cache2, id)) { + return; + } + var result = cache2[id]; + delete cache2[id]; + conf.emit('deleteasync', id, [ result ]); + }); + conf.on('clear', function() { + var oldCache = cache2; + cache2 = create(null); + waiting = create(null); + promises = create(null); + conf.emit('clearasync', objectMap(oldCache, function(data) { + return [ data ]; + })); + }); + }; + }); + var require_dispose = __commonJS(function() { + 'use strict'; + var callable = require_valid_callable(); + var forEach = require_for_each(); + var extensions = require_registered_extensions(); + var apply = Function.prototype.apply; + extensions.dispose = function(dispose, conf, options) { + var del; + callable(dispose); + if (options.async && extensions.async || options.promise && extensions.promise) { + conf.on('deleteasync', del = function del(id, resultArray) { + apply.call(dispose, null, resultArray); + }); + conf.on('clearasync', function(cache2) { + forEach(cache2, function(result, id) { + del(id, result); + }); + }); + return; + } + conf.on('delete', del = function del(id, result) { + dispose(result); + }); + conf.on('clear', function(cache2) { + forEach(cache2, function(result, id) { + del(id, result); + }); + }); + }; + }); + var require_max_timeout = __commonJS(function(exports, module) { + 'use strict'; + module.exports = 2147483647; + }); + var require_valid_timeout = __commonJS(function(exports, module) { + 'use strict'; + var toPosInt = require_to_pos_integer(); + var maxTimeout = require_max_timeout(); + module.exports = function(value) { + value = toPosInt(value); + if (value > maxTimeout) { + throw new TypeError(value + ' exceeds maximum possible timeout'); + } + return value; + }; + }); + var require_max_age = __commonJS(function() { + 'use strict'; + var aFrom = require_from4(); + var forEach = require_for_each(); + var nextTick = require_next_tick(); + var isPromise = require_is_promise(); + var timeout = require_valid_timeout(); + var extensions = require_registered_extensions(); + var noop3 = Function.prototype; + var max2 = Math.max; + var min = Math.min; + var create = Object.create; + extensions.maxAge = function(maxAge, conf, options) { + var timeouts, postfix, preFetchAge, preFetchTimeouts; + maxAge = timeout(maxAge); + if (!maxAge) { + return; + } + timeouts = create(null); + postfix = options.async && extensions.async || options.promise && extensions.promise ? 'async' : ''; + conf.on('set' + postfix, function(id) { + timeouts[id] = setTimeout(function() { + conf['delete'](id); + }, maxAge); + if (typeof timeouts[id].unref === 'function') { + timeouts[id].unref(); + } + if (!preFetchTimeouts) { + return; + } + if (preFetchTimeouts[id]) { + if (preFetchTimeouts[id] !== 'nextTick') { + clearTimeout(preFetchTimeouts[id]); + } + } + preFetchTimeouts[id] = setTimeout(function() { + delete preFetchTimeouts[id]; + }, preFetchAge); + if (typeof preFetchTimeouts[id].unref === 'function') { + preFetchTimeouts[id].unref(); + } + }); + conf.on('delete' + postfix, function(id) { + clearTimeout(timeouts[id]); + delete timeouts[id]; + if (!preFetchTimeouts) { + return; + } + if (preFetchTimeouts[id] !== 'nextTick') { + clearTimeout(preFetchTimeouts[id]); + } + delete preFetchTimeouts[id]; + }); + if (options.preFetch) { + if (options.preFetch === true || isNaN(options.preFetch)) { + preFetchAge = .333; + } else { + preFetchAge = max2(min(Number(options.preFetch), 1), 0); + } + if (preFetchAge) { + preFetchTimeouts = {}; + preFetchAge = (1 - preFetchAge) * maxAge; + conf.on('get' + postfix, function(id, args, context) { + if (!preFetchTimeouts[id]) { + preFetchTimeouts[id] = 'nextTick'; + nextTick(function() { + var result; + if (preFetchTimeouts[id] !== 'nextTick') { + return; + } + delete preFetchTimeouts[id]; + conf['delete'](id); + if (options.async) { + args = aFrom(args); + args.push(noop3); + } + result = conf.memoized.apply(context, args); + if (options.promise) { + if (isPromise(result)) { + if (typeof result.done === 'function') { + result.done(noop3, noop3); + } else { + result.then(noop3, noop3); + } + } + } + }); + } + }); + } + } + conf.on('clear' + postfix, function() { + forEach(timeouts, function(id) { + clearTimeout(id); + }); + timeouts = {}; + if (preFetchTimeouts) { + forEach(preFetchTimeouts, function(id) { + if (id !== 'nextTick') { + clearTimeout(id); + } + }); + preFetchTimeouts = {}; + } + }); + }; + }); + var require_lru_queue = __commonJS(function(exports, module) { + 'use strict'; + var toPosInt = require_to_pos_integer(); + var create = Object.create; + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + module.exports = function(limit) { + var size = 0, base = 1, queue2 = create(null), map = create(null), index = 0, del; + limit = toPosInt(limit); + return { + hit: function hit(id) { + var oldIndex = map[id], nuIndex = ++index; + queue2[nuIndex] = id; + map[id] = nuIndex; + if (!oldIndex) { + ++size; + if (size <= limit) { + return; + } + id = queue2[base]; + del(id); + return id; + } + delete queue2[oldIndex]; + if (base !== oldIndex) { + return; + } + while (!hasOwnProperty2.call(queue2, ++base)) { + continue; + } + }, + delete: del = function del(id) { + var oldIndex = map[id]; + if (!oldIndex) { + return; + } + delete queue2[oldIndex]; + delete map[id]; + --size; + if (base !== oldIndex) { + return; + } + if (!size) { + index = 0; + base = 1; + return; + } + while (!hasOwnProperty2.call(queue2, ++base)) { + continue; + } + }, + clear: function clear() { + size = 0; + base = 1; + queue2 = create(null); + map = create(null); + index = 0; + } + }; + }; + }); + var require_max = __commonJS(function() { + 'use strict'; + var toPosInteger = require_to_pos_integer(); + var lruQueue = require_lru_queue(); + var extensions = require_registered_extensions(); + extensions.max = function(max2, conf, options) { + var postfix, queue2, hit; + max2 = toPosInteger(max2); + if (!max2) { + return; + } + queue2 = lruQueue(max2); + postfix = options.async && extensions.async || options.promise && extensions.promise ? 'async' : ''; + conf.on('set' + postfix, hit = function hit(id) { + id = queue2.hit(id); + if (id === void 0) { + return; + } + conf['delete'](id); + }); + conf.on('get' + postfix, hit); + conf.on('delete' + postfix, queue2['delete']); + conf.on('clear' + postfix, queue2.clear); + }; + }); + var require_ref_counter = __commonJS(function() { + 'use strict'; + var d2 = require_d(); + var extensions = require_registered_extensions(); + var create = Object.create; + var defineProperties = Object.defineProperties; + extensions.refCounter = function(ignore, conf, options) { + var cache2, postfix; + cache2 = create(null); + postfix = options.async && extensions.async || options.promise && extensions.promise ? 'async' : ''; + conf.on('set' + postfix, function(id, length) { + cache2[id] = length || 1; + }); + conf.on('get' + postfix, function(id) { + ++cache2[id]; + }); + conf.on('delete' + postfix, function(id) { + delete cache2[id]; + }); + conf.on('clear' + postfix, function() { + cache2 = {}; + }); + defineProperties(conf.memoized, { + deleteRef: d2(function() { + var id = conf.get(arguments); + if (id === null) { + return null; + } + if (!cache2[id]) { + return null; + } + if (!--cache2[id]) { + conf['delete'](id); + return true; + } + return false; + }), + getRefCount: d2(function() { + var id = conf.get(arguments); + if (id === null) { + return 0; + } + if (!cache2[id]) { + return 0; + } + return cache2[id]; + }) + }); + }; + }); + var require_memoizee = __commonJS(function(exports, module) { + 'use strict'; + var normalizeOpts = require_normalize_options(); + var resolveLength = require_resolve_length(); + var plain = require_plain(); + module.exports = function(fn) { + var options = normalizeOpts(arguments[1]), length; + if (!options.normalizer) { + length = options.length = resolveLength(options.length, fn.length, options.async); + if (length !== 0) { + if (options.primitive) { + if (length === false) { + options.normalizer = require_primitive(); + } else if (length > 1) { + options.normalizer = require_get_primitive_fixed()(length); + } + } else if (length === false) { + options.normalizer = require_get()(); + } else if (length === 1) { + options.normalizer = require_get_1()(); + } else { + options.normalizer = require_get_fixed()(length); + } + } + } + if (options.async) { + require_async(); + } + if (options.promise) { + require_promise(); + } + if (options.dispose) { + require_dispose(); + } + if (options.maxAge) { + require_max_age(); + } + if (options.max) { + require_max(); + } + if (options.refCounter) { + require_ref_counter(); + } + return plain(fn, options); + }; + }); + var definitions = [ { + name: 'NA', + value: 'inapplicable', + priority: 0, + group: 'inapplicable' + }, { + name: 'PASS', + value: 'passed', + priority: 1, + group: 'passes' + }, { + name: 'CANTTELL', + value: 'cantTell', + priority: 2, + group: 'incomplete' + }, { + name: 'FAIL', + value: 'failed', + priority: 3, + group: 'violations' + } ]; + var constants = { + helpUrlBase: 'https://dequeuniversity.com/rules/', + gridSize: 200, + selectorSimilarFilterLimit: 700, + results: [], + resultGroups: [], + resultGroupMap: {}, + impact: Object.freeze([ 'minor', 'moderate', 'serious', 'critical' ]), + preload: Object.freeze({ + assets: [ 'cssom', 'media' ], + timeout: 1e4 + }), + allOrigins: '', + sameOrigin: '', + serializableErrorProps: Object.freeze([ 'message', 'stack', 'name', 'code', 'ruleId', 'method' ]) + }; + definitions.forEach(function(definition) { + var name = definition.name; + var value = definition.value; + var priority = definition.priority; + var group = definition.group; + constants[name] = value; + constants[name + '_PRIO'] = priority; + constants[name + '_GROUP'] = group; + constants.results[priority] = value; + constants.resultGroups[priority] = group; + constants.resultGroupMap[value] = group; + }); + Object.freeze(constants.results); + Object.freeze(constants.resultGroups); + Object.freeze(constants.resultGroupMap); + Object.freeze(constants); + var constants_default = constants; + function log() { + if ((typeof console === 'undefined' ? 'undefined' : _typeof(console)) === 'object' && console.log) { + Function.prototype.apply.call(console.log, console, arguments); + } + } + var log_default = log; + var whitespaceRegex = /[\t\r\n\f]/g; + var AbstractVirtualNode = function() { + function AbstractVirtualNode() { + _classCallCheck(this, AbstractVirtualNode); + this.parent = void 0; + } + return _createClass(AbstractVirtualNode, [ { + key: 'props', + get: function get() { + throw new Error('VirtualNode class must have a "props" object consisting of "nodeType" and "nodeName" properties'); + } + }, { + key: 'attrNames', + get: function get() { + throw new Error('VirtualNode class must have an "attrNames" property'); + } + }, { + key: 'attr', + value: function attr() { + throw new Error('VirtualNode class must have an "attr" function'); + } + }, { + key: 'hasAttr', + value: function hasAttr() { + throw new Error('VirtualNode class must have a "hasAttr" function'); + } + }, { + key: 'hasClass', + value: function hasClass(className) { + var classAttr = this.attr('class'); + if (!classAttr) { + return false; + } + var selector = ' ' + className + ' '; + return (' ' + classAttr + ' ').replace(whitespaceRegex, ' ').indexOf(selector) >= 0; + } + } ]); + }(); + var abstract_virtual_node_default = AbstractVirtualNode; + var utils_exports = {}; + __export(utils_exports, { + DqElement: function DqElement() { + return dq_element_default; + }, + RuleError: function RuleError() { + return rule_error_default; + }, + aggregate: function aggregate() { + return aggregate_default; + }, + aggregateChecks: function aggregateChecks() { + return aggregate_checks_default; + }, + aggregateNodeResults: function aggregateNodeResults() { + return aggregate_node_results_default; + }, + aggregateResult: function aggregateResult() { + return aggregate_result_default; + }, + areStylesSet: function areStylesSet() { + return are_styles_set_default; + }, + assert: function assert() { + return assert_default; + }, + checkHelper: function checkHelper() { + return check_helper_default; + }, + clone: function clone() { + return clone2; + }, + closest: function closest() { + return closest_default; + }, + collectResultsFromFrames: function collectResultsFromFrames() { + return _collectResultsFromFrames; + }, + contains: function contains() { + return _contains; + }, + convertSelector: function convertSelector() { + return _convertSelector; + }, + cssParser: function cssParser() { + return css_parser_default; + }, + deepMerge: function deepMerge() { + return deep_merge_default; + }, + escapeSelector: function escapeSelector() { + return escape_selector_default; + }, + extendMetaData: function extendMetaData() { + return extend_meta_data_default; + }, + filterHtmlAttrs: function filterHtmlAttrs() { + return _filterHtmlAttrs; + }, + finalizeRuleResult: function finalizeRuleResult() { + return _finalizeRuleResult; + }, + findBy: function findBy() { + return find_by_default; + }, + getAllChecks: function getAllChecks() { + return get_all_checks_default; + }, + getAncestry: function getAncestry() { + return _getAncestry; + }, + getBaseLang: function getBaseLang() { + return get_base_lang_default; + }, + getCheckMessage: function getCheckMessage() { + return get_check_message_default; + }, + getCheckOption: function getCheckOption() { + return get_check_option_default; + }, + getElementSource: function getElementSource() { + return _getElementSource; + }, + getEnvironmentData: function getEnvironmentData() { + return _getEnvironmentData; + }, + getFlattenedTree: function getFlattenedTree() { + return _getFlattenedTree; + }, + getFrameContexts: function getFrameContexts() { + return _getFrameContexts; + }, + getFriendlyUriEnd: function getFriendlyUriEnd() { + return get_friendly_uri_end_default; + }, + getNodeAttributes: function getNodeAttributes() { + return get_node_attributes_default; + }, + getNodeFromTree: function getNodeFromTree() { + return get_node_from_tree_default; + }, + getPreloadConfig: function getPreloadConfig() { + return _getPreloadConfig; + }, + getRootNode: function getRootNode() { + return get_root_node_default; + }, + getRule: function getRule() { + return _getRule; + }, + getScroll: function getScroll() { + return get_scroll_default; + }, + getScrollState: function getScrollState() { + return get_scroll_state_default; + }, + getSelector: function getSelector() { + return get_selector_default; + }, + getSelectorData: function getSelectorData() { + return _getSelectorData; + }, + getShadowSelector: function getShadowSelector() { + return _getShadowSelector; + }, + getStandards: function getStandards() { + return _getStandards; + }, + getStyleSheetFactory: function getStyleSheetFactory() { + return get_stylesheet_factory_default; + }, + getXpath: function getXpath() { + return get_xpath_default; + }, + injectStyle: function injectStyle() { + return inject_style_default; + }, + isArrayLike: function isArrayLike() { + return _isArrayLike; + }, + isContextObject: function isContextObject() { + return _isContextObject; + }, + isContextProp: function isContextProp() { + return _isContextProp; + }, + isContextSpec: function isContextSpec() { + return _isContextSpec; + }, + isHidden: function isHidden() { + return is_hidden_default; + }, + isHtmlElement: function isHtmlElement() { + return is_html_element_default; + }, + isLabelledFramesSelector: function isLabelledFramesSelector() { + return _isLabelledFramesSelector; + }, + isLabelledShadowDomSelector: function isLabelledShadowDomSelector() { + return _isLabelledShadowDomSelector; + }, + isNodeInContext: function isNodeInContext() { + return _isNodeInContext; + }, + isShadowRoot: function isShadowRoot() { + return is_shadow_root_default; + }, + isValidLang: function isValidLang() { + return valid_langs_default; + }, + isXHTML: function isXHTML() { + return is_xhtml_default; + }, + matchAncestry: function matchAncestry() { + return _matchAncestry; + }, + matches: function matches() { + return _matches; + }, + matchesExpression: function matchesExpression() { + return _matchesExpression; + }, + matchesSelector: function matchesSelector() { + return element_matches_default; + }, + memoize: function memoize() { + return memoize_default; + }, + mergeResults: function mergeResults() { + return merge_results_default; + }, + nodeLookup: function nodeLookup() { + return _nodeLookup; + }, + nodeSerializer: function nodeSerializer() { + return node_serializer_default; + }, + nodeSorter: function nodeSorter() { + return node_sorter_default; + }, + objectHasOwn: function objectHasOwn() { + return _objectHasOwn; + }, + parseCrossOriginStylesheet: function parseCrossOriginStylesheet() { + return parse_crossorigin_stylesheet_default; + }, + parseSameOriginStylesheet: function parseSameOriginStylesheet() { + return parse_sameorigin_stylesheet_default; + }, + parseStylesheet: function parseStylesheet() { + return parse_stylesheet_default; + }, + parseTabindex: function parseTabindex() { + return parse_tabindex_default; + }, + performanceTimer: function performanceTimer() { + return performance_timer_default; + }, + pollyfillElementsFromPoint: function pollyfillElementsFromPoint() { + return _pollyfillElementsFromPoint; + }, + preload: function preload() { + return _preload; + }, + preloadCssom: function preloadCssom() { + return preload_cssom_default; + }, + preloadMedia: function preloadMedia() { + return preload_media_default; + }, + processMessage: function processMessage() { + return process_message_default; + }, + publishMetaData: function publishMetaData() { + return _publishMetaData; + }, + querySelectorAll: function querySelectorAll() { + return query_selector_all_default; + }, + querySelectorAllFilter: function querySelectorAllFilter() { + return query_selector_all_filter_default; + }, + queue: function queue() { + return queue_default; + }, + respondable: function respondable() { + return _respondable; + }, + ruleShouldRun: function ruleShouldRun() { + return rule_should_run_default; + }, + select: function select() { + return _select; + }, + sendCommandToFrame: function sendCommandToFrame() { + return _sendCommandToFrame; + }, + serializeError: function serializeError() { + return _serializeError; + }, + setScrollState: function setScrollState() { + return set_scroll_state_default; + }, + shadowSelect: function shadowSelect() { + return _shadowSelect; + }, + shadowSelectAll: function shadowSelectAll() { + return _shadowSelectAll; + }, + shouldPreload: function shouldPreload() { + return _shouldPreload; + }, + toArray: function toArray() { + return to_array_default; + }, + tokenList: function tokenList() { + return token_list_default; + }, + uniqueArray: function uniqueArray() { + return unique_array_default; + }, + uuid: function uuid() { + return uuid_default; + }, + validInputTypes: function validInputTypes() { + return valid_input_type_default; + }, + validLangs: function validLangs() { + return _validLangs; + } + }); + function aggregate(map, values2, initial) { + values2 = values2.slice(); + if (initial) { + values2.push(initial); + } + var sorting = values2.map(function(val) { + return map.indexOf(val); + }).sort(); + return map[sorting.pop()]; + } + var aggregate_default = aggregate; + var CANTTELL_PRIO = constants_default.CANTTELL_PRIO, FAIL_PRIO = constants_default.FAIL_PRIO; + var checkMap = []; + checkMap[constants_default.PASS_PRIO] = true; + checkMap[constants_default.CANTTELL_PRIO] = null; + checkMap[constants_default.FAIL_PRIO] = false; + var checkTypes = [ 'any', 'all', 'none' ]; + function anyAllNone(obj, functor) { + return checkTypes.reduce(function(out, type2) { + out[type2] = (obj[type2] || []).map(function(val) { + return functor(val, type2); + }); + return out; + }, {}); + } + function aggregateChecks(nodeResOriginal) { + var nodeResult = Object.assign({}, nodeResOriginal); + anyAllNone(nodeResult, function(check, type2) { + var i = typeof check.result === 'undefined' ? -1 : checkMap.indexOf(check.result); + check.priority = i !== -1 ? i : constants_default.CANTTELL_PRIO; + if (type2 === 'none') { + if (check.priority === constants_default.PASS_PRIO) { + check.priority = constants_default.FAIL_PRIO; + } else if (check.priority === constants_default.FAIL_PRIO) { + check.priority = constants_default.PASS_PRIO; + } + } + }); + var priorities = { + all: nodeResult.all.reduce(function(a2, b2) { + return Math.max(a2, b2.priority); + }, 0), + none: nodeResult.none.reduce(function(a2, b2) { + return Math.max(a2, b2.priority); + }, 0), + any: nodeResult.any.reduce(function(a2, b2) { + return Math.min(a2, b2.priority); + }, 4) % 4 + }; + nodeResult.priority = Math.max(priorities.all, priorities.none, priorities.any); + var impacts = []; + checkTypes.forEach(function(type2) { + nodeResult[type2] = nodeResult[type2].filter(function(check) { + return check.priority === nodeResult.priority && check.priority === priorities[type2]; + }); + nodeResult[type2].forEach(function(check) { + return impacts.push(check.impact); + }); + }); + if ([ CANTTELL_PRIO, FAIL_PRIO ].includes(nodeResult.priority)) { + nodeResult.impact = aggregate_default(constants_default.impact, impacts); + } else { + nodeResult.impact = null; + } + anyAllNone(nodeResult, function(c4) { + delete c4.result; + delete c4.priority; + }); + nodeResult.result = constants_default.results[nodeResult.priority]; + delete nodeResult.priority; + return nodeResult; + } + var aggregate_checks_default = aggregateChecks; + function _finalizeRuleResult(ruleResult) { + var rule = axe._audit.rules.find(function(_ref) { + var id = _ref.id; + return id === ruleResult.id; + }); + if (rule && rule.impact) { + ruleResult.nodes.forEach(function(node) { + [ 'any', 'all', 'none' ].forEach(function(checkType) { + (node[checkType] || []).forEach(function(checkResult) { + checkResult.impact = rule.impact; + }); + }); + }); + } + Object.assign(ruleResult, aggregate_node_results_default(ruleResult.nodes)); + delete ruleResult.nodes; + return ruleResult; + } + function aggregateNodeResults(nodeResults) { + var ruleResult = {}; + nodeResults = nodeResults.map(function(nodeResult) { + if (nodeResult.any && nodeResult.all && nodeResult.none) { + return aggregate_checks_default(nodeResult); + } else if (Array.isArray(nodeResult.node)) { + return _finalizeRuleResult(nodeResult); + } else { + throw new TypeError('Invalid Result type'); + } + }); + if (nodeResults && nodeResults.length) { + var resultList = nodeResults.map(function(node) { + return node.result; + }); + ruleResult.result = aggregate_default(constants_default.results, resultList, ruleResult.result); + } else { + ruleResult.result = 'inapplicable'; + } + constants_default.resultGroups.forEach(function(group) { + return ruleResult[group] = []; + }); + nodeResults.forEach(function(nodeResult) { + var groupName = constants_default.resultGroupMap[nodeResult.result]; + ruleResult[groupName].push(nodeResult); + }); + var impactGroup = constants_default.FAIL_GROUP; + if (ruleResult[impactGroup].length === 0) { + impactGroup = constants_default.CANTTELL_GROUP; + } + if (ruleResult[impactGroup].length > 0) { + var impactList = ruleResult[impactGroup].map(function(failure) { + return failure.impact; + }); + ruleResult.impact = aggregate_default(constants_default.impact, impactList) || null; + } else { + ruleResult.impact = null; + } + return ruleResult; + } + var aggregate_node_results_default = aggregateNodeResults; + function copyToGroup(resultObject, subResult, group) { + var resultCopy = Object.assign({}, subResult); + resultCopy.nodes = (resultCopy[group] || []).concat(); + constants_default.resultGroups.forEach(function(resultGroup) { + delete resultCopy[resultGroup]; + }); + resultObject[group].push(resultCopy); + } + function aggregateResult(results) { + var resultObject = {}; + constants_default.resultGroups.forEach(function(groupName) { + return resultObject[groupName] = []; + }); + results.forEach(function(subResult) { + if (subResult.error) { + copyToGroup(resultObject, subResult, constants_default.CANTTELL_GROUP); + } else if (subResult.result === constants_default.NA) { + copyToGroup(resultObject, subResult, constants_default.NA_GROUP); + } else { + constants_default.resultGroups.forEach(function(group) { + if (Array.isArray(subResult[group]) && subResult[group].length > 0) { + copyToGroup(resultObject, subResult, group); + } + }); + } + }); + return resultObject; + } + var aggregate_result_default = aggregateResult; + function areStylesSet(el, styles, stopAt) { + var styl = window.getComputedStyle(el, null); + if (!styl) { + return false; + } + for (var i = 0; i < styles.length; ++i) { + var att = styles[i]; + if (styl.getPropertyValue(att.property) === att.value) { + return true; + } + } + if (!el.parentNode || el.nodeName.toUpperCase() === stopAt.toUpperCase()) { + return false; + } + return areStylesSet(el.parentNode, styles, stopAt); + } + var are_styles_set_default = areStylesSet; + function assert(bool, message) { + if (!bool) { + throw new Error(message); + } + } + var assert_default = assert; + function toArray(thing) { + return Array.prototype.slice.call(thing); + } + var to_array_default = toArray; + function escapeSelector(value) { + var string = String(value); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + if (codeUnit == 0) { + result += '\ufffd'; + continue; + } + if (codeUnit >= 1 && codeUnit <= 31 || codeUnit == 127 || index == 0 && codeUnit >= 48 && codeUnit <= 57 || index == 1 && codeUnit >= 48 && codeUnit <= 57 && firstCodeUnit == 45) { + result += '\\' + codeUnit.toString(16) + ' '; + continue; + } + if (index == 0 && length == 1 && codeUnit == 45) { + result += '\\' + string.charAt(index); + continue; + } + if (codeUnit >= 128 || codeUnit == 45 || codeUnit == 95 || codeUnit >= 48 && codeUnit <= 57 || codeUnit >= 65 && codeUnit <= 90 || codeUnit >= 97 && codeUnit <= 122) { + result += string.charAt(index); + continue; + } + result += '\\' + string.charAt(index); + } + return result; + } + var escape_selector_default = escapeSelector; + function isMostlyNumbers() { + var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + return str.length !== 0 && (str.match(/[0-9]/g) || '').length >= str.length / 2; + } + function splitString(str, splitIndex) { + return [ str.substring(0, splitIndex), str.substring(splitIndex) ]; + } + function trimRight(str) { + return str.replace(/\s+$/, ''); + } + function uriParser(url) { + var original = url; + var protocol = '', domain = '', port = '', path = '', query = '', hash = ''; + if (url.includes('#')) { + var _splitString = splitString(url, url.indexOf('#')); + var _splitString2 = _slicedToArray(_splitString, 2); + url = _splitString2[0]; + hash = _splitString2[1]; + } + if (url.includes('?')) { + var _splitString3 = splitString(url, url.indexOf('?')); + var _splitString4 = _slicedToArray(_splitString3, 2); + url = _splitString4[0]; + query = _splitString4[1]; + } + if (url.includes('://')) { + var _url$split = url.split('://'); + var _url$split2 = _slicedToArray(_url$split, 2); + protocol = _url$split2[0]; + url = _url$split2[1]; + var _splitString5 = splitString(url, url.indexOf('/')); + var _splitString6 = _slicedToArray(_splitString5, 2); + domain = _splitString6[0]; + url = _splitString6[1]; + } else if (url.substr(0, 2) === '//') { + url = url.substr(2); + var _splitString7 = splitString(url, url.indexOf('/')); + var _splitString8 = _slicedToArray(_splitString7, 2); + domain = _splitString8[0]; + url = _splitString8[1]; + } + if (domain.substr(0, 4) === 'www.') { + domain = domain.substr(4); + } + if (domain && domain.includes(':')) { + var _splitString9 = splitString(domain, domain.indexOf(':')); + var _splitString0 = _slicedToArray(_splitString9, 2); + domain = _splitString0[0]; + port = _splitString0[1]; + } + path = url; + return { + original: original, + protocol: protocol, + domain: domain, + port: port, + path: path, + query: query, + hash: hash + }; + } + function getFriendlyUriEnd() { + var uri = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (uri.length <= 1 || uri.substr(0, 5) === 'data:' || uri.substr(0, 11) === 'javascript:' || uri.includes('?')) { + return; + } + var currentDomain = options.currentDomain, _options$maxLength = options.maxLength, maxLength = _options$maxLength === void 0 ? 25 : _options$maxLength; + var _uriParser = uriParser(uri), path = _uriParser.path, domain = _uriParser.domain, hash = _uriParser.hash; + var pathEnd = path.substr(path.substr(0, path.length - 2).lastIndexOf('/') + 1); + if (hash) { + if (pathEnd && (pathEnd + hash).length <= maxLength) { + return trimRight(pathEnd + hash); + } else if (pathEnd.length < 2 && hash.length > 2 && hash.length <= maxLength) { + return trimRight(hash); + } else { + return; + } + } else if (domain && domain.length < maxLength && path.length <= 1) { + return trimRight(domain + path); + } + if (path === '/' + pathEnd && domain && currentDomain && domain !== currentDomain && (domain + path).length <= maxLength) { + return trimRight(domain + path); + } + var lastDotIndex = pathEnd.lastIndexOf('.'); + if ((lastDotIndex === -1 || lastDotIndex > 1) && (lastDotIndex !== -1 || pathEnd.length > 2) && pathEnd.length <= maxLength && !pathEnd.match(/index(\.[a-zA-Z]{2-4})?/) && !isMostlyNumbers(pathEnd)) { + return trimRight(pathEnd); + } + } + var get_friendly_uri_end_default = getFriendlyUriEnd; + function getNodeAttributes(node) { + if (node.attributes instanceof window.NamedNodeMap) { + return node.attributes; + } + return node.cloneNode(false).attributes; + } + var get_node_attributes_default = getNodeAttributes; + var matchesSelector = function() { + var method; + function getMethod(node) { + var candidates = [ 'matches', 'matchesSelector', 'mozMatchesSelector', 'webkitMatchesSelector', 'msMatchesSelector' ]; + var length = candidates.length; + var index, candidate; + for (index = 0; index < length; index++) { + candidate = candidates[index]; + if (node[candidate]) { + return candidate; + } + } + } + return function(node, selector) { + if (!method || !node[method]) { + method = getMethod(node); + } + if (node[method]) { + return node[method](selector); + } + return false; + }; + }(); + var element_matches_default = matchesSelector; + var imports_exports = {}; + __export(imports_exports, { + ArrayFrom: function ArrayFrom() { + return import_from2['default']; + }, + Colorjs: function Colorjs() { + return _Color; + }, + CssSelectorParser: function CssSelectorParser() { + return import_css_selector_parser.CssSelectorParser; + }, + doT: function doT() { + return import_dot['default']; + }, + emojiRegexText: function emojiRegexText() { + return emoji_regex_default; + }, + memoize: function memoize() { + return import_memoizee['default']; + } + }); + var import_es6_promise = __toModule(require_es6_promise()); + var import_typedarray = __toModule(require_typedarray()); + var import_weakmap_polyfill = __toModule(require_weakmap_polyfill()); + var import_has_own = __toModule(require_has_own3()); + var import_values = __toModule(require_values3()); + var import_from = __toModule(require_from3()); + if (!('hasOwn' in Object)) { + Object.hasOwn = import_has_own['default']; + } + if (!('values' in Object)) { + Object.values = import_values['default']; + } + if (!('Promise' in window)) { + import_es6_promise['default'].polyfill(); + } + if (!('Uint32Array' in window)) { + window.Uint32Array = import_typedarray.Uint32Array; + } + if (window.Uint32Array) { + if (!('some' in window.Uint32Array.prototype)) { + Object.defineProperty(window.Uint32Array.prototype, 'some', { + value: Array.prototype.some + }); + } + if (!('reduce' in window.Uint32Array.prototype)) { + Object.defineProperty(window.Uint32Array.prototype, 'reduce', { + value: Array.prototype.reduce + }); + } + } + if (typeof Object.assign !== 'function') { + (function() { + Object.assign = function(target) { + if (target === void 0 || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var output = Object(target); + for (var index = 1; index < arguments.length; index++) { + var source = arguments[index]; + if (source !== void 0 && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; + }; + })(); + } + if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function value(predicate) { + if (this === null) { + throw new TypeError('Array.prototype.find called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return value; + } + } + return void 0; + } + }); + } + if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function value(predicate, thisArg) { + if (this === null) { + throw new TypeError('Array.prototype.find called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var value; + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + } + }); + } + if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + value: function value(searchElement) { + var O = Object(this); + var len = parseInt(O.length, 10) || 0; + if (len === 0) { + return false; + } + var n2 = parseInt(arguments[1], 10) || 0; + var k; + if (n2 >= 0) { + k = n2; + } else { + k = len + n2; + if (k < 0) { + k = 0; + } + } + var currentElement; + while (k < len) { + currentElement = O[k]; + if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) { + return true; + } + k++; + } + return false; + } + }); + } + if (!Array.prototype.some) { + Object.defineProperty(Array.prototype, 'some', { + value: function value(fun) { + if (this == null) { + throw new TypeError('Array.prototype.some called on null or undefined'); + } + if (typeof fun !== 'function') { + throw new TypeError(); + } + var t = Object(this); + var len = t.length >>> 0; + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + for (var i = 0; i < len; i++) { + if (i in t && fun.call(thisArg, t[i], i, t)) { + return true; + } + } + return false; + } + }); + } + if (!Array.from) { + Array.from = import_from['default']; + } + if (!String.prototype.includes) { + String.prototype.includes = function(search, start) { + if (typeof start !== 'number') { + start = 0; + } + if (start + search.length > this.length) { + return false; + } else { + return this.indexOf(search, start) !== -1; + } + }; + } + if (!Array.prototype.flat) { + Object.defineProperty(Array.prototype, 'flat', { + configurable: true, + value: function flat() { + var depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]); + return depth ? Array.prototype.reduce.call(this, function(acc, cur) { + if (Array.isArray(cur)) { + acc.push.apply(acc, flat.call(cur, depth - 1)); + } else { + acc.push(cur); + } + return acc; + }, []) : Array.prototype.slice.call(this); + }, + writable: true + }); + } + if (window.Node && !('isConnected' in window.Node.prototype)) { + Object.defineProperty(window.Node.prototype, 'isConnected', { + get: function get() { + return !this.ownerDocument || !(this.ownerDocument.compareDocumentPosition(this) & this.DOCUMENT_POSITION_DISCONNECTED); + } + }); + } + var import_css_selector_parser = __toModule(require_lib()); + var import_dot = __toModule(require_doT()); + var emoji_regex_default = function emoji_regex_default() { + return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\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?|[\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](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\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-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; + }; + var import_memoizee = __toModule(require_memoizee()); + function multiplyMatrices(A, B) { + var m3 = A.length; + if (!Array.isArray(A[0])) { + A = [ A ]; + } + if (!Array.isArray(B[0])) { + B = B.map(function(x) { + return [ x ]; + }); + } + var p2 = B[0].length; + var B_cols = B[0].map(function(_, i) { + return B.map(function(x) { + return x[i]; + }); + }); + var product = A.map(function(row) { + return B_cols.map(function(col) { + var ret = 0; + if (!Array.isArray(row)) { + var _iterator2 = _createForOfIteratorHelper(col), _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) { + var c4 = _step2.value; + ret += row * c4; + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + return ret; + } + for (var i = 0; i < row.length; i++) { + ret += row[i] * (col[i] || 0); + } + return ret; + }); + }); + if (m3 === 1) { + product = product[0]; + } + if (p2 === 1) { + return product.map(function(x) { + return x[0]; + }); + } + return product; + } + function isString(str) { + return type(str) === 'string'; + } + function type(o) { + var str = Object.prototype.toString.call(o); + return (str.match(/^\[object\s+(.*?)\]$/)[1] || '').toLowerCase(); + } + function toPrecision(n2, precision) { + n2 = +n2; + precision = +precision; + var integerLength = (Math.floor(n2) + '').length; + if (precision > integerLength) { + return +n2.toFixed(precision - integerLength); + } else { + var p10 = Math.pow(10, integerLength - precision); + return Math.round(n2 / p10) * p10; + } + } + function parseFunction(str) { + if (!str) { + return; + } + str = str.trim(); + var isFunctionRegex = /^([a-z]+)\((.+?)\)$/i; + var isNumberRegex = /^-?[\d.]+$/; + var parts = str.match(isFunctionRegex); + if (parts) { + var args = []; + parts[2].replace(/\/?\s*([-\w.]+(?:%|deg)?)/g, function($0, arg) { + if (/%$/.test(arg)) { + arg = new Number(arg.slice(0, -1) / 100); + arg.type = ''; + } else if (/deg$/.test(arg)) { + arg = new Number(+arg.slice(0, -3)); + arg.type = ''; + arg.unit = 'deg'; + } else if (isNumberRegex.test(arg)) { + arg = new Number(arg); + arg.type = ''; + } + if ($0.startsWith('/')) { + arg = arg instanceof Number ? arg : new Number(arg); + arg.alpha = true; + } + args.push(arg); + }); + return { + name: parts[1].toLowerCase(), + rawName: parts[1], + rawArgs: parts[2], + args: args + }; + } + } + function last(arr) { + return arr[arr.length - 1]; + } + function interpolate(start, end, p2) { + if (isNaN(start)) { + return end; + } + if (isNaN(end)) { + return start; + } + return start + (end - start) * p2; + } + function interpolateInv(start, end, value) { + return (value - start) / (end - start); + } + function mapRange(from, to2, value) { + return interpolate(to2[0], to2[1], interpolateInv(from[0], from[1], value)); + } + function parseCoordGrammar(coordGrammars) { + return coordGrammars.map(function(coordGrammar2) { + return coordGrammar2.split('|').map(function(type2) { + type2 = type2.trim(); + var range2 = type2.match(/^(<[a-z]+>)\[(-?[.\d]+),\s*(-?[.\d]+)\]?$/); + if (range2) { + var ret = new String(range2[1]); + ret.range = [ +range2[2], +range2[3] ]; + return ret; + } + return type2; + }); + }); + } + var util = Object.freeze({ + __proto__: null, + isString: isString, + type: type, + toPrecision: toPrecision, + parseFunction: parseFunction, + last: last, + interpolate: interpolate, + interpolateInv: interpolateInv, + mapRange: mapRange, + parseCoordGrammar: parseCoordGrammar, + multiplyMatrices: multiplyMatrices + }); + var Hooks = function() { + function Hooks() { + _classCallCheck(this, Hooks); + } + return _createClass(Hooks, [ { + key: 'add', + value: function add(name, callback, first) { + if (typeof arguments[0] != 'string') { + for (var name in arguments[0]) { + this.add(name, arguments[0][name], arguments[1]); + } + return; + } + (Array.isArray(name) ? name : [ name ]).forEach(function(name2) { + this[name2] = this[name2] || []; + if (callback) { + this[name2][first ? 'unshift' : 'push'](callback); + } + }, this); + } + }, { + key: 'run', + value: function run(name, env) { + this[name] = this[name] || []; + this[name].forEach(function(callback) { + callback.call(env && env.context ? env.context : env, env); + }); + } + } ]); + }(); + var hooks = new Hooks(); + var defaults = { + gamut_mapping: 'lch.c', + precision: 5, + deltaE: '76' + }; + var WHITES = { + D50: [ .3457 / .3585, 1, (1 - .3457 - .3585) / .3585 ], + D65: [ .3127 / .329, 1, (1 - .3127 - .329) / .329 ] + }; + function getWhite(name) { + if (Array.isArray(name)) { + return name; + } + return WHITES[name]; + } + function adapt$1(W1, W2, XYZ) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + W1 = getWhite(W1); + W2 = getWhite(W2); + if (!W1 || !W2) { + throw new TypeError('Missing white point to convert '.concat(!W1 ? 'from' : '').concat(!W1 && !W2 ? '/' : '').concat(!W2 ? 'to' : '')); + } + if (W1 === W2) { + return XYZ; + } + var env = { + W1: W1, + W2: W2, + XYZ: XYZ, + options: options + }; + hooks.run('chromatic-adaptation-start', env); + if (!env.M) { + if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) { + env.M = [ [ 1.0479298208405488, .022946793341019088, -.05019222954313557 ], [ .029627815688159344, .990434484573249, -.01707382502938514 ], [ -.009243058152591178, .015055144896577895, .7518742899580008 ] ]; + } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) { + env.M = [ [ .9554734527042182, -.023098536874261423, .0632593086610217 ], [ -.028369706963208136, 1.0099954580058226, .021041398966943008 ], [ .012314001688319899, -.020507696433477912, 1.3303659366080753 ] ]; + } + } + hooks.run('chromatic-adaptation-end', env); + if (env.M) { + return multiplyMatrices(env.M, env.XYZ); + } else { + throw new TypeError('Only Bradford CAT with white points D50 and D65 supported for now.'); + } + } + var \u03b5$4 = 75e-6; + var _ColorSpace2 = (_Class_brand = new WeakSet(), _path = new WeakMap(), function() { + function _ColorSpace(options) { + var _options$coords, _ref2, _options$white, _options$formats, _this$formats$functio, _this$formats, _this$formats2; + _classCallCheck(this, _ColorSpace); + _classPrivateMethodInitSpec(this, _Class_brand); + _classPrivateFieldInitSpec(this, _path, void 0); + this.id = options.id; + this.name = options.name; + this.base = options.base ? _ColorSpace2.get(options.base) : null; + this.aliases = options.aliases; + if (this.base) { + this.fromBase = options.fromBase; + this.toBase = options.toBase; + } + var _coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords; + this.coords = _coords; + var white2 = (_ref2 = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref2 !== void 0 ? _ref2 : 'D65'; + this.white = getWhite(white2); + this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {}; + for (var name in this.formats) { + var format = this.formats[name]; + format.type || (format.type = 'function'); + format.name || (format.name = name); + } + if (options.cssId && !((_this$formats$functio = this.formats.functions) !== null && _this$formats$functio !== void 0 && _this$formats$functio.color)) { + this.formats.color = { + id: options.cssId + }; + Object.defineProperty(this, 'cssId', { + value: options.cssId + }); + } else if ((_this$formats = this.formats) !== null && _this$formats !== void 0 && _this$formats.color && !((_this$formats2 = this.formats) !== null && _this$formats2 !== void 0 && _this$formats2.color.id)) { + this.formats.color.id = this.id; + } + this.referred = options.referred; + _classPrivateFieldSet(_path, this, _assertClassBrand(_Class_brand, this, _getPath).call(this).reverse()); + hooks.run('colorspace-init-end', this); + } + return _createClass(_ColorSpace, [ { + key: 'inGamut', + value: function inGamut(coords) { + var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref3$epsilon = _ref3.epsilon, epsilon = _ref3$epsilon === void 0 ? \u03b5$4 : _ref3$epsilon; + if (this.isPolar) { + coords = this.toBase(coords); + return this.base.inGamut(coords, { + epsilon: epsilon + }); + } + var coordMeta = Object.values(this.coords); + return coords.every(function(c4, i) { + var meta = coordMeta[i]; + if (meta.type !== 'angle' && meta.range) { + if (Number.isNaN(c4)) { + return true; + } + var _meta$range = _slicedToArray(meta.range, 2), min = _meta$range[0], max2 = _meta$range[1]; + return (min === void 0 || c4 >= min - epsilon) && (max2 === void 0 || c4 <= max2 + epsilon); + } + return true; + }); + } + }, { + key: 'cssId', + get: function get() { + var _this$formats$functio2; + return ((_this$formats$functio2 = this.formats.functions) === null || _this$formats$functio2 === void 0 || (_this$formats$functio2 = _this$formats$functio2.color) === null || _this$formats$functio2 === void 0 ? void 0 : _this$formats$functio2.id) || this.id; + } + }, { + key: 'isPolar', + get: function get() { + for (var id in this.coords) { + if (this.coords[id].type === 'angle') { + return true; + } + } + return false; + } + }, { + key: 'getFormat', + value: function getFormat(format) { + if (_typeof(format) === 'object') { + format = _assertClassBrand(_Class_brand, this, _processFormat).call(this, format); + return format; + } + var ret; + if (format === 'default') { + ret = Object.values(this.formats)[0]; + } else { + ret = this.formats[format]; + } + if (ret) { + ret = _assertClassBrand(_Class_brand, this, _processFormat).call(this, ret); + return ret; + } + return null; + } + }, { + key: 'to', + value: function to(space, coords) { + if (arguments.length === 1) { + var _ref4 = [ space.space, space.coords ]; + space = _ref4[0]; + coords = _ref4[1]; + } + space = _ColorSpace2.get(space); + if (this === space) { + return coords; + } + coords = coords.map(function(c4) { + return Number.isNaN(c4) ? 0 : c4; + }); + var myPath = _classPrivateFieldGet(_path, this); + var otherPath = _classPrivateFieldGet(_path, space); + var connectionSpace, connectionSpaceIndex; + for (var i = 0; i < myPath.length; i++) { + if (myPath[i] === otherPath[i]) { + connectionSpace = myPath[i]; + connectionSpaceIndex = i; + } else { + break; + } + } + if (!connectionSpace) { + throw new Error('Cannot convert between color spaces '.concat(this, ' and ').concat(space, ': no connection space was found')); + } + for (var _i2 = myPath.length - 1; _i2 > connectionSpaceIndex; _i2--) { + coords = myPath[_i2].toBase(coords); + } + for (var _i3 = connectionSpaceIndex + 1; _i3 < otherPath.length; _i3++) { + coords = otherPath[_i3].fromBase(coords); + } + return coords; + } + }, { + key: 'from', + value: function from(space, coords) { + if (arguments.length === 1) { + var _ref5 = [ space.space, space.coords ]; + space = _ref5[0]; + coords = _ref5[1]; + } + space = _ColorSpace2.get(space); + return space.to(this, coords); + } + }, { + key: 'toString', + value: function toString() { + return ''.concat(this.name, ' (').concat(this.id, ')'); + } + }, { + key: 'getMinCoords', + value: function getMinCoords() { + var ret = []; + for (var id in this.coords) { + var _range2$min; + var meta = this.coords[id]; + var range2 = meta.range || meta.refRange; + ret.push((_range2$min = range2 === null || range2 === void 0 ? void 0 : range2.min) !== null && _range2$min !== void 0 ? _range2$min : 0); + } + return ret; + } + } ], [ { + key: 'all', + get: function get() { + return _toConsumableArray(new Set(Object.values(_ColorSpace2.registry))); + } + }, { + key: 'register', + value: function register(id, space) { + if (arguments.length === 1) { + space = arguments[0]; + id = space.id; + } + space = this.get(space); + if (this.registry[id] && this.registry[id] !== space) { + throw new Error('Duplicate color space registration: \''.concat(id, '\'')); + } + this.registry[id] = space; + if (arguments.length === 1 && space.aliases) { + var _iterator3 = _createForOfIteratorHelper(space.aliases), _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done; ) { + var alias = _step3.value; + this.register(alias, space); + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + } + return space; + } + }, { + key: 'get', + value: function get(space) { + if (!space || space instanceof _ColorSpace2) { + return space; + } + var argType = type(space); + if (argType === 'string') { + var ret = _ColorSpace2.registry[space.toLowerCase()]; + if (!ret) { + throw new TypeError('No color space found with id = "'.concat(space, '"')); + } + return ret; + } + for (var _len = arguments.length, alternatives = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + alternatives[_key - 1] = arguments[_key]; + } + if (alternatives.length) { + return _ColorSpace2.get.apply(_ColorSpace2, alternatives); + } + throw new TypeError(''.concat(space, ' is not a valid color space')); + } + }, { + key: 'resolveCoord', + value: function resolveCoord(ref, workingSpace) { + var coordType = type(ref); + var space, coord; + if (coordType === 'string') { + if (ref.includes('.')) { + var _ref$split = ref.split('.'); + var _ref$split2 = _slicedToArray(_ref$split, 2); + space = _ref$split2[0]; + coord = _ref$split2[1]; + } else { + space = void 0; + coord = ref; + } + } else if (Array.isArray(ref)) { + var _ref6 = _slicedToArray(ref, 2); + space = _ref6[0]; + coord = _ref6[1]; + } else { + space = ref.space; + coord = ref.coordId; + } + space = _ColorSpace2.get(space); + if (!space) { + space = workingSpace; + } + if (!space) { + throw new TypeError('Cannot resolve coordinate reference '.concat(ref, ': No color space specified and relative references are not allowed here')); + } + coordType = type(coord); + if (coordType === 'number' || coordType === 'string' && coord >= 0) { + var meta = Object.entries(space.coords)[coord]; + if (meta) { + return _extends({ + space: space, + id: meta[0], + index: coord + }, meta[1]); + } + } + space = _ColorSpace2.get(space); + var normalizedCoord = coord.toLowerCase(); + var i = 0; + for (var id in space.coords) { + var _meta$name; + var _meta = space.coords[id]; + if (id.toLowerCase() === normalizedCoord || ((_meta$name = _meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) { + return _extends({ + space: space, + id: id, + index: i + }, _meta); + } + i++; + } + throw new TypeError('No "'.concat(coord, '" coordinate found in ').concat(space.name, '. Its coordinates are: ').concat(Object.keys(space.coords).join(', '))); + } + } ]); + }()); + function _processFormat(format) { + if (format.coords && !format.coordGrammar) { + format.type || (format.type = 'function'); + format.name || (format.name = 'color'); + format.coordGrammar = parseCoordGrammar(format.coords); + var coordFormats = Object.entries(this.coords).map(function(_ref153, i) { + var _ref154 = _slicedToArray(_ref153, 2), id = _ref154[0], coordMeta = _ref154[1]; + var outputType = format.coordGrammar[i][0]; + var fromRange = coordMeta.range || coordMeta.refRange; + var toRange = outputType.range, suffix = ''; + if (outputType == '') { + toRange = [ 0, 100 ]; + suffix = '%'; + } else if (outputType == '') { + suffix = 'deg'; + } + return { + fromRange: fromRange, + toRange: toRange, + suffix: suffix + }; + }); + format.serializeCoords = function(coords, precision) { + return coords.map(function(c4, i) { + var _coordFormats$i = coordFormats[i], fromRange = _coordFormats$i.fromRange, toRange = _coordFormats$i.toRange, suffix = _coordFormats$i.suffix; + if (fromRange && toRange) { + c4 = mapRange(fromRange, toRange, c4); + } + c4 = toPrecision(c4, precision); + if (suffix) { + c4 += suffix; + } + return c4; + }); + }; + } + return format; + } + function _getPath() { + var ret = [ this ]; + for (var _space2 = this; _space2 = _space2.base; ) { + ret.push(_space2); + } + return ret; + } + var ColorSpace = _ColorSpace2; + __publicField(ColorSpace, 'registry', {}); + __publicField(ColorSpace, 'DEFAULT_FORMAT', { + type: 'functions', + name: 'color' + }); + var XYZ_D65 = new ColorSpace({ + id: 'xyz-d65', + name: 'XYZ D65', + coords: { + x: { + name: 'X' + }, + y: { + name: 'Y' + }, + z: { + name: 'Z' + } + }, + white: 'D65', + formats: { + color: { + ids: [ 'xyz-d65', 'xyz' ] + } + }, + aliases: [ 'xyz' ] + }); + var RGBColorSpace = function(_ColorSpace3) { + function RGBColorSpace(options) { + var _options$referred; + var _this; + _classCallCheck(this, RGBColorSpace); + if (!options.coords) { + options.coords = { + r: { + range: [ 0, 1 ], + name: 'Red' + }, + g: { + range: [ 0, 1 ], + name: 'Green' + }, + b: { + range: [ 0, 1 ], + name: 'Blue' + } + }; + } + if (!options.base) { + options.base = XYZ_D65; + } + if (options.toXYZ_M && options.fromXYZ_M) { + var _options$toBase, _options$fromBase; + (_options$toBase = options.toBase) !== null && _options$toBase !== void 0 ? _options$toBase : options.toBase = function(rgb) { + var xyz = multiplyMatrices(options.toXYZ_M, rgb); + if (_this.white !== _this.base.white) { + xyz = adapt$1(_this.white, _this.base.white, xyz); + } + return xyz; + }; + (_options$fromBase = options.fromBase) !== null && _options$fromBase !== void 0 ? _options$fromBase : options.fromBase = function(xyz) { + xyz = adapt$1(_this.base.white, _this.white, xyz); + return multiplyMatrices(options.fromXYZ_M, xyz); + }; + } + (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = 'display'; + return _this = _callSuper(this, RGBColorSpace, [ options ]); + } + _inherits(RGBColorSpace, _ColorSpace3); + return _createClass(RGBColorSpace); + }(ColorSpace); + function parse(str) { + var _String; + var env = { + str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim() + }; + hooks.run('parse-start', env); + if (env.color) { + return env.color; + } + env.parsed = parseFunction(env.str); + if (env.parsed) { + var name = env.parsed.name; + if (name === 'color') { + var id = env.parsed.args.shift(); + var alpha = env.parsed.rawArgs.indexOf('/') > 0 ? env.parsed.args.pop() : 1; + var _iterator4 = _createForOfIteratorHelper(ColorSpace.all), _step4; + try { + var _loop2 = function _loop2() { + var space = _step4.value; + var colorSpec = space.getFormat('color'); + if (colorSpec) { + var _colorSpec$ids; + if (id === colorSpec.id || (_colorSpec$ids = colorSpec.ids) !== null && _colorSpec$ids !== void 0 && _colorSpec$ids.includes(id)) { + var argCount = Object.keys(space.coords).length; + var coords = Array(argCount).fill(0); + coords.forEach(function(_, i) { + return coords[i] = env.parsed.args[i] || 0; + }); + return { + v: { + spaceId: space.id, + coords: coords, + alpha: alpha + } + }; + } + } + }, _ret; + for (_iterator4.s(); !(_step4 = _iterator4.n()).done; ) { + _ret = _loop2(); + if (_ret) { + return _ret.v; + } + } + } catch (err) { + _iterator4.e(err); + } finally { + _iterator4.f(); + } + var didYouMean = ''; + if (id in ColorSpace.registry) { + var _ColorSpace$registry$; + var cssId = (_ColorSpace$registry$ = ColorSpace.registry[id].formats) === null || _ColorSpace$registry$ === void 0 || (_ColorSpace$registry$ = _ColorSpace$registry$.functions) === null || _ColorSpace$registry$ === void 0 || (_ColorSpace$registry$ = _ColorSpace$registry$.color) === null || _ColorSpace$registry$ === void 0 ? void 0 : _ColorSpace$registry$.id; + if (cssId) { + didYouMean = 'Did you mean color('.concat(cssId, ')?'); + } + } + throw new TypeError('Cannot parse color('.concat(id, '). ') + (didYouMean || 'Missing a plugin?')); + } else { + var _iterator5 = _createForOfIteratorHelper(ColorSpace.all), _step5; + try { + var _loop3 = function _loop3() { + var space = _step5.value; + var format = space.getFormat(name); + if (format && format.type === 'function') { + var _alpha = 1; + if (format.lastAlpha || last(env.parsed.args).alpha) { + _alpha = env.parsed.args.pop(); + } + var coords = env.parsed.args; + if (format.coordGrammar) { + Object.entries(space.coords).forEach(function(_ref7, i) { + var _coords$i; + var _ref8 = _slicedToArray(_ref7, 2), id = _ref8[0], coordMeta = _ref8[1]; + var coordGrammar2 = format.coordGrammar[i]; + var providedType = (_coords$i = coords[i]) === null || _coords$i === void 0 ? void 0 : _coords$i.type; + coordGrammar2 = coordGrammar2.find(function(c4) { + return c4 == providedType; + }); + if (!coordGrammar2) { + var coordName = coordMeta.name || id; + throw new TypeError(''.concat(providedType, ' not allowed for ').concat(coordName, ' in ').concat(name, '()')); + } + var fromRange = coordGrammar2.range; + if (providedType === '') { + fromRange || (fromRange = [ 0, 1 ]); + } + var toRange = coordMeta.range || coordMeta.refRange; + if (fromRange && toRange) { + coords[i] = mapRange(fromRange, toRange, coords[i]); + } + }); + } + return { + v: { + spaceId: space.id, + coords: coords, + alpha: _alpha + } + }; + } + }, _ret2; + for (_iterator5.s(); !(_step5 = _iterator5.n()).done; ) { + _ret2 = _loop3(); + if (_ret2) { + return _ret2.v; + } + } + } catch (err) { + _iterator5.e(err); + } finally { + _iterator5.f(); + } + } + } else { + var _iterator6 = _createForOfIteratorHelper(ColorSpace.all), _step6; + try { + for (_iterator6.s(); !(_step6 = _iterator6.n()).done; ) { + var space = _step6.value; + for (var formatId in space.formats) { + var format = space.formats[formatId]; + if (format.type !== 'custom') { + continue; + } + if (format.test && !format.test(env.str)) { + continue; + } + var color = format.parse(env.str); + if (color) { + var _color$alpha; + (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : color.alpha = 1; + return color; + } + } + } + } catch (err) { + _iterator6.e(err); + } finally { + _iterator6.f(); + } + } + throw new TypeError('Could not parse '.concat(str, ' as a color. Missing a plugin?')); + } + function getColor(color) { + if (!color) { + throw new TypeError('Empty color reference'); + } + if (isString(color)) { + color = parse(color); + } + var space = color.space || color.spaceId; + if (!(space instanceof ColorSpace)) { + color.space = ColorSpace.get(space); + } + if (color.alpha === void 0) { + color.alpha = 1; + } + return color; + } + function getAll(color, space) { + space = ColorSpace.get(space); + return space.from(color); + } + function get(color, prop) { + var _ColorSpace$resolveCo = ColorSpace.resolveCoord(prop, color.space), space = _ColorSpace$resolveCo.space, index = _ColorSpace$resolveCo.index; + var coords = getAll(color, space); + return coords[index]; + } + function setAll(color, space, coords) { + space = ColorSpace.get(space); + color.coords = space.to(color.space, coords); + return color; + } + function set(color, prop, value) { + color = getColor(color); + if (arguments.length === 2 && type(arguments[1]) === 'object') { + var object = arguments[1]; + for (var p2 in object) { + set(color, p2, object[p2]); + } + } else { + if (typeof value === 'function') { + value = value(get(color, prop)); + } + var _ColorSpace$resolveCo2 = ColorSpace.resolveCoord(prop, color.space), space = _ColorSpace$resolveCo2.space, index = _ColorSpace$resolveCo2.index; + var coords = getAll(color, space); + coords[index] = value; + setAll(color, space, coords); + } + return color; + } + var XYZ_D50 = new ColorSpace({ + id: 'xyz-d50', + name: 'XYZ D50', + white: 'D50', + base: XYZ_D65, + fromBase: function fromBase(coords) { + return adapt$1(XYZ_D65.white, 'D50', coords); + }, + toBase: function toBase(coords) { + return adapt$1('D50', XYZ_D65.white, coords); + }, + formats: { + color: {} + } + }); + var \u03b5$3 = 216 / 24389; + var \u03b53$1 = 24 / 116; + var \u03ba$1 = 24389 / 27; + var white$1 = WHITES.D50; + var lab = new ColorSpace({ + id: 'lab', + name: 'Lab', + coords: { + l: { + refRange: [ 0, 100 ], + name: 'L' + }, + a: { + refRange: [ -125, 125 ] + }, + b: { + refRange: [ -125, 125 ] + } + }, + white: white$1, + base: XYZ_D50, + fromBase: function fromBase(XYZ) { + var xyz = XYZ.map(function(value, i) { + return value / white$1[i]; + }); + var f = xyz.map(function(value) { + return value > \u03b5$3 ? Math.cbrt(value) : (\u03ba$1 * value + 16) / 116; + }); + return [ 116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2]) ]; + }, + toBase: function toBase(Lab) { + var f = []; + f[1] = (Lab[0] + 16) / 116; + f[0] = Lab[1] / 500 + f[1]; + f[2] = f[1] - Lab[2] / 200; + var xyz = [ f[0] > \u03b53$1 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / \u03ba$1, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / \u03ba$1, f[2] > \u03b53$1 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / \u03ba$1 ]; + return xyz.map(function(value, i) { + return value * white$1[i]; + }); + }, + formats: { + lab: { + coords: [ ' | ', '', '' ] + } + } + }); + function constrain(angle) { + return (angle % 360 + 360) % 360; + } + function adjust(arc, angles) { + if (arc === 'raw') { + return angles; + } + var _angles$map = angles.map(constrain), _angles$map2 = _slicedToArray(_angles$map, 2), a1 = _angles$map2[0], a2 = _angles$map2[1]; + var angleDiff = a2 - a1; + if (arc === 'increasing') { + if (angleDiff < 0) { + a2 += 360; + } + } else if (arc === 'decreasing') { + if (angleDiff > 0) { + a1 += 360; + } + } else if (arc === 'longer') { + if (-180 < angleDiff && angleDiff < 180) { + if (angleDiff > 0) { + a2 += 360; + } else { + a1 += 360; + } + } + } else if (arc === 'shorter') { + if (angleDiff > 180) { + a1 += 360; + } else if (angleDiff < -180) { + a2 += 360; + } + } + return [ a1, a2 ]; + } + var lch = new ColorSpace({ + id: 'lch', + name: 'LCH', + coords: { + l: { + refRange: [ 0, 100 ], + name: 'Lightness' + }, + c: { + refRange: [ 0, 150 ], + name: 'Chroma' + }, + h: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + } + }, + base: lab, + fromBase: function fromBase(Lab) { + var _Lab = _slicedToArray(Lab, 3), L = _Lab[0], a2 = _Lab[1], b2 = _Lab[2]; + var hue; + var \u03b52 = .02; + if (Math.abs(a2) < \u03b52 && Math.abs(b2) < \u03b52) { + hue = NaN; + } else { + hue = Math.atan2(b2, a2) * 180 / Math.PI; + } + return [ L, Math.sqrt(Math.pow(a2, 2) + Math.pow(b2, 2)), constrain(hue) ]; + }, + toBase: function toBase(LCH) { + var _LCH = _slicedToArray(LCH, 3), Lightness = _LCH[0], Chroma = _LCH[1], Hue = _LCH[2]; + if (Chroma < 0) { + Chroma = 0; + } + if (isNaN(Hue)) { + Hue = 0; + } + return [ Lightness, Chroma * Math.cos(Hue * Math.PI / 180), Chroma * Math.sin(Hue * Math.PI / 180) ]; + }, + formats: { + lch: { + coords: [ ' | ', '', ' | ' ] + } + } + }); + var Gfactor = Math.pow(25, 7); + var \u03c0$1 = Math.PI; + var r2d = 180 / \u03c0$1; + var d2r$1 = \u03c0$1 / 180; + function deltaE2000(color, sample) { + var _ref9 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref9$kL = _ref9.kL, kL = _ref9$kL === void 0 ? 1 : _ref9$kL, _ref9$kC = _ref9.kC, kC = _ref9$kC === void 0 ? 1 : _ref9$kC, _ref9$kH = _ref9.kH, kH = _ref9$kH === void 0 ? 1 : _ref9$kH; + var _lab$from = lab.from(color), _lab$from2 = _slicedToArray(_lab$from, 3), L1 = _lab$from2[0], a1 = _lab$from2[1], b1 = _lab$from2[2]; + var C1 = lch.from(lab, [ L1, a1, b1 ])[1]; + var _lab$from3 = lab.from(sample), _lab$from4 = _slicedToArray(_lab$from3, 3), L2 = _lab$from4[0], a2 = _lab$from4[1], b2 = _lab$from4[2]; + var C2 = lch.from(lab, [ L2, a2, b2 ])[1]; + if (C1 < 0) { + C1 = 0; + } + if (C2 < 0) { + C2 = 0; + } + var Cbar = (C1 + C2) / 2; + var C7 = Math.pow(Cbar, 7); + var G = .5 * (1 - Math.sqrt(C7 / (C7 + Gfactor))); + var adash1 = (1 + G) * a1; + var adash2 = (1 + G) * a2; + var Cdash1 = Math.sqrt(Math.pow(adash1, 2) + Math.pow(b1, 2)); + var Cdash2 = Math.sqrt(Math.pow(adash2, 2) + Math.pow(b2, 2)); + var h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1); + var h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2); + if (h1 < 0) { + h1 += 2 * \u03c0$1; + } + if (h2 < 0) { + h2 += 2 * \u03c0$1; + } + h1 *= r2d; + h2 *= r2d; + var \u0394L = L2 - L1; + var \u0394C = Cdash2 - Cdash1; + var hdiff = h2 - h1; + var hsum = h1 + h2; + var habs = Math.abs(hdiff); + var \u0394h; + if (Cdash1 * Cdash2 === 0) { + \u0394h = 0; + } else if (habs <= 180) { + \u0394h = hdiff; + } else if (hdiff > 180) { + \u0394h = hdiff - 360; + } else if (hdiff < -180) { + \u0394h = hdiff + 360; + } else { + console.log('the unthinkable has happened'); + } + var \u0394H = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(\u0394h * d2r$1 / 2); + var Ldash = (L1 + L2) / 2; + var Cdash = (Cdash1 + Cdash2) / 2; + var Cdash7 = Math.pow(Cdash, 7); + var hdash; + if (Cdash1 * Cdash2 === 0) { + hdash = hsum; + } else if (habs <= 180) { + hdash = hsum / 2; + } else if (hsum < 360) { + hdash = (hsum + 360) / 2; + } else { + hdash = (hsum - 360) / 2; + } + var lsq = Math.pow(Ldash - 50, 2); + var SL = 1 + .015 * lsq / Math.sqrt(20 + lsq); + var SC = 1 + .045 * Cdash; + var T = 1; + T -= .17 * Math.cos((hdash - 30) * d2r$1); + T += .24 * Math.cos(2 * hdash * d2r$1); + T += .32 * Math.cos((3 * hdash + 6) * d2r$1); + T -= .2 * Math.cos((4 * hdash - 63) * d2r$1); + var SH = 1 + .015 * Cdash * T; + var \u0394\u03b8 = 30 * Math.exp(-1 * Math.pow((hdash - 275) / 25, 2)); + var RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor)); + var RT = -1 * Math.sin(2 * \u0394\u03b8 * d2r$1) * RC; + var dE = Math.pow(\u0394L / (kL * SL), 2); + dE += Math.pow(\u0394C / (kC * SC), 2); + dE += Math.pow(\u0394H / (kH * SH), 2); + dE += RT * (\u0394C / (kC * SC)) * (\u0394H / (kH * SH)); + return Math.sqrt(dE); + } + var \u03b5$2 = 75e-6; + function inGamut(color) { + var space = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : color.space; + var _ref0 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref0$epsilon = _ref0.epsilon, epsilon = _ref0$epsilon === void 0 ? \u03b5$2 : _ref0$epsilon; + color = getColor(color); + space = ColorSpace.get(space); + var coords = color.coords; + if (space !== color.space) { + coords = space.from(color); + } + return space.inGamut(coords, { + epsilon: epsilon + }); + } + function clone(color) { + return { + space: color.space, + coords: color.coords.slice(), + alpha: color.alpha + }; + } + function toGamut(color) { + var _ref1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref1$method = _ref1.method, method = _ref1$method === void 0 ? defaults.gamut_mapping : _ref1$method, _ref1$space = _ref1.space, space = _ref1$space === void 0 ? color.space : _ref1$space; + if (isString(arguments[1])) { + space = arguments[1]; + } + space = ColorSpace.get(space); + if (inGamut(color, space, { + epsilon: 0 + })) { + return color; + } + var spaceColor = to(color, space); + if (method !== 'clip' && !inGamut(color, space)) { + var clipped = toGamut(clone(spaceColor), { + method: 'clip', + space: space + }); + if (deltaE2000(color, clipped) > 2) { + var coordMeta = ColorSpace.resolveCoord(method); + var mapSpace = coordMeta.space; + var coordId = coordMeta.id; + var mappedColor = to(spaceColor, mapSpace); + var bounds = coordMeta.range || coordMeta.refRange; + var min = bounds[0]; + var \u03b52 = .01; + var low = min; + var high = get(mappedColor, coordId); + while (high - low > \u03b52) { + var clipped2 = clone(mappedColor); + clipped2 = toGamut(clipped2, { + space: space, + method: 'clip' + }); + var deltaE2 = deltaE2000(mappedColor, clipped2); + if (deltaE2 - 2 < \u03b52) { + low = get(mappedColor, coordId); + } else { + high = get(mappedColor, coordId); + } + set(mappedColor, coordId, (low + high) / 2); + } + spaceColor = to(mappedColor, space); + } else { + spaceColor = clipped; + } + } + if (method === 'clip' || !inGamut(spaceColor, space, { + epsilon: 0 + })) { + var _bounds = Object.values(space.coords).map(function(c4) { + return c4.range || []; + }); + spaceColor.coords = spaceColor.coords.map(function(c4, i) { + var _bounds$i = _slicedToArray(_bounds[i], 2), min = _bounds$i[0], max2 = _bounds$i[1]; + if (min !== void 0) { + c4 = Math.max(min, c4); + } + if (max2 !== void 0) { + c4 = Math.min(c4, max2); + } + return c4; + }); + } + if (space !== color.space) { + spaceColor = to(spaceColor, color.space); + } + color.coords = spaceColor.coords; + return color; + } + toGamut.returns = 'color'; + function to(color, space) { + var _ref10 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, inGamut2 = _ref10.inGamut; + color = getColor(color); + space = ColorSpace.get(space); + var coords = space.from(color); + var ret = { + space: space, + coords: coords, + alpha: color.alpha + }; + if (inGamut2) { + ret = toGamut(ret); + } + return ret; + } + to.returns = 'color'; + function serialize(color) { + var _ref12, _color$space$getForma; + var _ref11 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _ref11$precision = _ref11.precision, precision = _ref11$precision === void 0 ? defaults.precision : _ref11$precision, _ref11$format = _ref11.format, format = _ref11$format === void 0 ? 'default' : _ref11$format, _ref11$inGamut = _ref11.inGamut, inGamut$1 = _ref11$inGamut === void 0 ? true : _ref11$inGamut, customOptions = _objectWithoutProperties(_ref11, _excluded); + var ret; + color = getColor(color); + var formatId = format; + format = (_ref12 = (_color$space$getForma = color.space.getFormat(format)) !== null && _color$space$getForma !== void 0 ? _color$space$getForma : color.space.getFormat('default')) !== null && _ref12 !== void 0 ? _ref12 : ColorSpace.DEFAULT_FORMAT; + inGamut$1 || (inGamut$1 = format.toGamut); + var coords = color.coords; + coords = coords.map(function(c4) { + return c4 ? c4 : 0; + }); + if (inGamut$1 && !inGamut(color)) { + coords = toGamut(clone(color), inGamut$1 === true ? void 0 : inGamut$1).coords; + } + if (format.type === 'custom') { + customOptions.precision = precision; + if (format.serialize) { + ret = format.serialize(coords, color.alpha, customOptions); + } else { + throw new TypeError('format '.concat(formatId, ' can only be used to parse colors, not for serialization')); + } + } else { + var name = format.name || 'color'; + if (format.serializeCoords) { + coords = format.serializeCoords(coords, precision); + } else { + if (precision !== null) { + coords = coords.map(function(c4) { + return toPrecision(c4, precision); + }); + } + } + var args = _toConsumableArray(coords); + if (name === 'color') { + var _format$ids; + var cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || color.space.id; + args.unshift(cssId); + } + var alpha = color.alpha; + if (precision !== null) { + alpha = toPrecision(alpha, precision); + } + var strAlpha = color.alpha < 1 && !format.noAlpha ? ''.concat(format.commas ? ',' : ' /', ' ').concat(alpha) : ''; + ret = ''.concat(name, '(').concat(args.join(format.commas ? ', ' : ' ')).concat(strAlpha, ')'); + } + return ret; + } + var toXYZ_M$5 = [ [ .6369580483012914, .14461690358620832, .1688809751641721 ], [ .2627002120112671, .6779980715188708, .05930171646986196 ], [ 0, .028072693049087428, 1.060985057710791 ] ]; + var fromXYZ_M$5 = [ [ 1.716651187971268, -.355670783776392, -.25336628137366 ], [ -.666684351832489, 1.616481236634939, .0157685458139111 ], [ .017639857445311, -.042770613257809, .942103121235474 ] ]; + var REC2020Linear = new RGBColorSpace({ + id: 'rec2020-linear', + name: 'Linear REC.2020', + white: 'D65', + toXYZ_M: toXYZ_M$5, + fromXYZ_M: fromXYZ_M$5, + formats: { + color: {} + } + }); + var \u03b1 = 1.09929682680944; + var \u03b2 = .018053968510807; + var REC2020 = new RGBColorSpace({ + id: 'rec2020', + name: 'REC.2020', + base: REC2020Linear, + toBase: function toBase(RGB) { + return RGB.map(function(val) { + if (val < \u03b2 * 4.5) { + return val / 4.5; + } + return Math.pow((val + \u03b1 - 1) / \u03b1, 1 / .45); + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(val) { + if (val >= \u03b2) { + return \u03b1 * Math.pow(val, .45) - (\u03b1 - 1); + } + return 4.5 * val; + }); + }, + formats: { + color: {} + } + }); + var toXYZ_M$4 = [ [ .4865709486482162, .26566769316909306, .1982172852343625 ], [ .2289745640697488, .6917385218365064, .079286914093745 ], [ 0, .04511338185890264, 1.043944368900976 ] ]; + var fromXYZ_M$4 = [ [ 2.493496911941425, -.9313836179191239, -.40271078445071684 ], [ -.8294889695615747, 1.7626640603183463, .023624685841943577 ], [ .03584583024378447, -.07617238926804182, .9568845240076872 ] ]; + var P3Linear = new RGBColorSpace({ + id: 'p3-linear', + name: 'Linear P3', + white: 'D65', + toXYZ_M: toXYZ_M$4, + fromXYZ_M: fromXYZ_M$4 + }); + var toXYZ_M$3 = [ [ .41239079926595934, .357584339383878, .1804807884018343 ], [ .21263900587151027, .715168678767756, .07219231536073371 ], [ .01933081871559182, .11919477979462598, .9505321522496607 ] ]; + var fromXYZ_M$3 = [ [ 3.2409699419045226, -1.537383177570094, -.4986107602930034 ], [ -.9692436362808796, 1.8759675015077202, .04155505740717559 ], [ .05563007969699366, -.20397695888897652, 1.0569715142428786 ] ]; + var sRGBLinear = new RGBColorSpace({ + id: 'srgb-linear', + name: 'Linear sRGB', + white: 'D65', + toXYZ_M: toXYZ_M$3, + fromXYZ_M: fromXYZ_M$3, + formats: { + color: {} + } + }); + var KEYWORDS = { + aliceblue: [ 240 / 255, 248 / 255, 1 ], + antiquewhite: [ 250 / 255, 235 / 255, 215 / 255 ], + aqua: [ 0, 1, 1 ], + aquamarine: [ 127 / 255, 1, 212 / 255 ], + azure: [ 240 / 255, 1, 1 ], + beige: [ 245 / 255, 245 / 255, 220 / 255 ], + bisque: [ 1, 228 / 255, 196 / 255 ], + black: [ 0, 0, 0 ], + blanchedalmond: [ 1, 235 / 255, 205 / 255 ], + blue: [ 0, 0, 1 ], + blueviolet: [ 138 / 255, 43 / 255, 226 / 255 ], + brown: [ 165 / 255, 42 / 255, 42 / 255 ], + burlywood: [ 222 / 255, 184 / 255, 135 / 255 ], + cadetblue: [ 95 / 255, 158 / 255, 160 / 255 ], + chartreuse: [ 127 / 255, 1, 0 ], + chocolate: [ 210 / 255, 105 / 255, 30 / 255 ], + coral: [ 1, 127 / 255, 80 / 255 ], + cornflowerblue: [ 100 / 255, 149 / 255, 237 / 255 ], + cornsilk: [ 1, 248 / 255, 220 / 255 ], + crimson: [ 220 / 255, 20 / 255, 60 / 255 ], + cyan: [ 0, 1, 1 ], + darkblue: [ 0, 0, 139 / 255 ], + darkcyan: [ 0, 139 / 255, 139 / 255 ], + darkgoldenrod: [ 184 / 255, 134 / 255, 11 / 255 ], + darkgray: [ 169 / 255, 169 / 255, 169 / 255 ], + darkgreen: [ 0, 100 / 255, 0 ], + darkgrey: [ 169 / 255, 169 / 255, 169 / 255 ], + darkkhaki: [ 189 / 255, 183 / 255, 107 / 255 ], + darkmagenta: [ 139 / 255, 0, 139 / 255 ], + darkolivegreen: [ 85 / 255, 107 / 255, 47 / 255 ], + darkorange: [ 1, 140 / 255, 0 ], + darkorchid: [ 153 / 255, 50 / 255, 204 / 255 ], + darkred: [ 139 / 255, 0, 0 ], + darksalmon: [ 233 / 255, 150 / 255, 122 / 255 ], + darkseagreen: [ 143 / 255, 188 / 255, 143 / 255 ], + darkslateblue: [ 72 / 255, 61 / 255, 139 / 255 ], + darkslategray: [ 47 / 255, 79 / 255, 79 / 255 ], + darkslategrey: [ 47 / 255, 79 / 255, 79 / 255 ], + darkturquoise: [ 0, 206 / 255, 209 / 255 ], + darkviolet: [ 148 / 255, 0, 211 / 255 ], + deeppink: [ 1, 20 / 255, 147 / 255 ], + deepskyblue: [ 0, 191 / 255, 1 ], + dimgray: [ 105 / 255, 105 / 255, 105 / 255 ], + dimgrey: [ 105 / 255, 105 / 255, 105 / 255 ], + dodgerblue: [ 30 / 255, 144 / 255, 1 ], + firebrick: [ 178 / 255, 34 / 255, 34 / 255 ], + floralwhite: [ 1, 250 / 255, 240 / 255 ], + forestgreen: [ 34 / 255, 139 / 255, 34 / 255 ], + fuchsia: [ 1, 0, 1 ], + gainsboro: [ 220 / 255, 220 / 255, 220 / 255 ], + ghostwhite: [ 248 / 255, 248 / 255, 1 ], + gold: [ 1, 215 / 255, 0 ], + goldenrod: [ 218 / 255, 165 / 255, 32 / 255 ], + gray: [ 128 / 255, 128 / 255, 128 / 255 ], + green: [ 0, 128 / 255, 0 ], + greenyellow: [ 173 / 255, 1, 47 / 255 ], + grey: [ 128 / 255, 128 / 255, 128 / 255 ], + honeydew: [ 240 / 255, 1, 240 / 255 ], + hotpink: [ 1, 105 / 255, 180 / 255 ], + indianred: [ 205 / 255, 92 / 255, 92 / 255 ], + indigo: [ 75 / 255, 0, 130 / 255 ], + ivory: [ 1, 1, 240 / 255 ], + khaki: [ 240 / 255, 230 / 255, 140 / 255 ], + lavender: [ 230 / 255, 230 / 255, 250 / 255 ], + lavenderblush: [ 1, 240 / 255, 245 / 255 ], + lawngreen: [ 124 / 255, 252 / 255, 0 ], + lemonchiffon: [ 1, 250 / 255, 205 / 255 ], + lightblue: [ 173 / 255, 216 / 255, 230 / 255 ], + lightcoral: [ 240 / 255, 128 / 255, 128 / 255 ], + lightcyan: [ 224 / 255, 1, 1 ], + lightgoldenrodyellow: [ 250 / 255, 250 / 255, 210 / 255 ], + lightgray: [ 211 / 255, 211 / 255, 211 / 255 ], + lightgreen: [ 144 / 255, 238 / 255, 144 / 255 ], + lightgrey: [ 211 / 255, 211 / 255, 211 / 255 ], + lightpink: [ 1, 182 / 255, 193 / 255 ], + lightsalmon: [ 1, 160 / 255, 122 / 255 ], + lightseagreen: [ 32 / 255, 178 / 255, 170 / 255 ], + lightskyblue: [ 135 / 255, 206 / 255, 250 / 255 ], + lightslategray: [ 119 / 255, 136 / 255, 153 / 255 ], + lightslategrey: [ 119 / 255, 136 / 255, 153 / 255 ], + lightsteelblue: [ 176 / 255, 196 / 255, 222 / 255 ], + lightyellow: [ 1, 1, 224 / 255 ], + lime: [ 0, 1, 0 ], + limegreen: [ 50 / 255, 205 / 255, 50 / 255 ], + linen: [ 250 / 255, 240 / 255, 230 / 255 ], + magenta: [ 1, 0, 1 ], + maroon: [ 128 / 255, 0, 0 ], + mediumaquamarine: [ 102 / 255, 205 / 255, 170 / 255 ], + mediumblue: [ 0, 0, 205 / 255 ], + mediumorchid: [ 186 / 255, 85 / 255, 211 / 255 ], + mediumpurple: [ 147 / 255, 112 / 255, 219 / 255 ], + mediumseagreen: [ 60 / 255, 179 / 255, 113 / 255 ], + mediumslateblue: [ 123 / 255, 104 / 255, 238 / 255 ], + mediumspringgreen: [ 0, 250 / 255, 154 / 255 ], + mediumturquoise: [ 72 / 255, 209 / 255, 204 / 255 ], + mediumvioletred: [ 199 / 255, 21 / 255, 133 / 255 ], + midnightblue: [ 25 / 255, 25 / 255, 112 / 255 ], + mintcream: [ 245 / 255, 1, 250 / 255 ], + mistyrose: [ 1, 228 / 255, 225 / 255 ], + moccasin: [ 1, 228 / 255, 181 / 255 ], + navajowhite: [ 1, 222 / 255, 173 / 255 ], + navy: [ 0, 0, 128 / 255 ], + oldlace: [ 253 / 255, 245 / 255, 230 / 255 ], + olive: [ 128 / 255, 128 / 255, 0 ], + olivedrab: [ 107 / 255, 142 / 255, 35 / 255 ], + orange: [ 1, 165 / 255, 0 ], + orangered: [ 1, 69 / 255, 0 ], + orchid: [ 218 / 255, 112 / 255, 214 / 255 ], + palegoldenrod: [ 238 / 255, 232 / 255, 170 / 255 ], + palegreen: [ 152 / 255, 251 / 255, 152 / 255 ], + paleturquoise: [ 175 / 255, 238 / 255, 238 / 255 ], + palevioletred: [ 219 / 255, 112 / 255, 147 / 255 ], + papayawhip: [ 1, 239 / 255, 213 / 255 ], + peachpuff: [ 1, 218 / 255, 185 / 255 ], + peru: [ 205 / 255, 133 / 255, 63 / 255 ], + pink: [ 1, 192 / 255, 203 / 255 ], + plum: [ 221 / 255, 160 / 255, 221 / 255 ], + powderblue: [ 176 / 255, 224 / 255, 230 / 255 ], + purple: [ 128 / 255, 0, 128 / 255 ], + rebeccapurple: [ 102 / 255, 51 / 255, 153 / 255 ], + red: [ 1, 0, 0 ], + rosybrown: [ 188 / 255, 143 / 255, 143 / 255 ], + royalblue: [ 65 / 255, 105 / 255, 225 / 255 ], + saddlebrown: [ 139 / 255, 69 / 255, 19 / 255 ], + salmon: [ 250 / 255, 128 / 255, 114 / 255 ], + sandybrown: [ 244 / 255, 164 / 255, 96 / 255 ], + seagreen: [ 46 / 255, 139 / 255, 87 / 255 ], + seashell: [ 1, 245 / 255, 238 / 255 ], + sienna: [ 160 / 255, 82 / 255, 45 / 255 ], + silver: [ 192 / 255, 192 / 255, 192 / 255 ], + skyblue: [ 135 / 255, 206 / 255, 235 / 255 ], + slateblue: [ 106 / 255, 90 / 255, 205 / 255 ], + slategray: [ 112 / 255, 128 / 255, 144 / 255 ], + slategrey: [ 112 / 255, 128 / 255, 144 / 255 ], + snow: [ 1, 250 / 255, 250 / 255 ], + springgreen: [ 0, 1, 127 / 255 ], + steelblue: [ 70 / 255, 130 / 255, 180 / 255 ], + tan: [ 210 / 255, 180 / 255, 140 / 255 ], + teal: [ 0, 128 / 255, 128 / 255 ], + thistle: [ 216 / 255, 191 / 255, 216 / 255 ], + tomato: [ 1, 99 / 255, 71 / 255 ], + turquoise: [ 64 / 255, 224 / 255, 208 / 255 ], + violet: [ 238 / 255, 130 / 255, 238 / 255 ], + wheat: [ 245 / 255, 222 / 255, 179 / 255 ], + white: [ 1, 1, 1 ], + whitesmoke: [ 245 / 255, 245 / 255, 245 / 255 ], + yellow: [ 1, 1, 0 ], + yellowgreen: [ 154 / 255, 205 / 255, 50 / 255 ] + }; + var coordGrammar = Array(3).fill(' | [0, 255]'); + var coordGrammarNumber = Array(3).fill('[0, 255]'); + var sRGB = new RGBColorSpace({ + id: 'srgb', + name: 'sRGB', + base: sRGBLinear, + fromBase: function fromBase(rgb) { + return rgb.map(function(val) { + var sign = val < 0 ? -1 : 1; + var abs = val * sign; + if (abs > .0031308) { + return sign * (1.055 * Math.pow(abs, 1 / 2.4) - .055); + } + return 12.92 * val; + }); + }, + toBase: function toBase(rgb) { + return rgb.map(function(val) { + var sign = val < 0 ? -1 : 1; + var abs = val * sign; + if (abs < .04045) { + return val / 12.92; + } + return sign * Math.pow((abs + .055) / 1.055, 2.4); + }); + }, + formats: { + rgb: { + coords: coordGrammar + }, + rgb_number: { + name: 'rgb', + commas: true, + coords: coordGrammarNumber, + noAlpha: true + }, + color: {}, + rgba: { + coords: coordGrammar, + commas: true, + lastAlpha: true + }, + rgba_number: { + name: 'rgba', + commas: true, + coords: coordGrammarNumber + }, + hex: { + type: 'custom', + toGamut: true, + test: function test(str) { + return /^#([a-f0-9]{3,4}){1,2}$/i.test(str); + }, + parse: function parse(str) { + if (str.length <= 5) { + str = str.replace(/[a-f0-9]/gi, '$&$&'); + } + var rgba = []; + str.replace(/[a-f0-9]{2}/gi, function(component) { + rgba.push(parseInt(component, 16) / 255); + }); + return { + spaceId: 'srgb', + coords: rgba.slice(0, 3), + alpha: rgba.slice(3)[0] + }; + }, + serialize: function serialize(coords, alpha) { + var _ref13 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref13$collapse = _ref13.collapse, collapse = _ref13$collapse === void 0 ? true : _ref13$collapse; + if (alpha < 1) { + coords.push(alpha); + } + coords = coords.map(function(c4) { + return Math.round(c4 * 255); + }); + var collapsible = collapse && coords.every(function(c4) { + return c4 % 17 === 0; + }); + var hex = coords.map(function(c4) { + if (collapsible) { + return (c4 / 17).toString(16); + } + return c4.toString(16).padStart(2, '0'); + }).join(''); + return '#' + hex; + } + }, + keyword: { + type: 'custom', + test: function test(str) { + return /^[a-z]+$/i.test(str); + }, + parse: function parse(str) { + str = str.toLowerCase(); + var ret = { + spaceId: 'srgb', + coords: null, + alpha: 1 + }; + if (str === 'transparent') { + ret.coords = KEYWORDS.black; + ret.alpha = 0; + } else { + ret.coords = KEYWORDS[str]; + } + if (ret.coords) { + return ret; + } + } + } + } + }); + var P3 = new RGBColorSpace({ + id: 'p3', + name: 'P3', + base: P3Linear, + fromBase: sRGB.fromBase, + toBase: sRGB.toBase, + formats: { + color: { + id: 'display-p3' + } + } + }); + defaults.display_space = sRGB; + if (typeof CSS !== 'undefined' && (_CSS = CSS) !== null && _CSS !== void 0 && _CSS.supports) { + for (var _i4 = 0, _arr = [ lab, REC2020, P3 ]; _i4 < _arr.length; _i4++) { + var space = _arr[_i4]; + var coords = space.getMinCoords(); + var color = { + space: space, + coords: coords, + alpha: 1 + }; + var str = serialize(color); + if (CSS.supports('color', str)) { + defaults.display_space = space; + break; + } + } + } + function _display(color) { + var _CSS2; + var _ref14 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _ref14$space = _ref14.space, space = _ref14$space === void 0 ? defaults.display_space : _ref14$space, options = _objectWithoutProperties(_ref14, _excluded2); + var ret = serialize(color, options); + if (typeof CSS === 'undefined' || (_CSS2 = CSS) !== null && _CSS2 !== void 0 && _CSS2.supports('color', ret) || !defaults.display_space) { + ret = new String(ret); + ret.color = color; + } else { + var fallbackColor = to(color, space); + ret = new String(serialize(fallbackColor, options)); + ret.color = fallbackColor; + } + return ret; + } + function distance(color1, color2) { + var space = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'lab'; + space = ColorSpace.get(space); + var coords1 = space.from(color1); + var coords2 = space.from(color2); + return Math.sqrt(coords1.reduce(function(acc, c12, i) { + var c22 = coords2[i]; + if (isNaN(c12) || isNaN(c22)) { + return acc; + } + return acc + Math.pow(c22 - c12, 2); + }, 0)); + } + function equals(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every(function(c4, i) { + return c4 === color2.coords[i]; + }); + } + function getLuminance(color) { + return get(color, [ XYZ_D65, 'y' ]); + } + function setLuminance(color, value) { + set(color, [ XYZ_D65, 'y' ], value); + } + function register$2(Color3) { + Object.defineProperty(Color3.prototype, 'luminance', { + get: function get() { + return getLuminance(this); + }, + set: function set(value) { + setLuminance(this, value); + } + }); + } + var luminance = Object.freeze({ + __proto__: null, + getLuminance: getLuminance, + setLuminance: setLuminance, + register: register$2 + }); + function contrastWCAG21(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + var Y1 = Math.max(getLuminance(color1), 0); + var Y2 = Math.max(getLuminance(color2), 0); + if (Y2 > Y1) { + var _ref15 = [ Y2, Y1 ]; + Y1 = _ref15[0]; + Y2 = _ref15[1]; + } + return (Y1 + .05) / (Y2 + .05); + } + var normBG = .56; + var normTXT = .57; + var revTXT = .62; + var revBG = .65; + var blkThrs = .022; + var blkClmp = 1.414; + var loClip = .1; + var deltaYmin = 5e-4; + var scaleBoW = 1.14; + var loBoWoffset = .027; + var scaleWoB = 1.14; + function fclamp(Y) { + if (Y >= blkThrs) { + return Y; + } + return Y + Math.pow(blkThrs - Y, blkClmp); + } + function linearize(val) { + var sign = val < 0 ? -1 : 1; + var abs = Math.abs(val); + return sign * Math.pow(abs, 2.4); + } + function contrastAPCA(background, foreground) { + foreground = getColor(foreground); + background = getColor(background); + var S; + var C; + var Sapc; + var R, G, B; + foreground = to(foreground, 'srgb'); + var _foreground$coords = _slicedToArray(foreground.coords, 3); + R = _foreground$coords[0]; + G = _foreground$coords[1]; + B = _foreground$coords[2]; + var lumTxt = linearize(R) * .2126729 + linearize(G) * .7151522 + linearize(B) * .072175; + background = to(background, 'srgb'); + var _background$coords = _slicedToArray(background.coords, 3); + R = _background$coords[0]; + G = _background$coords[1]; + B = _background$coords[2]; + var lumBg = linearize(R) * .2126729 + linearize(G) * .7151522 + linearize(B) * .072175; + var Ytxt = fclamp(lumTxt); + var Ybg = fclamp(lumBg); + var BoW = Ybg > Ytxt; + if (Math.abs(Ybg - Ytxt) < deltaYmin) { + C = 0; + } else { + if (BoW) { + S = Math.pow(Ybg, normBG) - Math.pow(Ytxt, normTXT); + C = S * scaleBoW; + } else { + S = Math.pow(Ybg, revBG) - Math.pow(Ytxt, revTXT); + C = S * scaleWoB; + } + } + if (Math.abs(C) < loClip) { + Sapc = 0; + } else if (C > 0) { + Sapc = C - loBoWoffset; + } else { + Sapc = C + loBoWoffset; + } + return Sapc * 100; + } + function contrastMichelson(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + var Y1 = Math.max(getLuminance(color1), 0); + var Y2 = Math.max(getLuminance(color2), 0); + if (Y2 > Y1) { + var _ref16 = [ Y2, Y1 ]; + Y1 = _ref16[0]; + Y2 = _ref16[1]; + } + var denom = Y1 + Y2; + return denom === 0 ? 0 : (Y1 - Y2) / denom; + } + var max = 5e4; + function contrastWeber(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + var Y1 = Math.max(getLuminance(color1), 0); + var Y2 = Math.max(getLuminance(color2), 0); + if (Y2 > Y1) { + var _ref17 = [ Y2, Y1 ]; + Y1 = _ref17[0]; + Y2 = _ref17[1]; + } + return Y2 === 0 ? max : (Y1 - Y2) / Y2; + } + function contrastLstar(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + var L1 = get(color1, [ lab, 'l' ]); + var L2 = get(color2, [ lab, 'l' ]); + return Math.abs(L1 - L2); + } + var \u03b5$1 = 216 / 24389; + var \u03b53 = 24 / 116; + var \u03ba = 24389 / 27; + var white = WHITES.D65; + var lab_d65 = new ColorSpace({ + id: 'lab-d65', + name: 'Lab D65', + coords: { + l: { + refRange: [ 0, 100 ], + name: 'L' + }, + a: { + refRange: [ -125, 125 ] + }, + b: { + refRange: [ -125, 125 ] + } + }, + white: white, + base: XYZ_D65, + fromBase: function fromBase(XYZ) { + var xyz = XYZ.map(function(value, i) { + return value / white[i]; + }); + var f = xyz.map(function(value) { + return value > \u03b5$1 ? Math.cbrt(value) : (\u03ba * value + 16) / 116; + }); + return [ 116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2]) ]; + }, + toBase: function toBase(Lab) { + var f = []; + f[1] = (Lab[0] + 16) / 116; + f[0] = Lab[1] / 500 + f[1]; + f[2] = f[1] - Lab[2] / 200; + var xyz = [ f[0] > \u03b53 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / \u03ba, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / \u03ba, f[2] > \u03b53 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / \u03ba ]; + return xyz.map(function(value, i) { + return value * white[i]; + }); + }, + formats: { + 'lab-d65': { + coords: [ ' | ', '', '' ] + } + } + }); + var phi = Math.pow(5, .5) * .5 + .5; + function contrastDeltaPhi(color1, color2) { + color1 = getColor(color1); + color2 = getColor(color2); + var Lstr1 = get(color1, [ lab_d65, 'l' ]); + var Lstr2 = get(color2, [ lab_d65, 'l' ]); + var deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi)); + var contrast2 = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40; + return contrast2 < 7.5 ? 0 : contrast2; + } + var contrastMethods = Object.freeze({ + __proto__: null, + contrastWCAG21: contrastWCAG21, + contrastAPCA: contrastAPCA, + contrastMichelson: contrastMichelson, + contrastWeber: contrastWeber, + contrastLstar: contrastLstar, + contrastDeltaPhi: contrastDeltaPhi + }); + function contrast(background, foreground) { + var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (isString(o)) { + o = { + algorithm: o + }; + } + var _o = o, algorithm = _o.algorithm, rest = _objectWithoutProperties(_o, _excluded3); + if (!algorithm) { + var algorithms = Object.keys(contrastMethods).map(function(a2) { + return a2.replace(/^contrast/, ''); + }).join(', '); + throw new TypeError('contrast() function needs a contrast algorithm. Please specify one of: '.concat(algorithms)); + } + background = getColor(background); + foreground = getColor(foreground); + for (var a2 in contrastMethods) { + if ('contrast' + algorithm.toLowerCase() === a2.toLowerCase()) { + return contrastMethods[a2](background, foreground, rest); + } + } + throw new TypeError('Unknown contrast algorithm: '.concat(algorithm)); + } + function uv(color) { + var _getAll = getAll(color, XYZ_D65), _getAll2 = _slicedToArray(_getAll, 3), X = _getAll2[0], Y = _getAll2[1], Z = _getAll2[2]; + var denom = X + 15 * Y + 3 * Z; + return [ 4 * X / denom, 9 * Y / denom ]; + } + function xy(color) { + var _getAll3 = getAll(color, XYZ_D65), _getAll4 = _slicedToArray(_getAll3, 3), X = _getAll4[0], Y = _getAll4[1], Z = _getAll4[2]; + var sum = X + Y + Z; + return [ X / sum, Y / sum ]; + } + function register$1(Color3) { + Object.defineProperty(Color3.prototype, 'uv', { + get: function get() { + return uv(this); + } + }); + Object.defineProperty(Color3.prototype, 'xy', { + get: function get() { + return xy(this); + } + }); + } + var chromaticity = Object.freeze({ + __proto__: null, + uv: uv, + xy: xy, + register: register$1 + }); + function deltaE76(color, sample) { + return distance(color, sample, 'lab'); + } + var \u03c0 = Math.PI; + var d2r = \u03c0 / 180; + function deltaECMC(color, sample) { + var _ref18 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref18$l = _ref18.l, l = _ref18$l === void 0 ? 2 : _ref18$l, _ref18$c = _ref18.c, c4 = _ref18$c === void 0 ? 1 : _ref18$c; + var _lab$from5 = lab.from(color), _lab$from6 = _slicedToArray(_lab$from5, 3), L1 = _lab$from6[0], a1 = _lab$from6[1], b1 = _lab$from6[2]; + var _lch$from = lch.from(lab, [ L1, a1, b1 ]), _lch$from2 = _slicedToArray(_lch$from, 3), C1 = _lch$from2[1], H1 = _lch$from2[2]; + var _lab$from7 = lab.from(sample), _lab$from8 = _slicedToArray(_lab$from7, 3), L2 = _lab$from8[0], a2 = _lab$from8[1], b2 = _lab$from8[2]; + var C2 = lch.from(lab, [ L2, a2, b2 ])[1]; + if (C1 < 0) { + C1 = 0; + } + if (C2 < 0) { + C2 = 0; + } + var \u0394L = L1 - L2; + var \u0394C = C1 - C2; + var \u0394a = a1 - a2; + var \u0394b = b1 - b2; + var H2 = Math.pow(\u0394a, 2) + Math.pow(\u0394b, 2) - Math.pow(\u0394C, 2); + var SL = .511; + if (L1 >= 16) { + SL = .040975 * L1 / (1 + .01765 * L1); + } + var SC = .0638 * C1 / (1 + .0131 * C1) + .638; + var T; + if (Number.isNaN(H1)) { + H1 = 0; + } + if (H1 >= 164 && H1 <= 345) { + T = .56 + Math.abs(.2 * Math.cos((H1 + 168) * d2r)); + } else { + T = .36 + Math.abs(.4 * Math.cos((H1 + 35) * d2r)); + } + var C4 = Math.pow(C1, 4); + var F = Math.sqrt(C4 / (C4 + 1900)); + var SH = SC * (F * T + 1 - F); + var dE = Math.pow(\u0394L / (l * SL), 2); + dE += Math.pow(\u0394C / (c4 * SC), 2); + dE += H2 / Math.pow(SH, 2); + return Math.sqrt(dE); + } + var Yw$1 = 203; + var XYZ_Abs_D65 = new ColorSpace({ + id: 'xyz-abs-d65', + name: 'Absolute XYZ D65', + coords: { + x: { + refRange: [ 0, 9504.7 ], + name: 'Xa' + }, + y: { + refRange: [ 0, 1e4 ], + name: 'Ya' + }, + z: { + refRange: [ 0, 10888.3 ], + name: 'Za' + } + }, + base: XYZ_D65, + fromBase: function fromBase(XYZ) { + return XYZ.map(function(v) { + return Math.max(v * Yw$1, 0); + }); + }, + toBase: function toBase(AbsXYZ) { + return AbsXYZ.map(function(v) { + return Math.max(v / Yw$1, 0); + }); + } + }); + var b$1 = 1.15; + var g = .66; + var n$1 = 2610 / Math.pow(2, 14); + var ninv$1 = Math.pow(2, 14) / 2610; + var c1$2 = 3424 / Math.pow(2, 12); + var c2$2 = 2413 / Math.pow(2, 7); + var c3$2 = 2392 / Math.pow(2, 7); + var p = 1.7 * 2523 / Math.pow(2, 5); + var pinv = Math.pow(2, 5) / (1.7 * 2523); + var d = -.56; + var d0 = 16295499532821565e-27; + var XYZtoCone_M = [ [ .41478972, .579999, .014648 ], [ -.20151, 1.120649, .0531008 ], [ -.0166008, .2648, .6684799 ] ]; + var ConetoXYZ_M = [ [ 1.9242264357876067, -1.0047923125953657, .037651404030618 ], [ .35031676209499907, .7264811939316552, -.06538442294808501 ], [ -.09098281098284752, -.3127282905230739, 1.5227665613052603 ] ]; + var ConetoIab_M = [ [ .5, .5, 0 ], [ 3.524, -4.066708, .542708 ], [ .199076, 1.096799, -1.295875 ] ]; + var IabtoCone_M = [ [ 1, .1386050432715393, .05804731615611886 ], [ .9999999999999999, -.1386050432715393, -.05804731615611886 ], [ .9999999999999998, -.09601924202631895, -.8118918960560388 ] ]; + var Jzazbz = new ColorSpace({ + id: 'jzazbz', + name: 'Jzazbz', + coords: { + jz: { + refRange: [ 0, 1 ], + name: 'Jz' + }, + az: { + refRange: [ -.5, .5 ] + }, + bz: { + refRange: [ -.5, .5 ] + } + }, + base: XYZ_Abs_D65, + fromBase: function fromBase(XYZ) { + var _XYZ = _slicedToArray(XYZ, 3), Xa = _XYZ[0], Ya = _XYZ[1], Za = _XYZ[2]; + var Xm = b$1 * Xa - (b$1 - 1) * Za; + var Ym = g * Ya - (g - 1) * Xa; + var LMS = multiplyMatrices(XYZtoCone_M, [ Xm, Ym, Za ]); + var PQLMS = LMS.map(function(val) { + var num = c1$2 + c2$2 * Math.pow(val / 1e4, n$1); + var denom = 1 + c3$2 * Math.pow(val / 1e4, n$1); + return Math.pow(num / denom, p); + }); + var _multiplyMatrices = multiplyMatrices(ConetoIab_M, PQLMS), _multiplyMatrices2 = _slicedToArray(_multiplyMatrices, 3), Iz = _multiplyMatrices2[0], az = _multiplyMatrices2[1], bz = _multiplyMatrices2[2]; + var Jz = (1 + d) * Iz / (1 + d * Iz) - d0; + return [ Jz, az, bz ]; + }, + toBase: function toBase(Jzazbz2) { + var _Jzazbz = _slicedToArray(Jzazbz2, 3), Jz = _Jzazbz[0], az = _Jzazbz[1], bz = _Jzazbz[2]; + var Iz = (Jz + d0) / (1 + d - d * (Jz + d0)); + var PQLMS = multiplyMatrices(IabtoCone_M, [ Iz, az, bz ]); + var LMS = PQLMS.map(function(val) { + var num = c1$2 - Math.pow(val, pinv); + var denom = c3$2 * Math.pow(val, pinv) - c2$2; + var x = 1e4 * Math.pow(num / denom, ninv$1); + return x; + }); + var _multiplyMatrices3 = multiplyMatrices(ConetoXYZ_M, LMS), _multiplyMatrices4 = _slicedToArray(_multiplyMatrices3, 3), Xm = _multiplyMatrices4[0], Ym = _multiplyMatrices4[1], Za = _multiplyMatrices4[2]; + var Xa = (Xm + (b$1 - 1) * Za) / b$1; + var Ya = (Ym + (g - 1) * Xa) / g; + return [ Xa, Ya, Za ]; + }, + formats: { + color: {} + } + }); + var jzczhz = new ColorSpace({ + id: 'jzczhz', + name: 'JzCzHz', + coords: { + jz: { + refRange: [ 0, 1 ], + name: 'Jz' + }, + cz: { + refRange: [ 0, 1 ], + name: 'Chroma' + }, + hz: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + } + }, + base: Jzazbz, + fromBase: function fromBase(jzazbz) { + var _jzazbz = _slicedToArray(jzazbz, 3), Jz = _jzazbz[0], az = _jzazbz[1], bz = _jzazbz[2]; + var hue; + var \u03b52 = 2e-4; + if (Math.abs(az) < \u03b52 && Math.abs(bz) < \u03b52) { + hue = NaN; + } else { + hue = Math.atan2(bz, az) * 180 / Math.PI; + } + return [ Jz, Math.sqrt(Math.pow(az, 2) + Math.pow(bz, 2)), constrain(hue) ]; + }, + toBase: function toBase(jzczhz2) { + return [ jzczhz2[0], jzczhz2[1] * Math.cos(jzczhz2[2] * Math.PI / 180), jzczhz2[1] * Math.sin(jzczhz2[2] * Math.PI / 180) ]; + }, + formats: { + color: {} + } + }); + function deltaEJz(color, sample) { + var _jzczhz$from = jzczhz.from(color), _jzczhz$from2 = _slicedToArray(_jzczhz$from, 3), Jz1 = _jzczhz$from2[0], Cz1 = _jzczhz$from2[1], Hz1 = _jzczhz$from2[2]; + var _jzczhz$from3 = jzczhz.from(sample), _jzczhz$from4 = _slicedToArray(_jzczhz$from3, 3), Jz2 = _jzczhz$from4[0], Cz2 = _jzczhz$from4[1], Hz2 = _jzczhz$from4[2]; + var \u0394J = Jz1 - Jz2; + var \u0394C = Cz1 - Cz2; + if (Number.isNaN(Hz1) && Number.isNaN(Hz2)) { + Hz1 = 0; + Hz2 = 0; + } else if (Number.isNaN(Hz1)) { + Hz1 = Hz2; + } else if (Number.isNaN(Hz2)) { + Hz2 = Hz1; + } + var \u0394h = Hz1 - Hz2; + var \u0394H = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(\u0394h / 2 * (Math.PI / 180)); + return Math.sqrt(Math.pow(\u0394J, 2) + Math.pow(\u0394C, 2) + Math.pow(\u0394H, 2)); + } + var c1$1 = 3424 / 4096; + var c2$1 = 2413 / 128; + var c3$1 = 2392 / 128; + var m1 = 2610 / 16384; + var m2 = 2523 / 32; + var im1 = 16384 / 2610; + var im2 = 32 / 2523; + var XYZtoLMS_M$1 = [ [ .3592, .6976, -.0358 ], [ -.1922, 1.1004, .0755 ], [ .007, .0749, .8434 ] ]; + var LMStoIPT_M = [ [ 2048 / 4096, 2048 / 4096, 0 ], [ 6610 / 4096, -13613 / 4096, 7003 / 4096 ], [ 17933 / 4096, -17390 / 4096, -543 / 4096 ] ]; + var IPTtoLMS_M = [ [ .9999888965628402, .008605050147287059, .11103437159861648 ], [ 1.00001110343716, -.008605050147287059, -.11103437159861648 ], [ 1.0000320633910054, .56004913547279, -.3206339100541203 ] ]; + var LMStoXYZ_M$1 = [ [ 2.0701800566956137, -1.326456876103021, .20661600684785517 ], [ .3649882500326575, .6804673628522352, -.04542175307585323 ], [ -.04959554223893211, -.04942116118675749, 1.1879959417328034 ] ]; + var ictcp = new ColorSpace({ + id: 'ictcp', + name: 'ICTCP', + coords: { + i: { + refRange: [ 0, 1 ], + name: 'I' + }, + ct: { + refRange: [ -.5, .5 ], + name: 'CT' + }, + cp: { + refRange: [ -.5, .5 ], + name: 'CP' + } + }, + base: XYZ_Abs_D65, + fromBase: function fromBase(XYZ) { + var LMS = multiplyMatrices(XYZtoLMS_M$1, XYZ); + return LMStoICtCp(LMS); + }, + toBase: function toBase(ICtCp) { + var LMS = ICtCptoLMS(ICtCp); + return multiplyMatrices(LMStoXYZ_M$1, LMS); + }, + formats: { + color: {} + } + }); + function LMStoICtCp(LMS) { + var PQLMS = LMS.map(function(val) { + var num = c1$1 + c2$1 * Math.pow(val / 1e4, m1); + var denom = 1 + c3$1 * Math.pow(val / 1e4, m1); + return Math.pow(num / denom, m2); + }); + return multiplyMatrices(LMStoIPT_M, PQLMS); + } + function ICtCptoLMS(ICtCp) { + var PQLMS = multiplyMatrices(IPTtoLMS_M, ICtCp); + var LMS = PQLMS.map(function(val) { + var num = Math.max(Math.pow(val, im2) - c1$1, 0); + var denom = c2$1 - c3$1 * Math.pow(val, im2); + return 1e4 * Math.pow(num / denom, im1); + }); + return LMS; + } + function deltaEITP(color, sample) { + var _ictcp$from = ictcp.from(color), _ictcp$from2 = _slicedToArray(_ictcp$from, 3), I1 = _ictcp$from2[0], T1 = _ictcp$from2[1], P1 = _ictcp$from2[2]; + var _ictcp$from3 = ictcp.from(sample), _ictcp$from4 = _slicedToArray(_ictcp$from3, 3), I2 = _ictcp$from4[0], T2 = _ictcp$from4[1], P2 = _ictcp$from4[2]; + return 720 * Math.sqrt(Math.pow(I1 - I2, 2) + .25 * Math.pow(T1 - T2, 2) + Math.pow(P1 - P2, 2)); + } + var XYZtoLMS_M = [ [ .8190224432164319, .3619062562801221, -.12887378261216414 ], [ .0329836671980271, .9292868468965546, .03614466816999844 ], [ .048177199566046255, .26423952494422764, .6335478258136937 ] ]; + var LMStoXYZ_M = [ [ 1.2268798733741557, -.5578149965554813, .28139105017721583 ], [ -.04057576262431372, 1.1122868293970594, -.07171106666151701 ], [ -.07637294974672142, -.4214933239627914, 1.5869240244272418 ] ]; + var LMStoLab_M = [ [ .2104542553, .793617785, -.0040720468 ], [ 1.9779984951, -2.428592205, .4505937099 ], [ .0259040371, .7827717662, -.808675766 ] ]; + var LabtoLMS_M = [ [ .9999999984505198, .39633779217376786, .2158037580607588 ], [ 1.0000000088817609, -.10556134232365635, -.06385417477170591 ], [ 1.0000000546724108, -.08948418209496575, -1.2914855378640917 ] ]; + var OKLab = new ColorSpace({ + id: 'oklab', + name: 'OKLab', + coords: { + l: { + refRange: [ 0, 1 ], + name: 'L' + }, + a: { + refRange: [ -.4, .4 ] + }, + b: { + refRange: [ -.4, .4 ] + } + }, + white: 'D65', + base: XYZ_D65, + fromBase: function fromBase(XYZ) { + var LMS = multiplyMatrices(XYZtoLMS_M, XYZ); + var LMSg = LMS.map(function(val) { + return Math.cbrt(val); + }); + return multiplyMatrices(LMStoLab_M, LMSg); + }, + toBase: function toBase(OKLab2) { + var LMSg = multiplyMatrices(LabtoLMS_M, OKLab2); + var LMS = LMSg.map(function(val) { + return Math.pow(val, 3); + }); + return multiplyMatrices(LMStoXYZ_M, LMS); + }, + formats: { + oklab: { + coords: [ ' | ', '', '' ] + } + } + }); + function deltaEOK(color, sample) { + var _OKLab$from = OKLab.from(color), _OKLab$from2 = _slicedToArray(_OKLab$from, 3), L1 = _OKLab$from2[0], a1 = _OKLab$from2[1], b1 = _OKLab$from2[2]; + var _OKLab$from3 = OKLab.from(sample), _OKLab$from4 = _slicedToArray(_OKLab$from3, 3), L2 = _OKLab$from4[0], a2 = _OKLab$from4[1], b2 = _OKLab$from4[2]; + var \u0394L = L1 - L2; + var \u0394a = a1 - a2; + var \u0394b = b1 - b2; + return Math.sqrt(Math.pow(\u0394L, 2) + Math.pow(\u0394a, 2) + Math.pow(\u0394b, 2)); + } + var deltaEMethods = Object.freeze({ + __proto__: null, + deltaE76: deltaE76, + deltaECMC: deltaECMC, + deltaE2000: deltaE2000, + deltaEJz: deltaEJz, + deltaEITP: deltaEITP, + deltaEOK: deltaEOK + }); + function deltaE(c12, c22) { + var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (isString(o)) { + o = { + method: o + }; + } + var _o2 = o, _o2$method = _o2.method, method = _o2$method === void 0 ? defaults.deltaE : _o2$method, rest = _objectWithoutProperties(_o2, _excluded4); + c12 = getColor(c12); + c22 = getColor(c22); + for (var m3 in deltaEMethods) { + if ('deltae' + method.toLowerCase() === m3.toLowerCase()) { + return deltaEMethods[m3](c12, c22, rest); + } + } + throw new TypeError('Unknown deltaE method: '.concat(method)); + } + function lighten(color) { + var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : .25; + var space = ColorSpace.get('oklch', 'lch'); + var lightness = [ space, 'l' ]; + return set(color, lightness, function(l) { + return l * (1 + amount); + }); + } + function darken(color) { + var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : .25; + var space = ColorSpace.get('oklch', 'lch'); + var lightness = [ space, 'l' ]; + return set(color, lightness, function(l) { + return l * (1 - amount); + }); + } + var variations = Object.freeze({ + __proto__: null, + lighten: lighten, + darken: darken + }); + function mix(c12, c22) { + var p2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : .5; + var o = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var _ref19 = [ getColor(c12), getColor(c22) ]; + c12 = _ref19[0]; + c22 = _ref19[1]; + if (type(p2) === 'object') { + var _ref20 = [ .5, p2 ]; + p2 = _ref20[0]; + o = _ref20[1]; + } + var _o3 = o, space = _o3.space, outputSpace = _o3.outputSpace, premultiplied = _o3.premultiplied; + var r = range(c12, c22, { + space: space, + outputSpace: outputSpace, + premultiplied: premultiplied + }); + return r(p2); + } + function steps(c12, c22) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var colorRange; + if (isRange(c12)) { + colorRange = c12; + options = c22; + var _colorRange$rangeArgs = _slicedToArray(colorRange.rangeArgs.colors, 2); + c12 = _colorRange$rangeArgs[0]; + c22 = _colorRange$rangeArgs[1]; + } + var _options = options, maxDeltaE = _options.maxDeltaE, deltaEMethod = _options.deltaEMethod, _options$steps = _options.steps, steps2 = _options$steps === void 0 ? 2 : _options$steps, _options$maxSteps = _options.maxSteps, maxSteps = _options$maxSteps === void 0 ? 1e3 : _options$maxSteps, rangeOptions = _objectWithoutProperties(_options, _excluded5); + if (!colorRange) { + var _ref21 = [ getColor(c12), getColor(c22) ]; + c12 = _ref21[0]; + c22 = _ref21[1]; + colorRange = range(c12, c22, rangeOptions); + } + var totalDelta = deltaE(c12, c22); + var actualSteps = maxDeltaE > 0 ? Math.max(steps2, Math.ceil(totalDelta / maxDeltaE) + 1) : steps2; + var ret = []; + if (maxSteps !== void 0) { + actualSteps = Math.min(actualSteps, maxSteps); + } + if (actualSteps === 1) { + ret = [ { + p: .5, + color: colorRange(.5) + } ]; + } else { + var step = 1 / (actualSteps - 1); + ret = Array.from({ + length: actualSteps + }, function(_, i) { + var p2 = i * step; + return { + p: p2, + color: colorRange(p2) + }; + }); + } + if (maxDeltaE > 0) { + var maxDelta = ret.reduce(function(acc, cur, i) { + if (i === 0) { + return 0; + } + var \u0394\u0395 = deltaE(cur.color, ret[i - 1].color, deltaEMethod); + return Math.max(acc, \u0394\u0395); + }, 0); + while (maxDelta > maxDeltaE) { + maxDelta = 0; + for (var i = 1; i < ret.length && ret.length < maxSteps; i++) { + var prev = ret[i - 1]; + var cur = ret[i]; + var p2 = (cur.p + prev.p) / 2; + var _color = colorRange(p2); + maxDelta = Math.max(maxDelta, deltaE(_color, prev.color), deltaE(_color, cur.color)); + ret.splice(i, 0, { + p: p2, + color: colorRange(p2) + }); + i++; + } + } + } + ret = ret.map(function(a2) { + return a2.color; + }); + return ret; + } + function range(color1, color2) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (isRange(color1)) { + var r = color1, options2 = color2; + return range.apply(void 0, _toConsumableArray(r.rangeArgs.colors).concat([ _extends({}, r.rangeArgs.options, options2) ])); + } + var space = options.space, outputSpace = options.outputSpace, progression = options.progression, premultiplied = options.premultiplied; + color1 = getColor(color1); + color2 = getColor(color2); + color1 = clone(color1); + color2 = clone(color2); + var rangeArgs = { + colors: [ color1, color2 ], + options: options + }; + if (space) { + space = ColorSpace.get(space); + } else { + space = ColorSpace.registry[defaults.interpolationSpace] || color1.space; + } + outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space; + color1 = to(color1, space); + color2 = to(color2, space); + color1 = toGamut(color1); + color2 = toGamut(color2); + if (space.coords.h && space.coords.h.type === 'angle') { + var arc = options.hue = options.hue || 'shorter'; + var hue = [ space, 'h' ]; + var _ref22 = [ get(color1, hue), get(color2, hue) ], \u03b81 = _ref22[0], \u03b82 = _ref22[1]; + var _adjust = adjust(arc, [ \u03b81, \u03b82 ]); + var _adjust2 = _slicedToArray(_adjust, 2); + \u03b81 = _adjust2[0]; + \u03b82 = _adjust2[1]; + set(color1, hue, \u03b81); + set(color2, hue, \u03b82); + } + if (premultiplied) { + color1.coords = color1.coords.map(function(c4) { + return c4 * color1.alpha; + }); + color2.coords = color2.coords.map(function(c4) { + return c4 * color2.alpha; + }); + } + return Object.assign(function(p2) { + p2 = progression ? progression(p2) : p2; + var coords = color1.coords.map(function(start, i) { + var end = color2.coords[i]; + return interpolate(start, end, p2); + }); + var alpha = interpolate(color1.alpha, color2.alpha, p2); + var ret = { + space: space, + coords: coords, + alpha: alpha + }; + if (premultiplied) { + ret.coords = ret.coords.map(function(c4) { + return c4 / alpha; + }); + } + if (outputSpace !== space) { + ret = to(ret, outputSpace); + } + return ret; + }, { + rangeArgs: rangeArgs + }); + } + function isRange(val) { + return type(val) === 'function' && !!val.rangeArgs; + } + defaults.interpolationSpace = 'lab'; + function register(Color3) { + Color3.defineFunction('mix', mix, { + returns: 'color' + }); + Color3.defineFunction('range', range, { + returns: 'function' + }); + Color3.defineFunction('steps', steps, { + returns: 'array' + }); + } + var interpolation = Object.freeze({ + __proto__: null, + mix: mix, + steps: steps, + range: range, + isRange: isRange, + register: register + }); + var HSL = new ColorSpace({ + id: 'hsl', + name: 'HSL', + coords: { + h: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + }, + s: { + range: [ 0, 100 ], + name: 'Saturation' + }, + l: { + range: [ 0, 100 ], + name: 'Lightness' + } + }, + base: sRGB, + fromBase: function fromBase(rgb) { + var max2 = Math.max.apply(Math, _toConsumableArray(rgb)); + var min = Math.min.apply(Math, _toConsumableArray(rgb)); + var _rgb = _slicedToArray(rgb, 3), r = _rgb[0], g2 = _rgb[1], b2 = _rgb[2]; + var h = NaN, s = 0, l = (min + max2) / 2; + var d2 = max2 - min; + if (d2 !== 0) { + s = l === 0 || l === 1 ? 0 : (max2 - l) / Math.min(l, 1 - l); + switch (max2) { + case r: + h = (g2 - b2) / d2 + (g2 < b2 ? 6 : 0); + break; + + case g2: + h = (b2 - r) / d2 + 2; + break; + + case b2: + h = (r - g2) / d2 + 4; + } + h = h * 60; + } + return [ h, s * 100, l * 100 ]; + }, + toBase: function toBase(hsl) { + var _hsl = _slicedToArray(hsl, 3), h = _hsl[0], s = _hsl[1], l = _hsl[2]; + h = h % 360; + if (h < 0) { + h += 360; + } + s /= 100; + l /= 100; + function f(n2) { + var k = (n2 + h / 30) % 12; + var a2 = s * Math.min(l, 1 - l); + return l - a2 * Math.max(-1, Math.min(k - 3, 9 - k, 1)); + } + return [ f(0), f(8), f(4) ]; + }, + formats: { + hsl: { + toGamut: true, + coords: [ ' | ', '', '' ] + }, + hsla: { + coords: [ ' | ', '', '' ], + commas: true, + lastAlpha: true + } + } + }); + var HSV = new ColorSpace({ + id: 'hsv', + name: 'HSV', + coords: { + h: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + }, + s: { + range: [ 0, 100 ], + name: 'Saturation' + }, + v: { + range: [ 0, 100 ], + name: 'Value' + } + }, + base: HSL, + fromBase: function fromBase(hsl) { + var _hsl2 = _slicedToArray(hsl, 3), h = _hsl2[0], s = _hsl2[1], l = _hsl2[2]; + s /= 100; + l /= 100; + var v = l + s * Math.min(l, 1 - l); + return [ h, v === 0 ? 0 : 200 * (1 - l / v), 100 * v ]; + }, + toBase: function toBase(hsv) { + var _hsv = _slicedToArray(hsv, 3), h = _hsv[0], s = _hsv[1], v = _hsv[2]; + s /= 100; + v /= 100; + var l = v * (1 - s / 2); + return [ h, l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l) * 100, l * 100 ]; + }, + formats: { + color: { + toGamut: true + } + } + }); + var hwb = new ColorSpace({ + id: 'hwb', + name: 'HWB', + coords: { + h: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + }, + w: { + range: [ 0, 100 ], + name: 'Whiteness' + }, + b: { + range: [ 0, 100 ], + name: 'Blackness' + } + }, + base: HSV, + fromBase: function fromBase(hsv) { + var _hsv2 = _slicedToArray(hsv, 3), h = _hsv2[0], s = _hsv2[1], v = _hsv2[2]; + return [ h, v * (100 - s) / 100, 100 - v ]; + }, + toBase: function toBase(hwb2) { + var _hwb = _slicedToArray(hwb2, 3), h = _hwb[0], w = _hwb[1], b2 = _hwb[2]; + w /= 100; + b2 /= 100; + var sum = w + b2; + if (sum >= 1) { + var gray = w / sum; + return [ h, 0, gray * 100 ]; + } + var v = 1 - b2; + var s = v === 0 ? 0 : 1 - w / v; + return [ h, s * 100, v * 100 ]; + }, + formats: { + hwb: { + toGamut: true, + coords: [ ' | ', '', '' ] + } + } + }); + var toXYZ_M$2 = [ [ .5766690429101305, .1855582379065463, .1882286462349947 ], [ .29734497525053605, .6273635662554661, .07529145849399788 ], [ .02703136138641234, .07068885253582723, .9913375368376388 ] ]; + var fromXYZ_M$2 = [ [ 2.0415879038107465, -.5650069742788596, -.34473135077832956 ], [ -.9692436362808795, 1.8759675015077202, .04155505740717557 ], [ .013444280632031142, -.11836239223101838, 1.0151749943912054 ] ]; + var A98Linear = new RGBColorSpace({ + id: 'a98rgb-linear', + name: 'Linear Adobe\xae 98 RGB compatible', + white: 'D65', + toXYZ_M: toXYZ_M$2, + fromXYZ_M: fromXYZ_M$2 + }); + var a98rgb = new RGBColorSpace({ + id: 'a98rgb', + name: 'Adobe\xae 98 RGB compatible', + base: A98Linear, + toBase: function toBase(RGB) { + return RGB.map(function(val) { + return Math.pow(Math.abs(val), 563 / 256) * Math.sign(val); + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(val) { + return Math.pow(Math.abs(val), 256 / 563) * Math.sign(val); + }); + }, + formats: { + color: { + id: 'a98-rgb' + } + } + }); + var toXYZ_M$1 = [ [ .7977604896723027, .13518583717574031, .0313493495815248 ], [ .2880711282292934, .7118432178101014, 8565396060525902e-20 ], [ 0, 0, .8251046025104601 ] ]; + var fromXYZ_M$1 = [ [ 1.3457989731028281, -.25558010007997534, -.05110628506753401 ], [ -.5446224939028347, 1.5082327413132781, .02053603239147973 ], [ 0, 0, 1.2119675456389454 ] ]; + var ProPhotoLinear = new RGBColorSpace({ + id: 'prophoto-linear', + name: 'Linear ProPhoto', + white: 'D50', + base: XYZ_D50, + toXYZ_M: toXYZ_M$1, + fromXYZ_M: fromXYZ_M$1 + }); + var Et = 1 / 512; + var Et2 = 16 / 512; + var prophoto = new RGBColorSpace({ + id: 'prophoto', + name: 'ProPhoto', + base: ProPhotoLinear, + toBase: function toBase(RGB) { + return RGB.map(function(v) { + return v < Et2 ? v / 16 : Math.pow(v, 1.8); + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(v) { + return v >= Et ? Math.pow(v, 1 / 1.8) : 16 * v; + }); + }, + formats: { + color: { + id: 'prophoto-rgb' + } + } + }); + var oklch = new ColorSpace({ + id: 'oklch', + name: 'OKLCh', + coords: { + l: { + refRange: [ 0, 1 ], + name: 'Lightness' + }, + c: { + refRange: [ 0, .4 ], + name: 'Chroma' + }, + h: { + refRange: [ 0, 360 ], + type: 'angle', + name: 'Hue' + } + }, + white: 'D65', + base: OKLab, + fromBase: function fromBase(oklab) { + var _oklab = _slicedToArray(oklab, 3), L = _oklab[0], a2 = _oklab[1], b2 = _oklab[2]; + var h; + var \u03b52 = 2e-4; + if (Math.abs(a2) < \u03b52 && Math.abs(b2) < \u03b52) { + h = NaN; + } else { + h = Math.atan2(b2, a2) * 180 / Math.PI; + } + return [ L, Math.sqrt(Math.pow(a2, 2) + Math.pow(b2, 2)), constrain(h) ]; + }, + toBase: function toBase(oklch2) { + var _oklch = _slicedToArray(oklch2, 3), L = _oklch[0], C = _oklch[1], h = _oklch[2]; + var a2, b2; + if (isNaN(h)) { + a2 = 0; + b2 = 0; + } else { + a2 = C * Math.cos(h * Math.PI / 180); + b2 = C * Math.sin(h * Math.PI / 180); + } + return [ L, a2, b2 ]; + }, + formats: { + oklch: { + coords: [ ' | ', '', ' | ' ] + } + } + }); + var Yw = 203; + var n = 2610 / Math.pow(2, 14); + var ninv = Math.pow(2, 14) / 2610; + var m = 2523 / Math.pow(2, 5); + var minv = Math.pow(2, 5) / 2523; + var c1 = 3424 / Math.pow(2, 12); + var c2 = 2413 / Math.pow(2, 7); + var c3 = 2392 / Math.pow(2, 7); + var rec2100Pq = new RGBColorSpace({ + id: 'rec2100pq', + name: 'REC.2100-PQ', + base: REC2020Linear, + toBase: function toBase(RGB) { + return RGB.map(function(val) { + var x = Math.pow(Math.max(Math.pow(val, minv) - c1, 0) / (c2 - c3 * Math.pow(val, minv)), ninv); + return x * 1e4 / Yw; + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(val) { + var x = Math.max(val * Yw / 1e4, 0); + var num = c1 + c2 * Math.pow(x, n); + var denom = 1 + c3 * Math.pow(x, n); + return Math.pow(num / denom, m); + }); + }, + formats: { + color: { + id: 'rec2100-pq' + } + } + }); + var a = .17883277; + var b = .28466892; + var c = .55991073; + var scale = 3.7743; + var rec2100Hlg = new RGBColorSpace({ + id: 'rec2100hlg', + cssid: 'rec2100-hlg', + name: 'REC.2100-HLG', + referred: 'scene', + base: REC2020Linear, + toBase: function toBase(RGB) { + return RGB.map(function(val) { + if (val <= .5) { + return Math.pow(val, 2) / 3 * scale; + } + return Math.exp((val - c) / a + b) / 12 * scale; + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(val) { + val /= scale; + if (val <= 1 / 12) { + return Math.sqrt(3 * val); + } + return a * Math.log(12 * val - b) + c; + }); + }, + formats: { + color: { + id: 'rec2100-hlg' + } + } + }); + var CATs = {}; + hooks.add('chromatic-adaptation-start', function(env) { + if (env.options.method) { + env.M = adapt(env.W1, env.W2, env.options.method); + } + }); + hooks.add('chromatic-adaptation-end', function(env) { + if (!env.M) { + env.M = adapt(env.W1, env.W2, env.options.method); + } + }); + function defineCAT(_ref23) { + var id = _ref23.id, toCone_M = _ref23.toCone_M, fromCone_M = _ref23.fromCone_M; + CATs[id] = arguments[0]; + } + function adapt(W1, W2) { + var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Bradford'; + var method = CATs[id]; + var _multiplyMatrices5 = multiplyMatrices(method.toCone_M, W1), _multiplyMatrices6 = _slicedToArray(_multiplyMatrices5, 3), \u03c1s = _multiplyMatrices6[0], \u03b3s = _multiplyMatrices6[1], \u03b2s = _multiplyMatrices6[2]; + var _multiplyMatrices7 = multiplyMatrices(method.toCone_M, W2), _multiplyMatrices8 = _slicedToArray(_multiplyMatrices7, 3), \u03c1d = _multiplyMatrices8[0], \u03b3d = _multiplyMatrices8[1], \u03b2d = _multiplyMatrices8[2]; + var scale2 = [ [ \u03c1d / \u03c1s, 0, 0 ], [ 0, \u03b3d / \u03b3s, 0 ], [ 0, 0, \u03b2d / \u03b2s ] ]; + var scaled_cone_M = multiplyMatrices(scale2, method.toCone_M); + var adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M); + return adapt_M; + } + defineCAT({ + id: 'von Kries', + toCone_M: [ [ .40024, .7076, -.08081 ], [ -.2263, 1.16532, .0457 ], [ 0, 0, .91822 ] ], + fromCone_M: [ [ 1.8599364, -1.1293816, .2198974 ], [ .3611914, .6388125, -64e-7 ], [ 0, 0, 1.0890636 ] ] + }); + defineCAT({ + id: 'Bradford', + toCone_M: [ [ .8951, .2664, -.1614 ], [ -.7502, 1.7135, .0367 ], [ .0389, -.0685, 1.0296 ] ], + fromCone_M: [ [ .9869929, -.1470543, .1599627 ], [ .4323053, .5183603, .0492912 ], [ -.0085287, .0400428, .9684867 ] ] + }); + defineCAT({ + id: 'CAT02', + toCone_M: [ [ .7328, .4296, -.1624 ], [ -.7036, 1.6975, .0061 ], [ .003, .0136, .9834 ] ], + fromCone_M: [ [ 1.0961238, -.278869, .1827452 ], [ .454369, .4735332, .0720978 ], [ -.0096276, -.005698, 1.0153256 ] ] + }); + defineCAT({ + id: 'CAT16', + toCone_M: [ [ .401288, .650173, -.051461 ], [ -.250268, 1.204414, .045854 ], [ -.002079, .048952, .953127 ] ], + fromCone_M: [ [ 1.862067855087233, -1.011254630531685, .1491867754444518 ], [ .3875265432361372, .6214474419314753, -.008973985167612518 ], [ -.01584149884933386, -.03412293802851557, 1.04996443687785 ] ] + }); + Object.assign(WHITES, { + A: [ 1.0985, 1, .35585 ], + C: [ .98074, 1, 1.18232 ], + D55: [ .95682, 1, .92149 ], + D75: [ .94972, 1, 1.22638 ], + E: [ 1, 1, 1 ], + F2: [ .99186, 1, .67393 ], + F7: [ .95041, 1, 1.08747 ], + F11: [ 1.00962, 1, .6435 ] + }); + WHITES.ACES = [ .32168 / .33767, 1, (1 - .32168 - .33767) / .33767 ]; + var toXYZ_M = [ [ .6624541811085053, .13400420645643313, .1561876870049078 ], [ .27222871678091454, .6740817658111484, .05368951740793705 ], [ -.005574649490394108, .004060733528982826, 1.0103391003129971 ] ]; + var fromXYZ_M = [ [ 1.6410233796943257, -.32480329418479, -.23642469523761225 ], [ -.6636628587229829, 1.6153315916573379, .016756347685530137 ], [ .011721894328375376, -.008284441996237409, .9883948585390215 ] ]; + var ACEScg = new RGBColorSpace({ + id: 'acescg', + name: 'ACEScg', + coords: { + r: { + range: [ 0, 65504 ], + name: 'Red' + }, + g: { + range: [ 0, 65504 ], + name: 'Green' + }, + b: { + range: [ 0, 65504 ], + name: 'Blue' + } + }, + referred: 'scene', + white: WHITES.ACES, + toXYZ_M: toXYZ_M, + fromXYZ_M: fromXYZ_M, + formats: { + color: {} + } + }); + var \u03b5 = Math.pow(2, -16); + var ACES_min_nonzero = -.35828683; + var ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; + var acescc = new RGBColorSpace({ + id: 'acescc', + name: 'ACEScc', + coords: { + r: { + range: [ ACES_min_nonzero, ACES_cc_max ], + name: 'Red' + }, + g: { + range: [ ACES_min_nonzero, ACES_cc_max ], + name: 'Green' + }, + b: { + range: [ ACES_min_nonzero, ACES_cc_max ], + name: 'Blue' + } + }, + referred: 'scene', + base: ACEScg, + toBase: function toBase(RGB) { + var low = (9.72 - 15) / 17.52; + return RGB.map(function(val) { + if (val <= low) { + return (Math.pow(2, val * 17.52 - 9.72) - \u03b5) * 2; + } else if (val < ACES_cc_max) { + return Math.pow(2, val * 17.52 - 9.72); + } else { + return 65504; + } + }); + }, + fromBase: function fromBase(RGB) { + return RGB.map(function(val) { + if (val <= 0) { + return (Math.log2(\u03b5) + 9.72) / 17.52; + } else if (val < \u03b5) { + return (Math.log2(\u03b5 + val * .5) + 9.72) / 17.52; + } else { + return (Math.log2(val) + 9.72) / 17.52; + } + }); + }, + formats: { + color: {} + } + }); + var spaces = Object.freeze({ + __proto__: null, + XYZ_D65: XYZ_D65, + XYZ_D50: XYZ_D50, + XYZ_ABS_D65: XYZ_Abs_D65, + Lab_D65: lab_d65, + Lab: lab, + LCH: lch, + sRGB_Linear: sRGBLinear, + sRGB: sRGB, + HSL: HSL, + HWB: hwb, + HSV: HSV, + P3_Linear: P3Linear, + P3: P3, + A98RGB_Linear: A98Linear, + A98RGB: a98rgb, + ProPhoto_Linear: ProPhotoLinear, + ProPhoto: prophoto, + REC_2020_Linear: REC2020Linear, + REC_2020: REC2020, + OKLab: OKLab, + OKLCH: oklch, + Jzazbz: Jzazbz, + JzCzHz: jzczhz, + ICTCP: ictcp, + REC_2100_PQ: rec2100Pq, + REC_2100_HLG: rec2100Hlg, + ACEScg: ACEScg, + ACEScc: acescc + }); + var _Color = (_space = new WeakMap(), function() { + function Color() { + var _this2 = this; + _classCallCheck(this, Color); + _classPrivateFieldInitSpec(this, _space, void 0); + var color; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (args.length === 1) { + color = getColor(args[0]); + } + var space, coords, alpha; + if (color) { + space = color.space || color.spaceId; + coords = color.coords; + alpha = color.alpha; + } else { + space = args[0]; + coords = args[1]; + alpha = args[2]; + } + _classPrivateFieldSet(_space, this, ColorSpace.get(space)); + this.coords = coords ? coords.slice() : [ 0, 0, 0 ]; + this.alpha = alpha < 1 ? alpha : 1; + for (var i = 0; i < this.coords.length; i++) { + if (this.coords[i] === 'NaN') { + this.coords[i] = NaN; + } + } + var _loop4 = function _loop4(id) { + Object.defineProperty(_this2, id, { + get: function get() { + return _this2.get(id); + }, + set: function set(value) { + return _this2.set(id, value); + } + }); + }; + for (var id in _classPrivateFieldGet(_space, this).coords) { + _loop4(id); + } + } + return _createClass(Color, [ { + key: 'space', + get: function get() { + return _classPrivateFieldGet(_space, this); + } + }, { + key: 'spaceId', + get: function get() { + return _classPrivateFieldGet(_space, this).id; + } + }, { + key: 'clone', + value: function clone() { + return new _Color(this.space, this.coords, this.alpha); + } + }, { + key: 'toJSON', + value: function toJSON() { + return { + spaceId: this.spaceId, + coords: this.coords, + alpha: this.alpha + }; + } + }, { + key: 'display', + value: function display() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + var ret = _display.apply(void 0, [ this ].concat(args)); + ret.color = new _Color(ret.color); + return ret; + } + } ], [ { + key: 'get', + value: function get(color) { + if (color instanceof _Color) { + return color; + } + for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = arguments[_key4]; + } + return _construct(_Color, [ color ].concat(args)); + } + }, { + key: 'defineFunction', + value: function defineFunction(name, code) { + var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : code; + var _o$instance = o.instance, instance = _o$instance === void 0 ? true : _o$instance, returns = o.returns; + var func = function func() { + var ret = code.apply(void 0, arguments); + if (returns === 'color') { + ret = _Color.get(ret); + } else if (returns === 'function') { + var f = ret; + ret = function ret() { + var ret2 = f.apply(void 0, arguments); + return _Color.get(ret2); + }; + Object.assign(ret, f); + } else if (returns === 'array') { + ret = ret.map(function(c4) { + return _Color.get(c4); + }); + } + return ret; + }; + if (!(name in _Color)) { + _Color[name] = func; + } + if (instance) { + _Color.prototype[name] = function() { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + return func.apply(void 0, [ this ].concat(args)); + }; + } + } + }, { + key: 'defineFunctions', + value: function defineFunctions(o) { + for (var name in o) { + _Color.defineFunction(name, o[name], o[name]); + } + } + }, { + key: 'extend', + value: function extend(exports) { + if (exports.register) { + exports.register(_Color); + } else { + for (var name in exports) { + _Color.defineFunction(name, exports[name]); + } + } + } + } ]); + }()); + _Color.defineFunctions({ + get: get, + getAll: getAll, + set: set, + setAll: setAll, + to: to, + equals: equals, + inGamut: inGamut, + toGamut: toGamut, + distance: distance, + toString: serialize + }); + Object.assign(_Color, { + util: util, + hooks: hooks, + WHITES: WHITES, + Space: ColorSpace, + spaces: ColorSpace.registry, + parse: parse, + defaults: defaults + }); + for (var _i5 = 0, _Object$keys = Object.keys(spaces); _i5 < _Object$keys.length; _i5++) { + var key = _Object$keys[_i5]; + ColorSpace.register(spaces[key]); + } + for (var id in ColorSpace.registry) { + addSpaceAccessors(id, ColorSpace.registry[id]); + } + hooks.add('colorspace-init-end', function(space) { + var _space$aliases; + addSpaceAccessors(space.id, space); + (_space$aliases = space.aliases) === null || _space$aliases === void 0 || _space$aliases.forEach(function(alias) { + addSpaceAccessors(alias, space); + }); + }); + function addSpaceAccessors(id, space) { + Object.keys(space.coords); + Object.values(space.coords).map(function(c4) { + return c4.name; + }); + var propId = id.replace(/-/g, '_'); + Object.defineProperty(_Color.prototype, propId, { + get: function get() { + var _this3 = this; + var ret = this.getAll(id); + if (typeof Proxy === 'undefined') { + return ret; + } + return new Proxy(ret, { + has: function has(obj, property) { + try { + ColorSpace.resolveCoord([ space, property ]); + return true; + } catch (e) {} + return Reflect.has(obj, property); + }, + get: function get(obj, property, receiver) { + if (property && _typeof(property) !== 'symbol' && !(property in obj)) { + var _ColorSpace$resolveCo3 = ColorSpace.resolveCoord([ space, property ]), index = _ColorSpace$resolveCo3.index; + if (index >= 0) { + return obj[index]; + } + } + return Reflect.get(obj, property, receiver); + }, + set: function set(obj, property, value, receiver) { + if (property && _typeof(property) !== 'symbol' && !(property in obj) || property >= 0) { + var _ColorSpace$resolveCo4 = ColorSpace.resolveCoord([ space, property ]), index = _ColorSpace$resolveCo4.index; + if (index >= 0) { + obj[index] = value; + _this3.setAll(id, obj); + return true; + } + } + return Reflect.set(obj, property, value, receiver); + } + }); + }, + set: function set(coords) { + this.setAll(id, coords); + }, + configurable: true, + enumerable: true + }); + } + _Color.extend(deltaEMethods); + _Color.extend({ + deltaE: deltaE + }); + _Color.extend(variations); + _Color.extend({ + contrast: contrast + }); + _Color.extend(chromaticity); + _Color.extend(luminance); + _Color.extend(interpolation); + _Color.extend(contrastMethods); + var import_from2 = __toModule(require_from3()); + import_dot['default'].templateSettings.strip = false; + axe._memoizedFns = []; + function memoizeImplementation(fn) { + var memoized = (0, import_memoizee['default'])(fn); + axe._memoizedFns.push(memoized); + return memoized; + } + var memoize_default = memoizeImplementation; + var isXHTML = memoize_default(function(doc) { + if (!(doc !== null && doc !== void 0 && doc.createElement)) { + return false; + } + return doc.createElement('A').localName === 'A'; + }); + var is_xhtml_default = isXHTML; + function _getShadowSelector(generateSelector2, elm) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (!elm) { + return ''; + } + var doc = elm.getRootNode && elm.getRootNode() || document; + if (doc.nodeType !== 11) { + return generateSelector2(elm, options, doc); + } + var stack = []; + while (doc.nodeType === 11) { + if (!doc.host) { + return ''; + } + stack.unshift({ + elm: elm, + doc: doc + }); + elm = doc.host; + doc = elm.getRootNode(); + } + stack.unshift({ + elm: elm, + doc: doc + }); + return stack.map(function(item) { + return generateSelector2(item.elm, options, item.doc); + }); + } + var ignoredAttributes = [ 'class', 'style', 'id', 'selected', 'checked', 'disabled', 'tabindex', 'aria-checked', 'aria-selected', 'aria-invalid', 'aria-activedescendant', 'aria-busy', 'aria-disabled', 'aria-expanded', 'aria-grabbed', 'aria-pressed', 'aria-valuenow', 'xmlns' ]; + var MAXATTRIBUTELENGTH = 31; + var attrCharsRegex = /([\\"])/g; + var newlineChars = /(\r\n|\r|\n)/g; + function escapeAttribute(str) { + return str.replace(attrCharsRegex, '\\$1').replace(newlineChars, '\\a '); + } + function getAttributeNameValue(node, at) { + var name = at.name; + var atnv; + if (name.indexOf('href') !== -1 || name.indexOf('src') !== -1) { + var friendly = get_friendly_uri_end_default(node.getAttribute(name)); + if (friendly) { + atnv = escape_selector_default(at.name) + '$="' + escapeAttribute(friendly) + '"'; + } else { + atnv = escape_selector_default(at.name) + '="' + escapeAttribute(node.getAttribute(name)) + '"'; + } + } else { + atnv = escape_selector_default(name) + '="' + escapeAttribute(at.value) + '"'; + } + return atnv; + } + function countSort(a2, b2) { + return a2.count < b2.count ? -1 : a2.count === b2.count ? 0 : 1; + } + function filterAttributes(at) { + return !ignoredAttributes.includes(at.name) && at.name.indexOf(':') === -1 && (!at.value || at.value.length < MAXATTRIBUTELENGTH); + } + function _getSelectorData(domTree) { + var data = { + classes: {}, + tags: {}, + attributes: {} + }; + domTree = Array.isArray(domTree) ? domTree : [ domTree ]; + var currentLevel = domTree.slice(); + var stack = []; + var _loop5 = function _loop5() { + var current = currentLevel.pop(); + var node = current.actualNode; + if (!!node.querySelectorAll) { + var tag = node.nodeName; + if (data.tags[tag]) { + data.tags[tag]++; + } else { + data.tags[tag] = 1; + } + if (node.classList) { + Array.from(node.classList).forEach(function(cl) { + var ind = escape_selector_default(cl); + if (data.classes[ind]) { + data.classes[ind]++; + } else { + data.classes[ind] = 1; + } + }); + } + if (node.hasAttributes()) { + Array.from(get_node_attributes_default(node)).filter(filterAttributes).forEach(function(at) { + var atnv = getAttributeNameValue(node, at); + if (atnv) { + if (data.attributes[atnv]) { + data.attributes[atnv]++; + } else { + data.attributes[atnv] = 1; + } + } + }); + } + } + if (current.children.length) { + stack.push(currentLevel); + currentLevel = current.children.slice(); + } + while (!currentLevel.length && stack.length) { + currentLevel = stack.pop(); + } + }; + while (currentLevel.length) { + _loop5(); + } + return data; + } + function uncommonClasses(node, selectorData) { + var retVal = []; + var classData = selectorData.classes; + var tagData = selectorData.tags; + if (node.classList) { + Array.from(node.classList).forEach(function(cl) { + var ind = escape_selector_default(cl); + if (classData[ind] < tagData[node.nodeName]) { + retVal.push({ + name: ind, + count: classData[ind], + species: 'class' + }); + } + }); + } + return retVal.sort(countSort); + } + function getNthChildString(elm, selector) { + var siblings = elm.parentNode && Array.from(elm.parentNode.children || '') || []; + var hasMatchingSiblings = siblings.find(function(sibling) { + return sibling !== elm && element_matches_default(sibling, selector); + }); + if (hasMatchingSiblings) { + var nthChild = 1 + siblings.indexOf(elm); + return ':nth-child(' + nthChild + ')'; + } else { + return ''; + } + } + function getElmId(elm) { + if (!elm.getAttribute('id')) { + return; + } + var doc = elm.getRootNode && elm.getRootNode() || document; + var id = '#' + escape_selector_default(elm.getAttribute('id') || ''); + if (!id.match(/player_uid_/) && doc.querySelectorAll(id).length === 1) { + return id; + } + } + function getBaseSelector(elm) { + var xhtml = is_xhtml_default(document); + return escape_selector_default(xhtml ? elm.localName : elm.nodeName.toLowerCase()); + } + function uncommonAttributes(node, selectorData) { + var retVal = []; + var attData = selectorData.attributes; + var tagData = selectorData.tags; + if (node.hasAttributes()) { + Array.from(get_node_attributes_default(node)).filter(filterAttributes).forEach(function(at) { + var atnv = getAttributeNameValue(node, at); + if (atnv && attData[atnv] < tagData[node.nodeName]) { + retVal.push({ + name: atnv, + count: attData[atnv], + species: 'attribute' + }); + } + }); + } + return retVal.sort(countSort); + } + function getThreeLeastCommonFeatures(elm, selectorData) { + var selector = ''; + var features; + var clss = uncommonClasses(elm, selectorData); + var atts = uncommonAttributes(elm, selectorData); + if (clss.length && clss[0].count === 1) { + features = [ clss[0] ]; + } else if (atts.length && atts[0].count === 1) { + features = [ atts[0] ]; + selector = getBaseSelector(elm); + } else { + features = clss.concat(atts); + features.sort(countSort); + features = features.slice(0, 3); + if (!features.some(function(feat) { + return feat.species === 'class'; + })) { + selector = getBaseSelector(elm); + } else { + features.sort(function(a2, b2) { + return a2.species !== b2.species && a2.species === 'class' ? -1 : a2.species === b2.species ? 0 : 1; + }); + } + } + return selector += features.reduce(function(val, feat) { + switch (feat.species) { + case 'class': + return val + '.' + feat.name; + + case 'attribute': + return val + '[' + feat.name + ']'; + } + return val; + }, ''); + } + function generateSelector(elm, options, doc) { + if (!axe._selectorData) { + throw new Error('Expect axe._selectorData to be set up'); + } + var _options$toRoot = options.toRoot, toRoot = _options$toRoot === void 0 ? false : _options$toRoot; + var selector; + var similar; + do { + var features = getElmId(elm); + if (!features) { + features = getThreeLeastCommonFeatures(elm, axe._selectorData); + features += getNthChildString(elm, features); + } + if (selector) { + selector = features + ' > ' + selector; + } else { + selector = features; + } + if (!similar || similar.length > constants_default.selectorSimilarFilterLimit) { + similar = findSimilar(doc, selector); + } else { + similar = similar.filter(function(item) { + return element_matches_default(item, selector); + }); + } + elm = elm.parentElement; + } while ((similar.length > 1 || toRoot) && elm && elm.nodeType !== 11); + if (similar.length === 1) { + return selector; + } else if (selector.indexOf(' > ') !== -1) { + return ':root' + selector.substring(selector.indexOf(' > ')); + } + return ':root'; + } + function getSelector(elm, options) { + return _getShadowSelector(generateSelector, elm, options); + } + var get_selector_default = memoize_default(getSelector); + var findSimilar = memoize_default(function(doc, selector) { + return Array.from(doc.querySelectorAll(selector)); + }); + function generateAncestry(node) { + var nodeName2 = escape_selector_default(node.nodeName.toLowerCase()); + var parentElement = node.parentElement; + var parentNode = node.parentNode; + var nthChild = ''; + if (nodeName2 !== 'head' && nodeName2 !== 'body' && (parentNode === null || parentNode === void 0 ? void 0 : parentNode.children.length) > 1) { + var index = Array.prototype.indexOf.call(parentNode.children, node) + 1; + nthChild = ':nth-child('.concat(index, ')'); + } + if (!parentElement) { + return nodeName2 + nthChild; + } + return generateAncestry(parentElement) + ' > ' + nodeName2 + nthChild; + } + function _getAncestry(elm, options) { + return _getShadowSelector(generateAncestry, elm, options); + } + function getXPathArray(node, path) { + var sibling, count; + if (!node) { + return []; + } + if (!path && node.nodeType === 9) { + path = [ { + str: 'html' + } ]; + return path; + } + path = path || []; + if (node.parentNode && node.parentNode !== node) { + path = getXPathArray(node.parentNode, path); + } + if (node.previousSibling) { + count = 1; + sibling = node.previousSibling; + do { + if (sibling.nodeType === 1 && sibling.nodeName === node.nodeName) { + count++; + } + sibling = sibling.previousSibling; + } while (sibling); + if (count === 1) { + count = null; + } + } else if (node.nextSibling) { + sibling = node.nextSibling; + do { + if (sibling.nodeType === 1 && sibling.nodeName === node.nodeName) { + count = 1; + sibling = null; + } else { + count = null; + sibling = sibling.previousSibling; + } + } while (sibling); + } + if (node.nodeType === 1) { + var element = {}; + element.str = node.nodeName.toLowerCase(); + var _id = node.getAttribute && escape_selector_default(node.getAttribute('id')); + if (_id && node.ownerDocument.querySelectorAll('#' + _id).length === 1) { + element.id = node.getAttribute('id'); + } + if (count > 1) { + element.count = count; + } + path.push(element); + } + return path; + } + function xpathToString(xpathArray) { + return xpathArray.reduce(function(str, elm) { + if (elm.id) { + return '//'.concat(elm.str, '[@id=\'').concat(elm.id, '\']'); + } else { + return str + '/'.concat(elm.str) + (elm.count > 0 ? '['.concat(elm.count, ']') : ''); + } + }, ''); + } + function getXpath(node) { + var xpathArray = getXPathArray(node); + return xpathToString(xpathArray); + } + var get_xpath_default = getXpath; + var _cache = {}; + var cache = { + set: function set(key, value) { + validateKey(key); + _cache[key] = value; + }, + get: function get(key, creator) { + validateCreator(creator); + if (key in _cache) { + return _cache[key]; + } + if (typeof creator === 'function') { + var value = creator(); + assert_default(value !== void 0, 'Cache creator function should not return undefined'); + this.set(key, value); + return _cache[key]; + } + }, + clear: function clear() { + _cache = {}; + } + }; + function validateKey(key) { + assert_default(typeof key === 'string', 'key must be a string, ' + _typeof(key) + ' given'); + assert_default(key !== '', 'key must not be empty'); + } + function validateCreator(creator) { + assert_default(typeof creator === 'function' || typeof creator === 'undefined', 'creator must be a function or undefined, ' + _typeof(creator) + ' given'); + } + var cache_default = cache; + function getNodeFromTree(vNode, node) { + var el = node || vNode; + return cache_default.get('nodeMap') ? cache_default.get('nodeMap').get(el) : null; + } + var get_node_from_tree_default = getNodeFromTree; + function _getElementSource(node) { + var _ref24 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref24$maxLength = _ref24.maxLength, maxLength = _ref24$maxLength === void 0 ? 300 : _ref24$maxLength, _ref24$attrLimit = _ref24.attrLimit, attrLimit = _ref24$attrLimit === void 0 ? 20 : _ref24$attrLimit; + if (!node) { + return ''; + } + if (node.nodeType !== 1) { + var _node$nodeValue; + var value = (_node$nodeValue = node.nodeValue) !== null && _node$nodeValue !== void 0 ? _node$nodeValue : ''; + return truncate(value, maxLength); + } + var deepStr = getOuterHtml(node); + if (deepStr.length > maxLength) { + return getTruncatedElementSource(node, { + maxLength: maxLength, + attrLimit: attrLimit + }); + } + return deepStr; + } + function getOuterHtml(element) { + var source = element.outerHTML; + if (!source && typeof window.XMLSerializer === 'function') { + source = new window.XMLSerializer().serializeToString(element); + } + return source || ''; + } + function getTruncatedElementSource(elm, _ref25) { + var maxLength = _ref25.maxLength, attrLimit = _ref25.attrLimit; + var nodeName2 = is_xhtml_default(elm.ownerDocument || document) ? elm.nodeName : elm.nodeName.toLowerCase(); + var nodeAttrs = Array.from(get_node_attributes_default(elm)).map(function(_ref26) { + var name = _ref26.name, value = _ref26.value; + return { + name: name, + value: value + }; + }); + var attrsLength = nodeAttrs.reduce(function(acc, _ref27) { + var name = _ref27.name, value = _ref27.value; + return acc + name.length + value.length + 4; + }, 0); + if (2 + nodeName2.length + attrsLength > maxLength) { + nodeAttrs.forEach(function(attr) { + attr.name = truncate(attr.name, attrLimit); + attr.value = truncate(attr.value, attrLimit); + }); + } + var source = '<'.concat(nodeName2); + var tagEnd = '>'; + var truncateEnd = ' ...>'; + var _iterator7 = _createForOfIteratorHelper(nodeAttrs), _step7; + try { + for (_iterator7.s(); !(_step7 = _iterator7.n()).done; ) { + var attr = _step7.value; + var attrStr = ' '.concat(attr.name, '="').concat(attr.value, '"'); + if (source.length + attrStr.length > maxLength - truncateEnd.length) { + tagEnd = truncateEnd; + continue; + } + source += attrStr; + } + } catch (err) { + _iterator7.e(err); + } finally { + _iterator7.f(); + } + return source + tagEnd; + } + function truncate(str, attrLimit) { + return str.length <= attrLimit ? str : str.substring(0, attrLimit) + '...'; + } + var CACHE_KEY = 'DqElm.RunOptions'; + var DqElement = memoize_default(function DqElement2(elm, options, spec) { + var _this$spec$selector, _this$_virtualNode; + options !== null && options !== void 0 ? options : options = null; + spec !== null && spec !== void 0 ? spec : spec = {}; + if (!options) { + var _cache_default$get; + options = (_cache_default$get = cache_default.get(CACHE_KEY)) !== null && _cache_default$get !== void 0 ? _cache_default$get : {}; + } + this.spec = spec; + if (elm instanceof abstract_virtual_node_default) { + this._virtualNode = elm; + this._element = elm.actualNode; + } else { + this._element = elm; + this._virtualNode = get_node_from_tree_default(elm); + } + this.fromFrame = ((_this$spec$selector = this.spec.selector) === null || _this$spec$selector === void 0 ? void 0 : _this$spec$selector.length) > 1; + this._includeElementInJson = options.elementRef; + if (options.absolutePaths) { + this._options = { + toRoot: true + }; + } + this.nodeIndexes = []; + if (Array.isArray(this.spec.nodeIndexes)) { + this.nodeIndexes = this.spec.nodeIndexes; + } else if (typeof ((_this$_virtualNode = this._virtualNode) === null || _this$_virtualNode === void 0 ? void 0 : _this$_virtualNode.nodeIndex) === 'number') { + this.nodeIndexes = [ this._virtualNode.nodeIndex ]; + } + this.source = null; + if (!axe._audit.noHtml) { + var _this$spec$source; + this.source = (_this$spec$source = this.spec.source) !== null && _this$spec$source !== void 0 ? _this$spec$source : _getElementSource(this._element); + } + return this; + }); + DqElement.prototype = { + get selector() { + return this.spec.selector || [ get_selector_default(this.element, this._options) ]; + }, + get ancestry() { + return this.spec.ancestry || [ _getAncestry(this.element) ]; + }, + get xpath() { + return this.spec.xpath || [ get_xpath_default(this.element) ]; + }, + get element() { + return this._element; + }, + toJSON: function toJSON() { + var spec = { + selector: this.selector, + source: this.source, + xpath: this.xpath, + ancestry: this.ancestry, + nodeIndexes: this.nodeIndexes, + fromFrame: this.fromFrame + }; + if (this._includeElementInJson) { + spec.element = this._element; + } + return spec; + } + }; + DqElement.fromFrame = function fromFrame(node, options, frame) { + var spec = DqElement.mergeSpecs(node, frame); + return new DqElement(frame.element, options, spec); + }; + DqElement.mergeSpecs = function mergeSpecs(child, parentFrame) { + return _extends({}, child, { + selector: [].concat(_toConsumableArray(parentFrame.selector), _toConsumableArray(child.selector)), + ancestry: [].concat(_toConsumableArray(parentFrame.ancestry), _toConsumableArray(child.ancestry)), + xpath: [].concat(_toConsumableArray(parentFrame.xpath), _toConsumableArray(child.xpath)), + nodeIndexes: [].concat(_toConsumableArray(parentFrame.nodeIndexes), _toConsumableArray(child.nodeIndexes)), + fromFrame: true + }); + }; + DqElement.setRunOptions = function setRunOptions(_ref28) { + var elementRef = _ref28.elementRef, absolutePaths = _ref28.absolutePaths; + cache_default.set(CACHE_KEY, { + elementRef: elementRef, + absolutePaths: absolutePaths + }); + }; + var dq_element_default = DqElement; + function checkHelper(checkResult, options, resolve, reject) { + return { + isAsync: false, + async: function async() { + this.isAsync = true; + return function(result) { + if (result instanceof Error === false) { + checkResult.result = result; + resolve(checkResult); + } else { + reject(result); + } + }; + }, + data: function data(_data) { + checkResult.data = _data; + }, + relatedNodes: function relatedNodes(nodes) { + if (!window.Node) { + return; + } + if (nodes instanceof window.Node || nodes instanceof abstract_virtual_node_default) { + nodes = [ nodes ]; + } else { + nodes = to_array_default(nodes); + } + checkResult.relatedNodes = []; + nodes.forEach(function(node) { + if (node instanceof abstract_virtual_node_default) { + node = node.actualNode; + } + if (node instanceof window.Node) { + var dqElm = new dq_element_default(node); + checkResult.relatedNodes.push(dqElm); + } + }); + } + }; + } + var check_helper_default = checkHelper; + function clone2(obj) { + return cloneRecused(obj, new Map()); + } + function cloneRecused(obj, seen) { + var _window, _window2; + if (obj === null || _typeof(obj) !== 'object') { + return obj; + } + if ((_window = window) !== null && _window !== void 0 && _window.Node && obj instanceof window.Node || (_window2 = window) !== null && _window2 !== void 0 && _window2.HTMLCollection && obj instanceof window.HTMLCollection || 'nodeName' in obj && 'nodeType' in obj && 'ownerDocument' in obj) { + return obj; + } + if (seen.has(obj)) { + return seen.get(obj); + } + if (Array.isArray(obj)) { + var out2 = []; + seen.set(obj, out2); + obj.forEach(function(value) { + out2.push(cloneRecused(value, seen)); + }); + return out2; + } + var out = {}; + seen.set(obj, out); + for (var _key6 in obj) { + out[_key6] = cloneRecused(obj[_key6], seen); + } + return out; + } + var parser = new import_css_selector_parser.CssSelectorParser(); + parser.registerSelectorPseudos('not'); + parser.registerSelectorPseudos('is'); + parser.registerNestingOperators('>'); + parser.registerAttrEqualityMods('^', '$', '*', '~'); + var css_parser_default = parser; + function _matches(vNode, selector) { + var expressions = _convertSelector(selector); + return expressions.some(function(expression) { + return _matchesExpression(vNode, expression); + }); + } + function matchesTag(vNode, exp) { + return vNode.props.nodeType === 1 && (exp.tag === '*' || vNode.props.nodeName === exp.tag); + } + function matchesClasses(vNode, exp) { + return !exp.classes || exp.classes.every(function(cl) { + return vNode.hasClass(cl.value); + }); + } + function matchesAttributes(vNode, exp) { + return !exp.attributes || exp.attributes.every(function(att) { + var nodeAtt = vNode.attr(att.key); + return nodeAtt !== null && att.test(nodeAtt); + }); + } + function matchesId(vNode, exp) { + return !exp.id || vNode.props.id === exp.id; + } + function matchesPseudos(target, exp) { + if (!exp.pseudos || exp.pseudos.every(function(pseudo) { + if (pseudo.name === 'not') { + return !pseudo.expressions.some(function(expression) { + return _matchesExpression(target, expression); + }); + } else if (pseudo.name === 'is') { + return pseudo.expressions.some(function(expression) { + return _matchesExpression(target, expression); + }); + } + throw new Error('the pseudo selector ' + pseudo.name + ' has not yet been implemented'); + })) { + return true; + } + return false; + } + function matchExpression(vNode, expression) { + return matchesTag(vNode, expression) && matchesClasses(vNode, expression) && matchesAttributes(vNode, expression) && matchesId(vNode, expression) && matchesPseudos(vNode, expression); + } + var escapeRegExp = function() { + var from = /(?=[\-\[\]{}()*+?.\\\^$|,#\s])/g; + var to2 = '\\'; + return function(string) { + return string.replace(from, to2); + }; + }(); + var reUnescape = /\\/g; + function convertAttributes(atts) { + if (!atts) { + return; + } + return atts.map(function(att) { + var attributeKey = att.name.replace(reUnescape, ''); + var attributeValue = (att.value || '').replace(reUnescape, ''); + var test, regexp; + switch (att.operator) { + case '^=': + regexp = new RegExp('^' + escapeRegExp(attributeValue)); + break; + + case '$=': + regexp = new RegExp(escapeRegExp(attributeValue) + '$'); + break; + + case '~=': + regexp = new RegExp('(^|\\s)' + escapeRegExp(attributeValue) + '(\\s|$)'); + break; + + case '|=': + regexp = new RegExp('^' + escapeRegExp(attributeValue) + '(-|$)'); + break; + + case '=': + test = function test(value) { + return attributeValue === value; + }; + break; + + case '*=': + test = function test(value) { + return value && value.includes(attributeValue); + }; + break; + + case '!=': + test = function test(value) { + return attributeValue !== value; + }; + break; + + default: + test = function test(value) { + return value !== null; + }; + } + if (attributeValue === '' && /^[*$^]=$/.test(att.operator)) { + test = function test() { + return false; + }; + } + if (!test) { + test = function test(value) { + return value && regexp.test(value); + }; + } + return { + key: attributeKey, + value: attributeValue, + type: typeof att.value === 'undefined' ? 'attrExist' : 'attrValue', + test: test + }; + }); + } + function convertClasses(classes) { + if (!classes) { + return; + } + return classes.map(function(className) { + className = className.replace(reUnescape, ''); + return { + value: className, + regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)') + }; + }); + } + function convertPseudos(pseudos) { + if (!pseudos) { + return; + } + return pseudos.map(function(p2) { + var expressions; + if ([ 'is', 'not' ].includes(p2.name)) { + expressions = p2.value; + expressions = expressions.selectors ? expressions.selectors : [ expressions ]; + expressions = convertExpressions(expressions); + } + return { + name: p2.name, + expressions: expressions, + value: p2.value + }; + }); + } + function convertExpressions(expressions) { + return expressions.map(function(exp) { + var newExp = []; + var rule = exp.rule; + while (rule) { + newExp.push({ + tag: rule.tagName ? rule.tagName.toLowerCase() : '*', + combinator: rule.nestingOperator ? rule.nestingOperator : ' ', + id: rule.id, + attributes: convertAttributes(rule.attrs), + classes: convertClasses(rule.classNames), + pseudos: convertPseudos(rule.pseudos) + }); + rule = rule.rule; + } + return newExp; + }); + } + function _convertSelector(selector) { + var expressions = css_parser_default.parse(selector); + expressions = expressions.selectors ? expressions.selectors : [ expressions ]; + return convertExpressions(expressions); + } + function optimizedMatchesExpression(vNode, expressions, index, matchAnyParent) { + if (!vNode) { + return false; + } + var isArray = Array.isArray(expressions); + var expression = isArray ? expressions[index] : expressions; + var machedExpression = matchExpression(vNode, expression); + while (!machedExpression && matchAnyParent && vNode.parent) { + vNode = vNode.parent; + machedExpression = matchExpression(vNode, expression); + } + if (index > 0) { + if ([ ' ', '>' ].includes(expression.combinator) === false) { + throw new Error('axe.utils.matchesExpression does not support the combinator: ' + expression.combinator); + } + machedExpression = machedExpression && optimizedMatchesExpression(vNode.parent, expressions, index - 1, expression.combinator === ' '); + } + return machedExpression; + } + function _matchesExpression(vNode, expressions, matchAnyParent) { + return optimizedMatchesExpression(vNode, expressions, expressions.length - 1, matchAnyParent); + } + function closest(vNode, selector) { + while (vNode) { + if (_matches(vNode, selector)) { + return vNode; + } + if (typeof vNode.parent === 'undefined') { + throw new TypeError('Cannot resolve parent for non-DOM nodes'); + } + vNode = vNode.parent; + } + return null; + } + var closest_default = closest; + function noop() {} + function funcGuard(f) { + if (typeof f !== 'function') { + throw new TypeError('Queue methods require functions as arguments'); + } + } + function queue() { + var tasks = []; + var started = 0; + var remaining = 0; + var completeQueue = noop; + var complete = false; + var err2; + var defaultFail = function defaultFail(e) { + err2 = e; + setTimeout(function() { + if (err2 !== void 0 && err2 !== null) { + log_default('Uncaught error (of queue)', err2); + } + }, 1); + }; + var failed = defaultFail; + function createResolve(i) { + return function(r) { + tasks[i] = r; + remaining -= 1; + if (!remaining && completeQueue !== noop) { + complete = true; + completeQueue(tasks); + } + }; + } + function abort(msg) { + completeQueue = noop; + failed(msg); + return tasks; + } + function pop() { + var length = tasks.length; + for (;started < length; started++) { + var task = tasks[started]; + try { + task.call(null, createResolve(started), abort); + } catch (e) { + abort(e); + } + } + } + var q = { + defer: function defer(fn) { + if (_typeof(fn) === 'object' && fn.then && fn['catch']) { + var defer = fn; + fn = function fn(resolve, reject) { + defer.then(resolve)['catch'](reject); + }; + } + funcGuard(fn); + if (err2 !== void 0) { + return; + } else if (complete) { + throw new Error('Queue already completed'); + } + tasks.push(fn); + ++remaining; + pop(); + return q; + }, + then: function then(fn) { + funcGuard(fn); + if (completeQueue !== noop) { + throw new Error('queue `then` already set'); + } + if (!err2) { + completeQueue = fn; + if (!remaining) { + complete = true; + completeQueue(tasks); + } + } + return q; + }, + catch: function _catch(fn) { + funcGuard(fn); + if (failed !== defaultFail) { + throw new Error('queue `catch` already set'); + } + if (!err2) { + failed = fn; + } else { + fn(err2); + err2 = null; + } + return q; + }, + abort: abort + }; + return q; + } + var queue_default = queue; + var uuid; + var _rng; + var _crypto = window.crypto || window.msCrypto; + if (!_rng && _crypto && _crypto.getRandomValues) { + var _rnds8 = new Uint8Array(16); + _rng = function whatwgRNG() { + _crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } + if (!_rng) { + var _rnds = new Array(16); + _rng = function _rng() { + for (var i = 0, r; i < 16; i++) { + if ((i & 3) === 0) { + r = Math.random() * 4294967296; + } + _rnds[i] = r >>> ((i & 3) << 3) & 255; + } + return _rnds; + }; + } + var BufferClass = typeof window.Buffer == 'function' ? window.Buffer : Array; + var _byteToHex = []; + var _hexToByte = {}; + for (var i = 0; i < 256; i++) { + _byteToHex[i] = (i + 256).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; + } + function parse2(s, buf, offset) { + var i = buf && offset || 0, ii = 0; + buf = buf || []; + s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { + if (ii < 16) { + buf[i + ii++] = _hexToByte[oct]; + } + }); + while (ii < 16) { + buf[i + ii++] = 0; + } + return buf; + } + function unparse(buf, offset) { + var i = offset || 0, bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; + } + var _seedBytes = _rng(); + var _nodeId = [ _seedBytes[0] | 1, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; + var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 16383; + var _lastMSecs = 0; + var _lastNSecs = 0; + function v1(options, buf, offset) { + var i = buf && offset || 0; + var b2 = buf || []; + options = options || {}; + var clockseq = options.clockseq != null ? options.clockseq : _clockseq; + var msecs = options.msecs != null ? options.msecs : new Date().getTime(); + var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1; + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; + if (dt < 0 && options.clockseq == null) { + clockseq = clockseq + 1 & 16383; + } + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { + nsecs = 0; + } + if (nsecs >= 1e4) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + msecs += 122192928e5; + var tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + b2[i++] = tl >>> 24 & 255; + b2[i++] = tl >>> 16 & 255; + b2[i++] = tl >>> 8 & 255; + b2[i++] = tl & 255; + var tmh = msecs / 4294967296 * 1e4 & 268435455; + b2[i++] = tmh >>> 8 & 255; + b2[i++] = tmh & 255; + b2[i++] = tmh >>> 24 & 15 | 16; + b2[i++] = tmh >>> 16 & 255; + b2[i++] = clockseq >>> 8 | 128; + b2[i++] = clockseq & 255; + var node = options.node || _nodeId; + for (var n2 = 0; n2 < 6; n2++) { + b2[i + n2] = node[n2]; + } + return buf ? buf : unparse(b2); + } + function v4(options, buf, offset) { + var i = buf && offset || 0; + if (typeof options == 'string') { + buf = options == 'binary' ? new BufferClass(16) : null; + options = null; + } + options = options || {}; + var rnds = options.random || (options.rng || _rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + for (var ii = 0; ii < 16; ii++) { + buf[i + ii] = rnds[ii]; + } + } + return buf || unparse(rnds); + } + uuid = v4; + uuid.v1 = v1; + uuid.v4 = v4; + uuid.parse = parse2; + uuid.unparse = unparse; + uuid.BufferClass = BufferClass; + axe._uuid = v1(); + var uuid_default = v4; + var errorTypes = Object.freeze([ 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError' ]); + function stringifyMessage(_ref29) { + var topic = _ref29.topic, channelId = _ref29.channelId, message = _ref29.message, messageId = _ref29.messageId, keepalive = _ref29.keepalive; + var data = { + channelId: channelId, + topic: topic, + messageId: messageId, + keepalive: !!keepalive, + source: getSource() + }; + if (message instanceof Error) { + data.error = { + name: message.name, + message: message.message, + stack: message.stack + }; + } else { + data.payload = message; + } + return JSON.stringify(data); + } + function parseMessage(dataString) { + var data; + try { + data = JSON.parse(dataString); + } catch (_unused) { + return; + } + if (!isRespondableMessage(data)) { + return; + } + var _data2 = data, topic = _data2.topic, channelId = _data2.channelId, messageId = _data2.messageId, keepalive = _data2.keepalive; + var message = _typeof(data.error) === 'object' ? buildErrorObject(data.error) : data.payload; + return { + topic: topic, + message: message, + messageId: messageId, + channelId: channelId, + keepalive: !!keepalive + }; + } + function isRespondableMessage(postedMessage) { + return postedMessage !== null && _typeof(postedMessage) === 'object' && typeof postedMessage.channelId === 'string' && postedMessage.source === getSource(); + } + function buildErrorObject(error) { + var msg = error.message || 'Unknown error occurred'; + var errorName = errorTypes.includes(error.name) ? error.name : 'Error'; + var ErrConstructor = window[errorName] || Error; + if (error.stack) { + msg += '\n' + error.stack.replace(error.message, ''); + } + return new ErrConstructor(msg); + } + function getSource() { + var application = 'axeAPI'; + var version = ''; + if (typeof axe !== 'undefined' && axe._audit && axe._audit.application) { + application = axe._audit.application; + } + if (typeof axe !== 'undefined') { + version = axe.version; + } + return application + '.' + version; + } + function assertIsParentWindow(win) { + assetNotGlobalWindow(win); + assert_default(window.parent === win, 'Source of the response must be the parent window.'); + } + function assertIsFrameWindow(win) { + assetNotGlobalWindow(win); + assert_default(win.parent === window, 'Respondable target must be a frame in the current window'); + } + function assetNotGlobalWindow(win) { + assert_default(window !== win, 'Messages can not be sent to the same window.'); + } + var channels = {}; + function storeReplyHandler(channelId, replyHandler) { + var sendToParent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + assert_default(!Object.prototype.hasOwnProperty.call(channels, channelId), 'A replyHandler already exists for this message channel.'); + channels[channelId] = { + replyHandler: replyHandler, + sendToParent: sendToParent + }; + } + function getReplyHandler(channelId) { + return Object.prototype.hasOwnProperty.call(channels, channelId) ? channels[channelId] : void 0; + } + function deleteReplyHandler(channelId) { + delete channels[channelId]; + } + var messageIds = []; + function createMessageId() { + var uuid2 = ''.concat(v4(), ':').concat(v4()); + if (messageIds.includes(uuid2)) { + return createMessageId(); + } + messageIds.push(uuid2); + return uuid2; + } + function isNewMessage(uuid2) { + if (messageIds.includes(uuid2)) { + return false; + } + messageIds.push(uuid2); + return true; + } + function postMessage(win, data, sendToParent, replyHandler) { + sendToParent ? assertIsParentWindow(win) : assertIsFrameWindow(win); + if (data.message instanceof Error && !sendToParent) { + axe.log(data.message); + return false; + } + var dataString = stringifyMessage(_extends({ + messageId: createMessageId() + }, data)); + var allowedOrigins = axe._audit.allowedOrigins; + if (!allowedOrigins || !allowedOrigins.length) { + return false; + } + if (typeof replyHandler === 'function') { + storeReplyHandler(data.channelId, replyHandler, sendToParent); + } + allowedOrigins.forEach(function(origin) { + try { + win.postMessage(dataString, origin); + } catch (err2) { + if (err2 instanceof win.DOMException) { + throw new Error('allowedOrigins value "'.concat(origin, '" is not a valid origin')); + } + throw err2; + } + }); + return true; + } + function processError(win, error, channelId) { + if (!win.parent !== window) { + return axe.log(error); + } + try { + postMessage(win, { + topic: null, + channelId: channelId, + message: error, + messageId: createMessageId(), + keepalive: true + }, true); + } catch (err2) { + return axe.log(err2); + } + } + function createResponder(win, channelId) { + var sendToParent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + return function respond(message, keepalive, replyHandler) { + var data = { + channelId: channelId, + message: message, + keepalive: keepalive + }; + postMessage(win, data, sendToParent, replyHandler); + }; + } + function originIsAllowed(origin) { + var allowedOrigins = axe._audit.allowedOrigins; + return allowedOrigins && allowedOrigins.includes('*') || allowedOrigins.includes(origin); + } + function messageHandler(_ref30, topicHandler) { + var origin = _ref30.origin, dataString = _ref30.data, win = _ref30.source; + try { + var data = parseMessage(dataString) || {}; + var channelId = data.channelId, message = data.message, messageId = data.messageId; + if (!originIsAllowed(origin) || !isNewMessage(messageId)) { + return; + } + if (message instanceof Error && win.parent !== window) { + axe.log(message); + return false; + } + try { + if (data.topic) { + var responder = createResponder(win, channelId); + assertIsParentWindow(win); + topicHandler(data, responder); + } else { + callReplyHandler(win, data); + } + } catch (error) { + processError(win, error, channelId); + } + } catch (error) { + axe.log(error); + return false; + } + } + function callReplyHandler(win, data) { + var channelId = data.channelId, message = data.message, keepalive = data.keepalive; + var _ref31 = getReplyHandler(channelId) || {}, replyHandler = _ref31.replyHandler, sendToParent = _ref31.sendToParent; + if (!replyHandler) { + return; + } + sendToParent ? assertIsParentWindow(win) : assertIsFrameWindow(win); + var responder = createResponder(win, channelId, sendToParent); + if (!keepalive && channelId) { + deleteReplyHandler(channelId); + } + try { + replyHandler(message, keepalive, responder); + } catch (error) { + axe.log(error); + responder(error, keepalive); + } + } + var frameMessenger = { + open: function open(topicHandler) { + if (typeof window.addEventListener !== 'function') { + return; + } + var handler = function handler(messageEvent) { + messageHandler(messageEvent, topicHandler); + }; + window.addEventListener('message', handler, false); + return function() { + window.removeEventListener('message', handler, false); + }; + }, + post: function post(win, data, replyHandler) { + if (typeof window.addEventListener !== 'function') { + return false; + } + return postMessage(win, data, false, replyHandler); + } + }; + function setDefaultFrameMessenger(respondable2) { + respondable2.updateMessenger(frameMessenger); + } + var closeHandler; + var postMessage2; + var topicHandlers = {}; + function _respondable(win, topic, message, keepalive, replyHandler) { + var data = { + topic: topic, + message: message, + channelId: ''.concat(v4(), ':').concat(v4()), + keepalive: keepalive + }; + return postMessage2(win, data, replyHandler); + } + function messageListener(data, responder) { + var topic = data.topic, message = data.message, keepalive = data.keepalive; + var topicHandler = Object.prototype.hasOwnProperty.call(topicHandlers, topic) ? topicHandlers[topic] : void 0; + if (!topicHandler) { + return; + } + try { + topicHandler(message, keepalive, responder); + } catch (error) { + axe.log(error); + responder(error, keepalive); + } + } + _respondable.updateMessenger = function updateMessenger(_ref32) { + var open = _ref32.open, post = _ref32.post; + assert_default(typeof open === 'function', 'open callback must be a function'); + assert_default(typeof post === 'function', 'post callback must be a function'); + if (closeHandler) { + closeHandler(); + } + var close = open(messageListener); + if (close) { + assert_default(typeof close === 'function', 'open callback must return a cleanup function'); + closeHandler = close; + } else { + closeHandler = null; + } + postMessage2 = post; + }; + _respondable.subscribe = function subscribe(topic, topicHandler) { + assert_default(typeof topicHandler === 'function', 'Subscriber callback must be a function'); + assert_default(!Object.prototype.hasOwnProperty.call(topicHandlers, topic), 'Topic '.concat(topic, ' is already registered to.')); + topicHandlers[topic] = topicHandler; + }; + _respondable.isInFrame = function isInFrame() { + var win = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; + return !!win.frameElement; + }; + setDefaultFrameMessenger(_respondable); + function _sendCommandToFrame(node, parameters, resolve, reject) { + var _parameters$options$p, _parameters$options; + var win = node.contentWindow; + var pingWaitTime = (_parameters$options$p = (_parameters$options = parameters.options) === null || _parameters$options === void 0 ? void 0 : _parameters$options.pingWaitTime) !== null && _parameters$options$p !== void 0 ? _parameters$options$p : 500; + if (!win) { + log_default('Frame does not have a content window', node); + resolve(null); + return; + } + if (pingWaitTime === 0) { + callAxeStart(node, parameters, resolve, reject); + return; + } + var timeout = setTimeout(function() { + timeout = setTimeout(function() { + if (!parameters.debug) { + resolve(null); + } else { + reject(err('No response from frame', node)); + } + }, 0); + }, pingWaitTime); + _respondable(win, 'axe.ping', null, void 0, function() { + clearTimeout(timeout); + callAxeStart(node, parameters, resolve, reject); + }); + } + function callAxeStart(node, parameters, resolve, reject) { + var _parameters$options$f, _parameters$options2; + var frameWaitTime = (_parameters$options$f = (_parameters$options2 = parameters.options) === null || _parameters$options2 === void 0 ? void 0 : _parameters$options2.frameWaitTime) !== null && _parameters$options$f !== void 0 ? _parameters$options$f : 6e4; + var win = node.contentWindow; + var timeout = setTimeout(function collectResultFramesTimeout() { + reject(err('Axe in frame timed out', node)); + }, frameWaitTime); + _respondable(win, 'axe.start', parameters, void 0, function(data) { + clearTimeout(timeout); + if (data instanceof Error === false) { + resolve(data); + } else { + reject(data); + } + }); + } + function err(message, node) { + var selector; + if (axe._tree) { + selector = get_selector_default(node); + } + return new Error(message + ': ' + (selector || node)); + } + var customSerializer = null; + var nodeSerializer = { + update: function update(serializer) { + assert_default(_typeof(serializer) === 'object', 'serializer must be an object'); + customSerializer = serializer; + }, + toSpec: function toSpec(node) { + return nodeSerializer.dqElmToSpec(new dq_element_default(node)); + }, + dqElmToSpec: function dqElmToSpec(dqElm, runOptions) { + var _customSerializer; + if (dqElm instanceof dq_element_default === false) { + return dqElm; + } + if (runOptions) { + dqElm = cloneLimitedDqElement(dqElm, runOptions); + } + if (typeof ((_customSerializer = customSerializer) === null || _customSerializer === void 0 ? void 0 : _customSerializer.toSpec) === 'function') { + return customSerializer.toSpec(dqElm); + } + return dqElm.toJSON(); + }, + mergeSpecs: function mergeSpecs(nodeSpec, parentFrameSpec) { + var _customSerializer2; + if (typeof ((_customSerializer2 = customSerializer) === null || _customSerializer2 === void 0 ? void 0 : _customSerializer2.mergeSpecs) === 'function') { + return customSerializer.mergeSpecs(nodeSpec, parentFrameSpec); + } + return dq_element_default.mergeSpecs(nodeSpec, parentFrameSpec); + }, + mapRawResults: function mapRawResults(rawResults) { + return rawResults.map(function(rawResult) { + return _extends({}, rawResult, { + nodes: nodeSerializer.mapRawNodeResults(rawResult.nodes) + }); + }); + }, + mapRawNodeResults: function mapRawNodeResults(nodeResults) { + return nodeResults === null || nodeResults === void 0 ? void 0 : nodeResults.map(function(_ref33) { + var node = _ref33.node, nodeResult = _objectWithoutProperties(_ref33, _excluded6); + nodeResult.node = nodeSerializer.dqElmToSpec(node); + for (var _i6 = 0, _arr2 = [ 'any', 'all', 'none' ]; _i6 < _arr2.length; _i6++) { + var type2 = _arr2[_i6]; + nodeResult[type2] = nodeResult[type2].map(function(_ref34) { + var relatedNodes = _ref34.relatedNodes, checkResult = _objectWithoutProperties(_ref34, _excluded7); + checkResult.relatedNodes = relatedNodes.map(nodeSerializer.dqElmToSpec); + return checkResult; + }); + } + return nodeResult; + }); + } + }; + var node_serializer_default = nodeSerializer; + function cloneLimitedDqElement(dqElm, runOptions) { + var fromFrame2 = dqElm.fromFrame; + var hasAncestry = runOptions.ancestry, hasXpath = runOptions.xpath; + var hasSelectors = runOptions.selectors !== false || fromFrame2; + dqElm = new dq_element_default(dqElm.element, runOptions, { + source: dqElm.source, + nodeIndexes: dqElm.nodeIndexes, + selector: hasSelectors ? dqElm.selector : [ ':root' ], + ancestry: hasAncestry ? dqElm.ancestry : [ ':root' ], + xpath: hasXpath ? dqElm.xpath : '/' + }); + dqElm.fromFrame = fromFrame2; + return dqElm; + } + function getAllChecks(object) { + var result = []; + return result.concat(object.any || []).concat(object.all || []).concat(object.none || []); + } + var get_all_checks_default = getAllChecks; + function findBy(array, key, value) { + if (Array.isArray(array)) { + return array.find(function(obj) { + return obj !== null && _typeof(obj) === 'object' && Object.hasOwn(obj, key) && obj[key] === value; + }); + } + } + var find_by_default = findBy; + function pushFrame(resultSet, options, frameSpec) { + resultSet.forEach(function(res) { + res.node = node_serializer_default.mergeSpecs(res.node, frameSpec); + var checks = get_all_checks_default(res); + checks.forEach(function(check) { + check.relatedNodes = check.relatedNodes.map(function(node) { + return node_serializer_default.mergeSpecs(node, frameSpec); + }); + }); + }); + } + function spliceNodes(target, to2) { + var firstFromFrame = to2[0].node; + var node; + for (var _i7 = 0; _i7 < target.length; _i7++) { + node = target[_i7].node; + var resultSort = nodeIndexSort(node.nodeIndexes, firstFromFrame.nodeIndexes); + if (resultSort > 0 || resultSort === 0 && firstFromFrame.selector.length < node.selector.length) { + target.splice.apply(target, [ _i7, 0 ].concat(_toConsumableArray(to2))); + return; + } + } + target.push.apply(target, _toConsumableArray(to2)); + } + function normalizeResult(result) { + if (!result || !result.results) { + return null; + } + if (!Array.isArray(result.results)) { + return [ result.results ]; + } + if (!result.results.length) { + return null; + } + return result.results; + } + function mergeResults(frameResults, options) { + var mergedResult = []; + frameResults.forEach(function(frameResult) { + var results = normalizeResult(frameResult); + if (!results || !results.length) { + return; + } + var frameSpec = getFrameSpec(frameResult); + results.forEach(function(ruleResult) { + if (ruleResult.nodes && frameSpec) { + pushFrame(ruleResult.nodes, options, frameSpec); + } + var res = find_by_default(mergedResult, 'id', ruleResult.id); + if (!res) { + mergedResult.push(ruleResult); + } else { + if (ruleResult.nodes.length) { + spliceNodes(res.nodes, ruleResult.nodes); + } + if (ruleResult.error) { + var _res$error; + (_res$error = res.error) !== null && _res$error !== void 0 ? _res$error : res.error = ruleResult.error; + } + } + }); + }); + mergedResult.forEach(function(result) { + if (result.nodes) { + result.nodes.sort(function(nodeA, nodeB) { + return nodeIndexSort(nodeA.node.nodeIndexes, nodeB.node.nodeIndexes); + }); + } + }); + return mergedResult; + } + function nodeIndexSort() { + var nodeIndexesA = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var nodeIndexesB = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var length = Math.max(nodeIndexesA === null || nodeIndexesA === void 0 ? void 0 : nodeIndexesA.length, nodeIndexesB === null || nodeIndexesB === void 0 ? void 0 : nodeIndexesB.length); + for (var _i8 = 0; _i8 < length; _i8++) { + var indexA = nodeIndexesA === null || nodeIndexesA === void 0 ? void 0 : nodeIndexesA[_i8]; + var indexB = nodeIndexesB === null || nodeIndexesB === void 0 ? void 0 : nodeIndexesB[_i8]; + if (typeof indexA !== 'number' || isNaN(indexA)) { + return _i8 === 0 ? 1 : -1; + } + if (typeof indexB !== 'number' || isNaN(indexB)) { + return _i8 === 0 ? -1 : 1; + } + if (indexA !== indexB) { + return indexA - indexB; + } + } + return 0; + } + var merge_results_default = mergeResults; + function getFrameSpec(frameResult) { + if (frameResult.frameElement) { + return node_serializer_default.toSpec(frameResult.frameElement); + } else if (frameResult.frameSpec) { + return frameResult.frameSpec; + } + return null; + } + function _collectResultsFromFrames(parentContent, options, command, parameter, resolve, reject) { + options = _extends({}, options, { + elementRef: false + }); + var q = queue_default(); + var frames = parentContent.frames; + frames.forEach(function(_ref35) { + var frameElement = _ref35.node, context = _objectWithoutProperties(_ref35, _excluded8); + q.defer(function(res, rej) { + var params = { + options: options, + command: command, + parameter: parameter, + context: context + }; + function callback(results) { + if (!results) { + return res(null); + } + return res({ + results: results, + frameElement: frameElement + }); + } + _sendCommandToFrame(frameElement, params, callback, rej); + }); + }); + q.then(function(data) { + resolve(merge_results_default(data, options)); + })['catch'](reject); + } + function _contains(vNode, otherVNode) { + if (!vNode.shadowId && !otherVNode.shadowId && vNode.actualNode && typeof vNode.actualNode.contains === 'function') { + return vNode.actualNode.contains(otherVNode.actualNode); + } + do { + if (vNode === otherVNode) { + return true; + } else if (otherVNode.nodeIndex < vNode.nodeIndex) { + return false; + } + otherVNode = otherVNode.parent; + } while (otherVNode); + return false; + } + function deepMerge() { + var target = {}; + for (var _len6 = arguments.length, sources = new Array(_len6), _key7 = 0; _key7 < _len6; _key7++) { + sources[_key7] = arguments[_key7]; + } + sources.forEach(function(source) { + if (!source || _typeof(source) !== 'object' || Array.isArray(source)) { + return; + } + for (var _i9 = 0, _Object$keys2 = Object.keys(source); _i9 < _Object$keys2.length; _i9++) { + var _key8 = _Object$keys2[_i9]; + if (!target.hasOwnProperty(_key8) || _typeof(source[_key8]) !== 'object' || Array.isArray(target[_key8])) { + target[_key8] = source[_key8]; + } else { + target[_key8] = deepMerge(target[_key8], source[_key8]); + } + } + }); + return target; + } + var deep_merge_default = deepMerge; + function extendMetaData(to2, from) { + Object.assign(to2, from); + Object.keys(from).filter(function(prop) { + return typeof from[prop] === 'function'; + }).forEach(function(prop) { + to2[prop] = null; + try { + to2[prop] = from[prop](to2); + } catch (_unused2) {} + }); + } + var extend_meta_data_default = extendMetaData; + var possibleShadowRoots = [ 'article', 'aside', 'blockquote', 'body', 'div', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'main', 'nav', 'p', 'section', 'span' ]; + function isShadowRoot(node) { + if (node.shadowRoot) { + var nodeName2 = node.nodeName.toLowerCase(); + if (possibleShadowRoots.includes(nodeName2) || /^[a-z][a-z0-9_.-]*-[a-z0-9_.-]*$/.test(nodeName2)) { + return true; + } + } + return false; + } + var is_shadow_root_default = isShadowRoot; + var dom_exports = {}; + __export(dom_exports, { + createGrid: function createGrid() { + return _createGrid; + }, + findElmsInContext: function findElmsInContext() { + return find_elms_in_context_default; + }, + findNearbyElms: function findNearbyElms() { + return _findNearbyElms; + }, + findUp: function findUp() { + return find_up_default; + }, + findUpVirtual: function findUpVirtual() { + return find_up_virtual_default; + }, + focusDisabled: function focusDisabled() { + return focus_disabled_default; + }, + getComposedParent: function getComposedParent() { + return get_composed_parent_default; + }, + getElementByReference: function getElementByReference() { + return get_element_by_reference_default; + }, + getElementCoordinates: function getElementCoordinates() { + return get_element_coordinates_default; + }, + getElementStack: function getElementStack() { + return get_element_stack_default; + }, + getModalDialog: function getModalDialog() { + return get_modal_dialog_default; + }, + getNodeGrid: function getNodeGrid() { + return _getNodeGrid; + }, + getOverflowHiddenAncestors: function getOverflowHiddenAncestors() { + return get_overflow_hidden_ancestors_default; + }, + getRootNode: function getRootNode() { + return get_root_node_default2; + }, + getScrollOffset: function getScrollOffset() { + return get_scroll_offset_default; + }, + getTabbableElements: function getTabbableElements() { + return get_tabbable_elements_default; + }, + getTargetRects: function getTargetRects() { + return get_target_rects_default; + }, + getTargetSize: function getTargetSize() { + return get_target_size_default; + }, + getTextElementStack: function getTextElementStack() { + return get_text_element_stack_default; + }, + getViewportSize: function getViewportSize() { + return get_viewport_size_default; + }, + getVisibleChildTextRects: function getVisibleChildTextRects() { + return get_visible_child_text_rects_default; + }, + hasContent: function hasContent() { + return has_content_default; + }, + hasContentVirtual: function hasContentVirtual() { + return has_content_virtual_default; + }, + hasLangText: function hasLangText() { + return _hasLangText; + }, + idrefs: function idrefs() { + return idrefs_default; + }, + insertedIntoFocusOrder: function insertedIntoFocusOrder() { + return inserted_into_focus_order_default; + }, + isCurrentPageLink: function isCurrentPageLink() { + return _isCurrentPageLink; + }, + isFixedPosition: function isFixedPosition() { + return _isFixedPosition; + }, + isFocusable: function isFocusable() { + return _isFocusable; + }, + isHTML5: function isHTML5() { + return is_html5_default; + }, + isHiddenForEveryone: function isHiddenForEveryone() { + return _isHiddenForEveryone; + }, + isHiddenWithCSS: function isHiddenWithCSS() { + return is_hidden_with_css_default; + }, + isInTabOrder: function isInTabOrder() { + return _isInTabOrder; + }, + isInTextBlock: function isInTextBlock() { + return is_in_text_block_default; + }, + isInert: function isInert() { + return _isInert; + }, + isModalOpen: function isModalOpen() { + return is_modal_open_default; + }, + isMultiline: function isMultiline() { + return _isMultiline; + }, + isNativelyFocusable: function isNativelyFocusable() { + return is_natively_focusable_default; + }, + isNode: function isNode() { + return is_node_default; + }, + isOffscreen: function isOffscreen() { + return is_offscreen_default; + }, + isOpaque: function isOpaque() { + return is_opaque_default; + }, + isSkipLink: function isSkipLink() { + return _isSkipLink; + }, + isVisible: function isVisible() { + return is_visible_default; + }, + isVisibleOnScreen: function isVisibleOnScreen() { + return _isVisibleOnScreen; + }, + isVisibleToScreenReaders: function isVisibleToScreenReaders() { + return _isVisibleToScreenReaders; + }, + isVisualContent: function isVisualContent() { + return is_visual_content_default; + }, + reduceToElementsBelowFloating: function reduceToElementsBelowFloating() { + return reduce_to_elements_below_floating_default; + }, + shadowElementsFromPoint: function shadowElementsFromPoint() { + return shadow_elements_from_point_default; + }, + urlPropsFromAttribute: function urlPropsFromAttribute() { + return url_props_from_attribute_default; + }, + visuallyContains: function visuallyContains() { + return _visuallyContains; + }, + visuallyOverlaps: function visuallyOverlaps() { + return visually_overlaps_default; + }, + visuallySort: function visuallySort() { + return _visuallySort; + } + }); + function getRootNode(node) { + var doc = node.getRootNode && node.getRootNode() || document; + if (doc === node) { + doc = document; + } + return doc; + } + var get_root_node_default = getRootNode; + var get_root_node_default2 = get_root_node_default; + function findElmsInContext(_ref36) { + var context = _ref36.context, value = _ref36.value, attr = _ref36.attr, _ref36$elm = _ref36.elm, elm = _ref36$elm === void 0 ? '' : _ref36$elm; + var root; + var escapedValue = escape_selector_default(value); + if (context.nodeType === 9 || context.nodeType === 11) { + root = context; + } else { + root = get_root_node_default2(context); + } + return Array.from(root.querySelectorAll(elm + '[' + attr + '=' + escapedValue + ']')); + } + var find_elms_in_context_default = findElmsInContext; + function findUpVirtual(element, target) { + var parent; + parent = element.actualNode; + if (!element.shadowId && typeof element.actualNode.closest === 'function') { + var match = element.actualNode.closest(target); + if (match) { + return match; + } + return null; + } + do { + parent = parent.assignedSlot ? parent.assignedSlot : parent.parentNode; + if (parent && parent.nodeType === 11) { + parent = parent.host; + } + } while (parent && !element_matches_default(parent, target) && parent !== document.documentElement); + if (!parent) { + return null; + } + if (!element_matches_default(parent, target)) { + return null; + } + return parent; + } + var find_up_virtual_default = findUpVirtual; + function findUp(element, target) { + return find_up_virtual_default(get_node_from_tree_default(element), target); + } + var find_up_default = findUp; + function _rectsOverlap(rect1, rect2) { + return (rect1.left | 0) < (rect2.right | 0) && (rect1.right | 0) > (rect2.left | 0) && (rect1.top | 0) < (rect2.bottom | 0) && (rect1.bottom | 0) > (rect2.top | 0); + } + var getOverflowHiddenAncestors = memoize_default(function getOverflowHiddenAncestorsMemoized(vNode) { + var ancestors = []; + if (!vNode) { + return ancestors; + } + var overflow = vNode.getComputedStylePropertyValue('overflow'); + if (overflow === 'hidden') { + ancestors.push(vNode); + } + return ancestors.concat(getOverflowHiddenAncestors(vNode.parent)); + }); + var get_overflow_hidden_ancestors_default = getOverflowHiddenAncestors; + var clipRegex = /rect\s*\(([0-9]+)px,?\s*([0-9]+)px,?\s*([0-9]+)px,?\s*([0-9]+)px\s*\)/; + var clipPathRegex = /(\w+)\((\d+)/; + function nativelyHidden(vNode) { + return [ 'style', 'script', 'noscript', 'template' ].includes(vNode.props.nodeName); + } + function displayHidden(vNode) { + if (vNode.props.nodeName === 'area') { + return false; + } + return vNode.getComputedStylePropertyValue('display') === 'none'; + } + function visibilityHidden(vNode) { + var _ref37 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, isAncestor = _ref37.isAncestor; + return !isAncestor && [ 'hidden', 'collapse' ].includes(vNode.getComputedStylePropertyValue('visibility')); + } + function contentVisibiltyHidden(vNode) { + var _ref38 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, isAncestor = _ref38.isAncestor; + return !!isAncestor && vNode.getComputedStylePropertyValue('content-visibility') === 'hidden'; + } + function ariaHidden(vNode) { + return vNode.attr('aria-hidden') === 'true'; + } + function opacityHidden(vNode) { + return vNode.getComputedStylePropertyValue('opacity') === '0'; + } + function scrollHidden(vNode) { + var scroll = get_scroll_default(vNode.actualNode); + var elHeight = parseInt(vNode.getComputedStylePropertyValue('height')); + var elWidth = parseInt(vNode.getComputedStylePropertyValue('width')); + return !!scroll && (elHeight === 0 || elWidth === 0); + } + function overflowHidden(vNode) { + var _ref39 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, isAncestor = _ref39.isAncestor; + if (isAncestor) { + return false; + } + var position = vNode.getComputedStylePropertyValue('position'); + if (position === 'fixed') { + return false; + } + var nodes = get_overflow_hidden_ancestors_default(vNode); + if (!nodes.length) { + return false; + } + var rect = vNode.boundingClientRect; + return nodes.some(function(node) { + if (position === 'absolute' && !hasPositionedAncestorBetween(vNode, node) && node.getComputedStylePropertyValue('position') === 'static') { + return false; + } + var nodeRect = node.boundingClientRect; + if (nodeRect.width < 2 || nodeRect.height < 2) { + return true; + } + return !_rectsOverlap(rect, nodeRect); + }); + } + function clipHidden(vNode) { + var matchesClip = vNode.getComputedStylePropertyValue('clip').match(clipRegex); + var matchesClipPath = vNode.getComputedStylePropertyValue('clip-path').match(clipPathRegex); + if (matchesClip && matchesClip.length === 5) { + var position = vNode.getComputedStylePropertyValue('position'); + if ([ 'fixed', 'absolute' ].includes(position)) { + return matchesClip[3] - matchesClip[1] <= 0 && matchesClip[2] - matchesClip[4] <= 0; + } + } + if (matchesClipPath) { + var type2 = matchesClipPath[1]; + var value = parseInt(matchesClipPath[2], 10); + switch (type2) { + case 'inset': + return value >= 50; + + case 'circle': + return value === 0; + + default: + } + } + return false; + } + function areaHidden(vNode, visibleFunction) { + var mapEl = closest_default(vNode, 'map'); + if (!mapEl) { + return true; + } + var mapElName = mapEl.attr('name'); + if (!mapElName) { + return true; + } + var mapElRootNode = get_root_node_default(vNode.actualNode); + if (!mapElRootNode || mapElRootNode.nodeType !== 9) { + return true; + } + var refs = query_selector_all_default(axe._tree, 'img[usemap="#'.concat(escape_selector_default(mapElName), '"]')); + if (!refs || !refs.length) { + return true; + } + return refs.some(function(ref) { + return !visibleFunction(ref); + }); + } + function detailsHidden(vNode) { + var _vNode$parent; + if (((_vNode$parent = vNode.parent) === null || _vNode$parent === void 0 ? void 0 : _vNode$parent.props.nodeName) !== 'details') { + return false; + } + if (vNode.props.nodeName === 'summary') { + var firstSummary = vNode.parent.children.find(function(node) { + return node.props.nodeName === 'summary'; + }); + if (firstSummary === vNode) { + return false; + } + } + return !vNode.parent.hasAttr('open'); + } + function hasPositionedAncestorBetween(child, ancestor) { + var node = child.parent; + while (node && node !== ancestor) { + if ([ 'relative', 'sticky' ].includes(node.getComputedStylePropertyValue('position'))) { + return true; + } + node = node.parent; + } + return false; + } + var hiddenMethods = [ displayHidden, visibilityHidden, contentVisibiltyHidden, detailsHidden ]; + function _isHiddenForEveryone(vNode) { + var _ref40 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, skipAncestors = _ref40.skipAncestors, _ref40$isAncestor = _ref40.isAncestor, isAncestor = _ref40$isAncestor === void 0 ? false : _ref40$isAncestor; + vNode = _nodeLookup(vNode).vNode; + if (skipAncestors) { + return isHiddenSelf(vNode, isAncestor); + } + return isHiddenAncestors(vNode, isAncestor); + } + var isHiddenSelf = memoize_default(function isHiddenSelfMemoized(vNode, isAncestor) { + if (nativelyHidden(vNode)) { + return true; + } + if (!vNode.actualNode) { + return false; + } + if (hiddenMethods.some(function(method) { + return method(vNode, { + isAncestor: isAncestor + }); + })) { + return true; + } + if (!vNode.actualNode.isConnected) { + return true; + } + return false; + }); + var isHiddenAncestors = memoize_default(function isHiddenAncestorsMemoized(vNode, isAncestor) { + if (isHiddenSelf(vNode, isAncestor)) { + return true; + } + if (!vNode.parent) { + return false; + } + return isHiddenAncestors(vNode.parent, true); + }); + function getComposedParent(element) { + if (element.assignedSlot) { + return getComposedParent(element.assignedSlot); + } else if (element.parentNode) { + var parentNode = element.parentNode; + if (parentNode.nodeType === 1) { + return parentNode; + } else if (parentNode.host) { + return parentNode.host; + } + } + return null; + } + var get_composed_parent_default = getComposedParent; + function getScrollOffset(element) { + if (!element.nodeType && element.document) { + element = element.document; + } + if (element.nodeType === 9) { + var docElement = element.documentElement, body = element.body; + return { + left: docElement && docElement.scrollLeft || body && body.scrollLeft || 0, + top: docElement && docElement.scrollTop || body && body.scrollTop || 0 + }; + } + return { + left: element.scrollLeft, + top: element.scrollTop + }; + } + var get_scroll_offset_default = getScrollOffset; + function getElementCoordinates(element) { + var scrollOffset = get_scroll_offset_default(document), xOffset = scrollOffset.left, yOffset = scrollOffset.top, coords = element.getBoundingClientRect(); + return { + top: coords.top + yOffset, + right: coords.right + xOffset, + bottom: coords.bottom + yOffset, + left: coords.left + xOffset, + width: coords.right - coords.left, + height: coords.bottom - coords.top + }; + } + var get_element_coordinates_default = getElementCoordinates; + function getViewportSize(win) { + var doc = win.document; + var docElement = doc.documentElement; + if (win.innerWidth) { + return { + width: win.innerWidth, + height: win.innerHeight + }; + } + if (docElement) { + return { + width: docElement.clientWidth, + height: docElement.clientHeight + }; + } + var body = doc.body; + return { + width: body.clientWidth, + height: body.clientHeight + }; + } + var get_viewport_size_default = getViewportSize; + function _isFixedPosition(node) { + var _ref41 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, skipAncestors = _ref41.skipAncestors; + var _nodeLookup2 = _nodeLookup(node), vNode = _nodeLookup2.vNode; + if (!vNode) { + return false; + } + if (skipAncestors) { + return isFixedSelf(vNode); + } + return isFixedAncestors(vNode); + } + var isFixedSelf = memoize_default(function isFixedSelfMemoized(vNode) { + return vNode.getComputedStylePropertyValue('position') === 'fixed'; + }); + var isFixedAncestors = memoize_default(function isFixedAncestorsMemoized(vNode) { + if (isFixedSelf(vNode)) { + return true; + } + if (!vNode.parent) { + return false; + } + return isFixedAncestors(vNode.parent); + }); + function noParentScrolled(element, offset) { + element = get_composed_parent_default(element); + while (element && element.nodeName.toLowerCase() !== 'html') { + if (element.scrollTop) { + offset += element.scrollTop; + if (offset >= 0) { + return false; + } + } + element = get_composed_parent_default(element); + } + return true; + } + function isOffscreen(element) { + var _ref42 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, isAncestor = _ref42.isAncestor; + if (isAncestor) { + return false; + } + var _nodeLookup3 = _nodeLookup(element), domNode = _nodeLookup3.domNode; + if (!domNode) { + return void 0; + } + var docElement = document.documentElement; + var styl = window.getComputedStyle(domNode); + var dir = window.getComputedStyle(document.body || docElement).getPropertyValue('direction'); + var isFixed = _isFixedPosition(domNode); + var coords = isFixed ? domNode.getBoundingClientRect() : get_element_coordinates_default(domNode); + if (coords.top === 0 && coords.bottom === 0) { + return false; + } + if (coords.left === 0 && coords.right === 0) { + return false; + } + if (coords.bottom <= 0 && (noParentScrolled(domNode, coords.bottom) || styl.position === 'absolute')) { + return true; + } + var viewportSize = get_viewport_size_default(window); + if (isFixed && coords.top >= viewportSize.height) { + return true; + } + var rightEdge = Math.max(docElement.scrollWidth, viewportSize.width); + if ((isFixed || dir === 'rtl') && coords.left >= rightEdge) { + return true; + } + if ((isFixed || dir === 'ltr') && coords.right <= 0) { + return true; + } + return false; + } + var is_offscreen_default = isOffscreen; + var hiddenMethods2 = [ opacityHidden, scrollHidden, overflowHidden, clipHidden, is_offscreen_default ]; + function _isVisibleOnScreen(vNode) { + vNode = _nodeLookup(vNode).vNode; + return isVisibleOnScreenVirtual(vNode); + } + var isVisibleOnScreenVirtual = memoize_default(function isVisibleOnScreenMemoized(vNode, isAncestor) { + if (vNode.actualNode && vNode.props.nodeName === 'area') { + return !areaHidden(vNode, isVisibleOnScreenVirtual); + } + if (_isHiddenForEveryone(vNode, { + skipAncestors: true, + isAncestor: isAncestor + })) { + return false; + } + if (vNode.actualNode && hiddenMethods2.some(function(method) { + return method(vNode, { + isAncestor: isAncestor + }); + })) { + return false; + } + if (!vNode.parent) { + return true; + } + return isVisibleOnScreenVirtual(vNode.parent, true); + }); + function _getBoundingRect(rectA, rectB) { + var top = Math.min(rectA.top, rectB.top); + var right = Math.max(rectA.right, rectB.right); + var bottom = Math.max(rectA.bottom, rectB.bottom); + var left = Math.min(rectA.left, rectB.left); + return new window.DOMRect(left, top, right - left, bottom - top); + } + function _isPointInRect(_ref43, _ref44) { + var x = _ref43.x, y = _ref43.y; + var top = _ref44.top, right = _ref44.right, bottom = _ref44.bottom, left = _ref44.left; + return y >= top && x <= right && y <= bottom && x >= left; + } + var math_exports = {}; + __export(math_exports, { + getBoundingRect: function getBoundingRect() { + return _getBoundingRect; + }, + getIntersectionRect: function getIntersectionRect() { + return _getIntersectionRect; + }, + getOffset: function getOffset() { + return _getOffset; + }, + getRectCenter: function getRectCenter() { + return _getRectCenter; + }, + hasVisualOverlap: function hasVisualOverlap() { + return _hasVisualOverlap; + }, + isPointInRect: function isPointInRect() { + return _isPointInRect; + }, + rectHasMinimumSize: function rectHasMinimumSize() { + return _rectHasMinimumSize; + }, + rectsOverlap: function rectsOverlap() { + return _rectsOverlap; + }, + splitRects: function splitRects() { + return _splitRects; + } + }); + function _getIntersectionRect(rect1, rect2) { + var leftX = Math.max(rect1.left, rect2.left); + var rightX = Math.min(rect1.right, rect2.right); + var topY = Math.max(rect1.top, rect2.top); + var bottomY = Math.min(rect1.bottom, rect2.bottom); + if (leftX >= rightX || topY >= bottomY) { + return null; + } + return new window.DOMRect(leftX, topY, rightX - leftX, bottomY - topY); + } + function _getRectCenter(_ref45) { + var left = _ref45.left, top = _ref45.top, width = _ref45.width, height = _ref45.height; + return new window.DOMPoint(left + width / 2, top + height / 2); + } + var roundingMargin = .05; + function _rectHasMinimumSize(minSize, _ref46) { + var width = _ref46.width, height = _ref46.height; + return width + roundingMargin >= minSize && height + roundingMargin >= minSize; + } + function _getOffset(vTarget, vNeighbor) { + var minRadiusNeighbour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 12; + var targetRects = get_target_rects_default(vTarget); + var neighborRects = get_target_rects_default(vNeighbor); + if (!targetRects.length || !neighborRects.length) { + return null; + } + return targetRects.reduce(function(minDistance, targetRect) { + var targetCenter = _getRectCenter(targetRect); + var _iterator8 = _createForOfIteratorHelper(neighborRects), _step8; + try { + for (_iterator8.s(); !(_step8 = _iterator8.n()).done; ) { + var rect = _step8.value; + if (_isPointInRect(targetCenter, rect)) { + return 0; + } + var closestPoint = getClosestPoint(targetCenter, rect); + var distance2 = pointDistance(targetCenter, closestPoint); + minDistance = Math.min(minDistance, distance2); + } + } catch (err) { + _iterator8.e(err); + } finally { + _iterator8.f(); + } + var neighborTargetSize = get_target_size_default(vNeighbor); + if (_rectHasMinimumSize(minRadiusNeighbour * 2, neighborTargetSize)) { + return minDistance; + } + var neighborBoundingBox = neighborRects.reduce(_getBoundingRect); + var neighborCenter = _getRectCenter(neighborBoundingBox); + var centerDistance = pointDistance(targetCenter, neighborCenter) - minRadiusNeighbour; + return Math.max(0, Math.min(minDistance, centerDistance)); + }, Infinity); + } + function getClosestPoint(point, rect) { + var x; + var y; + if (point.x < rect.left) { + x = rect.left; + } else if (point.x > rect.right) { + x = rect.right; + } else { + x = point.x; + } + if (point.y < rect.top) { + y = rect.top; + } else if (point.y > rect.bottom) { + y = rect.bottom; + } else { + y = point.y; + } + return { + x: x, + y: y + }; + } + function pointDistance(pointA, pointB) { + return Math.hypot(pointA.x - pointB.x, pointA.y - pointB.y); + } + function _hasVisualOverlap(vNodeA, vNodeB) { + var rectA = vNodeA.boundingClientRect; + var rectB = vNodeB.boundingClientRect; + if (rectA.left >= rectB.right || rectA.right <= rectB.left || rectA.top >= rectB.bottom || rectA.bottom <= rectB.top) { + return false; + } + return _visuallySort(vNodeA, vNodeB) > 0; + } + function _splitRects(outerRect, overlapRects) { + var uniqueRects = Array.isArray(outerRect) ? outerRect : [ outerRect ]; + var _iterator9 = _createForOfIteratorHelper(overlapRects), _step9; + try { + var _loop6 = function _loop6() { + var overlapRect = _step9.value; + uniqueRects = uniqueRects.reduce(function(rects, inputRect) { + return rects.concat(splitRect(inputRect, overlapRect)); + }, []); + if (uniqueRects.length > 4e3) { + throw new Error('splitRects: Too many rects'); + } + }; + for (_iterator9.s(); !(_step9 = _iterator9.n()).done; ) { + _loop6(); + } + } catch (err) { + _iterator9.e(err); + } finally { + _iterator9.f(); + } + return uniqueRects; + } + function splitRect(inputRect, clipRect) { + var top = inputRect.top, left = inputRect.left, bottom = inputRect.bottom, right = inputRect.right; + var yAligned = top < clipRect.bottom && bottom > clipRect.top; + var xAligned = left < clipRect.right && right > clipRect.left; + var rects = []; + if (between(clipRect.top, top, bottom) && xAligned) { + rects.push({ + top: top, + left: left, + bottom: clipRect.top, + right: right + }); + } + if (between(clipRect.right, left, right) && yAligned) { + rects.push({ + top: top, + left: clipRect.right, + bottom: bottom, + right: right + }); + } + if (between(clipRect.bottom, top, bottom) && xAligned) { + rects.push({ + top: clipRect.bottom, + right: right, + bottom: bottom, + left: left + }); + } + if (between(clipRect.left, left, right) && yAligned) { + rects.push({ + top: top, + left: left, + bottom: bottom, + right: clipRect.left + }); + } + if (rects.length === 0) { + if (isEnclosedRect(inputRect, clipRect)) { + return []; + } + rects.push(inputRect); + } + return rects.map(computeRect); + } + var between = function between(num, min, max2) { + return num > min && num < max2; + }; + function computeRect(baseRect) { + return new window.DOMRect(baseRect.left, baseRect.top, baseRect.right - baseRect.left, baseRect.bottom - baseRect.top); + } + function isEnclosedRect(rectA, rectB) { + return rectA.top >= rectB.top && rectA.left >= rectB.left && rectA.bottom <= rectB.bottom && rectA.right <= rectB.right; + } + var ROOT_LEVEL = 0; + var DEFAULT_LEVEL = .1; + var FLOAT_LEVEL = .2; + var POSITION_LEVEL = .3; + var nodeIndex = 0; + function _createGrid() { + var root = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document.body; + var rootGrid = arguments.length > 1 ? arguments[1] : undefined; + var parentVNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (cache_default.get('gridCreated') && !parentVNode) { + return constants_default.gridSize; + } + cache_default.set('gridCreated', true); + if (!parentVNode) { + var vNode = get_node_from_tree_default(document.documentElement); + if (!vNode) { + vNode = new virtual_node_default(document.documentElement); + } + nodeIndex = 0; + vNode._stackingOrder = [ createStackingContext(ROOT_LEVEL, nodeIndex++, null) ]; + rootGrid !== null && rootGrid !== void 0 ? rootGrid : rootGrid = new Grid(); + addNodeToGrid(rootGrid, vNode); + if (get_scroll_default(vNode.actualNode)) { + var subGrid = new Grid(vNode); + vNode._subGrid = subGrid; + } + } + var treeWalker = document.createTreeWalker(root, window.NodeFilter.SHOW_ELEMENT, null, false); + var node = parentVNode ? treeWalker.nextNode() : treeWalker.currentNode; + while (node) { + var _vNode = get_node_from_tree_default(node); + if (_vNode && _vNode.parent) { + parentVNode = _vNode.parent; + } else if (node.assignedSlot) { + parentVNode = get_node_from_tree_default(node.assignedSlot); + } else if (node.parentElement) { + parentVNode = get_node_from_tree_default(node.parentElement); + } else if (node.parentNode && get_node_from_tree_default(node.parentNode)) { + parentVNode = get_node_from_tree_default(node.parentNode); + } + if (!_vNode) { + _vNode = new axe.VirtualNode(node, parentVNode); + } + _vNode._stackingOrder = createStackingOrder(_vNode, parentVNode, nodeIndex++); + var scrollRegionParent = findScrollRegionParent(_vNode, parentVNode); + var grid = scrollRegionParent ? scrollRegionParent._subGrid : rootGrid; + if (get_scroll_default(_vNode.actualNode)) { + var _subGrid = new Grid(_vNode); + _vNode._subGrid = _subGrid; + } + var rect = _vNode.boundingClientRect; + if (rect.width !== 0 && rect.height !== 0 && _isVisibleOnScreen(node)) { + addNodeToGrid(grid, _vNode); + } + if (is_shadow_root_default(node)) { + _createGrid(node.shadowRoot, grid, _vNode); + } + node = treeWalker.nextNode(); + } + return constants_default.gridSize; + } + function isStackingContext(vNode, parentVNode) { + var position = vNode.getComputedStylePropertyValue('position'); + var zIndex = vNode.getComputedStylePropertyValue('z-index'); + if (position === 'fixed' || position === 'sticky') { + return true; + } + if (zIndex !== 'auto' && position !== 'static') { + return true; + } + if (vNode.getComputedStylePropertyValue('opacity') !== '1') { + return true; + } + var transform = vNode.getComputedStylePropertyValue('-webkit-transform') || vNode.getComputedStylePropertyValue('-ms-transform') || vNode.getComputedStylePropertyValue('transform') || 'none'; + if (transform !== 'none') { + return true; + } + var mixBlendMode = vNode.getComputedStylePropertyValue('mix-blend-mode'); + if (mixBlendMode && mixBlendMode !== 'normal') { + return true; + } + var filter = vNode.getComputedStylePropertyValue('filter'); + if (filter && filter !== 'none') { + return true; + } + var perspective = vNode.getComputedStylePropertyValue('perspective'); + if (perspective && perspective !== 'none') { + return true; + } + var clipPath = vNode.getComputedStylePropertyValue('clip-path'); + if (clipPath && clipPath !== 'none') { + return true; + } + var mask = vNode.getComputedStylePropertyValue('-webkit-mask') || vNode.getComputedStylePropertyValue('mask') || 'none'; + if (mask !== 'none') { + return true; + } + var maskImage = vNode.getComputedStylePropertyValue('-webkit-mask-image') || vNode.getComputedStylePropertyValue('mask-image') || 'none'; + if (maskImage !== 'none') { + return true; + } + var maskBorder = vNode.getComputedStylePropertyValue('-webkit-mask-border') || vNode.getComputedStylePropertyValue('mask-border') || 'none'; + if (maskBorder !== 'none') { + return true; + } + if (vNode.getComputedStylePropertyValue('isolation') === 'isolate') { + return true; + } + var willChange = vNode.getComputedStylePropertyValue('will-change'); + if (willChange === 'transform' || willChange === 'opacity') { + return true; + } + if (vNode.getComputedStylePropertyValue('-webkit-overflow-scrolling') === 'touch') { + return true; + } + var contain = vNode.getComputedStylePropertyValue('contain'); + if ([ 'layout', 'paint', 'strict', 'content' ].includes(contain)) { + return true; + } + if (zIndex !== 'auto' && isFlexOrGridContainer(parentVNode)) { + return true; + } + return false; + } + function isFlexOrGridContainer(vNode) { + if (!vNode) { + return false; + } + var display2 = vNode.getComputedStylePropertyValue('display'); + return [ 'flex', 'inline-flex', 'grid', 'inline-grid' ].includes(display2); + } + function createStackingOrder(vNode, parentVNode, treeOrder) { + var stackingOrder = parentVNode._stackingOrder.slice(); + if (isStackingContext(vNode, parentVNode)) { + var index = stackingOrder.findIndex(function(_ref47) { + var stackLevel2 = _ref47.stackLevel; + return [ ROOT_LEVEL, FLOAT_LEVEL, POSITION_LEVEL ].includes(stackLevel2); + }); + if (index !== -1) { + stackingOrder.splice(index, stackingOrder.length - index); + } + } + var stackLevel = getStackLevel(vNode, parentVNode); + if (stackLevel !== null) { + stackingOrder.push(createStackingContext(stackLevel, treeOrder, vNode)); + } + return stackingOrder; + } + function createStackingContext(stackLevel, treeOrder, vNode) { + return { + stackLevel: stackLevel, + treeOrder: treeOrder, + vNode: vNode + }; + } + function getStackLevel(vNode, parentVNode) { + var zIndex = getRealZIndex(vNode, parentVNode); + if (![ 'auto', '0' ].includes(zIndex)) { + return parseInt(zIndex); + } + if (vNode.getComputedStylePropertyValue('position') !== 'static') { + return POSITION_LEVEL; + } + if (vNode.getComputedStylePropertyValue('float') !== 'none') { + return FLOAT_LEVEL; + } + if (isStackingContext(vNode, parentVNode)) { + return DEFAULT_LEVEL; + } + return null; + } + function getRealZIndex(vNode, parentVNode) { + var position = vNode.getComputedStylePropertyValue('position'); + if (position === 'static' && !isFlexOrGridContainer(parentVNode)) { + return 'auto'; + } + return vNode.getComputedStylePropertyValue('z-index'); + } + function findScrollRegionParent(vNode, parentVNode) { + var scrollRegionParent = null; + var checkedNodes = [ vNode ]; + while (parentVNode) { + if (get_scroll_default(parentVNode.actualNode)) { + scrollRegionParent = parentVNode; + break; + } + if (parentVNode._scrollRegionParent) { + scrollRegionParent = parentVNode._scrollRegionParent; + break; + } + checkedNodes.push(parentVNode); + parentVNode = get_node_from_tree_default(parentVNode.actualNode.parentElement || parentVNode.actualNode.parentNode); + } + checkedNodes.forEach(function(virtualNode) { + return virtualNode._scrollRegionParent = scrollRegionParent; + }); + return scrollRegionParent; + } + function addNodeToGrid(grid, vNode) { + var overflowHiddenNodes = get_overflow_hidden_ancestors_default(vNode); + vNode.clientRects.forEach(function(clientRect) { + var _vNode$_grid; + var visibleRect = overflowHiddenNodes.reduce(function(rect, overflowNode) { + return rect && _getIntersectionRect(rect, overflowNode.boundingClientRect); + }, clientRect); + if (!visibleRect) { + return; + } + (_vNode$_grid = vNode._grid) !== null && _vNode$_grid !== void 0 ? _vNode$_grid : vNode._grid = grid; + var gridRect = grid.getGridPositionOfRect(visibleRect); + grid.loopGridPosition(gridRect, function(gridCell) { + if (!gridCell.includes(vNode)) { + gridCell.push(vNode); + } + }); + }); + } + var Grid = function() { + function Grid() { + var container = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + _classCallCheck(this, Grid); + this.container = container; + this.cells = []; + } + return _createClass(Grid, [ { + key: 'toGridIndex', + value: function toGridIndex(num) { + return Math.floor(num / constants_default.gridSize); + } + }, { + key: 'getCellFromPoint', + value: function getCellFromPoint(_ref48) { + var _this$cells, _row; + var x = _ref48.x, y = _ref48.y; + assert_default(this.boundaries, 'Grid does not have cells added'); + var rowIndex = this.toGridIndex(y); + var colIndex = this.toGridIndex(x); + assert_default(_isPointInRect({ + y: rowIndex, + x: colIndex + }, this.boundaries), 'Element midpoint exceeds the grid bounds'); + var row = (_this$cells = this.cells[rowIndex - this.cells._negativeIndex]) !== null && _this$cells !== void 0 ? _this$cells : []; + return (_row = row[colIndex - row._negativeIndex]) !== null && _row !== void 0 ? _row : []; + } + }, { + key: 'loopGridPosition', + value: function loopGridPosition(gridPosition, callback) { + var _gridPosition = gridPosition, left = _gridPosition.left, right = _gridPosition.right, top = _gridPosition.top, bottom = _gridPosition.bottom; + if (this.boundaries) { + gridPosition = _getBoundingRect(this.boundaries, gridPosition); + } + this.boundaries = gridPosition; + loopNegativeIndexMatrix(this.cells, top, bottom, function(gridRow, row) { + loopNegativeIndexMatrix(gridRow, left, right, function(gridCell, col) { + callback(gridCell, { + row: row, + col: col + }); + }); + }); + } + }, { + key: 'getGridPositionOfRect', + value: function getGridPositionOfRect(_ref49) { + var top = _ref49.top, right = _ref49.right, bottom = _ref49.bottom, left = _ref49.left; + var margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + top = this.toGridIndex(top - margin); + right = this.toGridIndex(right + margin - 1); + bottom = this.toGridIndex(bottom + margin - 1); + left = this.toGridIndex(left - margin); + return new window.DOMRect(left, top, right - left, bottom - top); + } + } ]); + }(); + function loopNegativeIndexMatrix(matrix, start, end, callback) { + var _matrix$_negativeInde; + (_matrix$_negativeInde = matrix._negativeIndex) !== null && _matrix$_negativeInde !== void 0 ? _matrix$_negativeInde : matrix._negativeIndex = 0; + if (start < matrix._negativeIndex) { + for (var _i0 = 0; _i0 < matrix._negativeIndex - start; _i0++) { + matrix.splice(0, 0, []); + } + matrix._negativeIndex = start; + } + var startOffset = start - matrix._negativeIndex; + var endOffset = end - matrix._negativeIndex; + for (var index = startOffset; index <= endOffset; index++) { + var _index, _matrix$_index; + (_matrix$_index = matrix[_index = index]) !== null && _matrix$_index !== void 0 ? _matrix$_index : matrix[_index] = []; + callback(matrix[index], index + matrix._negativeIndex); + } + } + function _getNodeGrid(node) { + _createGrid(); + var _nodeLookup4 = _nodeLookup(node), vNode = _nodeLookup4.vNode; + return vNode._grid; + } + function _findNearbyElms(vNode) { + var _grid$cells; + var margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var grid = _getNodeGrid(vNode); + if (!(grid !== null && grid !== void 0 && (_grid$cells = grid.cells) !== null && _grid$cells !== void 0 && _grid$cells.length)) { + return []; + } + var rect = vNode.boundingClientRect; + var selfIsFixed = _isFixedPosition(vNode); + var gridPosition = grid.getGridPositionOfRect(rect, margin); + var neighbors = []; + grid.loopGridPosition(gridPosition, function(vNeighbors) { + var _iterator0 = _createForOfIteratorHelper(vNeighbors), _step0; + try { + for (_iterator0.s(); !(_step0 = _iterator0.n()).done; ) { + var vNeighbor = _step0.value; + if (vNeighbor && vNeighbor !== vNode && !neighbors.includes(vNeighbor) && selfIsFixed === _isFixedPosition(vNeighbor)) { + neighbors.push(vNeighbor); + } + } + } catch (err) { + _iterator0.e(err); + } finally { + _iterator0.f(); + } + }); + return neighbors; + } + var getModalDialog = memoize_default(function getModalDialogMemoized() { + var _dialogs$find; + if (!axe._tree) { + return null; + } + var dialogs = query_selector_all_filter_default(axe._tree[0], 'dialog[open]', function(vNode) { + var rect = vNode.boundingClientRect; + var stack = document.elementsFromPoint(rect.left + 1, rect.top + 1); + return stack.includes(vNode.actualNode) && _isVisibleOnScreen(vNode); + }); + if (!dialogs.length) { + return null; + } + var modalDialog = dialogs.find(function(dialog) { + var rect = dialog.boundingClientRect; + var stack = document.elementsFromPoint(rect.left - 10, rect.top - 10); + return stack.includes(dialog.actualNode); + }); + if (modalDialog) { + return modalDialog; + } + return (_dialogs$find = dialogs.find(function(dialog) { + var _getNodeFromGrid; + var _ref50 = (_getNodeFromGrid = getNodeFromGrid(dialog)) !== null && _getNodeFromGrid !== void 0 ? _getNodeFromGrid : {}, vNode = _ref50.vNode, rect = _ref50.rect; + if (!vNode) { + return false; + } + var stack = document.elementsFromPoint(rect.left + 1, rect.top + 1); + return !stack.includes(vNode.actualNode); + })) !== null && _dialogs$find !== void 0 ? _dialogs$find : null; + }); + var get_modal_dialog_default = getModalDialog; + function getNodeFromGrid(dialog) { + _createGrid(); + var grid = axe._tree[0]._grid; + var viewRect = new window.DOMRect(0, 0, window.innerWidth, window.innerHeight); + if (!grid) { + return; + } + for (var row = 0; row < grid.cells.length; row++) { + var cols = grid.cells[row]; + if (!cols) { + continue; + } + for (var col = 0; col < cols.length; col++) { + var cells = cols[col]; + if (!cells) { + continue; + } + for (var _i1 = 0; _i1 < cells.length; _i1++) { + var vNode = cells[_i1]; + var rect = vNode.boundingClientRect; + var intersection = _getIntersectionRect(rect, viewRect); + if (vNode.props.nodeName !== 'html' && vNode !== dialog && vNode.getComputedStylePropertyValue('pointer-events') !== 'none' && intersection) { + return { + vNode: vNode, + rect: intersection + }; + } + } + } + } + } + function _isInert(vNode) { + var _ref51 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, skipAncestors = _ref51.skipAncestors, isAncestor = _ref51.isAncestor; + if (skipAncestors) { + return isInertSelf(vNode, isAncestor); + } + return isInertAncestors(vNode, isAncestor); + } + var isInertSelf = memoize_default(function isInertSelfMemoized(vNode, isAncestor) { + if (vNode.hasAttr('inert')) { + return true; + } + if (!isAncestor && vNode.actualNode) { + var modalDialog = get_modal_dialog_default(); + if (modalDialog && !_contains(modalDialog, vNode)) { + return true; + } + } + return false; + }); + var isInertAncestors = memoize_default(function isInertAncestorsMemoized(vNode, isAncestor) { + if (isInertSelf(vNode, isAncestor)) { + return true; + } + if (!vNode.parent) { + return false; + } + return isInertAncestors(vNode.parent, true); + }); + var allowedDisabledNodeNames = [ 'button', 'command', 'fieldset', 'keygen', 'optgroup', 'option', 'select', 'textarea', 'input' ]; + function isDisabledAttrAllowed(nodeName2) { + return allowedDisabledNodeNames.includes(nodeName2); + } + function focusDisabled(el) { + var _nodeLookup5 = _nodeLookup(el), vNode = _nodeLookup5.vNode; + if (isDisabledAttrAllowed(vNode.props.nodeName) && vNode.hasAttr('disabled') || _isInert(vNode)) { + return true; + } + var parentNode = vNode.parent; + var ancestors = []; + var fieldsetDisabled = false; + while (parentNode && parentNode.shadowId === vNode.shadowId && !fieldsetDisabled) { + ancestors.push(parentNode); + if (parentNode.props.nodeName === 'legend') { + break; + } + if (parentNode._inDisabledFieldset !== void 0) { + fieldsetDisabled = parentNode._inDisabledFieldset; + break; + } + if (parentNode.props.nodeName === 'fieldset' && parentNode.hasAttr('disabled')) { + fieldsetDisabled = true; + } + parentNode = parentNode.parent; + } + ancestors.forEach(function(ancestor) { + return ancestor._inDisabledFieldset = fieldsetDisabled; + }); + if (fieldsetDisabled) { + return true; + } + if (vNode.props.nodeName !== 'area') { + if (!vNode.actualNode) { + return false; + } + return _isHiddenForEveryone(vNode); + } + return false; + } + var focus_disabled_default = focusDisabled; + var angularSkipLinkRegex = /^\/\#/; + var angularRouterLinkRegex = /^#[!/]/; + function _isCurrentPageLink(anchor) { + var _window$location; + var href = anchor.getAttribute('href'); + if (!href || href === '#') { + return false; + } + if (angularSkipLinkRegex.test(href)) { + return true; + } + var hash = anchor.hash, protocol = anchor.protocol, hostname = anchor.hostname, port = anchor.port, pathname = anchor.pathname; + if (angularRouterLinkRegex.test(hash)) { + return false; + } + if (href.charAt(0) === '#') { + return true; + } + if (typeof ((_window$location = window.location) === null || _window$location === void 0 ? void 0 : _window$location.origin) !== 'string' || window.location.origin.indexOf('://') === -1) { + return null; + } + var currentPageUrl = window.location.origin + window.location.pathname; + var url; + if (!hostname) { + url = window.location.origin; + } else { + url = ''.concat(protocol, '//').concat(hostname).concat(port ? ':'.concat(port) : ''); + } + if (!pathname) { + url += window.location.pathname; + } else { + url += (pathname[0] !== '/' ? '/' : '') + pathname; + } + return url === currentPageUrl; + } + function getElementByReference(node, attr) { + var fragment = node.getAttribute(attr); + if (!fragment) { + return null; + } + if (attr === 'href' && !_isCurrentPageLink(node)) { + return null; + } + if (fragment.indexOf('#') !== -1) { + fragment = decodeURIComponent(fragment.substr(fragment.indexOf('#') + 1)); + } + var candidate = document.getElementById(fragment); + if (candidate) { + return candidate; + } + candidate = document.getElementsByName(fragment); + if (candidate.length) { + return candidate[0]; + } + return null; + } + var get_element_by_reference_default = getElementByReference; + function _visuallySort(a2, b2) { + _createGrid(); + var length = Math.max(a2._stackingOrder.length, b2._stackingOrder.length); + for (var _i10 = 0; _i10 < length; _i10++) { + if (typeof b2._stackingOrder[_i10] === 'undefined') { + return -1; + } else if (typeof a2._stackingOrder[_i10] === 'undefined') { + return 1; + } + if (b2._stackingOrder[_i10].stackLevel > a2._stackingOrder[_i10].stackLevel) { + return 1; + } + if (b2._stackingOrder[_i10].stackLevel < a2._stackingOrder[_i10].stackLevel) { + return -1; + } + if (b2._stackingOrder[_i10].treeOrder !== a2._stackingOrder[_i10].treeOrder) { + return b2._stackingOrder[_i10].treeOrder - a2._stackingOrder[_i10].treeOrder; + } + } + var aNode = a2.actualNode; + var bNode = b2.actualNode; + if (aNode.getRootNode && aNode.getRootNode() !== bNode.getRootNode()) { + var boundaries = []; + while (aNode) { + boundaries.push({ + root: aNode.getRootNode(), + node: aNode + }); + aNode = aNode.getRootNode().host; + } + while (bNode && !boundaries.find(function(boundary) { + return boundary.root === bNode.getRootNode(); + })) { + bNode = bNode.getRootNode().host; + } + aNode = boundaries.find(function(boundary) { + return boundary.root === bNode.getRootNode(); + }).node; + if (aNode === bNode) { + return a2.actualNode.getRootNode() !== aNode.getRootNode() ? -1 : 1; + } + } + var _window$Node = window.Node, DOCUMENT_POSITION_FOLLOWING = _window$Node.DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_CONTAINS = _window$Node.DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_CONTAINED_BY = _window$Node.DOCUMENT_POSITION_CONTAINED_BY; + var docPosition = aNode.compareDocumentPosition(bNode); + var DOMOrder = docPosition & DOCUMENT_POSITION_FOLLOWING ? 1 : -1; + var isDescendant = docPosition & DOCUMENT_POSITION_CONTAINS || docPosition & DOCUMENT_POSITION_CONTAINED_BY; + var aPosition = getPositionOrder(a2); + var bPosition = getPositionOrder(b2); + if (aPosition === bPosition || isDescendant) { + return DOMOrder; + } + return bPosition - aPosition; + } + function getPositionOrder(vNode) { + if (vNode.getComputedStylePropertyValue('display').indexOf('inline') !== -1) { + return 2; + } + if (isFloated(vNode)) { + return 1; + } + return 0; + } + function isFloated(vNode) { + if (!vNode) { + return false; + } + if (vNode._isFloated !== void 0) { + return vNode._isFloated; + } + var floatStyle = vNode.getComputedStylePropertyValue('float'); + if (floatStyle !== 'none') { + vNode._isFloated = true; + return true; + } + var floated = isFloated(vNode.parent); + vNode._isFloated = floated; + return floated; + } + function getRectStack(grid, rect) { + var recursed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var center = _getRectCenter(rect); + var gridCell = grid.getCellFromPoint(center) || []; + var floorX = Math.floor(center.x); + var floorY = Math.floor(center.y); + var stack = gridCell.filter(function(gridCellNode) { + return gridCellNode.clientRects.some(function(clientRect) { + var rectX = clientRect.left; + var rectY = clientRect.top; + return floorX < Math.floor(rectX + clientRect.width) && floorX >= Math.floor(rectX) && floorY < Math.floor(rectY + clientRect.height) && floorY >= Math.floor(rectY); + }); + }); + var gridContainer = grid.container; + if (gridContainer) { + stack = getRectStack(gridContainer._grid, gridContainer.boundingClientRect, true).concat(stack); + } + if (!recursed) { + stack = stack.sort(_visuallySort).map(function(vNode) { + return vNode.actualNode; + }).concat(document.documentElement).filter(function(node, index, array) { + return array.indexOf(node) === index; + }); + } + return stack; + } + function getElementStack(node) { + var grid = _getNodeGrid(node); + if (!grid) { + return []; + } + var rect = get_node_from_tree_default(node).boundingClientRect; + return getRectStack(grid, rect); + } + var get_element_stack_default = getElementStack; + function getTabbableElements(virtualNode) { + var nodeAndDescendents = query_selector_all_default(virtualNode, '*'); + var tabbableElements = nodeAndDescendents.filter(function(vNode) { + var isFocusable2 = vNode.isFocusable; + var tabIndex = parse_tabindex_default(vNode.actualNode.getAttribute('tabindex')); + return tabIndex !== null ? isFocusable2 && tabIndex >= 0 : isFocusable2; + }); + return tabbableElements; + } + var get_tabbable_elements_default = getTabbableElements; + function isNativelyFocusable(el) { + var _nodeLookup6 = _nodeLookup(el), vNode = _nodeLookup6.vNode; + if (!vNode || focus_disabled_default(vNode)) { + return false; + } + switch (vNode.props.nodeName) { + case 'a': + case 'area': + if (vNode.hasAttr('href')) { + return true; + } + break; + + case 'input': + return vNode.props.type !== 'hidden'; + + case 'textarea': + case 'select': + case 'summary': + case 'button': + return true; + + case 'details': + return !query_selector_all_default(vNode, 'summary').length; + } + return false; + } + var is_natively_focusable_default = isNativelyFocusable; + function _isFocusable(el) { + var _nodeLookup7 = _nodeLookup(el), vNode = _nodeLookup7.vNode; + if (vNode.props.nodeType !== 1) { + return false; + } + if (focus_disabled_default(vNode)) { + return false; + } else if (is_natively_focusable_default(vNode)) { + return true; + } + var tabindex = parse_tabindex_default(vNode.attr('tabindex')); + return tabindex !== null; + } + function _isInTabOrder(el) { + var _nodeLookup8 = _nodeLookup(el), vNode = _nodeLookup8.vNode; + if (vNode.props.nodeType !== 1) { + return false; + } + var tabindex = parse_tabindex_default(vNode.attr('tabindex')); + if (tabindex <= -1) { + return false; + } + return _isFocusable(vNode); + } + var get_target_rects_default = memoize_default(getTargetRects); + function getTargetRects(vNode) { + var display2 = vNode.getComputedStylePropertyValue('display'); + var nodeRects = display2 === 'inline' ? vNode.clientRects : [ vNode.boundingClientRect ]; + var overlappingVNodes = _findNearbyElms(vNode).filter(function(vNeighbor) { + return _hasVisualOverlap(vNode, vNeighbor) && vNeighbor.getComputedStylePropertyValue('pointer-events') !== 'none' && !isDescendantNotInTabOrder(vNode, vNeighbor); + }); + if (!overlappingVNodes.length) { + return nodeRects; + } + var obscuringRects = overlappingVNodes.map(function(overlappingVNode) { + var overlappingDisplay = overlappingVNode.getComputedStylePropertyValue('display'); + return overlappingDisplay === 'inline' ? overlappingVNode.clientRects : overlappingVNode.boundingClientRect; + }).flat(Infinity); + return _splitRects(nodeRects, obscuringRects); + } + function isDescendantNotInTabOrder(vAncestor, vNode) { + return _contains(vAncestor, vNode) && !_isInTabOrder(vNode); + } + var get_target_size_default = memoize_default(getTargetSize); + function getTargetSize(vNode, minSize) { + var rects = get_target_rects_default(vNode); + return getLargestRect(rects, minSize); + } + function getLargestRect(rects, minSize) { + return rects.reduce(function(rectA, rectB) { + var rectAisMinimum = _rectHasMinimumSize(minSize, rectA); + var rectBisMinimum = _rectHasMinimumSize(minSize, rectB); + if (rectAisMinimum !== rectBisMinimum) { + return rectAisMinimum ? rectA : rectB; + } + var areaA = rectA.width * rectA.height; + var areaB = rectB.width * rectB.height; + return areaA > areaB ? rectA : rectB; + }); + } + var text_exports = {}; + __export(text_exports, { + accessibleText: function accessibleText() { + return accessible_text_default; + }, + accessibleTextVirtual: function accessibleTextVirtual() { + return _accessibleTextVirtual; + }, + autocomplete: function autocomplete() { + return _autocomplete; + }, + formControlValue: function formControlValue() { + return form_control_value_default; + }, + formControlValueMethods: function formControlValueMethods() { + return _formControlValueMethods; + }, + hasUnicode: function hasUnicode() { + return has_unicode_default; + }, + isHumanInterpretable: function isHumanInterpretable() { + return is_human_interpretable_default; + }, + isIconLigature: function isIconLigature() { + return _isIconLigature; + }, + isValidAutocomplete: function isValidAutocomplete() { + return is_valid_autocomplete_default; + }, + label: function label() { + return label_default; + }, + labelText: function labelText() { + return label_text_default; + }, + labelVirtual: function labelVirtual() { + return label_virtual_default2; + }, + nativeElementType: function nativeElementType() { + return native_element_type_default; + }, + nativeTextAlternative: function nativeTextAlternative() { + return _nativeTextAlternative; + }, + nativeTextMethods: function nativeTextMethods() { + return native_text_methods_default; + }, + removeUnicode: function removeUnicode() { + return remove_unicode_default; + }, + sanitize: function sanitize() { + return sanitize_default; + }, + subtreeText: function subtreeText() { + return subtree_text_default; + }, + titleText: function titleText() { + return title_text_default; + }, + unsupported: function unsupported() { + return unsupported_default; + }, + visible: function visible() { + return visible_default; + }, + visibleTextNodes: function visibleTextNodes() { + return visible_text_nodes_default; + }, + visibleVirtual: function visibleVirtual() { + return visible_virtual_default; + } + }); + function idrefs(node, attr) { + node = node.actualNode || node; + try { + var doc = get_root_node_default2(node); + var result = []; + var attrValue = node.getAttribute(attr); + if (attrValue) { + attrValue = token_list_default(attrValue); + for (var index = 0; index < attrValue.length; index++) { + result.push(doc.getElementById(attrValue[index])); + } + } + return result; + } catch (_unused3) { + throw new TypeError('Cannot resolve id references for non-DOM nodes'); + } + } + var idrefs_default = idrefs; + function accessibleText(element, context) { + var virtualNode = get_node_from_tree_default(element); + return _accessibleTextVirtual(virtualNode, context); + } + var accessible_text_default = accessibleText; + function arialabelledbyText(element) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var _nodeLookup9 = _nodeLookup(element), vNode = _nodeLookup9.vNode; + if ((vNode === null || vNode === void 0 ? void 0 : vNode.props.nodeType) !== 1) { + return ''; + } + if (vNode.props.nodeType !== 1 || context.inLabelledByContext || context.inControlContext || !vNode.attr('aria-labelledby')) { + return ''; + } + var refs = idrefs_default(vNode, 'aria-labelledby').filter(function(elm) { + return elm; + }); + return refs.reduce(function(accessibleName, elm) { + var accessibleNameAdd = accessible_text_default(elm, _extends({ + inLabelledByContext: true, + startNode: context.startNode || vNode + }, context)); + if (!accessibleName) { + return accessibleNameAdd; + } else { + return ''.concat(accessibleName, ' ').concat(accessibleNameAdd); + } + }, ''); + } + var arialabelledby_text_default = arialabelledbyText; + function _arialabelText(element) { + var _nodeLookup0 = _nodeLookup(element), vNode = _nodeLookup0.vNode; + if ((vNode === null || vNode === void 0 ? void 0 : vNode.props.nodeType) !== 1) { + return ''; + } + return vNode.attr('aria-label') || ''; + } + var ariaAttrs = { + 'aria-activedescendant': { + type: 'idref', + allowEmpty: true + }, + 'aria-atomic': { + type: 'boolean', + global: true + }, + 'aria-autocomplete': { + type: 'nmtoken', + values: [ 'inline', 'list', 'both', 'none' ] + }, + 'aria-braillelabel': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-brailleroledescription': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-busy': { + type: 'boolean', + global: true + }, + 'aria-checked': { + type: 'nmtoken', + values: [ 'false', 'mixed', 'true', 'undefined' ] + }, + 'aria-colcount': { + type: 'int', + minValue: -1 + }, + 'aria-colindex': { + type: 'int', + minValue: 1 + }, + 'aria-colspan': { + type: 'int', + minValue: 1 + }, + 'aria-controls': { + type: 'idrefs', + allowEmpty: true, + global: true + }, + 'aria-current': { + type: 'nmtoken', + allowEmpty: true, + values: [ 'page', 'step', 'location', 'date', 'time', 'true', 'false' ], + global: true + }, + 'aria-describedby': { + type: 'idrefs', + allowEmpty: true, + global: true + }, + 'aria-description': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-details': { + type: 'idref', + allowEmpty: true, + global: true + }, + 'aria-disabled': { + type: 'boolean', + global: true + }, + 'aria-dropeffect': { + type: 'nmtokens', + values: [ 'copy', 'execute', 'link', 'move', 'none', 'popup' ], + global: true + }, + 'aria-errormessage': { + type: 'idref', + allowEmpty: true, + global: true + }, + 'aria-expanded': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ] + }, + 'aria-flowto': { + type: 'idrefs', + allowEmpty: true, + global: true + }, + 'aria-grabbed': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ], + global: true + }, + 'aria-haspopup': { + type: 'nmtoken', + allowEmpty: true, + values: [ 'true', 'false', 'menu', 'listbox', 'tree', 'grid', 'dialog' ], + global: true + }, + 'aria-hidden': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ], + global: true + }, + 'aria-invalid': { + type: 'nmtoken', + values: [ 'grammar', 'false', 'spelling', 'true' ], + global: true + }, + 'aria-keyshortcuts': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-label': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-labelledby': { + type: 'idrefs', + allowEmpty: true, + global: true + }, + 'aria-level': { + type: 'int', + minValue: 1 + }, + 'aria-live': { + type: 'nmtoken', + values: [ 'assertive', 'off', 'polite' ], + global: true + }, + 'aria-modal': { + type: 'boolean' + }, + 'aria-multiline': { + type: 'boolean' + }, + 'aria-multiselectable': { + type: 'boolean' + }, + 'aria-orientation': { + type: 'nmtoken', + values: [ 'horizontal', 'undefined', 'vertical' ] + }, + 'aria-owns': { + type: 'idrefs', + allowEmpty: true, + global: true + }, + 'aria-placeholder': { + type: 'string', + allowEmpty: true + }, + 'aria-posinset': { + type: 'int', + minValue: 1 + }, + 'aria-pressed': { + type: 'nmtoken', + values: [ 'false', 'mixed', 'true', 'undefined' ] + }, + 'aria-readonly': { + type: 'boolean' + }, + 'aria-relevant': { + type: 'nmtokens', + values: [ 'additions', 'all', 'removals', 'text' ], + global: true + }, + 'aria-required': { + type: 'boolean' + }, + 'aria-roledescription': { + type: 'string', + allowEmpty: true, + global: true + }, + 'aria-rowcount': { + type: 'int', + minValue: -1 + }, + 'aria-rowindex': { + type: 'int', + minValue: 1 + }, + 'aria-rowspan': { + type: 'int', + minValue: 0 + }, + 'aria-selected': { + type: 'nmtoken', + values: [ 'false', 'true', 'undefined' ] + }, + 'aria-setsize': { + type: 'int', + minValue: -1 + }, + 'aria-sort': { + type: 'nmtoken', + values: [ 'ascending', 'descending', 'none', 'other' ] + }, + 'aria-valuemax': { + type: 'decimal' + }, + 'aria-valuemin': { + type: 'decimal' + }, + 'aria-valuenow': { + type: 'decimal' + }, + 'aria-valuetext': { + type: 'string', + allowEmpty: true + } + }; + var aria_attrs_default = ariaAttrs; + var ariaRoles = { + alert: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + alertdialog: { + type: 'window', + allowedAttrs: [ 'aria-expanded', 'aria-modal' ], + superclassRole: [ 'alert', 'dialog' ], + accessibleNameRequired: true + }, + application: { + type: 'landmark', + allowedAttrs: [ 'aria-activedescendant', 'aria-expanded' ], + superclassRole: [ 'structure' ], + accessibleNameRequired: true + }, + article: { + type: 'structure', + allowedAttrs: [ 'aria-posinset', 'aria-setsize', 'aria-expanded' ], + superclassRole: [ 'document' ] + }, + banner: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + blockquote: { + type: 'structure', + superclassRole: [ 'section' ] + }, + button: { + type: 'widget', + allowedAttrs: [ 'aria-expanded', 'aria-pressed' ], + superclassRole: [ 'command' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + caption: { + type: 'structure', + requiredContext: [ 'figure', 'table', 'grid', 'treegrid' ], + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + cell: { + type: 'structure', + requiredContext: [ 'row' ], + allowedAttrs: [ 'aria-colindex', 'aria-colspan', 'aria-rowindex', 'aria-rowspan', 'aria-expanded' ], + superclassRole: [ 'section' ], + nameFromContent: true + }, + checkbox: { + type: 'widget', + requiredAttrs: [ 'aria-checked' ], + allowedAttrs: [ 'aria-readonly', 'aria-expanded', 'aria-required' ], + superclassRole: [ 'input' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + code: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + columnheader: { + type: 'structure', + requiredContext: [ 'row' ], + allowedAttrs: [ 'aria-sort', 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-readonly', 'aria-required', 'aria-rowindex', 'aria-rowspan', 'aria-selected' ], + superclassRole: [ 'cell', 'gridcell', 'sectionhead' ], + accessibleNameRequired: false, + nameFromContent: true + }, + combobox: { + type: 'widget', + requiredAttrs: [ 'aria-expanded', 'aria-controls' ], + allowedAttrs: [ 'aria-owns', 'aria-autocomplete', 'aria-readonly', 'aria-required', 'aria-activedescendant', 'aria-orientation' ], + superclassRole: [ 'select' ], + accessibleNameRequired: true + }, + command: { + type: 'abstract', + superclassRole: [ 'widget' ] + }, + complementary: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + composite: { + type: 'abstract', + superclassRole: [ 'widget' ] + }, + contentinfo: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + comment: { + type: 'structure', + allowedAttrs: [ 'aria-level', 'aria-posinset', 'aria-setsize' ], + superclassRole: [ 'article' ] + }, + definition: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + deletion: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + dialog: { + type: 'window', + allowedAttrs: [ 'aria-expanded', 'aria-modal' ], + superclassRole: [ 'window' ], + accessibleNameRequired: true + }, + directory: { + type: 'structure', + deprecated: true, + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'list' ], + nameFromContent: true + }, + document: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'structure' ] + }, + emphasis: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + feed: { + type: 'structure', + requiredOwned: [ 'article' ], + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'list' ] + }, + figure: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + nameFromContent: true + }, + form: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + grid: { + type: 'composite', + requiredOwned: [ 'rowgroup', 'row' ], + allowedAttrs: [ 'aria-level', 'aria-multiselectable', 'aria-readonly', 'aria-activedescendant', 'aria-colcount', 'aria-expanded', 'aria-rowcount' ], + superclassRole: [ 'composite', 'table' ], + accessibleNameRequired: false + }, + gridcell: { + type: 'widget', + requiredContext: [ 'row' ], + allowedAttrs: [ 'aria-readonly', 'aria-required', 'aria-selected', 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-rowindex', 'aria-rowspan' ], + superclassRole: [ 'cell', 'widget' ], + nameFromContent: true + }, + group: { + type: 'structure', + allowedAttrs: [ 'aria-activedescendant', 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + heading: { + type: 'structure', + requiredAttrs: [ 'aria-level' ], + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'sectionhead' ], + accessibleNameRequired: false, + nameFromContent: true + }, + img: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + accessibleNameRequired: true, + childrenPresentational: true + }, + input: { + type: 'abstract', + superclassRole: [ 'widget' ] + }, + insertion: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + landmark: { + type: 'abstract', + superclassRole: [ 'section' ] + }, + link: { + type: 'widget', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'command' ], + accessibleNameRequired: true, + nameFromContent: true + }, + list: { + type: 'structure', + requiredOwned: [ 'listitem' ], + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + listbox: { + type: 'widget', + requiredOwned: [ 'group', 'option' ], + allowedAttrs: [ 'aria-multiselectable', 'aria-readonly', 'aria-required', 'aria-activedescendant', 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'select' ], + accessibleNameRequired: true + }, + listitem: { + type: 'structure', + requiredContext: [ 'list' ], + allowedAttrs: [ 'aria-level', 'aria-posinset', 'aria-setsize', 'aria-expanded' ], + superclassRole: [ 'section' ], + nameFromContent: true + }, + log: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + main: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + marquee: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + math: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + childrenPresentational: true + }, + menu: { + type: 'composite', + requiredOwned: [ 'group', 'menuitemradio', 'menuitem', 'menuitemcheckbox', 'menu', 'separator' ], + allowedAttrs: [ 'aria-activedescendant', 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'select' ] + }, + menubar: { + type: 'composite', + requiredOwned: [ 'group', 'menuitemradio', 'menuitem', 'menuitemcheckbox', 'menu', 'separator' ], + allowedAttrs: [ 'aria-activedescendant', 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'menu' ] + }, + menuitem: { + type: 'widget', + requiredContext: [ 'menu', 'menubar', 'group' ], + allowedAttrs: [ 'aria-posinset', 'aria-setsize', 'aria-expanded' ], + superclassRole: [ 'command' ], + accessibleNameRequired: true, + nameFromContent: true + }, + menuitemcheckbox: { + type: 'widget', + requiredContext: [ 'menu', 'menubar', 'group' ], + requiredAttrs: [ 'aria-checked' ], + allowedAttrs: [ 'aria-expanded', 'aria-posinset', 'aria-readonly', 'aria-setsize' ], + superclassRole: [ 'checkbox', 'menuitem' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + menuitemradio: { + type: 'widget', + requiredContext: [ 'menu', 'menubar', 'group' ], + requiredAttrs: [ 'aria-checked' ], + allowedAttrs: [ 'aria-expanded', 'aria-posinset', 'aria-readonly', 'aria-setsize' ], + superclassRole: [ 'menuitemcheckbox', 'radio' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + meter: { + type: 'structure', + requiredAttrs: [ 'aria-valuenow' ], + allowedAttrs: [ 'aria-valuemax', 'aria-valuemin', 'aria-valuetext' ], + superclassRole: [ 'range' ], + accessibleNameRequired: true, + childrenPresentational: true + }, + mark: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + navigation: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + none: { + type: 'structure', + superclassRole: [ 'structure' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + note: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + option: { + type: 'widget', + requiredContext: [ 'group', 'listbox' ], + allowedAttrs: [ 'aria-selected', 'aria-checked', 'aria-posinset', 'aria-setsize' ], + superclassRole: [ 'input' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + paragraph: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + presentation: { + type: 'structure', + superclassRole: [ 'structure' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + progressbar: { + type: 'widget', + allowedAttrs: [ 'aria-expanded', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext' ], + superclassRole: [ 'range' ], + accessibleNameRequired: true, + childrenPresentational: true + }, + radio: { + type: 'widget', + requiredAttrs: [ 'aria-checked' ], + allowedAttrs: [ 'aria-posinset', 'aria-setsize', 'aria-required' ], + superclassRole: [ 'input' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + radiogroup: { + type: 'composite', + allowedAttrs: [ 'aria-readonly', 'aria-required', 'aria-activedescendant', 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'select' ], + accessibleNameRequired: false + }, + range: { + type: 'abstract', + superclassRole: [ 'widget' ] + }, + region: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ], + accessibleNameRequired: false + }, + roletype: { + type: 'abstract', + superclassRole: [] + }, + row: { + type: 'structure', + requiredContext: [ 'grid', 'rowgroup', 'table', 'treegrid' ], + requiredOwned: [ 'cell', 'columnheader', 'gridcell', 'rowheader' ], + allowedAttrs: [ 'aria-colindex', 'aria-level', 'aria-rowindex', 'aria-selected', 'aria-activedescendant', 'aria-expanded', 'aria-posinset', 'aria-setsize' ], + superclassRole: [ 'group', 'widget' ], + nameFromContent: true + }, + rowgroup: { + type: 'structure', + requiredContext: [ 'grid', 'table', 'treegrid' ], + requiredOwned: [ 'row' ], + superclassRole: [ 'structure' ], + nameFromContent: true + }, + rowheader: { + type: 'structure', + requiredContext: [ 'row' ], + allowedAttrs: [ 'aria-sort', 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-readonly', 'aria-required', 'aria-rowindex', 'aria-rowspan', 'aria-selected' ], + superclassRole: [ 'cell', 'gridcell', 'sectionhead' ], + accessibleNameRequired: false, + nameFromContent: true + }, + scrollbar: { + type: 'widget', + requiredAttrs: [ 'aria-valuenow' ], + allowedAttrs: [ 'aria-controls', 'aria-orientation', 'aria-valuemax', 'aria-valuemin', 'aria-valuetext' ], + superclassRole: [ 'range' ], + childrenPresentational: true + }, + search: { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + searchbox: { + type: 'widget', + allowedAttrs: [ 'aria-activedescendant', 'aria-autocomplete', 'aria-multiline', 'aria-placeholder', 'aria-readonly', 'aria-required' ], + superclassRole: [ 'textbox' ], + accessibleNameRequired: true + }, + section: { + type: 'abstract', + superclassRole: [ 'structure' ], + nameFromContent: true + }, + sectionhead: { + type: 'abstract', + superclassRole: [ 'structure' ], + nameFromContent: true + }, + select: { + type: 'abstract', + superclassRole: [ 'composite', 'group' ] + }, + separator: { + type: 'structure', + requiredAttrs: [ 'aria-valuenow' ], + allowedAttrs: [ 'aria-valuemax', 'aria-valuemin', 'aria-orientation', 'aria-valuetext' ], + superclassRole: [ 'structure', 'widget' ], + childrenPresentational: true + }, + slider: { + type: 'widget', + requiredAttrs: [ 'aria-valuenow' ], + allowedAttrs: [ 'aria-valuemax', 'aria-valuemin', 'aria-orientation', 'aria-readonly', 'aria-required', 'aria-valuetext' ], + superclassRole: [ 'input', 'range' ], + accessibleNameRequired: true, + childrenPresentational: true + }, + spinbutton: { + type: 'widget', + allowedAttrs: [ 'aria-valuemax', 'aria-valuemin', 'aria-readonly', 'aria-required', 'aria-activedescendant', 'aria-valuetext', 'aria-valuenow' ], + superclassRole: [ 'composite', 'input', 'range' ], + accessibleNameRequired: true + }, + status: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + strong: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + structure: { + type: 'abstract', + superclassRole: [ 'roletype' ] + }, + subscript: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + superscript: { + type: 'structure', + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + switch: { + type: 'widget', + requiredAttrs: [ 'aria-checked' ], + allowedAttrs: [ 'aria-expanded', 'aria-readonly', 'aria-required' ], + superclassRole: [ 'checkbox' ], + accessibleNameRequired: true, + nameFromContent: true, + childrenPresentational: true + }, + suggestion: { + type: 'structure', + requiredOwned: [ 'insertion', 'deletion' ], + superclassRole: [ 'section' ], + prohibitedAttrs: [ 'aria-label', 'aria-labelledby' ] + }, + tab: { + type: 'widget', + requiredContext: [ 'tablist' ], + allowedAttrs: [ 'aria-posinset', 'aria-selected', 'aria-setsize', 'aria-expanded' ], + superclassRole: [ 'sectionhead', 'widget' ], + nameFromContent: true, + childrenPresentational: true + }, + table: { + type: 'structure', + requiredOwned: [ 'rowgroup', 'row' ], + allowedAttrs: [ 'aria-colcount', 'aria-rowcount', 'aria-expanded' ], + superclassRole: [ 'section' ], + accessibleNameRequired: false, + nameFromContent: true + }, + tablist: { + type: 'composite', + requiredOwned: [ 'tab' ], + allowedAttrs: [ 'aria-level', 'aria-multiselectable', 'aria-orientation', 'aria-activedescendant', 'aria-expanded' ], + superclassRole: [ 'composite' ] + }, + tabpanel: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + accessibleNameRequired: false + }, + term: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + nameFromContent: true + }, + text: { + type: 'structure', + superclassRole: [ 'section' ], + nameFromContent: true + }, + textbox: { + type: 'widget', + allowedAttrs: [ 'aria-activedescendant', 'aria-autocomplete', 'aria-multiline', 'aria-placeholder', 'aria-readonly', 'aria-required' ], + superclassRole: [ 'input' ], + accessibleNameRequired: true + }, + time: { + type: 'structure', + superclassRole: [ 'section' ] + }, + timer: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'status' ] + }, + toolbar: { + type: 'structure', + allowedAttrs: [ 'aria-orientation', 'aria-activedescendant', 'aria-expanded' ], + superclassRole: [ 'group' ], + accessibleNameRequired: true + }, + tooltip: { + type: 'structure', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ], + nameFromContent: true + }, + tree: { + type: 'composite', + requiredOwned: [ 'group', 'treeitem' ], + allowedAttrs: [ 'aria-multiselectable', 'aria-required', 'aria-activedescendant', 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'select' ], + accessibleNameRequired: false + }, + treegrid: { + type: 'composite', + requiredOwned: [ 'rowgroup', 'row' ], + allowedAttrs: [ 'aria-activedescendant', 'aria-colcount', 'aria-expanded', 'aria-level', 'aria-multiselectable', 'aria-orientation', 'aria-readonly', 'aria-required', 'aria-rowcount' ], + superclassRole: [ 'grid', 'tree' ], + accessibleNameRequired: false + }, + treeitem: { + type: 'widget', + requiredContext: [ 'group', 'tree' ], + allowedAttrs: [ 'aria-checked', 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-selected', 'aria-setsize' ], + superclassRole: [ 'listitem', 'option' ], + accessibleNameRequired: true, + nameFromContent: true + }, + widget: { + type: 'abstract', + superclassRole: [ 'roletype' ] + }, + window: { + type: 'abstract', + superclassRole: [ 'roletype' ] + } + }; + var aria_roles_default = ariaRoles; + var dpubRoles = { + 'doc-abstract': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-acknowledgments': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-afterword': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-appendix': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-backlink': { + type: 'link', + allowedAttrs: [ 'aria-expanded' ], + nameFromContent: true, + superclassRole: [ 'link' ] + }, + 'doc-biblioentry': { + type: 'listitem', + allowedAttrs: [ 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize' ], + superclassRole: [ 'listitem' ], + deprecated: true + }, + 'doc-bibliography': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-biblioref': { + type: 'link', + allowedAttrs: [ 'aria-expanded' ], + nameFromContent: true, + superclassRole: [ 'link' ] + }, + 'doc-chapter': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-colophon': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-conclusion': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-cover': { + type: 'img', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'img' ] + }, + 'doc-credit': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-credits': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-dedication': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-endnote': { + type: 'listitem', + allowedAttrs: [ 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize' ], + superclassRole: [ 'listitem' ], + deprecated: true + }, + 'doc-endnotes': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-epigraph': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-epilogue': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-errata': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-example': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-footnote': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-foreword': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-glossary': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-glossref': { + type: 'link', + allowedAttrs: [ 'aria-expanded' ], + nameFromContent: true, + superclassRole: [ 'link' ] + }, + 'doc-index': { + type: 'navigation', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'navigation' ] + }, + 'doc-introduction': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-noteref': { + type: 'link', + allowedAttrs: [ 'aria-expanded' ], + nameFromContent: true, + superclassRole: [ 'link' ] + }, + 'doc-notice': { + type: 'note', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'note' ] + }, + 'doc-pagebreak': { + type: 'separator', + allowedAttrs: [ 'aria-expanded', 'aria-orientation' ], + superclassRole: [ 'separator' ], + childrenPresentational: true + }, + 'doc-pagelist': { + type: 'navigation', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'navigation' ] + }, + 'doc-part': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-preface': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-prologue': { + type: 'landmark', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'landmark' ] + }, + 'doc-pullquote': { + type: 'none', + superclassRole: [ 'none' ] + }, + 'doc-qna': { + type: 'section', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'section' ] + }, + 'doc-subtitle': { + type: 'sectionhead', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'sectionhead' ] + }, + 'doc-tip': { + type: 'note', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'note' ] + }, + 'doc-toc': { + type: 'navigation', + allowedAttrs: [ 'aria-expanded' ], + superclassRole: [ 'navigation' ] + } + }; + var dpub_roles_default = dpubRoles; + var graphicsRoles = { + 'graphics-document': { + type: 'structure', + superclassRole: [ 'document' ], + accessibleNameRequired: true + }, + 'graphics-object': { + type: 'structure', + superclassRole: [ 'group' ], + nameFromContent: true + }, + 'graphics-symbol': { + type: 'structure', + superclassRole: [ 'img' ], + accessibleNameRequired: true, + childrenPresentational: true + } + }; + var graphics_roles_default = graphicsRoles; + var htmlElms = { + a: { + variant: { + href: { + matches: '[href]', + contentTypes: [ 'interactive', 'phrasing', 'flow' ], + allowedRoles: [ 'button', 'checkbox', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'switch', 'tab', 'treeitem', 'doc-backlink', 'doc-biblioref', 'doc-glossref', 'doc-noteref' ], + namingMethods: [ 'subtreeText' ] + }, + default: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + } + } + }, + abbr: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + address: { + contentTypes: [ 'flow' ], + allowedRoles: true + }, + area: { + variant: { + href: { + matches: '[href]', + allowedRoles: false + }, + default: { + allowedRoles: [ 'button', 'link' ] + } + }, + contentTypes: [ 'phrasing', 'flow' ], + namingMethods: [ 'altText' ] + }, + article: { + contentTypes: [ 'sectioning', 'flow' ], + allowedRoles: [ 'feed', 'presentation', 'none', 'document', 'application', 'main', 'region' ], + shadowRoot: true + }, + aside: { + contentTypes: [ 'sectioning', 'flow' ], + allowedRoles: [ 'feed', 'note', 'presentation', 'none', 'region', 'search', 'doc-dedication', 'doc-example', 'doc-footnote', 'doc-glossary', 'doc-pullquote', 'doc-tip' ] + }, + audio: { + variant: { + controls: { + matches: '[controls]', + contentTypes: [ 'interactive', 'embedded', 'phrasing', 'flow' ] + }, + default: { + contentTypes: [ 'embedded', 'phrasing', 'flow' ] + } + }, + allowedRoles: [ 'application' ], + chromiumRole: 'Audio' + }, + b: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + base: { + allowedRoles: false, + noAriaAttrs: true + }, + bdi: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + bdo: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + blockquote: { + contentTypes: [ 'flow' ], + allowedRoles: true, + shadowRoot: true + }, + body: { + allowedRoles: false, + shadowRoot: true + }, + br: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: [ 'presentation', 'none' ], + namingMethods: [ 'titleText', 'singleSpace' ], + allowedAriaAttrs: [ 'aria-hidden' ] + }, + button: { + contentTypes: [ 'interactive', 'phrasing', 'flow' ], + allowedRoles: [ 'checkbox', 'combobox', 'gridcell', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'separator', 'slider', 'switch', 'tab', 'treeitem' ], + namingMethods: [ 'subtreeText' ] + }, + canvas: { + allowedRoles: true, + contentTypes: [ 'embedded', 'phrasing', 'flow' ], + chromiumRole: 'Canvas' + }, + caption: { + allowedRoles: false + }, + cite: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + code: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + col: { + allowedRoles: false, + noAriaAttrs: true + }, + colgroup: { + allowedRoles: false, + noAriaAttrs: true + }, + data: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + datalist: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true, + implicitAttrs: { + 'aria-multiselectable': 'false' + } + }, + dd: { + allowedRoles: false + }, + del: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + dfn: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + details: { + contentTypes: [ 'interactive', 'flow' ], + allowedRoles: false + }, + dialog: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'alertdialog' ] + }, + div: { + contentTypes: [ 'flow' ], + allowedRoles: true, + shadowRoot: true + }, + dl: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'group', 'list', 'presentation', 'none' ], + chromiumRole: 'DescriptionList' + }, + dt: { + allowedRoles: [ 'listitem' ] + }, + em: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + embed: { + contentTypes: [ 'interactive', 'embedded', 'phrasing', 'flow' ], + allowedRoles: [ 'application', 'document', 'img', 'presentation', 'none' ], + chromiumRole: 'EmbeddedObject' + }, + fieldset: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'none', 'presentation', 'radiogroup' ], + namingMethods: [ 'fieldsetLegendText' ] + }, + figcaption: { + allowedRoles: [ 'group', 'none', 'presentation' ] + }, + figure: { + contentTypes: [ 'flow' ], + allowedRoles: true, + namingMethods: [ 'figureText', 'titleText' ] + }, + footer: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'group', 'none', 'presentation', 'doc-footnote' ], + shadowRoot: true + }, + form: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'form', 'search', 'none', 'presentation' ] + }, + h1: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '1' + } + }, + h2: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '2' + } + }, + h3: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '3' + } + }, + h4: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '4' + } + }, + h5: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '5' + } + }, + h6: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: [ 'none', 'presentation', 'tab', 'doc-subtitle' ], + shadowRoot: true, + implicitAttrs: { + 'aria-level': '6' + } + }, + head: { + allowedRoles: false, + noAriaAttrs: true + }, + header: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'group', 'none', 'presentation', 'doc-footnote' ], + shadowRoot: true + }, + hgroup: { + contentTypes: [ 'heading', 'flow' ], + allowedRoles: true + }, + hr: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'none', 'presentation', 'doc-pagebreak' ], + namingMethods: [ 'titleText', 'singleSpace' ] + }, + html: { + allowedRoles: false, + noAriaAttrs: true + }, + i: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + iframe: { + contentTypes: [ 'interactive', 'embedded', 'phrasing', 'flow' ], + allowedRoles: [ 'application', 'document', 'img', 'none', 'presentation' ], + chromiumRole: 'Iframe' + }, + img: { + variant: { + nonEmptyAlt: { + matches: [ { + attributes: { + alt: '/.+/' + } + }, { + hasAccessibleName: true + } ], + allowedRoles: [ 'button', 'checkbox', 'link', 'math', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'meter', 'option', 'progressbar', 'radio', 'scrollbar', 'separator', 'slider', 'switch', 'tab', 'treeitem', 'doc-cover' ] + }, + usemap: { + matches: '[usemap]', + contentTypes: [ 'interactive', 'embedded', 'flow' ] + }, + default: { + allowedRoles: [ 'presentation', 'none' ], + contentTypes: [ 'embedded', 'flow' ] + } + }, + namingMethods: [ 'altText' ] + }, + input: { + variant: { + button: { + matches: { + properties: { + type: 'button' + } + }, + allowedRoles: [ 'checkbox', 'combobox', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'switch', 'tab' ] + }, + buttonType: { + matches: { + properties: { + type: [ 'button', 'submit', 'reset' ] + } + }, + namingMethods: [ 'valueText', 'titleText', 'buttonDefaultText' ] + }, + checkboxPressed: { + matches: { + properties: { + type: 'checkbox' + }, + attributes: { + 'aria-pressed': '/.*/' + } + }, + allowedRoles: [ 'button', 'menuitemcheckbox', 'option', 'switch' ], + implicitAttrs: { + 'aria-checked': 'false' + } + }, + checkbox: { + matches: { + properties: { + type: 'checkbox' + }, + attributes: { + 'aria-pressed': null + } + }, + allowedRoles: [ 'menuitemcheckbox', 'option', 'switch' ], + implicitAttrs: { + 'aria-checked': 'false' + } + }, + noRoles: { + matches: { + properties: { + type: [ 'color', 'date', 'datetime-local', 'file', 'month', 'number', 'password', 'range', 'reset', 'submit', 'time', 'week' ] + } + }, + allowedRoles: false + }, + hidden: { + matches: { + properties: { + type: 'hidden' + } + }, + contentTypes: [ 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + image: { + matches: { + properties: { + type: 'image' + } + }, + allowedRoles: [ 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'radio', 'switch' ], + namingMethods: [ 'altText', 'valueText', 'labelText', 'titleText', 'buttonDefaultText' ] + }, + radio: { + matches: { + properties: { + type: 'radio' + } + }, + allowedRoles: [ 'menuitemradio' ], + implicitAttrs: { + 'aria-checked': 'false' + } + }, + textWithList: { + matches: { + properties: { + type: 'text' + }, + attributes: { + list: '/.*/' + } + }, + allowedRoles: false + }, + default: { + contentTypes: [ 'interactive', 'flow' ], + allowedRoles: [ 'combobox', 'searchbox', 'spinbutton' ], + implicitAttrs: { + 'aria-valuenow': '' + }, + namingMethods: [ 'labelText', 'placeholderText' ] + } + } + }, + ins: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + kbd: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + label: { + contentTypes: [ 'interactive', 'phrasing', 'flow' ], + allowedRoles: false, + chromiumRole: 'Label' + }, + legend: { + allowedRoles: false + }, + li: { + allowedRoles: [ 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'none', 'presentation', 'radio', 'separator', 'tab', 'treeitem', 'doc-biblioentry', 'doc-endnote' ], + implicitAttrs: { + 'aria-setsize': '1', + 'aria-posinset': '1' + } + }, + link: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + main: { + contentTypes: [ 'flow' ], + allowedRoles: false, + shadowRoot: true + }, + map: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + math: { + contentTypes: [ 'embedded', 'phrasing', 'flow' ], + allowedRoles: false + }, + mark: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + menu: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'directory', 'group', 'listbox', 'menu', 'menubar', 'none', 'presentation', 'radiogroup', 'tablist', 'toolbar', 'tree' ] + }, + meta: { + variant: { + itemprop: { + matches: '[itemprop]', + contentTypes: [ 'phrasing', 'flow' ] + } + }, + allowedRoles: false, + noAriaAttrs: true + }, + meter: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + chromiumRole: 'progressbar' + }, + nav: { + contentTypes: [ 'sectioning', 'flow' ], + allowedRoles: [ 'doc-index', 'doc-pagelist', 'doc-toc', 'menu', 'menubar', 'none', 'presentation', 'tablist' ], + shadowRoot: true + }, + noscript: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + object: { + variant: { + usemap: { + matches: '[usemap]', + contentTypes: [ 'interactive', 'embedded', 'phrasing', 'flow' ] + }, + default: { + contentTypes: [ 'embedded', 'phrasing', 'flow' ] + } + }, + allowedRoles: [ 'application', 'document', 'img' ], + chromiumRole: 'PluginObject' + }, + ol: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'directory', 'group', 'listbox', 'menu', 'menubar', 'none', 'presentation', 'radiogroup', 'tablist', 'toolbar', 'tree' ] + }, + optgroup: { + allowedRoles: false + }, + option: { + allowedRoles: false, + implicitAttrs: { + 'aria-selected': 'false' + } + }, + output: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true, + namingMethods: [ 'subtreeText' ] + }, + p: { + contentTypes: [ 'flow' ], + allowedRoles: true, + shadowRoot: true + }, + param: { + allowedRoles: false, + noAriaAttrs: true + }, + picture: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + pre: { + contentTypes: [ 'flow' ], + allowedRoles: true + }, + progress: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + implicitAttrs: { + 'aria-valuemax': '100', + 'aria-valuemin': '0', + 'aria-valuenow': '0' + } + }, + q: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + rp: { + allowedRoles: true + }, + rt: { + allowedRoles: true + }, + ruby: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + s: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + samp: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + script: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + search: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'form', 'group', 'none', 'presentation', 'region', 'search' ] + }, + section: { + contentTypes: [ 'sectioning', 'flow' ], + allowedRoles: [ 'alert', 'alertdialog', 'application', 'banner', 'complementary', 'contentinfo', 'dialog', 'document', 'feed', 'group', 'log', 'main', 'marquee', 'navigation', 'none', 'note', 'presentation', 'search', 'status', 'tabpanel', 'doc-abstract', 'doc-acknowledgments', 'doc-afterword', 'doc-appendix', 'doc-bibliography', 'doc-chapter', 'doc-colophon', 'doc-conclusion', 'doc-credit', 'doc-credits', 'doc-dedication', 'doc-endnotes', 'doc-epigraph', 'doc-epilogue', 'doc-errata', 'doc-example', 'doc-foreword', 'doc-glossary', 'doc-index', 'doc-introduction', 'doc-notice', 'doc-pagelist', 'doc-part', 'doc-preface', 'doc-prologue', 'doc-pullquote', 'doc-qna', 'doc-toc' ], + shadowRoot: true + }, + select: { + variant: { + combobox: { + matches: { + attributes: { + multiple: null, + size: [ null, '1' ] + } + }, + allowedRoles: [ 'menu' ] + }, + default: { + allowedRoles: false + } + }, + contentTypes: [ 'interactive', 'phrasing', 'flow' ], + implicitAttrs: { + 'aria-valuenow': '' + }, + namingMethods: [ 'labelText' ] + }, + slot: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + small: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + source: { + allowedRoles: false, + noAriaAttrs: true + }, + span: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true, + shadowRoot: true + }, + strong: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + style: { + allowedRoles: false, + noAriaAttrs: true + }, + svg: { + contentTypes: [ 'embedded', 'phrasing', 'flow' ], + allowedRoles: true, + chromiumRole: 'SVGRoot', + namingMethods: [ 'svgTitleText' ] + }, + sub: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + summary: { + allowedRoles: false, + namingMethods: [ 'subtreeText' ] + }, + sup: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + table: { + contentTypes: [ 'flow' ], + allowedRoles: true, + namingMethods: [ 'tableCaptionText', 'tableSummaryText' ] + }, + tbody: { + allowedRoles: true + }, + template: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: false, + noAriaAttrs: true + }, + textarea: { + contentTypes: [ 'interactive', 'phrasing', 'flow' ], + allowedRoles: false, + implicitAttrs: { + 'aria-valuenow': '', + 'aria-multiline': 'true' + }, + namingMethods: [ 'labelText', 'placeholderText' ] + }, + tfoot: { + allowedRoles: true + }, + thead: { + allowedRoles: true + }, + time: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + title: { + allowedRoles: false, + noAriaAttrs: true + }, + td: { + allowedRoles: true + }, + th: { + allowedRoles: true + }, + tr: { + allowedRoles: true + }, + track: { + allowedRoles: false, + noAriaAttrs: true + }, + u: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + ul: { + contentTypes: [ 'flow' ], + allowedRoles: [ 'directory', 'group', 'listbox', 'menu', 'menubar', 'none', 'presentation', 'radiogroup', 'tablist', 'toolbar', 'tree' ] + }, + var: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: true + }, + video: { + variant: { + controls: { + matches: '[controls]', + contentTypes: [ 'interactive', 'embedded', 'phrasing', 'flow' ] + }, + default: { + contentTypes: [ 'embedded', 'phrasing', 'flow' ] + } + }, + allowedRoles: [ 'application' ], + chromiumRole: 'video' + }, + wbr: { + contentTypes: [ 'phrasing', 'flow' ], + allowedRoles: [ 'presentation', 'none' ], + allowedAriaAttrs: [ 'aria-hidden' ] + } + }; + var html_elms_default = htmlElms; + var cssColors = { + aliceblue: [ 240, 248, 255 ], + antiquewhite: [ 250, 235, 215 ], + aqua: [ 0, 255, 255 ], + aquamarine: [ 127, 255, 212 ], + azure: [ 240, 255, 255 ], + beige: [ 245, 245, 220 ], + bisque: [ 255, 228, 196 ], + black: [ 0, 0, 0 ], + blanchedalmond: [ 255, 235, 205 ], + blue: [ 0, 0, 255 ], + blueviolet: [ 138, 43, 226 ], + brown: [ 165, 42, 42 ], + burlywood: [ 222, 184, 135 ], + cadetblue: [ 95, 158, 160 ], + chartreuse: [ 127, 255, 0 ], + chocolate: [ 210, 105, 30 ], + coral: [ 255, 127, 80 ], + cornflowerblue: [ 100, 149, 237 ], + cornsilk: [ 255, 248, 220 ], + crimson: [ 220, 20, 60 ], + cyan: [ 0, 255, 255 ], + darkblue: [ 0, 0, 139 ], + darkcyan: [ 0, 139, 139 ], + darkgoldenrod: [ 184, 134, 11 ], + darkgray: [ 169, 169, 169 ], + darkgreen: [ 0, 100, 0 ], + darkgrey: [ 169, 169, 169 ], + darkkhaki: [ 189, 183, 107 ], + darkmagenta: [ 139, 0, 139 ], + darkolivegreen: [ 85, 107, 47 ], + darkorange: [ 255, 140, 0 ], + darkorchid: [ 153, 50, 204 ], + darkred: [ 139, 0, 0 ], + darksalmon: [ 233, 150, 122 ], + darkseagreen: [ 143, 188, 143 ], + darkslateblue: [ 72, 61, 139 ], + darkslategray: [ 47, 79, 79 ], + darkslategrey: [ 47, 79, 79 ], + darkturquoise: [ 0, 206, 209 ], + darkviolet: [ 148, 0, 211 ], + deeppink: [ 255, 20, 147 ], + deepskyblue: [ 0, 191, 255 ], + dimgray: [ 105, 105, 105 ], + dimgrey: [ 105, 105, 105 ], + dodgerblue: [ 30, 144, 255 ], + firebrick: [ 178, 34, 34 ], + floralwhite: [ 255, 250, 240 ], + forestgreen: [ 34, 139, 34 ], + fuchsia: [ 255, 0, 255 ], + gainsboro: [ 220, 220, 220 ], + ghostwhite: [ 248, 248, 255 ], + gold: [ 255, 215, 0 ], + goldenrod: [ 218, 165, 32 ], + gray: [ 128, 128, 128 ], + green: [ 0, 128, 0 ], + greenyellow: [ 173, 255, 47 ], + grey: [ 128, 128, 128 ], + honeydew: [ 240, 255, 240 ], + hotpink: [ 255, 105, 180 ], + indianred: [ 205, 92, 92 ], + indigo: [ 75, 0, 130 ], + ivory: [ 255, 255, 240 ], + khaki: [ 240, 230, 140 ], + lavender: [ 230, 230, 250 ], + lavenderblush: [ 255, 240, 245 ], + lawngreen: [ 124, 252, 0 ], + lemonchiffon: [ 255, 250, 205 ], + lightblue: [ 173, 216, 230 ], + lightcoral: [ 240, 128, 128 ], + lightcyan: [ 224, 255, 255 ], + lightgoldenrodyellow: [ 250, 250, 210 ], + lightgray: [ 211, 211, 211 ], + lightgreen: [ 144, 238, 144 ], + lightgrey: [ 211, 211, 211 ], + lightpink: [ 255, 182, 193 ], + lightsalmon: [ 255, 160, 122 ], + lightseagreen: [ 32, 178, 170 ], + lightskyblue: [ 135, 206, 250 ], + lightslategray: [ 119, 136, 153 ], + lightslategrey: [ 119, 136, 153 ], + lightsteelblue: [ 176, 196, 222 ], + lightyellow: [ 255, 255, 224 ], + lime: [ 0, 255, 0 ], + limegreen: [ 50, 205, 50 ], + linen: [ 250, 240, 230 ], + magenta: [ 255, 0, 255 ], + maroon: [ 128, 0, 0 ], + mediumaquamarine: [ 102, 205, 170 ], + mediumblue: [ 0, 0, 205 ], + mediumorchid: [ 186, 85, 211 ], + mediumpurple: [ 147, 112, 219 ], + mediumseagreen: [ 60, 179, 113 ], + mediumslateblue: [ 123, 104, 238 ], + mediumspringgreen: [ 0, 250, 154 ], + mediumturquoise: [ 72, 209, 204 ], + mediumvioletred: [ 199, 21, 133 ], + midnightblue: [ 25, 25, 112 ], + mintcream: [ 245, 255, 250 ], + mistyrose: [ 255, 228, 225 ], + moccasin: [ 255, 228, 181 ], + navajowhite: [ 255, 222, 173 ], + navy: [ 0, 0, 128 ], + oldlace: [ 253, 245, 230 ], + olive: [ 128, 128, 0 ], + olivedrab: [ 107, 142, 35 ], + orange: [ 255, 165, 0 ], + orangered: [ 255, 69, 0 ], + orchid: [ 218, 112, 214 ], + palegoldenrod: [ 238, 232, 170 ], + palegreen: [ 152, 251, 152 ], + paleturquoise: [ 175, 238, 238 ], + palevioletred: [ 219, 112, 147 ], + papayawhip: [ 255, 239, 213 ], + peachpuff: [ 255, 218, 185 ], + peru: [ 205, 133, 63 ], + pink: [ 255, 192, 203 ], + plum: [ 221, 160, 221 ], + powderblue: [ 176, 224, 230 ], + purple: [ 128, 0, 128 ], + rebeccapurple: [ 102, 51, 153 ], + red: [ 255, 0, 0 ], + rosybrown: [ 188, 143, 143 ], + royalblue: [ 65, 105, 225 ], + saddlebrown: [ 139, 69, 19 ], + salmon: [ 250, 128, 114 ], + sandybrown: [ 244, 164, 96 ], + seagreen: [ 46, 139, 87 ], + seashell: [ 255, 245, 238 ], + sienna: [ 160, 82, 45 ], + silver: [ 192, 192, 192 ], + skyblue: [ 135, 206, 235 ], + slateblue: [ 106, 90, 205 ], + slategray: [ 112, 128, 144 ], + slategrey: [ 112, 128, 144 ], + snow: [ 255, 250, 250 ], + springgreen: [ 0, 255, 127 ], + steelblue: [ 70, 130, 180 ], + tan: [ 210, 180, 140 ], + teal: [ 0, 128, 128 ], + thistle: [ 216, 191, 216 ], + tomato: [ 255, 99, 71 ], + turquoise: [ 64, 224, 208 ], + violet: [ 238, 130, 238 ], + wheat: [ 245, 222, 179 ], + white: [ 255, 255, 255 ], + whitesmoke: [ 245, 245, 245 ], + yellow: [ 255, 255, 0 ], + yellowgreen: [ 154, 205, 50 ] + }; + var css_colors_default = cssColors; + var originals = { + ariaAttrs: aria_attrs_default, + ariaRoles: _extends({}, aria_roles_default, dpub_roles_default, graphics_roles_default), + htmlElms: html_elms_default, + cssColors: css_colors_default + }; + var standards = _extends({}, originals); + function configureStandards(config) { + Object.keys(standards).forEach(function(propName) { + if (config[propName]) { + standards[propName] = deep_merge_default(standards[propName], config[propName]); + } + }); + } + function resetStandards() { + Object.keys(standards).forEach(function(propName) { + standards[propName] = originals[propName]; + }); + } + var standards_default = standards; + function isUnsupportedRole(role) { + var roleDefinition = standards_default.ariaRoles[role]; + return roleDefinition ? !!roleDefinition.unsupported : false; + } + var is_unsupported_role_default = isUnsupportedRole; + function isValidRole(role) { + var _ref52 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, allowAbstract = _ref52.allowAbstract, _ref52$flagUnsupporte = _ref52.flagUnsupported, flagUnsupported = _ref52$flagUnsupporte === void 0 ? false : _ref52$flagUnsupporte; + var roleDefinition = standards_default.ariaRoles[role]; + var isRoleUnsupported = is_unsupported_role_default(role); + if (!roleDefinition || flagUnsupported && isRoleUnsupported) { + return false; + } + return allowAbstract ? true : roleDefinition.type !== 'abstract'; + } + var is_valid_role_default = isValidRole; + function getExplicitRole(vNode) { + var _ref53 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, fallback = _ref53.fallback, abstracts = _ref53.abstracts, dpub = _ref53.dpub; + vNode = vNode instanceof abstract_virtual_node_default ? vNode : get_node_from_tree_default(vNode); + if (vNode.props.nodeType !== 1) { + return null; + } + var roleAttr = (vNode.attr('role') || '').trim().toLowerCase(); + var roleList = fallback ? token_list_default(roleAttr) : [ roleAttr ]; + var firstValidRole = roleList.find(function(role) { + if (!dpub && role.substr(0, 4) === 'doc-') { + return false; + } + return is_valid_role_default(role, { + allowAbstract: abstracts + }); + }); + return firstValidRole || null; + } + var get_explicit_role_default = getExplicitRole; + function getElementsByContentType(type2) { + return Object.keys(standards_default.htmlElms).filter(function(nodeName2) { + var elm = standards_default.htmlElms[nodeName2]; + if (elm.contentTypes) { + return elm.contentTypes.includes(type2); + } + if (!elm.variant) { + return false; + } + if (elm.variant['default'] && elm.variant['default'].contentTypes) { + return elm.variant['default'].contentTypes.includes(type2); + } + return false; + }); + } + var get_elements_by_content_type_default = getElementsByContentType; + function getGlobalAriaAttrs() { + return cache_default.get('globalAriaAttrs', function() { + return Object.keys(standards_default.ariaAttrs).filter(function(attrName) { + return standards_default.ariaAttrs[attrName].global; + }); + }); + } + var get_global_aria_attrs_default = getGlobalAriaAttrs; + function toGrid(node) { + var table = []; + var rows = node.rows; + for (var _i11 = 0, rowLength = rows.length; _i11 < rowLength; _i11++) { + var cells = rows[_i11].cells; + table[_i11] = table[_i11] || []; + var columnIndex = 0; + for (var j = 0, cellLength = cells.length; j < cellLength; j++) { + for (var colSpan = 0; colSpan < cells[j].colSpan; colSpan++) { + var rowspanAttr = cells[j].getAttribute('rowspan'); + var rowspanValue = parseInt(rowspanAttr) === 0 || cells[j].rowspan === 0 ? rows.length : cells[j].rowSpan; + for (var rowSpan = 0; rowSpan < rowspanValue; rowSpan++) { + table[_i11 + rowSpan] = table[_i11 + rowSpan] || []; + while (table[_i11 + rowSpan][columnIndex]) { + columnIndex++; + } + table[_i11 + rowSpan][columnIndex] = cells[j]; + } + columnIndex++; + } + } + } + return table; + } + var to_grid_default = memoize_default(toGrid); + function getCellPosition(cell, tableGrid) { + var rowIndex, index; + if (!tableGrid) { + tableGrid = to_grid_default(find_up_default(cell, 'table')); + } + for (rowIndex = 0; rowIndex < tableGrid.length; rowIndex++) { + if (tableGrid[rowIndex]) { + index = tableGrid[rowIndex].indexOf(cell); + if (index !== -1) { + return { + x: index, + y: rowIndex + }; + } + } + } + } + var get_cell_position_default = memoize_default(getCellPosition); + function _getScope(el) { + var _nodeLookup1 = _nodeLookup(el), vNode = _nodeLookup1.vNode, cell = _nodeLookup1.domNode; + var scope = vNode.attr('scope'); + var role = get_explicit_role_default(vNode); + if (![ 'td', 'th' ].includes(vNode.props.nodeName)) { + throw new TypeError('Expected TD or TH element'); + } + if (role === 'columnheader') { + return 'col'; + } else if (role === 'rowheader') { + return 'row'; + } else if (scope === 'col' || scope === 'row') { + return scope; + } else if (vNode.props.nodeName !== 'th') { + return false; + } else if (!vNode.actualNode) { + return 'auto'; + } + var tableGrid = to_grid_default(find_up_default(cell, 'table')); + var pos = get_cell_position_default(cell, tableGrid); + var headerRow = tableGrid[pos.y].every(function(node) { + return node.nodeName.toUpperCase() === 'TH'; + }); + if (headerRow) { + return 'col'; + } + var headerCol = tableGrid.map(function(col) { + return col[pos.x]; + }).every(function(node) { + return node && node.nodeName.toUpperCase() === 'TH'; + }); + if (headerCol) { + return 'row'; + } + return 'auto'; + } + function isColumnHeader(element) { + return [ 'col', 'auto' ].indexOf(_getScope(element)) !== -1; + } + var is_column_header_default = isColumnHeader; + function isRowHeader(cell) { + return [ 'row', 'auto' ].includes(_getScope(cell)); + } + var is_row_header_default = isRowHeader; + function sanitize(str) { + if (!str) { + return ''; + } + return str.replace(/\r\n/g, '\n').replace(/\u00A0/g, ' ').replace(/[\s]{2,}/g, ' ').trim(); + } + var sanitize_default = sanitize; + var getSectioningContentSelector = function getSectioningContentSelector() { + return cache_default.get('sectioningContentSelector', function() { + return get_elements_by_content_type_default('sectioning').map(function(nodeName2) { + return ''.concat(nodeName2, ':not([role])'); + }).join(', ') + ' , [role=article], [role=complementary], [role=navigation], [role=region]'; + }); + }; + var getSectioningContentPlusMainSelector = function getSectioningContentPlusMainSelector() { + return cache_default.get('sectioningContentPlusMainSelector', function() { + return getSectioningContentSelector() + ' , main:not([role]), [role=main]'; + }); + }; + function hasAccessibleName(vNode) { + var _ref54 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref54$checkTitle = _ref54.checkTitle, checkTitle = _ref54$checkTitle === void 0 ? false : _ref54$checkTitle; + return !!(sanitize_default(arialabelledby_text_default(vNode)) || sanitize_default(_arialabelText(vNode)) || checkTitle && (vNode === null || vNode === void 0 ? void 0 : vNode.props.nodeType) === 1 && sanitize_default(vNode.attr('title'))); + } + var implicitHtmlRoles = { + a: function a(vNode) { + return vNode.hasAttr('href') ? 'link' : null; + }, + area: function area(vNode) { + return vNode.hasAttr('href') ? 'link' : null; + }, + article: 'article', + aside: function aside(vNode) { + if (closest_default(vNode.parent, getSectioningContentSelector()) && !hasAccessibleName(vNode, { + checkTitle: true + })) { + return null; + } + return 'complementary'; + }, + body: 'document', + button: 'button', + datalist: 'listbox', + dd: 'definition', + dfn: 'term', + details: 'group', + dialog: 'dialog', + dt: 'term', + fieldset: 'group', + figure: 'figure', + footer: function footer(vNode) { + var sectioningElement = closest_default(vNode, getSectioningContentPlusMainSelector()); + return !sectioningElement ? 'contentinfo' : null; + }, + form: function form(vNode) { + return hasAccessibleName(vNode) ? 'form' : null; + }, + h1: 'heading', + h2: 'heading', + h3: 'heading', + h4: 'heading', + h5: 'heading', + h6: 'heading', + header: function header(vNode) { + var sectioningElement = closest_default(vNode, getSectioningContentPlusMainSelector()); + return !sectioningElement ? 'banner' : null; + }, + hr: 'separator', + img: function img(vNode) { + var emptyAlt = vNode.hasAttr('alt') && !vNode.attr('alt'); + var hasGlobalAria = get_global_aria_attrs_default().find(function(attr) { + return vNode.hasAttr(attr); + }); + return emptyAlt && !hasGlobalAria && !_isFocusable(vNode) ? 'presentation' : 'img'; + }, + input: function input(vNode) { + var suggestionsSourceElement; + if (vNode.hasAttr('list')) { + var listElement = idrefs_default(vNode.actualNode, 'list').filter(function(node) { + return !!node; + })[0]; + suggestionsSourceElement = listElement && listElement.nodeName.toLowerCase() === 'datalist'; + } + switch (vNode.props.type) { + case 'checkbox': + return 'checkbox'; + + case 'number': + return 'spinbutton'; + + case 'radio': + return 'radio'; + + case 'range': + return 'slider'; + + case 'search': + return !suggestionsSourceElement ? 'searchbox' : 'combobox'; + + case 'button': + case 'image': + case 'reset': + case 'submit': + return 'button'; + + case 'text': + case 'tel': + case 'url': + case 'email': + case '': + return !suggestionsSourceElement ? 'textbox' : 'combobox'; + + default: + return 'textbox'; + } + }, + li: 'listitem', + main: 'main', + math: 'math', + menu: 'list', + meter: 'meter', + nav: 'navigation', + ol: 'list', + optgroup: 'group', + option: 'option', + output: 'status', + progress: 'progressbar', + search: 'search', + section: function section(vNode) { + return hasAccessibleName(vNode) ? 'region' : null; + }, + select: function select(vNode) { + return vNode.hasAttr('multiple') || parseInt(vNode.attr('size')) > 1 ? 'listbox' : 'combobox'; + }, + summary: 'button', + table: 'table', + tbody: 'rowgroup', + td: function td(vNode) { + var table = closest_default(vNode, 'table'); + var role = get_explicit_role_default(table); + return [ 'grid', 'treegrid' ].includes(role) ? 'gridcell' : 'cell'; + }, + textarea: 'textbox', + tfoot: 'rowgroup', + th: function th(vNode) { + if (is_column_header_default(vNode)) { + return 'columnheader'; + } + if (is_row_header_default(vNode)) { + return 'rowheader'; + } + }, + thead: 'rowgroup', + tr: 'row', + ul: 'list' + }; + var implicit_html_roles_default = implicitHtmlRoles; + function fromPrimative(someString, matcher) { + var matcherType = _typeof(matcher); + if (Array.isArray(matcher) && typeof someString !== 'undefined') { + return matcher.includes(someString); + } + if (matcherType === 'function') { + return !!matcher(someString); + } + if (someString !== null && someString !== void 0) { + if (matcher instanceof RegExp) { + return matcher.test(someString); + } + if (/^\/.*\/$/.test(matcher)) { + var pattern = matcher.substring(1, matcher.length - 1); + return new RegExp(pattern).test(someString); + } + } + return matcher === someString; + } + var from_primative_default = fromPrimative; + function hasAccessibleName2(vNode, matcher) { + return from_primative_default(!!_accessibleTextVirtual(vNode), matcher); + } + var has_accessible_name_default = hasAccessibleName2; + function fromFunction(getValue, matcher) { + var matcherType = _typeof(matcher); + if (matcherType !== 'object' || Array.isArray(matcher) || matcher instanceof RegExp) { + throw new Error('Expect matcher to be an object'); + } + return Object.keys(matcher).every(function(propName) { + return from_primative_default(getValue(propName), matcher[propName]); + }); + } + var from_function_default = fromFunction; + function attributes(vNode, matcher) { + vNode = _nodeLookup(vNode).vNode; + return from_function_default(function(attrName) { + return vNode.attr(attrName); + }, matcher); + } + var attributes_default = attributes; + function condition(arg, matcher) { + return !!matcher(arg); + } + function explicitRole(vNode, matcher) { + return from_primative_default(get_explicit_role_default(vNode), matcher); + } + var explicit_role_default = explicitRole; + function implicitRole(vNode, matcher) { + return from_primative_default(implicit_role_default(vNode), matcher); + } + var implicit_role_default2 = implicitRole; + function nodeName(vNode, matcher) { + vNode = _nodeLookup(vNode).vNode; + return from_primative_default(vNode.props.nodeName, matcher); + } + var node_name_default = nodeName; + function properties(vNode, matcher) { + vNode = _nodeLookup(vNode).vNode; + return from_function_default(function(propName) { + return vNode.props[propName]; + }, matcher); + } + var properties_default = properties; + function semanticRole(vNode, matcher) { + return from_primative_default(get_role_default(vNode), matcher); + } + var semantic_role_default = semanticRole; + var matchers = { + hasAccessibleName: has_accessible_name_default, + attributes: attributes_default, + condition: condition, + explicitRole: explicit_role_default, + implicitRole: implicit_role_default2, + nodeName: node_name_default, + properties: properties_default, + semanticRole: semantic_role_default + }; + function fromDefinition(vNode, definition) { + vNode = _nodeLookup(vNode).vNode; + if (Array.isArray(definition)) { + return definition.some(function(definitionItem) { + return fromDefinition(vNode, definitionItem); + }); + } + if (typeof definition === 'string') { + return _matches(vNode, definition); + } + return Object.keys(definition).every(function(matcherName) { + if (!matchers[matcherName]) { + throw new Error('Unknown matcher type "'.concat(matcherName, '"')); + } + var matchMethod = matchers[matcherName]; + var matcher = definition[matcherName]; + return matchMethod(vNode, matcher); + }); + } + var from_definition_default = fromDefinition; + function matches2(vNode, definition) { + return from_definition_default(vNode, definition); + } + var matches_default = matches2; + matches_default.hasAccessibleName = has_accessible_name_default; + matches_default.attributes = attributes_default; + matches_default.condition = condition; + matches_default.explicitRole = explicit_role_default; + matches_default.fromDefinition = from_definition_default; + matches_default.fromFunction = from_function_default; + matches_default.fromPrimative = from_primative_default; + matches_default.implicitRole = implicit_role_default2; + matches_default.nodeName = node_name_default; + matches_default.properties = properties_default; + matches_default.semanticRole = semantic_role_default; + var matches_default2 = matches_default; + function getElementSpec(vNode) { + var _ref55 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref55$noMatchAccessi = _ref55.noMatchAccessibleName, noMatchAccessibleName = _ref55$noMatchAccessi === void 0 ? false : _ref55$noMatchAccessi; + var standard = standards_default.htmlElms[vNode.props.nodeName]; + if (!standard) { + return {}; + } + if (!standard.variant) { + return standard; + } + var variant = standard.variant, spec = _objectWithoutProperties(standard, _excluded9); + for (var variantName in variant) { + if (!variant.hasOwnProperty(variantName) || variantName === 'default') { + continue; + } + var _variant$variantName = variant[variantName], matches4 = _variant$variantName.matches, props = _objectWithoutProperties(_variant$variantName, _excluded0); + var matchProperties = Array.isArray(matches4) ? matches4 : [ matches4 ]; + for (var _i12 = 0; _i12 < matchProperties.length && noMatchAccessibleName; _i12++) { + if (matchProperties[_i12].hasOwnProperty('hasAccessibleName')) { + return standard; + } + } + if (matches_default2(vNode, matches4)) { + for (var propName in props) { + if (props.hasOwnProperty(propName)) { + spec[propName] = props[propName]; + } + } + } + } + for (var _propName in variant['default']) { + if (variant['default'].hasOwnProperty(_propName) && typeof spec[_propName] === 'undefined') { + spec[_propName] = variant['default'][_propName]; + } + } + return spec; + } + var get_element_spec_default = getElementSpec; + function implicitRole2(node) { + var _ref56 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, chromium = _ref56.chromium; + var vNode = node instanceof abstract_virtual_node_default ? node : get_node_from_tree_default(node); + node = vNode.actualNode; + if (!vNode) { + throw new ReferenceError('Cannot get implicit role of a node outside the current scope.'); + } + var nodeName2 = vNode.props.nodeName; + var role = implicit_html_roles_default[nodeName2]; + if (!role && chromium) { + var _get_element_spec_def = get_element_spec_default(vNode), chromiumRole = _get_element_spec_def.chromiumRole; + return chromiumRole || null; + } + if (typeof role === 'function') { + return role(vNode); + } + return role || null; + } + var implicit_role_default = implicitRole2; + var inheritsPresentationChain = { + td: [ 'tr' ], + th: [ 'tr' ], + tr: [ 'thead', 'tbody', 'tfoot', 'table' ], + thead: [ 'table' ], + tbody: [ 'table' ], + tfoot: [ 'table' ], + li: [ 'ol', 'ul' ], + dt: [ 'dl', 'div' ], + dd: [ 'dl', 'div' ], + div: [ 'dl' ] + }; + function getInheritedRole(vNode, explicitRoleOptions) { + var parentNodeNames = inheritsPresentationChain[vNode.props.nodeName]; + if (!parentNodeNames) { + return null; + } + if (!vNode.parent) { + if (!vNode.actualNode) { + return null; + } + throw new ReferenceError('Cannot determine role presentational inheritance of a required parent outside the current scope.'); + } + if (!parentNodeNames.includes(vNode.parent.props.nodeName)) { + return null; + } + var parentRole = get_explicit_role_default(vNode.parent, explicitRoleOptions); + if ([ 'none', 'presentation' ].includes(parentRole) && !hasConflictResolution(vNode.parent)) { + return parentRole; + } + if (parentRole) { + return null; + } + return getInheritedRole(vNode.parent, explicitRoleOptions); + } + function resolveImplicitRole(vNode, _ref57) { + var chromium = _ref57.chromium, explicitRoleOptions = _objectWithoutProperties(_ref57, _excluded1); + var implicitRole3 = implicit_role_default(vNode, { + chromium: chromium + }); + if (!implicitRole3) { + return null; + } + var presentationalRole = getInheritedRole(vNode, explicitRoleOptions); + if (presentationalRole) { + return presentationalRole; + } + return implicitRole3; + } + function hasConflictResolution(vNode) { + var hasGlobalAria = get_global_aria_attrs_default().some(function(attr) { + return vNode.hasAttr(attr); + }); + return hasGlobalAria || _isFocusable(vNode); + } + function resolveRole(node) { + var _ref58 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var noImplicit = _ref58.noImplicit, roleOptions = _objectWithoutProperties(_ref58, _excluded10); + var _nodeLookup10 = _nodeLookup(node), vNode = _nodeLookup10.vNode; + if (vNode.props.nodeType !== 1) { + return null; + } + var explicitRole2 = get_explicit_role_default(vNode, roleOptions); + if (!explicitRole2) { + return noImplicit ? null : resolveImplicitRole(vNode, roleOptions); + } + if (![ 'presentation', 'none' ].includes(explicitRole2)) { + return explicitRole2; + } + if (hasConflictResolution(vNode)) { + return noImplicit ? null : resolveImplicitRole(vNode, roleOptions); + } + return explicitRole2; + } + function getRole(node) { + var _ref59 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var noPresentational = _ref59.noPresentational, options = _objectWithoutProperties(_ref59, _excluded11); + var role = resolveRole(node, options); + if (noPresentational && [ 'presentation', 'none' ].includes(role)) { + return null; + } + return role; + } + var get_role_default = getRole; + var alwaysTitleElements = [ 'iframe' ]; + function titleText(node) { + var _nodeLookup11 = _nodeLookup(node), vNode = _nodeLookup11.vNode; + if (vNode.props.nodeType !== 1 || !node.hasAttr('title')) { + return ''; + } + if (!matches_default(vNode, alwaysTitleElements) && [ 'none', 'presentation' ].includes(get_role_default(vNode))) { + return ''; + } + return vNode.attr('title'); + } + var title_text_default = titleText; + function namedFromContents(vNode) { + var _ref60 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, strict = _ref60.strict; + vNode = vNode instanceof abstract_virtual_node_default ? vNode : get_node_from_tree_default(vNode); + if (vNode.props.nodeType !== 1) { + return false; + } + var role = get_role_default(vNode); + var roleDef = standards_default.ariaRoles[role]; + if (roleDef && roleDef.nameFromContent) { + return true; + } + if (strict) { + return false; + } + return !roleDef || [ 'presentation', 'none' ].includes(role); + } + var named_from_contents_default = namedFromContents; + function getOwnedVirtual(virtualNode) { + var actualNode = virtualNode.actualNode, children = virtualNode.children; + if (!children) { + throw new Error('getOwnedVirtual requires a virtual node'); + } + if (virtualNode.hasAttr('aria-owns')) { + var owns = idrefs_default(actualNode, 'aria-owns').filter(function(element) { + return !!element; + }).map(function(element) { + return axe.utils.getNodeFromTree(element); + }); + var uniqueOwns = owns.filter(function(own, index) { + return owns.indexOf(own) === index; + }); + var nativeChildren = children.filter(function(child) { + return !uniqueOwns.includes(child); + }); + return [].concat(_toConsumableArray(nativeChildren), _toConsumableArray(uniqueOwns)); + } + return _toConsumableArray(children); + } + var get_owned_virtual_default = getOwnedVirtual; + var unsupported_default = { + accessibleNameFromFieldValue: [ 'progressbar' ] + }; + function _isVisibleToScreenReaders(vNode) { + vNode = _nodeLookup(vNode).vNode; + return isVisibleToScreenReadersVirtual(vNode); + } + var isVisibleToScreenReadersVirtual = memoize_default(function isVisibleToScreenReadersMemoized(vNode, isAncestor) { + if (ariaHidden(vNode) || _isInert(vNode, { + skipAncestors: true, + isAncestor: isAncestor + })) { + return false; + } + if (vNode.actualNode && vNode.props.nodeName === 'area') { + return !areaHidden(vNode, isVisibleToScreenReadersVirtual); + } + if (_isHiddenForEveryone(vNode, { + skipAncestors: true, + isAncestor: isAncestor + })) { + return false; + } + if (!vNode.parent) { + return true; + } + return isVisibleToScreenReadersVirtual(vNode.parent, true); + }); + function visibleVirtual(element, screenReader, noRecursing) { + var _nodeLookup12 = _nodeLookup(element), vNode = _nodeLookup12.vNode; + var visibleMethod = screenReader ? _isVisibleToScreenReaders : _isVisibleOnScreen; + var visible2 = !element.actualNode || element.actualNode && visibleMethod(element); + var result = vNode.children.map(function(child) { + var _child$props = child.props, nodeType = _child$props.nodeType, nodeValue = _child$props.nodeValue; + if (nodeType === 3) { + if (nodeValue && visible2) { + return nodeValue; + } + } else if (!noRecursing) { + return visibleVirtual(child, screenReader); + } + }).join(''); + return sanitize_default(result); + } + var visible_virtual_default = visibleVirtual; + var nonTextInputTypes = [ 'button', 'checkbox', 'color', 'file', 'hidden', 'image', 'password', 'radio', 'reset', 'submit' ]; + function isNativeTextbox(node) { + node = node instanceof abstract_virtual_node_default ? node : get_node_from_tree_default(node); + var nodeName2 = node.props.nodeName; + return nodeName2 === 'textarea' || nodeName2 === 'input' && !nonTextInputTypes.includes((node.attr('type') || '').toLowerCase()); + } + var is_native_textbox_default = isNativeTextbox; + function isNativeSelect(node) { + node = node instanceof abstract_virtual_node_default ? node : get_node_from_tree_default(node); + var nodeName2 = node.props.nodeName; + return nodeName2 === 'select'; + } + var is_native_select_default = isNativeSelect; + function isAriaTextbox(node) { + var role = get_explicit_role_default(node); + return role === 'textbox'; + } + var is_aria_textbox_default = isAriaTextbox; + function isAriaListbox(node) { + var role = get_explicit_role_default(node); + return role === 'listbox'; + } + var is_aria_listbox_default = isAriaListbox; + function isAriaCombobox(node) { + var role = get_explicit_role_default(node); + return role === 'combobox'; + } + var is_aria_combobox_default = isAriaCombobox; + var rangeRoles = [ 'progressbar', 'scrollbar', 'slider', 'spinbutton' ]; + function isAriaRange(node) { + var role = get_explicit_role_default(node); + return rangeRoles.includes(role); + } + var is_aria_range_default = isAriaRange; + var controlValueRoles = [ 'textbox', 'progressbar', 'scrollbar', 'slider', 'spinbutton', 'combobox', 'listbox' ]; + var _formControlValueMethods = { + nativeTextboxValue: nativeTextboxValue, + nativeSelectValue: nativeSelectValue, + ariaTextboxValue: ariaTextboxValue, + ariaListboxValue: ariaListboxValue, + ariaComboboxValue: ariaComboboxValue, + ariaRangeValue: ariaRangeValue + }; + function formControlValue(virtualNode) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var actualNode = virtualNode.actualNode; + var unsupportedRoles = unsupported_default.accessibleNameFromFieldValue || []; + var role = get_role_default(virtualNode); + if (context.startNode === virtualNode || !controlValueRoles.includes(role) || unsupportedRoles.includes(role)) { + return ''; + } + var valueMethods = Object.keys(_formControlValueMethods).map(function(name) { + return _formControlValueMethods[name]; + }); + var valueString = valueMethods.reduce(function(accName, step) { + return accName || step(virtualNode, context); + }, ''); + if (context.debug) { + log_default(valueString || '{empty-value}', actualNode, context); + } + return valueString; + } + function nativeTextboxValue(node) { + var _nodeLookup13 = _nodeLookup(node), vNode = _nodeLookup13.vNode; + if (is_native_textbox_default(vNode)) { + return vNode.props.value || ''; + } + return ''; + } + function nativeSelectValue(node) { + var _nodeLookup14 = _nodeLookup(node), vNode = _nodeLookup14.vNode; + if (!is_native_select_default(vNode)) { + return ''; + } + var options = query_selector_all_default(vNode, 'option'); + var selectedOptions = options.filter(function(option) { + return option.props.selected; + }); + if (!selectedOptions.length) { + selectedOptions.push(options[0]); + } + return selectedOptions.map(function(option) { + return visible_virtual_default(option); + }).join(' ') || ''; + } + function ariaTextboxValue(node) { + var _nodeLookup15 = _nodeLookup(node), vNode = _nodeLookup15.vNode, domNode = _nodeLookup15.domNode; + if (!is_aria_textbox_default(vNode)) { + return ''; + } + if (!domNode || domNode && !_isHiddenForEveryone(domNode)) { + return visible_virtual_default(vNode, true); + } else { + return domNode.textContent; + } + } + function ariaListboxValue(node, context) { + var _nodeLookup16 = _nodeLookup(node), vNode = _nodeLookup16.vNode; + if (!is_aria_listbox_default(vNode)) { + return ''; + } + var selected = get_owned_virtual_default(vNode).filter(function(owned) { + return get_role_default(owned) === 'option' && owned.attr('aria-selected') === 'true'; + }); + if (selected.length === 0) { + return ''; + } + return _accessibleTextVirtual(selected[0], context); + } + function ariaComboboxValue(node, context) { + var _nodeLookup17 = _nodeLookup(node), vNode = _nodeLookup17.vNode; + if (!is_aria_combobox_default(vNode)) { + return ''; + } + var listbox = get_owned_virtual_default(vNode).filter(function(elm) { + return get_role_default(elm) === 'listbox'; + })[0]; + return listbox ? ariaListboxValue(listbox, context) : ''; + } + function ariaRangeValue(node) { + var _nodeLookup18 = _nodeLookup(node), vNode = _nodeLookup18.vNode; + if (!is_aria_range_default(vNode) || !vNode.hasAttr('aria-valuenow')) { + return ''; + } + var valueNow = +vNode.attr('aria-valuenow'); + return !isNaN(valueNow) ? String(valueNow) : '0'; + } + var form_control_value_default = formControlValue; + function subtreeText(virtualNode) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var alreadyProcessed2 = _accessibleTextVirtual.alreadyProcessed; + context.startNode = context.startNode || virtualNode; + var _context = context, strict = _context.strict, inControlContext = _context.inControlContext, inLabelledByContext = _context.inLabelledByContext; + var role = get_role_default(virtualNode); + var _get_element_spec_def2 = get_element_spec_default(virtualNode, { + noMatchAccessibleName: true + }), contentTypes = _get_element_spec_def2.contentTypes; + if (alreadyProcessed2(virtualNode, context) || virtualNode.props.nodeType !== 1 || contentTypes !== null && contentTypes !== void 0 && contentTypes.includes('embedded') || controlValueRoles.includes(role)) { + return ''; + } + if (!context.subtreeDescendant && !context.inLabelledByContext && !named_from_contents_default(virtualNode, { + strict: strict + })) { + return ''; + } + if (!strict) { + var subtreeDescendant = !inControlContext && !inLabelledByContext; + context = _extends({ + subtreeDescendant: subtreeDescendant + }, context); + } + return get_owned_virtual_default(virtualNode).reduce(function(contentText, child) { + return appendAccessibleText(contentText, child, context); + }, ''); + } + var phrasingElements = get_elements_by_content_type_default('phrasing').concat([ '#text' ]); + function appendAccessibleText(contentText, virtualNode, context) { + var nodeName2 = virtualNode.props.nodeName; + var contentTextAdd = _accessibleTextVirtual(virtualNode, context); + if (!contentTextAdd) { + return contentText; + } + if (!phrasingElements.includes(nodeName2)) { + if (contentTextAdd[0] !== ' ') { + contentTextAdd += ' '; + } + if (contentText && contentText[contentText.length - 1] !== ' ') { + contentTextAdd = ' ' + contentTextAdd; + } + } + return contentText + contentTextAdd; + } + var subtree_text_default = subtreeText; + function labelText(virtualNode) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var alreadyProcessed2 = _accessibleTextVirtual.alreadyProcessed; + if (context.inControlContext || context.inLabelledByContext || alreadyProcessed2(virtualNode, context)) { + return ''; + } + if (!context.startNode) { + context.startNode = virtualNode; + } + var labelContext = _extends({ + inControlContext: true + }, context); + var explicitLabels = getExplicitLabels(virtualNode); + var implicitLabel = closest_default(virtualNode, 'label'); + var labels; + if (implicitLabel) { + labels = [].concat(_toConsumableArray(explicitLabels), [ implicitLabel.actualNode ]); + labels.sort(node_sorter_default); + } else { + labels = explicitLabels; + } + return labels.map(function(label3) { + return accessible_text_default(label3, labelContext); + }).filter(function(text) { + return text !== ''; + }).join(' '); + } + function getExplicitLabels(virtualNode) { + if (!virtualNode.attr('id')) { + return []; + } + if (!virtualNode.actualNode) { + throw new TypeError('Cannot resolve explicit label reference for non-DOM nodes'); + } + return find_elms_in_context_default({ + elm: 'label', + attr: 'for', + value: virtualNode.attr('id'), + context: virtualNode.actualNode + }); + } + var label_text_default = labelText; + var defaultButtonValues = { + submit: 'Submit', + image: 'Submit', + reset: 'Reset', + button: '' + }; + var nativeTextMethods = { + valueText: function valueText(vNode) { + return vNode.props.value || ''; + }, + buttonDefaultText: function buttonDefaultText(vNode) { + return defaultButtonValues[vNode.props.type] || ''; + }, + tableCaptionText: descendantText.bind(null, 'caption'), + figureText: descendantText.bind(null, 'figcaption'), + svgTitleText: descendantText.bind(null, 'title'), + fieldsetLegendText: descendantText.bind(null, 'legend'), + altText: attrText.bind(null, 'alt'), + tableSummaryText: attrText.bind(null, 'summary'), + titleText: title_text_default, + subtreeText: subtree_text_default, + labelText: label_text_default, + singleSpace: function singleSpace() { + return ' '; + }, + placeholderText: attrText.bind(null, 'placeholder') + }; + function attrText(attr, vNode) { + return vNode.attr(attr) || ''; + } + function descendantText(nodeName2, _ref61, context) { + var actualNode = _ref61.actualNode; + nodeName2 = nodeName2.toLowerCase(); + var nodeNames2 = [ nodeName2, actualNode.nodeName.toLowerCase() ].join(','); + var candidate = actualNode.querySelector(nodeNames2); + if (!candidate || candidate.nodeName.toLowerCase() !== nodeName2) { + return ''; + } + return accessible_text_default(candidate, context); + } + var native_text_methods_default = nativeTextMethods; + function _nativeTextAlternative(virtualNode) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var actualNode = virtualNode.actualNode; + if (virtualNode.props.nodeType !== 1 || [ 'presentation', 'none' ].includes(get_role_default(virtualNode))) { + return ''; + } + var textMethods = findTextMethods(virtualNode); + var accessibleName = textMethods.reduce(function(accName, step) { + return accName || step(virtualNode, context); + }, ''); + if (context.debug) { + axe.log(accessibleName || '{empty-value}', actualNode, context); + } + return accessibleName; + } + function findTextMethods(virtualNode) { + var elmSpec = get_element_spec_default(virtualNode, { + noMatchAccessibleName: true + }); + var methods = elmSpec.namingMethods || []; + return methods.map(function(methodName) { + return native_text_methods_default[methodName]; + }); + } + function getUnicodeNonBmpRegExp() { + return /[\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u20A0-\u20CF\u20D0-\u20FF\u2100-\u214F\u2150-\u218F\u2190-\u21FF\u2200-\u22FF\u2300-\u23FF\u2400-\u243F\u2440-\u245F\u2460-\u24FF\u2500-\u257F\u2580-\u259F\u25A0-\u25FF\u2600-\u26FF\u2700-\u27BF\uE000-\uF8FF]/g; + } + function getPunctuationRegExp() { + return /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\xa3\xa2\xa5\xa7\u20ac()*+,\-.\/:;<=>?@\[\]^_`{|}~\xb1]/g; + } + function getSupplementaryPrivateUseRegExp() { + return /[\uDB80-\uDBBF][\uDC00-\uDFFF]/g; + } + function getCategoryFormatRegExp() { + return /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC38]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/g; + } + function hasUnicode(str, options) { + var emoji = options.emoji, nonBmp = options.nonBmp, punctuations = options.punctuations; + var value = false; + if (emoji) { + value || (value = emoji_regex_default().test(str)); + } + if (nonBmp) { + value || (value = getUnicodeNonBmpRegExp().test(str) || getSupplementaryPrivateUseRegExp().test(str) || getCategoryFormatRegExp().test(str)); + } + if (punctuations) { + value || (value = getPunctuationRegExp().test(str)); + } + return value; + } + var has_unicode_default = hasUnicode; + function _isIconLigature(textVNode) { + var differenceThreshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : .15; + var occurrenceThreshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3; + var nodeValue = textVNode.actualNode.nodeValue.trim(); + if (!sanitize_default(nodeValue) || has_unicode_default(nodeValue, { + emoji: true, + nonBmp: true + })) { + return false; + } + var canvasContext = cache_default.get('canvasContext', function() { + return document.createElement('canvas').getContext('2d', { + willReadFrequently: true + }); + }); + var canvas = canvasContext.canvas; + var fonts = cache_default.get('fonts', function() { + return {}; + }); + var style = window.getComputedStyle(textVNode.parent.actualNode); + var fontFamily = style.getPropertyValue('font-family'); + if (!fonts[fontFamily]) { + fonts[fontFamily] = { + occurrences: 0, + numLigatures: 0 + }; + } + var font = fonts[fontFamily]; + if (font.occurrences >= occurrenceThreshold) { + if (font.numLigatures / font.occurrences === 1) { + return true; + } else if (font.numLigatures === 0) { + return false; + } + } + font.occurrences++; + var fontSize = 30; + var fontStyle = ''.concat(fontSize, 'px ').concat(fontFamily); + canvasContext.font = fontStyle; + var firstChar = nodeValue.charAt(0); + var width = canvasContext.measureText(firstChar).width; + if (width === 0) { + font.numLigatures++; + return true; + } + if (width < 30) { + var diff = 30 / width; + width *= diff; + fontSize *= diff; + fontStyle = ''.concat(fontSize, 'px ').concat(fontFamily); + } + canvas.width = width; + canvas.height = fontSize; + canvasContext.font = fontStyle; + canvasContext.textAlign = 'left'; + canvasContext.textBaseline = 'top'; + canvasContext.fillText(firstChar, 0, 0); + var compareData = new Uint32Array(canvasContext.getImageData(0, 0, width, fontSize).data.buffer); + if (!compareData.some(function(pixel) { + return pixel; + })) { + font.numLigatures++; + return true; + } + canvasContext.clearRect(0, 0, width, fontSize); + canvasContext.fillText(nodeValue, 0, 0); + var compareWith = new Uint32Array(canvasContext.getImageData(0, 0, width, fontSize).data.buffer); + var differences = compareData.reduce(function(diff, pixel, i) { + if (pixel === 0 && compareWith[i] === 0) { + return diff; + } + if (pixel !== 0 && compareWith[i] !== 0) { + return diff; + } + return ++diff; + }, 0); + var expectedWidth = nodeValue.split('').reduce(function(totalWidth, _char2) { + return totalWidth + canvasContext.measureText(_char2).width; + }, 0); + var actualWidth = canvasContext.measureText(nodeValue).width; + var pixelDifference = differences / compareData.length; + var sizeDifference = 1 - actualWidth / expectedWidth; + if (pixelDifference >= differenceThreshold && sizeDifference >= differenceThreshold) { + font.numLigatures++; + return true; + } + return false; + } + function _accessibleTextVirtual(virtualNode) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + context = prepareContext(virtualNode, context); + if (shouldIgnoreHidden(virtualNode, context)) { + return ''; + } + if (shouldIgnoreIconLigature(virtualNode, context)) { + return ''; + } + var computationSteps = [ arialabelledby_text_default, _arialabelText, _nativeTextAlternative, form_control_value_default, subtree_text_default, textNodeValue, title_text_default ]; + var accessibleName = computationSteps.reduce(function(accName, step) { + if (context.startNode === virtualNode) { + accName = sanitize_default(accName); + } + if (accName !== '') { + return accName; + } + return step(virtualNode, context); + }, ''); + if (context.debug) { + axe.log(accessibleName || '{empty-value}', virtualNode.actualNode, context); + } + return accessibleName; + } + function textNodeValue(virtualNode) { + if (virtualNode.props.nodeType !== 3) { + return ''; + } + return virtualNode.props.nodeValue; + } + function shouldIgnoreHidden(virtualNode, context) { + if (!virtualNode) { + return false; + } + if (context.includeHidden && !nativelyHidden(virtualNode)) { + return false; + } + if (virtualNode.props.nodeType !== 1) { + return false; + } + return !_isVisibleToScreenReaders(virtualNode); + } + function shouldIgnoreIconLigature(virtualNode, context) { + var _context$occurrenceTh; + var ignoreIconLigature = context.ignoreIconLigature, pixelThreshold = context.pixelThreshold; + var occurrenceThreshold = (_context$occurrenceTh = context.occurrenceThreshold) !== null && _context$occurrenceTh !== void 0 ? _context$occurrenceTh : context.occuranceThreshold; + if (virtualNode.props.nodeType !== 3 || !ignoreIconLigature) { + return false; + } + return _isIconLigature(virtualNode, pixelThreshold, occurrenceThreshold); + } + function prepareContext(virtualNode, context) { + if (!context.startNode) { + context = _extends({ + startNode: virtualNode + }, context); + } + if (virtualNode.props.nodeType === 1 && context.inLabelledByContext && context.includeHidden === void 0) { + context = _extends({ + includeHidden: !_isVisibleToScreenReaders(virtualNode) + }, context); + } + return context; + } + _accessibleTextVirtual.alreadyProcessed = function alreadyProcessed(virtualnode, context) { + context.processed = context.processed || []; + if (context.processed.includes(virtualnode)) { + return true; + } + context.processed.push(virtualnode); + return false; + }; + function removeUnicode(str, options) { + var emoji = options.emoji, nonBmp = options.nonBmp, punctuations = options.punctuations; + if (emoji) { + str = str.replace(emoji_regex_default(), ''); + } + if (nonBmp) { + str = str.replace(getUnicodeNonBmpRegExp(), '').replace(getSupplementaryPrivateUseRegExp(), '').replace(getCategoryFormatRegExp(), ''); + } + if (punctuations) { + str = str.replace(getPunctuationRegExp(), ''); + } + return str; + } + var remove_unicode_default = removeUnicode; + function isHumanInterpretable(str) { + if (isEmpty(str) || isNonDigitCharacter(str) || isSymbolicText(str) || isUnicodeOrPunctuation(str)) { + return 0; + } + return 1; + } + function isEmpty(str) { + return sanitize_default(str).length === 0; + } + function isNonDigitCharacter(str) { + return str.length === 1 && str.match(/\D/); + } + function isSymbolicText(str) { + var symbolicText = [ 'aa', 'abc' ]; + return symbolicText.includes(str.toLowerCase()); + } + function isUnicodeOrPunctuation(str) { + var noUnicodeStr = remove_unicode_default(str, { + emoji: true, + nonBmp: true, + punctuations: true + }); + return !sanitize_default(noUnicodeStr); + } + var is_human_interpretable_default = isHumanInterpretable; + var _autocomplete = { + stateTerms: [ 'on', 'off' ], + standaloneTerms: [ 'name', 'honorific-prefix', 'given-name', 'additional-name', 'family-name', 'honorific-suffix', 'nickname', 'username', 'new-password', 'current-password', 'organization-title', 'organization', 'street-address', 'address-line1', 'address-line2', 'address-line3', 'address-level4', 'address-level3', 'address-level2', 'address-level1', 'country', 'country-name', 'postal-code', 'cc-name', 'cc-given-name', 'cc-additional-name', 'cc-family-name', 'cc-number', 'cc-exp', 'cc-exp-month', 'cc-exp-year', 'cc-csc', 'cc-type', 'transaction-currency', 'transaction-amount', 'language', 'bday', 'bday-day', 'bday-month', 'bday-year', 'sex', 'url', 'photo', 'one-time-code' ], + qualifiers: [ 'home', 'work', 'mobile', 'fax', 'pager' ], + qualifiedTerms: [ 'tel', 'tel-country-code', 'tel-national', 'tel-area-code', 'tel-local', 'tel-local-prefix', 'tel-local-suffix', 'tel-extension', 'email', 'impp' ], + locations: [ 'billing', 'shipping' ] + }; + function isValidAutocomplete(autocompleteValue) { + var _ref62 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref62$looseTyped = _ref62.looseTyped, looseTyped = _ref62$looseTyped === void 0 ? false : _ref62$looseTyped, _ref62$stateTerms = _ref62.stateTerms, stateTerms = _ref62$stateTerms === void 0 ? [] : _ref62$stateTerms, _ref62$locations = _ref62.locations, locations = _ref62$locations === void 0 ? [] : _ref62$locations, _ref62$qualifiers = _ref62.qualifiers, qualifiers = _ref62$qualifiers === void 0 ? [] : _ref62$qualifiers, _ref62$standaloneTerm = _ref62.standaloneTerms, standaloneTerms = _ref62$standaloneTerm === void 0 ? [] : _ref62$standaloneTerm, _ref62$qualifiedTerms = _ref62.qualifiedTerms, qualifiedTerms = _ref62$qualifiedTerms === void 0 ? [] : _ref62$qualifiedTerms, _ref62$ignoredValues = _ref62.ignoredValues, ignoredValues = _ref62$ignoredValues === void 0 ? [] : _ref62$ignoredValues; + autocompleteValue = autocompleteValue.toLowerCase().trim(); + stateTerms = stateTerms.concat(_autocomplete.stateTerms); + if (stateTerms.includes(autocompleteValue) || autocompleteValue === '') { + return true; + } + qualifiers = qualifiers.concat(_autocomplete.qualifiers); + locations = locations.concat(_autocomplete.locations); + standaloneTerms = standaloneTerms.concat(_autocomplete.standaloneTerms); + qualifiedTerms = qualifiedTerms.concat(_autocomplete.qualifiedTerms); + var autocompleteTerms = autocompleteValue.split(/\s+/g); + if (autocompleteTerms[autocompleteTerms.length - 1] === 'webauthn') { + autocompleteTerms.pop(); + if (autocompleteTerms.length === 0) { + return false; + } + } + if (!looseTyped) { + if (autocompleteTerms[0].length > 8 && autocompleteTerms[0].substr(0, 8) === 'section-') { + autocompleteTerms.shift(); + } + if (locations.includes(autocompleteTerms[0])) { + autocompleteTerms.shift(); + } + if (qualifiers.includes(autocompleteTerms[0])) { + autocompleteTerms.shift(); + standaloneTerms = []; + } + if (autocompleteTerms.length !== 1) { + return false; + } + } + var purposeTerm = autocompleteTerms[autocompleteTerms.length - 1]; + if (ignoredValues.includes(purposeTerm)) { + return void 0; + } + return standaloneTerms.includes(purposeTerm) || qualifiedTerms.includes(purposeTerm); + } + var is_valid_autocomplete_default = isValidAutocomplete; + function labelVirtual(virtualNode) { + var ref, candidate; + if (virtualNode.attr('aria-labelledby')) { + ref = idrefs_default(virtualNode.actualNode, 'aria-labelledby'); + candidate = ref.map(function(thing) { + var vNode = get_node_from_tree_default(thing); + return vNode ? visible_virtual_default(vNode) : ''; + }).join(' ').trim(); + if (candidate) { + return candidate; + } + } + candidate = virtualNode.attr('aria-label'); + if (candidate) { + candidate = sanitize_default(candidate); + if (candidate) { + return candidate; + } + } + return null; + } + var label_virtual_default = labelVirtual; + function visible(element, screenReader, noRecursing) { + element = get_node_from_tree_default(element); + return visible_virtual_default(element, screenReader, noRecursing); + } + var visible_default = visible; + function labelVirtual2(virtualNode) { + var ref, candidate, doc; + candidate = label_virtual_default(virtualNode); + if (candidate) { + return candidate; + } + if (virtualNode.attr('id')) { + if (!virtualNode.actualNode) { + throw new TypeError('Cannot resolve explicit label reference for non-DOM nodes'); + } + var _id2 = escape_selector_default(virtualNode.attr('id')); + doc = get_root_node_default2(virtualNode.actualNode); + ref = doc.querySelector('label[for="' + _id2 + '"]'); + candidate = ref && visible_default(ref, true); + if (candidate) { + return candidate; + } + } + ref = closest_default(virtualNode, 'label'); + candidate = ref && visible_virtual_default(ref, true); + if (candidate) { + return candidate; + } + return null; + } + var label_virtual_default2 = labelVirtual2; + function label(node) { + node = get_node_from_tree_default(node); + return label_virtual_default2(node); + } + var label_default = label; + var nativeElementType = [ { + matches: [ { + nodeName: 'textarea' + }, { + nodeName: 'input', + properties: { + type: [ 'text', 'password', 'search', 'tel', 'email', 'url' ] + } + } ], + namingMethods: 'labelText' + }, { + matches: { + nodeName: 'input', + properties: { + type: [ 'button', 'submit', 'reset' ] + } + }, + namingMethods: [ 'valueText', 'titleText', 'buttonDefaultText' ] + }, { + matches: { + nodeName: 'input', + properties: { + type: 'image' + } + }, + namingMethods: [ 'altText', 'valueText', 'labelText', 'titleText', 'buttonDefaultText' ] + }, { + matches: 'button', + namingMethods: 'subtreeText' + }, { + matches: 'fieldset', + namingMethods: 'fieldsetLegendText' + }, { + matches: 'OUTPUT', + namingMethods: 'subtreeText' + }, { + matches: [ { + nodeName: 'select' + }, { + nodeName: 'input', + properties: { + type: /^(?!text|password|search|tel|email|url|button|submit|reset)/ + } + } ], + namingMethods: 'labelText' + }, { + matches: 'summary', + namingMethods: 'subtreeText' + }, { + matches: 'figure', + namingMethods: [ 'figureText', 'titleText' ] + }, { + matches: 'img', + namingMethods: 'altText' + }, { + matches: 'table', + namingMethods: [ 'tableCaptionText', 'tableSummaryText' ] + }, { + matches: [ 'hr', 'br' ], + namingMethods: [ 'titleText', 'singleSpace' ] + } ]; + var native_element_type_default = nativeElementType; + function visibleTextNodes(vNode) { + var parentVisible = _isVisibleOnScreen(vNode); + var nodes = []; + vNode.children.forEach(function(child) { + if (child.actualNode.nodeType === 3) { + if (parentVisible) { + nodes.push(child); + } + } else { + nodes = nodes.concat(visibleTextNodes(child)); + } + }); + return nodes; + } + var visible_text_nodes_default = visibleTextNodes; + var getVisibleChildTextRects = memoize_default(function getVisibleChildTextRectsMemoized(node) { + var vNode = get_node_from_tree_default(node); + var nodeRect = vNode.boundingClientRect; + var clientRects = []; + var overflowHiddenNodes = get_overflow_hidden_ancestors_default(vNode); + node.childNodes.forEach(function(textNode) { + if (textNode.nodeType !== 3 || sanitize_default(textNode.nodeValue) === '') { + return; + } + var contentRects = getContentRects(textNode); + if (isOutsideNodeBounds(contentRects, nodeRect)) { + return; + } + clientRects.push.apply(clientRects, _toConsumableArray(filterHiddenRects(contentRects, overflowHiddenNodes))); + }); + return clientRects.length ? clientRects : filterHiddenRects([ nodeRect ], overflowHiddenNodes); + }); + var get_visible_child_text_rects_default = getVisibleChildTextRects; + function getContentRects(node) { + var range2 = document.createRange(); + range2.selectNodeContents(node); + return Array.from(range2.getClientRects()); + } + function isOutsideNodeBounds(rects, nodeRect) { + return rects.some(function(rect) { + var centerPoint = _getRectCenter(rect); + return !_isPointInRect(centerPoint, nodeRect); + }); + } + function filterHiddenRects(contentRects, overflowHiddenNodes) { + var visibleRects = []; + contentRects.forEach(function(contentRect) { + if (contentRect.width < 1 || contentRect.height < 1) { + return; + } + var visibleRect = overflowHiddenNodes.reduce(function(rect, overflowNode) { + return rect && _getIntersectionRect(rect, overflowNode.boundingClientRect); + }, contentRect); + if (visibleRect) { + visibleRects.push(visibleRect); + } + }); + return visibleRects; + } + function getTextElementStack(node) { + var grid = _getNodeGrid(node); + if (!grid) { + return []; + } + var clientRects = get_visible_child_text_rects_default(node); + return clientRects.map(function(rect) { + return getRectStack(grid, rect); + }); + } + var get_text_element_stack_default = getTextElementStack; + var visualRoles = [ 'checkbox', 'img', 'meter', 'progressbar', 'scrollbar', 'radio', 'slider', 'spinbutton', 'textbox' ]; + function isVisualContent(el) { + var _nodeLookup19 = _nodeLookup(el), vNode = _nodeLookup19.vNode; + var role = axe.commons.aria.getExplicitRole(vNode); + if (role) { + return visualRoles.indexOf(role) !== -1; + } + switch (vNode.props.nodeName) { + case 'img': + case 'iframe': + case 'object': + case 'video': + case 'audio': + case 'canvas': + case 'svg': + case 'math': + case 'button': + case 'select': + case 'textarea': + case 'keygen': + case 'progress': + case 'meter': + return true; + + case 'input': + return vNode.props.type !== 'hidden'; + + default: + return false; + } + } + var is_visual_content_default = isVisualContent; + var hiddenTextElms = [ 'head', 'title', 'template', 'script', 'style', 'iframe', 'object', 'video', 'audio', 'noscript' ]; + function hasChildTextNodes(elm) { + if (hiddenTextElms.includes(elm.props.nodeName)) { + return false; + } + return elm.children.some(function(_ref63) { + var props = _ref63.props; + return props.nodeType === 3 && props.nodeValue.trim(); + }); + } + function hasContentVirtual(elm, noRecursion, ignoreAria) { + return hasChildTextNodes(elm) || is_visual_content_default(elm.actualNode) || !ignoreAria && !!label_virtual_default(elm) || !noRecursion && elm.children.some(function(child) { + return child.actualNode.nodeType === 1 && hasContentVirtual(child); + }); + } + var has_content_virtual_default = hasContentVirtual; + function hasContent(elm, noRecursion, ignoreAria) { + elm = get_node_from_tree_default(elm); + return has_content_virtual_default(elm, noRecursion, ignoreAria); + } + var has_content_default = hasContent; + function _hasLangText(virtualNode) { + if (typeof virtualNode.children === 'undefined' || hasChildTextNodes(virtualNode)) { + return true; + } + if (virtualNode.props.nodeType === 1 && is_visual_content_default(virtualNode)) { + return !!axe.commons.text.accessibleTextVirtual(virtualNode); + } + return virtualNode.children.some(function(child) { + return !child.attr('lang') && _hasLangText(child) && !_isHiddenForEveryone(child); + }); + } + function insertedIntoFocusOrder(el) { + var tabIndex = parse_tabindex_default(el.getAttribute('tabindex')); + return tabIndex > -1 && _isFocusable(el) && !is_natively_focusable_default(el); + } + var inserted_into_focus_order_default = insertedIntoFocusOrder; + function isHiddenWithCSS(el, descendentVisibilityValue) { + var _nodeLookup20 = _nodeLookup(el), vNode = _nodeLookup20.vNode, domNode = _nodeLookup20.domNode; + if (!vNode) { + return _isHiddenWithCSS(domNode, descendentVisibilityValue); + } + if (vNode._isHiddenWithCSS === void 0) { + vNode._isHiddenWithCSS = _isHiddenWithCSS(domNode, descendentVisibilityValue); + } + return vNode._isHiddenWithCSS; + } + function _isHiddenWithCSS(el, descendentVisibilityValue) { + if (el.nodeType === 9) { + return false; + } + if (el.nodeType === 11) { + el = el.host; + } + if ([ 'STYLE', 'SCRIPT' ].includes(el.nodeName.toUpperCase())) { + return false; + } + var style = window.getComputedStyle(el, null); + if (!style) { + throw new Error('Style does not exist for the given element.'); + } + var displayValue = style.getPropertyValue('display'); + if (displayValue === 'none') { + return true; + } + var HIDDEN_VISIBILITY_VALUES = [ 'hidden', 'collapse' ]; + var visibilityValue = style.getPropertyValue('visibility'); + if (HIDDEN_VISIBILITY_VALUES.includes(visibilityValue) && !descendentVisibilityValue) { + return true; + } + if (HIDDEN_VISIBILITY_VALUES.includes(visibilityValue) && descendentVisibilityValue && HIDDEN_VISIBILITY_VALUES.includes(descendentVisibilityValue)) { + return true; + } + var parent = get_composed_parent_default(el); + if (parent && !HIDDEN_VISIBILITY_VALUES.includes(visibilityValue)) { + return isHiddenWithCSS(parent, visibilityValue); + } + return false; + } + var is_hidden_with_css_default = isHiddenWithCSS; + function isHTML5(doc) { + var node = doc.doctype; + if (node === null) { + return false; + } + return node.name === 'html' && !node.publicId && !node.systemId; + } + var is_html5_default = isHTML5; + function getRoleType(role) { + var _window3; + if (role instanceof abstract_virtual_node_default || (_window3 = window) !== null && _window3 !== void 0 && _window3.Node && role instanceof window.Node) { + role = axe.commons.aria.getRole(role); + } + var roleDef = standards_default.ariaRoles[role]; + return (roleDef === null || roleDef === void 0 ? void 0 : roleDef.type) || null; + } + var get_role_type_default = getRoleType; + var blockLike = [ 'block', 'list-item', 'table', 'flex', 'grid' ]; + var inlineBlockLike = [ 'inline-block', 'inline-flex', 'inline-grid' ]; + function isInTextBlock(node) { + var _ref64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, noLengthCompare = _ref64.noLengthCompare, _ref64$includeInlineB = _ref64.includeInlineBlock, includeInlineBlock = _ref64$includeInlineB === void 0 ? false : _ref64$includeInlineB; + var _nodeLookup21 = _nodeLookup(node), vNode = _nodeLookup21.vNode, domNode = _nodeLookup21.domNode; + if (isBlock(domNode) || !includeInlineBlock && isInlineBlockLike(vNode)) { + return false; + } + var virtualParent = getBlockParent(domNode); + var parentText = ''; + var widgetText = ''; + var inBrBlock = 0; + walkDomNode(virtualParent, function(currNode) { + if (currNode === virtualParent.actualNode) { + return true; + } + if (inBrBlock === 2) { + return false; + } + if (currNode.nodeType === 3) { + parentText += currNode.nodeValue; + } + if (currNode.nodeType !== 1) { + return; + } + var nodeName2 = (currNode.nodeName || '').toUpperCase(); + if (currNode === domNode) { + inBrBlock = 1; + } + var nodeIsBlock = isBlock(currNode); + if (nodeIsBlock || [ 'BR', 'HR' ].includes(nodeName2)) { + if (inBrBlock === 0) { + parentText = ''; + widgetText = ''; + } else { + inBrBlock = 2; + } + } + if (nodeIsBlock || currNode.style.display === 'none' || currNode.style.overflow === 'hidden' || ![ '', null, 'none' ].includes(currNode.style['float']) || ![ '', null, 'relative' ].includes(currNode.style.position)) { + return false; + } else if (get_role_type_default(currNode) === 'widget') { + widgetText += currNode.textContent; + return false; + } + }); + parentText = sanitize_default(parentText); + if (noLengthCompare) { + return parentText.length !== 0; + } + widgetText = sanitize_default(widgetText); + return parentText.length > widgetText.length; + } + var is_in_text_block_default = isInTextBlock; + function isBlock(node) { + var _nodeLookup22 = _nodeLookup(node), vNode = _nodeLookup22.vNode; + var display2 = vNode.getComputedStylePropertyValue('display'); + return blockLike.includes(display2) || display2.substr(0, 6) === 'table-'; + } + function isInlineBlockLike(vNode) { + var display2 = vNode.getComputedStylePropertyValue('display'); + return inlineBlockLike.includes(display2); + } + function walkDomNode(node, functor) { + if (functor(node.actualNode) !== false) { + node.children.forEach(function(child) { + return walkDomNode(child, functor); + }); + } + } + function getBlockParent(node) { + var parentBlock = get_composed_parent_default(node); + while (parentBlock && !isBlock(parentBlock)) { + parentBlock = get_composed_parent_default(parentBlock); + } + return get_node_from_tree_default(parentBlock); + } + function isModalOpen(options) { + options = options || {}; + var modalPercent = options.modalPercent || .75; + if (cache_default.get('isModalOpen')) { + return cache_default.get('isModalOpen'); + } + var definiteModals = query_selector_all_filter_default(axe._tree[0], 'dialog, [role=dialog], [aria-modal=true]', _isVisibleOnScreen); + if (definiteModals.length) { + cache_default.set('isModalOpen', true); + return true; + } + var viewport = get_viewport_size_default(window); + var percentWidth = viewport.width * modalPercent; + var percentHeight = viewport.height * modalPercent; + var x = (viewport.width - percentWidth) / 2; + var y = (viewport.height - percentHeight) / 2; + var points = [ { + x: x, + y: y + }, { + x: viewport.width - x, + y: y + }, { + x: viewport.width / 2, + y: viewport.height / 2 + }, { + x: x, + y: viewport.height - y + }, { + x: viewport.width - x, + y: viewport.height - y + } ]; + var stacks = points.map(function(point) { + return Array.from(document.elementsFromPoint(point.x, point.y)); + }); + var _loop7 = function _loop7() { + var modalElement = stacks[_i13].find(function(elm) { + var style = window.getComputedStyle(elm); + return parseInt(style.width, 10) >= percentWidth && parseInt(style.height, 10) >= percentHeight && style.getPropertyValue('pointer-events') !== 'none' && (style.position === 'absolute' || style.position === 'fixed'); + }); + if (modalElement && stacks.every(function(stack) { + return stack.includes(modalElement); + })) { + cache_default.set('isModalOpen', true); + return { + v: true + }; + } + }, _ret3; + for (var _i13 = 0; _i13 < stacks.length; _i13++) { + _ret3 = _loop7(); + if (_ret3) { + return _ret3.v; + } + } + cache_default.set('isModalOpen', void 0); + return void 0; + } + var is_modal_open_default = isModalOpen; + function _isMultiline(domNode) { + var margin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; + var range2 = domNode.ownerDocument.createRange(); + range2.setStart(domNode, 0); + range2.setEnd(domNode, domNode.childNodes.length); + var lastLineEnd = 0; + var lineCount = 0; + var _iterator1 = _createForOfIteratorHelper(range2.getClientRects()), _step1; + try { + for (_iterator1.s(); !(_step1 = _iterator1.n()).done; ) { + var rect = _step1.value; + if (rect.height <= margin) { + continue; + } + if (lastLineEnd > rect.top + margin) { + lastLineEnd = Math.max(lastLineEnd, rect.bottom); + } else if (lineCount === 0) { + lastLineEnd = rect.bottom; + lineCount++; + } else { + return true; + } + } + } catch (err) { + _iterator1.e(err); + } finally { + _iterator1.f(); + } + return false; + } + function isNode(element) { + return element instanceof window.Node; + } + var is_node_default = isNode; + var cacheKey = 'color.incompleteData'; + var incompleteData = { + set: function set(key, reason) { + if (typeof key !== 'string') { + throw new Error('Incomplete data: key must be a string'); + } + var data = cache_default.get(cacheKey, function() { + return {}; + }); + if (reason) { + data[key] = reason; + } + return data[key]; + }, + get: function get(key) { + var data = cache_default.get(cacheKey); + return data === null || data === void 0 ? void 0 : data[key]; + }, + clear: function clear() { + cache_default.set(cacheKey, {}); + } + }; + var incomplete_data_default = incompleteData; + function elementHasImage(elm, style) { + var graphicNodes = [ 'IMG', 'CANVAS', 'OBJECT', 'IFRAME', 'VIDEO', 'SVG' ]; + var nodeName2 = elm.nodeName.toUpperCase(); + if (graphicNodes.includes(nodeName2)) { + incomplete_data_default.set('bgColor', 'imgNode'); + return true; + } + style = style || window.getComputedStyle(elm); + var bgImageStyle = style.getPropertyValue('background-image'); + var hasBgImage = bgImageStyle !== 'none'; + if (hasBgImage) { + var hasGradient = /gradient/.test(bgImageStyle); + incomplete_data_default.set('bgColor', hasGradient ? 'bgGradient' : 'bgImage'); + } + return hasBgImage; + } + var element_has_image_default = elementHasImage; + var hexRegex = /^#[0-9a-f]{3,8}$/i; + var hslRegex = /hsl\(\s*([-\d.]+)(rad|turn)/; + var _Color2 = (_r = new WeakMap(), _g = new WeakMap(), _b = new WeakMap(), _red = new WeakMap(), + _green = new WeakMap(), _blue = new WeakMap(), _Class3_brand = new WeakSet(), + function() { + function Color2(red, green, blue) { + var alpha = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + _classCallCheck(this, Color2); + _classPrivateMethodInitSpec(this, _Class3_brand); + _classPrivateFieldInitSpec(this, _r, void 0); + _classPrivateFieldInitSpec(this, _g, void 0); + _classPrivateFieldInitSpec(this, _b, void 0); + _classPrivateFieldInitSpec(this, _red, void 0); + _classPrivateFieldInitSpec(this, _green, void 0); + _classPrivateFieldInitSpec(this, _blue, void 0); + if (red instanceof _Color2) { + var r = red.r, g2 = red.g, b2 = red.b; + this.r = r; + this.g = g2; + this.b = b2; + this.alpha = red.alpha; + return; + } + this.red = red; + this.green = green; + this.blue = blue; + this.alpha = alpha; + } + return _createClass(Color2, [ { + key: 'r', + get: function get() { + return _classPrivateFieldGet(_r, this); + }, + set: function set(value) { + _classPrivateFieldSet(_r, this, value); + _classPrivateFieldSet(_red, this, Math.round(clamp(value, 0, 1) * 255)); + } + }, { + key: 'g', + get: function get() { + return _classPrivateFieldGet(_g, this); + }, + set: function set(value) { + _classPrivateFieldSet(_g, this, value); + _classPrivateFieldSet(_green, this, Math.round(clamp(value, 0, 1) * 255)); + } + }, { + key: 'b', + get: function get() { + return _classPrivateFieldGet(_b, this); + }, + set: function set(value) { + _classPrivateFieldSet(_b, this, value); + _classPrivateFieldSet(_blue, this, Math.round(clamp(value, 0, 1) * 255)); + } + }, { + key: 'red', + get: function get() { + return _classPrivateFieldGet(_red, this); + }, + set: function set(value) { + _classPrivateFieldSet(_r, this, value / 255); + _classPrivateFieldSet(_red, this, clamp(value, 0, 255)); + } + }, { + key: 'green', + get: function get() { + return _classPrivateFieldGet(_green, this); + }, + set: function set(value) { + _classPrivateFieldSet(_g, this, value / 255); + _classPrivateFieldSet(_green, this, clamp(value, 0, 255)); + } + }, { + key: 'blue', + get: function get() { + return _classPrivateFieldGet(_blue, this); + }, + set: function set(value) { + _classPrivateFieldSet(_b, this, value / 255); + _classPrivateFieldSet(_blue, this, clamp(value, 0, 255)); + } + }, { + key: 'toHexString', + value: function toHexString() { + var redString = Math.round(this.red).toString(16); + var greenString = Math.round(this.green).toString(16); + var blueString = Math.round(this.blue).toString(16); + return '#' + (this.red > 15.5 ? redString : '0' + redString) + (this.green > 15.5 ? greenString : '0' + greenString) + (this.blue > 15.5 ? blueString : '0' + blueString); + } + }, { + key: 'toJSON', + value: function toJSON() { + var red = this.red, green = this.green, blue = this.blue, alpha = this.alpha; + return { + red: red, + green: green, + blue: blue, + alpha: alpha + }; + } + }, { + key: 'parseString', + value: function parseString(colorString) { + colorString = colorString.replace(hslRegex, function(match, angle, unit) { + var value = angle + unit; + switch (unit) { + case 'rad': + return match.replace(value, radToDeg(angle)); + + case 'turn': + return match.replace(value, turnToDeg(angle)); + } + }); + try { + var prototypeArrayFrom; + if ('Prototype' in window && 'Version' in window.Prototype) { + prototypeArrayFrom = Array.from; + Array.from = import_from2['default']; + } + var _color2 = new _Color(colorString).toGamut({ + space: 'srgb', + method: 'clip' + }).to('srgb'); + if (prototypeArrayFrom) { + Array.from = prototypeArrayFrom; + prototypeArrayFrom = null; + } + this.r = _color2.r; + this.g = _color2.g; + this.b = _color2.b; + this.alpha = +_color2.alpha; + } catch (_unused4) { + incomplete_data_default.set('colorParse', colorString); + throw new Error('Unable to parse color "'.concat(colorString, '"')); + } + return this; + } + }, { + key: 'parseRgbString', + value: function parseRgbString(colorString) { + this.parseString(colorString); + } + }, { + key: 'parseHexString', + value: function parseHexString(colorString) { + if (!colorString.match(hexRegex) || [ 6, 8 ].includes(colorString.length)) { + return; + } + this.parseString(colorString); + } + }, { + key: 'parseColorFnString', + value: function parseColorFnString(colorString) { + this.parseString(colorString); + } + }, { + key: 'getRelativeLuminance', + value: function getRelativeLuminance() { + var rSRGB = this.r, gSRGB = this.g, bSRGB = this.b; + var r = rSRGB <= .04045 ? rSRGB / 12.92 : Math.pow((rSRGB + .055) / 1.055, 2.4); + var g2 = gSRGB <= .04045 ? gSRGB / 12.92 : Math.pow((gSRGB + .055) / 1.055, 2.4); + var b2 = bSRGB <= .04045 ? bSRGB / 12.92 : Math.pow((bSRGB + .055) / 1.055, 2.4); + return .2126 * r + .7152 * g2 + .0722 * b2; + } + }, { + key: 'getLuminosity', + value: function getLuminosity() { + return .3 * this.r + .59 * this.g + .11 * this.b; + } + }, { + key: 'setLuminosity', + value: function setLuminosity(L) { + var d2 = L - this.getLuminosity(); + return _assertClassBrand(_Class3_brand, this, _add).call(this, d2).clip(); + } + }, { + key: 'getSaturation', + value: function getSaturation() { + return Math.max(this.r, this.g, this.b) - Math.min(this.r, this.g, this.b); + } + }, { + key: 'setSaturation', + value: function setSaturation(s) { + var C = new _Color2(this); + var colorEntires = [ { + name: 'r', + value: C.r + }, { + name: 'g', + value: C.g + }, { + name: 'b', + value: C.b + } ]; + var _colorEntires$sort = colorEntires.sort(function(a2, b2) { + return a2.value - b2.value; + }), _colorEntires$sort2 = _slicedToArray(_colorEntires$sort, 3), Cmin = _colorEntires$sort2[0], Cmid = _colorEntires$sort2[1], Cmax = _colorEntires$sort2[2]; + if (Cmax.value > Cmin.value) { + Cmid.value = (Cmid.value - Cmin.value) * s / (Cmax.value - Cmin.value); + Cmax.value = s; + } else { + Cmid.value = Cmax.value = 0; + } + Cmin.value = 0; + C[Cmax.name] = Cmax.value; + C[Cmin.name] = Cmin.value; + C[Cmid.name] = Cmid.value; + return C; + } + }, { + key: 'clip', + value: function clip() { + var C = new _Color2(this); + var L = C.getLuminosity(); + var n2 = Math.min(C.r, C.g, C.b); + var x = Math.max(C.r, C.g, C.b); + if (n2 < 0) { + C.r = L + (C.r - L) * L / (L - n2); + C.g = L + (C.g - L) * L / (L - n2); + C.b = L + (C.b - L) * L / (L - n2); + } + if (x > 1) { + C.r = L + (C.r - L) * (1 - L) / (x - L); + C.g = L + (C.g - L) * (1 - L) / (x - L); + C.b = L + (C.b - L) * (1 - L) / (x - L); + } + return C; + } + } ]); + }()); + function _add(value) { + var C = new _Color2(this); + C.r += value; + C.g += value; + C.b += value; + return C; + } + var color_default = _Color2; + function clamp(value, min, max2) { + return Math.min(Math.max(min, value), max2); + } + function radToDeg(rad) { + return rad * 180 / Math.PI; + } + function turnToDeg(turn) { + return turn * 360; + } + function getOwnBackgroundColor(elmStyle) { + var bgColor = new color_default(); + bgColor.parseString(elmStyle.getPropertyValue('background-color')); + if (bgColor.alpha !== 0) { + var opacity = elmStyle.getPropertyValue('opacity'); + bgColor.alpha = bgColor.alpha * opacity; + } + return bgColor; + } + var get_own_background_color_default = getOwnBackgroundColor; + function isOpaque(node) { + var style = window.getComputedStyle(node); + return element_has_image_default(node, style) || get_own_background_color_default(style).alpha === 1; + } + var is_opaque_default = isOpaque; + function _isSkipLink(element) { + if (!element.href) { + return false; + } + var firstPageLink = cache_default.get('firstPageLink', generateFirstPageLink); + if (!firstPageLink) { + return true; + } + return element.compareDocumentPosition(firstPageLink.actualNode) === element.DOCUMENT_POSITION_FOLLOWING; + } + function generateFirstPageLink() { + var firstPageLink; + if (!window.location.origin) { + firstPageLink = query_selector_all_default(axe._tree, 'a:not([href^="#"]):not([href^="/#"]):not([href^="javascript:"])')[0]; + } else { + firstPageLink = query_selector_all_default(axe._tree, 'a[href]:not([href^="javascript:"])').find(function(link) { + return !_isCurrentPageLink(link.actualNode); + }); + } + return firstPageLink || null; + } + var clipRegex2 = /rect\s*\(([0-9]+)px,?\s*([0-9]+)px,?\s*([0-9]+)px,?\s*([0-9]+)px\s*\)/; + var clipPathRegex2 = /(\w+)\((\d+)/; + function isClipped(style) { + var matchesClip = style.getPropertyValue('clip').match(clipRegex2); + var matchesClipPath = style.getPropertyValue('clip-path').match(clipPathRegex2); + if (matchesClip && matchesClip.length === 5) { + var position = style.getPropertyValue('position'); + if ([ 'fixed', 'absolute' ].includes(position)) { + return matchesClip[3] - matchesClip[1] <= 0 && matchesClip[2] - matchesClip[4] <= 0; + } + } + if (matchesClipPath) { + var type2 = matchesClipPath[1]; + var value = parseInt(matchesClipPath[2], 10); + switch (type2) { + case 'inset': + return value >= 50; + + case 'circle': + return value === 0; + + default: + } + } + return false; + } + function isAreaVisible(el, screenReader, recursed) { + var mapEl = find_up_default(el, 'map'); + if (!mapEl) { + return false; + } + var mapElName = mapEl.getAttribute('name'); + if (!mapElName) { + return false; + } + var mapElRootNode = get_root_node_default2(el); + if (!mapElRootNode || mapElRootNode.nodeType !== 9) { + return false; + } + var refs = query_selector_all_default(axe._tree, 'img[usemap="#'.concat(escape_selector_default(mapElName), '"]')); + if (!refs || !refs.length) { + return false; + } + return refs.some(function(_ref65) { + var actualNode = _ref65.actualNode; + return isVisible(actualNode, screenReader, recursed); + }); + } + function isVisible(el, screenReader, recursed) { + var _window$Node2; + if (!el) { + throw new TypeError('Cannot determine if element is visible for non-DOM nodes'); + } + var vNode = el instanceof abstract_virtual_node_default ? el : get_node_from_tree_default(el); + el = vNode ? vNode.actualNode : el; + var cacheName = '_isVisible' + (screenReader ? 'ScreenReader' : ''); + var _ref66 = (_window$Node2 = window.Node) !== null && _window$Node2 !== void 0 ? _window$Node2 : {}, DOCUMENT_NODE = _ref66.DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE = _ref66.DOCUMENT_FRAGMENT_NODE; + var nodeType = vNode ? vNode.props.nodeType : el.nodeType; + var nodeName2 = vNode ? vNode.props.nodeName : el.nodeName.toLowerCase(); + if (vNode && typeof vNode[cacheName] !== 'undefined') { + return vNode[cacheName]; + } + if (nodeType === DOCUMENT_NODE) { + return true; + } + if ([ 'style', 'script', 'noscript', 'template' ].includes(nodeName2)) { + return false; + } + if (el && nodeType === DOCUMENT_FRAGMENT_NODE) { + el = el.host; + } + if (screenReader) { + var ariaHiddenValue = vNode ? vNode.attr('aria-hidden') : el.getAttribute('aria-hidden'); + if (ariaHiddenValue === 'true') { + return false; + } + } + if (!el) { + var parent2 = vNode.parent; + var visible3 = true; + if (parent2) { + visible3 = isVisible(parent2, screenReader, true); + } + if (vNode) { + vNode[cacheName] = visible3; + } + return visible3; + } + var style = window.getComputedStyle(el, null); + if (style === null) { + return false; + } + if (nodeName2 === 'area') { + return isAreaVisible(el, screenReader, recursed); + } + if (style.getPropertyValue('display') === 'none') { + return false; + } + var elHeight = parseInt(style.getPropertyValue('height')); + var elWidth = parseInt(style.getPropertyValue('width')); + var scroll = get_scroll_default(el); + var scrollableWithZeroHeight = scroll && elHeight === 0; + var scrollableWithZeroWidth = scroll && elWidth === 0; + var posAbsoluteOverflowHiddenAndSmall = style.getPropertyValue('position') === 'absolute' && (elHeight < 2 || elWidth < 2) && style.getPropertyValue('overflow') === 'hidden'; + if (!screenReader && (isClipped(style) || style.getPropertyValue('opacity') === '0' || scrollableWithZeroHeight || scrollableWithZeroWidth || posAbsoluteOverflowHiddenAndSmall)) { + return false; + } + if (!recursed && (style.getPropertyValue('visibility') === 'hidden' || !screenReader && is_offscreen_default(el))) { + return false; + } + var parent = el.assignedSlot ? el.assignedSlot : el.parentNode; + var visible2 = false; + if (parent) { + visible2 = isVisible(parent, screenReader, true); + } + if (vNode) { + vNode[cacheName] = visible2; + } + return visible2; + } + var is_visible_default = isVisible; + function reduceToElementsBelowFloating(elements, targetNode) { + var floatingPositions = [ 'fixed', 'sticky' ]; + var finalElements = []; + var targetFound = false; + for (var index = 0; index < elements.length; ++index) { + var currentNode = elements[index]; + if (currentNode === targetNode) { + targetFound = true; + } + var style = window.getComputedStyle(currentNode); + if (!targetFound && floatingPositions.indexOf(style.position) !== -1) { + finalElements = []; + continue; + } + finalElements.push(currentNode); + } + return finalElements; + } + var reduce_to_elements_below_floating_default = reduceToElementsBelowFloating; + function _visuallyContains(node, parent) { + var parentScrollAncestor = getScrollAncestor(parent); + do { + var nextScrollAncestor = getScrollAncestor(node); + if (nextScrollAncestor === parentScrollAncestor || nextScrollAncestor === parent) { + return contains2(node, parent); + } + node = nextScrollAncestor; + } while (node); + return false; + } + function getScrollAncestor(node) { + var vNode = get_node_from_tree_default(node); + var ancestor = vNode.parent; + while (ancestor) { + if (get_scroll_default(ancestor.actualNode)) { + return ancestor.actualNode; + } + ancestor = ancestor.parent; + } + } + function contains2(node, parent) { + var style = window.getComputedStyle(parent); + var overflow = style.getPropertyValue('overflow'); + if (style.getPropertyValue('display') === 'inline') { + return true; + } + var clientRects = Array.from(node.getClientRects()); + var boundingRect = parent.getBoundingClientRect(); + var rect = { + left: boundingRect.left, + top: boundingRect.top, + width: boundingRect.width, + height: boundingRect.height + }; + if ([ 'scroll', 'auto' ].includes(overflow) || parent instanceof window.HTMLHtmlElement) { + rect.width = parent.scrollWidth; + rect.height = parent.scrollHeight; + } + if (clientRects.length === 1 && overflow === 'hidden' && style.getPropertyValue('white-space') === 'nowrap') { + clientRects[0] = rect; + } + return clientRects.some(function(clientRect) { + return !(Math.ceil(clientRect.left) < Math.floor(rect.left) || Math.ceil(clientRect.top) < Math.floor(rect.top) || Math.floor(clientRect.left + clientRect.width) > Math.ceil(rect.left + rect.width) || Math.floor(clientRect.top + clientRect.height) > Math.ceil(rect.top + rect.height)); + }); + } + function shadowElementsFromPoint(nodeX, nodeY) { + var root = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document; + var i = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + if (i > 999) { + throw new Error('Infinite loop detected'); + } + return Array.from(root.elementsFromPoint(nodeX, nodeY) || []).filter(function(nodes) { + return get_root_node_default2(nodes) === root; + }).reduce(function(stack, elm) { + if (is_shadow_root_default(elm)) { + var shadowStack = shadowElementsFromPoint(nodeX, nodeY, elm.shadowRoot, i + 1); + stack = stack.concat(shadowStack); + if (stack.length && _visuallyContains(stack[0], elm)) { + stack.push(elm); + } + } else { + stack.push(elm); + } + return stack; + }, []); + } + var shadow_elements_from_point_default = shadowElementsFromPoint; + function urlPropsFromAttribute(node, attribute) { + if (!node.hasAttribute(attribute)) { + return void 0; + } + var nodeName2 = node.nodeName.toUpperCase(); + var parser2 = node; + if (![ 'A', 'AREA' ].includes(nodeName2) || node.ownerSVGElement) { + parser2 = document.createElement('a'); + parser2.href = node.getAttribute(attribute); + } + var protocol = [ 'https:', 'ftps:' ].includes(parser2.protocol) ? parser2.protocol.replace(/s:$/, ':') : parser2.protocol; + var parserPathname = /^\//.test(parser2.pathname) ? parser2.pathname : '/'.concat(parser2.pathname); + var _getPathnameOrFilenam = getPathnameOrFilename(parserPathname), pathname = _getPathnameOrFilenam.pathname, filename = _getPathnameOrFilenam.filename; + return { + protocol: protocol, + hostname: parser2.hostname, + port: getPort(parser2.port), + pathname: /\/$/.test(pathname) ? pathname : ''.concat(pathname, '/'), + search: getSearchPairs(parser2.search), + hash: getHashRoute(parser2.hash), + filename: filename + }; + } + function getPort(port) { + var excludePorts = [ '443', '80' ]; + return !excludePorts.includes(port) ? port : ''; + } + function getPathnameOrFilename(pathname) { + var filename = pathname.split('/').pop(); + if (!filename || filename.indexOf('.') === -1) { + return { + pathname: pathname, + filename: '' + }; + } + return { + pathname: pathname.replace(filename, ''), + filename: /index./.test(filename) ? '' : filename + }; + } + function getSearchPairs(searchStr) { + var query = {}; + if (!searchStr || !searchStr.length) { + return query; + } + var pairs = searchStr.substring(1).split('&'); + if (!pairs || !pairs.length) { + return query; + } + for (var index = 0; index < pairs.length; index++) { + var pair = pairs[index]; + var _pair$split = pair.split('='), _pair$split2 = _slicedToArray(_pair$split, 2), _key9 = _pair$split2[0], _pair$split2$ = _pair$split2[1], value = _pair$split2$ === void 0 ? '' : _pair$split2$; + query[decodeURIComponent(_key9)] = decodeURIComponent(value); + } + return query; + } + function getHashRoute(hash) { + if (!hash) { + return ''; + } + var hashRegex = /#!?\/?/g; + var hasMatch = hash.match(hashRegex); + if (!hasMatch) { + return ''; + } + var _hasMatch = _slicedToArray(hasMatch, 1), matchedStr = _hasMatch[0]; + if (matchedStr === '#') { + return ''; + } + return hash; + } + var url_props_from_attribute_default = urlPropsFromAttribute; + function visuallyOverlaps(rect, parent) { + var parentRect = parent.getBoundingClientRect(); + var parentTop = parentRect.top; + var parentLeft = parentRect.left; + var parentScrollArea = { + top: parentTop - parent.scrollTop, + bottom: parentTop - parent.scrollTop + parent.scrollHeight, + left: parentLeft - parent.scrollLeft, + right: parentLeft - parent.scrollLeft + parent.scrollWidth + }; + if (rect.left > parentScrollArea.right && rect.left > parentRect.right || rect.top > parentScrollArea.bottom && rect.top > parentRect.bottom || rect.right < parentScrollArea.left && rect.right < parentRect.left || rect.bottom < parentScrollArea.top && rect.bottom < parentRect.top) { + return false; + } + var style = window.getComputedStyle(parent); + if (rect.left > parentRect.right || rect.top > parentRect.bottom) { + return style.overflow === 'scroll' || style.overflow === 'auto' || parent instanceof window.HTMLBodyElement || parent instanceof window.HTMLHtmlElement; + } + return true; + } + var visually_overlaps_default = visuallyOverlaps; + var nodeIndex2 = 0; + var VirtualNode = function(_abstract_virtual_nod) { + function VirtualNode(node, parent, shadowId) { + var _this4; + _classCallCheck(this, VirtualNode); + _this4 = _callSuper(this, VirtualNode); + _this4.shadowId = shadowId; + _this4.children = []; + _this4.actualNode = node; + _this4.parent = parent; + if (!parent) { + nodeIndex2 = 0; + } + _this4.nodeIndex = nodeIndex2++; + _this4._isHidden = null; + _this4._cache = {}; + _this4._isXHTML = is_xhtml_default(node.ownerDocument); + if (node.nodeName.toLowerCase() === 'input') { + var type2 = node.getAttribute('type'); + type2 = _this4._isXHTML ? type2 : (type2 || '').toLowerCase(); + if (!valid_input_type_default().includes(type2)) { + type2 = 'text'; + } + _this4._type = type2; + } + if (cache_default.get('nodeMap')) { + cache_default.get('nodeMap').set(node, _this4); + } + return _this4; + } + _inherits(VirtualNode, _abstract_virtual_nod); + return _createClass(VirtualNode, [ { + key: 'props', + get: function get() { + if (!this._cache.hasOwnProperty('props')) { + var _this$actualNode = this.actualNode, nodeType = _this$actualNode.nodeType, nodeName2 = _this$actualNode.nodeName, _id3 = _this$actualNode.id, nodeValue = _this$actualNode.nodeValue; + this._cache.props = { + nodeType: nodeType, + nodeName: this._isXHTML ? nodeName2 : nodeName2.toLowerCase(), + id: _id3, + type: this._type, + nodeValue: nodeValue + }; + if (nodeType === 1) { + this._cache.props.multiple = this.actualNode.multiple; + this._cache.props.value = this.actualNode.value; + this._cache.props.selected = this.actualNode.selected; + this._cache.props.checked = this.actualNode.checked; + this._cache.props.indeterminate = this.actualNode.indeterminate; + } + } + return this._cache.props; + } + }, { + key: 'attr', + value: function attr(attrName) { + if (typeof this.actualNode.getAttribute !== 'function') { + return null; + } + return this.actualNode.getAttribute(attrName); + } + }, { + key: 'hasAttr', + value: function hasAttr(attrName) { + if (typeof this.actualNode.hasAttribute !== 'function') { + return false; + } + return this.actualNode.hasAttribute(attrName); + } + }, { + key: 'attrNames', + get: function get() { + if (!this._cache.hasOwnProperty('attrNames')) { + var attrs; + if (this.actualNode.attributes instanceof window.NamedNodeMap) { + attrs = this.actualNode.attributes; + } else { + attrs = this.actualNode.cloneNode(false).attributes; + } + this._cache.attrNames = Array.from(attrs).map(function(attr) { + return attr.name; + }); + } + return this._cache.attrNames; + } + }, { + key: 'getComputedStylePropertyValue', + value: function getComputedStylePropertyValue(property) { + var key = 'computedStyle_' + property; + if (!this._cache.hasOwnProperty(key)) { + if (!this._cache.hasOwnProperty('computedStyle')) { + this._cache.computedStyle = window.getComputedStyle(this.actualNode); + } + this._cache[key] = this._cache.computedStyle.getPropertyValue(property); + } + return this._cache[key]; + } + }, { + key: 'isFocusable', + get: function get() { + if (!this._cache.hasOwnProperty('isFocusable')) { + this._cache.isFocusable = _isFocusable(this.actualNode); + } + return this._cache.isFocusable; + } + }, { + key: 'tabbableElements', + get: function get() { + if (!this._cache.hasOwnProperty('tabbableElements')) { + this._cache.tabbableElements = get_tabbable_elements_default(this); + } + return this._cache.tabbableElements; + } + }, { + key: 'clientRects', + get: function get() { + if (!this._cache.hasOwnProperty('clientRects')) { + this._cache.clientRects = Array.from(this.actualNode.getClientRects()).filter(function(rect) { + return rect.width > 0; + }); + } + return this._cache.clientRects; + } + }, { + key: 'boundingClientRect', + get: function get() { + if (!this._cache.hasOwnProperty('boundingClientRect')) { + this._cache.boundingClientRect = this.actualNode.getBoundingClientRect(); + } + return this._cache.boundingClientRect; + } + } ]); + }(abstract_virtual_node_default); + var virtual_node_default = VirtualNode; + function tokenList(str) { + return (str || '').trim().replace(/\s{2,}/g, ' ').split(' '); + } + var token_list_default = tokenList; + var idsKey = ' [idsMap]'; + function getNodesMatchingExpression(domTree, expressions, filter) { + var selectorMap = domTree[0]._selectorMap; + if (!selectorMap) { + return; + } + var shadowId = domTree[0].shadowId; + for (var _i14 = 0; _i14 < expressions.length; _i14++) { + if (expressions[_i14].length > 1 && expressions[_i14].some(function(expression) { + return isGlobalSelector(expression); + })) { + return; + } + } + var nodeSet = new Set(); + expressions.forEach(function(expression) { + var _matchingNodes$nodes; + var matchingNodes = findMatchingNodes(expression, selectorMap, shadowId); + matchingNodes === null || matchingNodes === void 0 || (_matchingNodes$nodes = matchingNodes.nodes) === null || _matchingNodes$nodes === void 0 || _matchingNodes$nodes.forEach(function(node) { + if (matchingNodes.isComplexSelector && !_matchesExpression(node, expression)) { + return; + } + nodeSet.add(node); + }); + }); + var matchedNodes = []; + nodeSet.forEach(function(node) { + return matchedNodes.push(node); + }); + if (filter) { + matchedNodes = matchedNodes.filter(filter); + } + return matchedNodes.sort(function(a2, b2) { + return a2.nodeIndex - b2.nodeIndex; + }); + } + function findMatchingNodes(expression, selectorMap, shadowId) { + var exp = expression[expression.length - 1]; + var nodes = null; + var isComplexSelector = expression.length > 1 || !!exp.pseudos || !!exp.classes; + if (isGlobalSelector(exp)) { + nodes = selectorMap['*']; + } else { + if (exp.id) { + var _selectorMap$idsKey$e; + if (!selectorMap[idsKey] || !Object.hasOwn(selectorMap[idsKey], exp.id) || !((_selectorMap$idsKey$e = selectorMap[idsKey][exp.id]) !== null && _selectorMap$idsKey$e !== void 0 && _selectorMap$idsKey$e.length)) { + return; + } + nodes = selectorMap[idsKey][exp.id].filter(function(node) { + return node.shadowId === shadowId; + }); + } + if (exp.tag && exp.tag !== '*') { + var _selectorMap$exp$tag; + if (!((_selectorMap$exp$tag = selectorMap[exp.tag]) !== null && _selectorMap$exp$tag !== void 0 && _selectorMap$exp$tag.length)) { + return; + } + var cachedNodes = selectorMap[exp.tag]; + nodes = nodes ? getSharedValues(cachedNodes, nodes) : cachedNodes; + } + if (exp.classes) { + var _selectorMap$Class; + if (!((_selectorMap$Class = selectorMap['[class]']) !== null && _selectorMap$Class !== void 0 && _selectorMap$Class.length)) { + return; + } + var _cachedNodes = selectorMap['[class]']; + nodes = nodes ? getSharedValues(_cachedNodes, nodes) : _cachedNodes; + } + if (exp.attributes) { + for (var _i15 = 0; _i15 < exp.attributes.length; _i15++) { + var _selectorMap; + var attr = exp.attributes[_i15]; + if (attr.type === 'attrValue') { + isComplexSelector = true; + } + if (!((_selectorMap = selectorMap['['.concat(attr.key, ']')]) !== null && _selectorMap !== void 0 && _selectorMap.length)) { + return; + } + var _cachedNodes2 = selectorMap['['.concat(attr.key, ']')]; + nodes = nodes ? getSharedValues(_cachedNodes2, nodes) : _cachedNodes2; + } + } + } + return { + nodes: nodes, + isComplexSelector: isComplexSelector + }; + } + function isGlobalSelector(expression) { + return expression.tag === '*' && !expression.attributes && !expression.id && !expression.classes; + } + function getSharedValues(a2, b2) { + return a2.filter(function(node) { + return b2.includes(node); + }); + } + function cacheSelector(key, vNode, map) { + if (!Object.hasOwn(map, key)) { + map[key] = []; + } + map[key].push(vNode); + } + function cacheNodeSelectors(vNode, selectorMap) { + if (vNode.props.nodeType !== 1) { + return; + } + cacheSelector(vNode.props.nodeName, vNode, selectorMap); + cacheSelector('*', vNode, selectorMap); + vNode.attrNames.forEach(function(attrName) { + if (attrName === 'id') { + selectorMap[idsKey] = selectorMap[idsKey] || {}; + token_list_default(vNode.attr(attrName)).forEach(function(value) { + cacheSelector(value, vNode, selectorMap[idsKey]); + }); + } + cacheSelector('['.concat(attrName, ']'), vNode, selectorMap); + }); + } + var hasShadowRoot; + function _getFlattenedTree() { + var node = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document.documentElement; + var shadowId = arguments.length > 1 ? arguments[1] : undefined; + hasShadowRoot = false; + var selectorMap = {}; + cache_default.set('nodeMap', new WeakMap()); + cache_default.set('selectorMap', selectorMap); + var tree = flattenTree(node, shadowId, null); + tree[0]._selectorMap = selectorMap; + tree[0]._hasShadowRoot = hasShadowRoot; + return tree; + } + function getSlotChildren(node) { + var childNodes = []; + node = node.firstChild; + while (node) { + childNodes.push(node); + node = node.nextSibling; + } + return childNodes; + } + function createNode(node, parent, shadowId) { + var vNode = new virtual_node_default(node, parent, shadowId); + cacheNodeSelectors(vNode, cache_default.get('selectorMap')); + return vNode; + } + function createChildren(childNodes, parent, shadowId) { + var children = []; + childNodes.forEach(function(childNode) { + var child = flattenTree(childNode, shadowId, parent); + if (child) { + children.push.apply(children, _toConsumableArray(child)); + } + }); + return children; + } + function flattenTree(node, shadowId, parent) { + var vNode, childNodes; + if (node.documentElement) { + node = node.documentElement; + } + var nodeName2 = node.nodeName.toLowerCase(); + if (is_shadow_root_default(node)) { + hasShadowRoot = true; + vNode = createNode(node, parent, shadowId); + shadowId = 'a' + Math.random().toString().substring(2); + childNodes = Array.from(node.shadowRoot.childNodes); + vNode.children = createChildren(childNodes, vNode, shadowId); + return [ vNode ]; + } + if (nodeName2 === 'content' && typeof node.getDistributedNodes === 'function') { + childNodes = Array.from(node.getDistributedNodes()); + return createChildren(childNodes, parent, shadowId); + } + if (nodeName2 === 'slot' && typeof node.assignedNodes === 'function') { + childNodes = Array.from(node.assignedNodes()); + if (!childNodes.length) { + childNodes = getSlotChildren(node); + } + var styl = window.getComputedStyle(node); + if (false) { + vNode = createNode(node, parent, shadowId); + vNode.children = createChildren(childNodes, vNode, shadowId); + return [ vNode ]; + } + return createChildren(childNodes, parent, shadowId); + } + if (node.nodeType === document.ELEMENT_NODE) { + vNode = createNode(node, parent, shadowId); + childNodes = Array.from(node.childNodes); + vNode.children = createChildren(childNodes, vNode, shadowId); + return [ vNode ]; + } + if (node.nodeType === document.TEXT_NODE) { + return [ createNode(node, parent) ]; + } + return void 0; + } + function getBaseLang(lang) { + if (!lang) { + return ''; + } + return lang.trim().split('-')[0].toLowerCase(); + } + var get_base_lang_default = getBaseLang; + function failureSummary(nodeData) { + var failingChecks = {}; + failingChecks.none = nodeData.none.concat(nodeData.all); + failingChecks.any = nodeData.any; + return Object.keys(failingChecks).map(function(key) { + if (!failingChecks[key].length) { + return; + } + var sum = axe._audit.data.failureSummaries[key]; + if (sum && typeof sum.failureMessage === 'function') { + return sum.failureMessage(failingChecks[key].map(function(check) { + return check.message || ''; + })); + } + }).filter(function(i) { + return i !== void 0; + }).join('\n\n'); + } + var failure_summary_default = failureSummary; + function incompleteFallbackMessage() { + var message = axe._audit.data.incompleteFallbackMessage; + if (typeof message === 'function') { + message = message(); + } + if (typeof message !== 'string') { + return ''; + } + return message; + } + var resultKeys = constants_default.resultGroups; + function processAggregate(results, options) { + var resultObject = axe.utils.aggregateResult(results); + resultKeys.forEach(function(key) { + if (options.resultTypes && !options.resultTypes.includes(key)) { + (resultObject[key] || []).forEach(function(ruleResult) { + if (Array.isArray(ruleResult.nodes) && ruleResult.nodes.length > 0) { + ruleResult.nodes = [ ruleResult.nodes[0] ]; + } + }); + } + resultObject[key] = (resultObject[key] || []).map(function(ruleResult) { + ruleResult = Object.assign({}, ruleResult); + if (Array.isArray(ruleResult.nodes) && ruleResult.nodes.length > 0) { + ruleResult.nodes = ruleResult.nodes.map(function(subResult) { + if (_typeof(subResult.node) === 'object') { + var serialElm = trimElementSpec(subResult.node, options); + Object.assign(subResult, serialElm); + } + delete subResult.result; + delete subResult.node; + normalizeRelatedNodes(subResult, options); + return subResult; + }); + } + resultKeys.forEach(function(resultKey) { + return delete ruleResult[resultKey]; + }); + delete ruleResult.pageLevel; + delete ruleResult.result; + return ruleResult; + }); + }); + return resultObject; + } + function normalizeRelatedNodes(node, options) { + [ 'any', 'all', 'none' ].forEach(function(type2) { + if (!Array.isArray(node[type2])) { + return; + } + node[type2].filter(function(checkRes) { + return Array.isArray(checkRes.relatedNodes); + }).forEach(function(checkRes) { + checkRes.relatedNodes = checkRes.relatedNodes.map(function(relatedNode) { + return trimElementSpec(relatedNode, options); + }); + }); + }); + } + function trimElementSpec() { + var elmSpec = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var runOptions = arguments.length > 1 ? arguments[1] : undefined; + elmSpec = node_serializer_default.dqElmToSpec(elmSpec, runOptions); + var serialElm = {}; + if (axe._audit.noHtml) { + serialElm.html = null; + } else { + var _elmSpec$source; + serialElm.html = (_elmSpec$source = elmSpec.source) !== null && _elmSpec$source !== void 0 ? _elmSpec$source : 'Undefined'; + } + if (runOptions.elementRef && !elmSpec.fromFrame) { + var _elmSpec$element; + serialElm.element = (_elmSpec$element = elmSpec.element) !== null && _elmSpec$element !== void 0 ? _elmSpec$element : null; + } + if (runOptions.selectors !== false || elmSpec.fromFrame) { + var _elmSpec$selector; + serialElm.target = (_elmSpec$selector = elmSpec.selector) !== null && _elmSpec$selector !== void 0 ? _elmSpec$selector : [ ':root' ]; + } + if (runOptions.ancestry) { + var _elmSpec$ancestry; + serialElm.ancestry = (_elmSpec$ancestry = elmSpec.ancestry) !== null && _elmSpec$ancestry !== void 0 ? _elmSpec$ancestry : [ ':root' ]; + } + if (runOptions.xpath) { + var _elmSpec$xpath; + serialElm.xpath = (_elmSpec$xpath = elmSpec.xpath) !== null && _elmSpec$xpath !== void 0 ? _elmSpec$xpath : [ '/' ]; + } + return serialElm; + } + var dataRegex = /\$\{\s?data\s?\}/g; + function substitute(str, data) { + if (typeof data === 'string') { + return str.replace(dataRegex, data); + } + for (var prop in data) { + if (data.hasOwnProperty(prop)) { + var regex = new RegExp('\\${\\s?data\\.' + prop + '\\s?}', 'g'); + var replace = typeof data[prop] === 'undefined' ? '' : String(data[prop]); + str = str.replace(regex, replace); + } + } + return str; + } + function processMessage(message, data) { + if (!message) { + return; + } + if (Array.isArray(data)) { + data.values = data.join(', '); + if (typeof message.singular === 'string' && typeof message.plural === 'string') { + var str2 = data.length === 1 ? message.singular : message.plural; + return substitute(str2, data); + } + return substitute(message, data); + } + if (typeof message === 'string') { + return substitute(message, data); + } + if (typeof data === 'string') { + var _str = message[data]; + return substitute(_str, data); + } + var str = message['default'] || incompleteFallbackMessage(); + if (data && data.messageKey && message[data.messageKey]) { + str = message[data.messageKey]; + } + return processMessage(str, data); + } + var process_message_default = processMessage; + function getCheckMessage(checkId, type2, data) { + var check = axe._audit.data.checks[checkId]; + if (!check) { + throw new Error('Cannot get message for unknown check: '.concat(checkId, '.')); + } + if (!check.messages[type2]) { + throw new Error('Check "'.concat(checkId, '"" does not have a "').concat(type2, '" message.')); + } + return process_message_default(check.messages[type2], data); + } + var get_check_message_default = getCheckMessage; + function getCheckOption(check, ruleID, options) { + var ruleCheckOption = ((options.rules && options.rules[ruleID] || {}).checks || {})[check.id]; + var checkOption = (options.checks || {})[check.id]; + var enabled = check.enabled; + var opts = check.options; + if (checkOption) { + if (checkOption.hasOwnProperty('enabled')) { + enabled = checkOption.enabled; + } + if (checkOption.hasOwnProperty('options')) { + opts = checkOption.options; + } + } + if (ruleCheckOption) { + if (ruleCheckOption.hasOwnProperty('enabled')) { + enabled = ruleCheckOption.enabled; + } + if (ruleCheckOption.hasOwnProperty('options')) { + opts = ruleCheckOption.options; + } + } + return { + enabled: enabled, + options: opts, + absolutePaths: options.absolutePaths + }; + } + var get_check_option_default = getCheckOption; + function _getEnvironmentData() { + var _win$location; + var metadata = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var win = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; + if (metadata && _typeof(metadata) === 'object') { + return metadata; + } else if (_typeof(win) !== 'object') { + return {}; + } + return { + testEngine: { + name: 'axe-core', + version: axe.version + }, + testRunner: { + name: axe._audit.brand + }, + testEnvironment: getTestEnvironment(win), + timestamp: new Date().toISOString(), + url: (_win$location = win.location) === null || _win$location === void 0 ? void 0 : _win$location.href + }; + } + function getTestEnvironment(win) { + if (!win.navigator || _typeof(win.navigator) !== 'object') { + return {}; + } + var navigator = win.navigator, innerHeight = win.innerHeight, innerWidth = win.innerWidth; + var _ref67 = getOrientation(win) || {}, angle = _ref67.angle, type2 = _ref67.type; + return { + userAgent: navigator.userAgent, + windowWidth: innerWidth, + windowHeight: innerHeight, + orientationAngle: angle, + orientationType: type2 + }; + } + function getOrientation(_ref68) { + var screen = _ref68.screen; + return screen.orientation || screen.msOrientation || screen.mozOrientation; + } + function createFrameContext(frame, _ref69) { + var focusable = _ref69.focusable, page = _ref69.page; + return { + node: frame, + include: [], + exclude: [], + initiator: false, + focusable: focusable && frameFocusable(frame), + size: getBoundingSize(frame), + page: page + }; + } + function frameFocusable(frame) { + var tabIndex = parse_tabindex_default(frame.getAttribute('tabindex')); + return tabIndex === null || tabIndex >= 0; + } + function getBoundingSize(domNode) { + var width = parseInt(domNode.getAttribute('width'), 10); + var height = parseInt(domNode.getAttribute('height'), 10); + if (isNaN(width) || isNaN(height)) { + var rect = domNode.getBoundingClientRect(); + width = isNaN(width) ? rect.width : width; + height = isNaN(height) ? rect.height : height; + } + return { + width: width, + height: height + }; + } + function normalizeContext(contextSpec) { + if (_isContextObject(contextSpec)) { + var msg = ' must be used inside include or exclude. It should not be on the same object.'; + assert2(!_objectHasOwn(contextSpec, 'fromFrames'), 'fromFrames' + msg); + assert2(!_objectHasOwn(contextSpec, 'fromShadowDom'), 'fromShadowDom' + msg); + } else if (_isContextProp(contextSpec)) { + contextSpec = { + include: contextSpec, + exclude: [] + }; + } else { + return { + include: [ document ], + exclude: [] + }; + } + var include = normalizeContextList(contextSpec.include); + if (include.length === 0) { + include.push(document); + } + var exclude = normalizeContextList(contextSpec.exclude); + return { + include: include, + exclude: exclude + }; + } + function normalizeContextList() { + var selectorList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var normalizedList = []; + if (!_isArrayLike(selectorList)) { + selectorList = [ selectorList ]; + } + for (var _i16 = 0; _i16 < selectorList.length; _i16++) { + var normalizedSelector = normalizeContextSelector(selectorList[_i16]); + if (normalizedSelector) { + normalizedList.push(normalizedSelector); + } + } + return normalizedList; + } + function normalizeContextSelector(selector) { + if (selector instanceof window.Node) { + return selector; + } + if (typeof selector === 'string') { + return [ selector ]; + } + if (_isLabelledFramesSelector(selector)) { + assertLabelledFrameSelector(selector); + selector = selector.fromFrames; + } else if (_isLabelledShadowDomSelector(selector)) { + selector = [ selector ]; + } + return normalizeFrameSelectors(selector); + } + function normalizeFrameSelectors(frameSelectors) { + if (!Array.isArray(frameSelectors)) { + return; + } + var normalizedSelectors = []; + var _iterator10 = _createForOfIteratorHelper(frameSelectors), _step10; + try { + for (_iterator10.s(); !(_step10 = _iterator10.n()).done; ) { + var selector = _step10.value; + if (_isLabelledShadowDomSelector(selector)) { + assertLabelledShadowDomSelector(selector); + selector = selector.fromShadowDom; + } + if (typeof selector !== 'string' && !isShadowSelector(selector)) { + return; + } + normalizedSelectors.push(selector); + } + } catch (err) { + _iterator10.e(err); + } finally { + _iterator10.f(); + } + return normalizedSelectors; + } + function assertLabelledFrameSelector(selector) { + assert2(Array.isArray(selector.fromFrames), 'fromFrames property must be an array'); + assert2(selector.fromFrames.every(function(fromFrameSelector) { + return !_objectHasOwn(fromFrameSelector, 'fromFrames'); + }), 'Invalid context; fromFrames selector must be appended, rather than nested'); + assert2(!_objectHasOwn(selector, 'fromShadowDom'), 'fromFrames and fromShadowDom cannot be used on the same object'); + } + function assertLabelledShadowDomSelector(selector) { + assert2(Array.isArray(selector.fromShadowDom), 'fromShadowDom property must be an array'); + assert2(selector.fromShadowDom.every(function(fromShadowDomSelector) { + return !_objectHasOwn(fromShadowDomSelector, 'fromFrames'); + }), 'shadow selector must be inside fromFrame instead'); + assert2(selector.fromShadowDom.every(function(fromShadowDomSelector) { + return !_objectHasOwn(fromShadowDomSelector, 'fromShadowDom'); + }), 'fromShadowDom selector must be appended, rather than nested'); + } + function isShadowSelector(selector) { + return Array.isArray(selector) && selector.every(function(str) { + return typeof str === 'string'; + }); + } + function assert2(bool, str) { + assert_default(bool, 'Invalid context; '.concat(str, '\nSee: https://github.com/dequelabs/axe-core/blob/master/doc/context.md')); + } + function parseSelectorArray(context, type2) { + var result = []; + for (var _i17 = 0, l = context[type2].length; _i17 < l; _i17++) { + var item = context[type2][_i17]; + if (item instanceof window.Node) { + if (item.documentElement instanceof window.Node) { + result.push(context.flatTree[0]); + } else if (item.host instanceof window.Node) { + var children = Array.from(item.children).map(function(child) { + return get_node_from_tree_default(child); + }); + result.push.apply(result, _toConsumableArray(children)); + } else { + result.push(get_node_from_tree_default(item)); + } + } else if (item && item.length) { + if (item.length > 1) { + pushUniqueFrameSelector(context, type2, item); + } else { + var nodeList = _shadowSelectAll(item[0]); + result.push.apply(result, _toConsumableArray(nodeList.map(function(node) { + return get_node_from_tree_default(node); + }))); + } + } + } + return result.filter(function(r) { + return r; + }); + } + function pushUniqueFrameSelector(context, type2, selectorArray) { + context.frames = context.frames || []; + var frameSelector = selectorArray.shift(); + var frames = _shadowSelectAll(frameSelector); + frames.forEach(function(frame) { + var frameContext = context.frames.find(function(result) { + return result.node === frame; + }); + if (!frameContext) { + frameContext = createFrameContext(frame, context); + context.frames.push(frameContext); + } + frameContext[type2].push(selectorArray); + }); + } + function Context(spec, flatTree) { + var _spec, _spec2, _spec3, _spec4, _this5 = this; + spec = clone2(spec); + this.frames = []; + this.page = typeof ((_spec = spec) === null || _spec === void 0 ? void 0 : _spec.page) === 'boolean' ? spec.page : void 0; + this.initiator = typeof ((_spec2 = spec) === null || _spec2 === void 0 ? void 0 : _spec2.initiator) === 'boolean' ? spec.initiator : true; + this.focusable = typeof ((_spec3 = spec) === null || _spec3 === void 0 ? void 0 : _spec3.focusable) === 'boolean' ? spec.focusable : true; + this.size = _typeof((_spec4 = spec) === null || _spec4 === void 0 ? void 0 : _spec4.size) === 'object' ? spec.size : {}; + spec = normalizeContext(spec); + this.flatTree = flatTree !== null && flatTree !== void 0 ? flatTree : _getFlattenedTree(getRootNode2(spec)); + this.exclude = spec.exclude; + this.include = spec.include; + this.include = parseSelectorArray(this, 'include'); + this.exclude = parseSelectorArray(this, 'exclude'); + _select('frame, iframe', this).forEach(function(frame) { + if (_isNodeInContext(frame, _this5)) { + pushUniqueFrame(_this5, frame.actualNode); + } + }); + if (typeof this.page === 'undefined') { + this.page = isPageContext(this); + this.frames.forEach(function(frame) { + frame.page = _this5.page; + }); + } + validateContext(this); + if (!Array.isArray(this.include)) { + this.include = Array.from(this.include); + } + this.include.sort(node_sorter_default); + } + function pushUniqueFrame(context, frame) { + if (!_isVisibleToScreenReaders(frame) || find_by_default(context.frames, 'node', frame)) { + return; + } + context.frames.push(createFrameContext(frame, context)); + } + function isPageContext(_ref70) { + var include = _ref70.include; + return include.length === 1 && include[0].actualNode === document.documentElement; + } + function validateContext(context) { + if (context.include.length === 0 && context.frames.length === 0) { + var env = _respondable.isInFrame() ? 'frame' : 'page'; + throw new Error('No elements found for include in ' + env + ' Context'); + } + } + function getRootNode2(_ref71) { + var include = _ref71.include, exclude = _ref71.exclude; + var selectors = Array.from(include).concat(Array.from(exclude)); + for (var _i18 = 0; _i18 < selectors.length; _i18++) { + var item = selectors[_i18]; + if (item instanceof window.Element) { + return item.ownerDocument.documentElement; + } + if (item instanceof window.Document) { + return item.documentElement; + } + } + return document.documentElement; + } + function _getFrameContexts(context) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (options.iframes === false) { + return []; + } + var _Context = new Context(context), frames = _Context.frames; + return frames.map(function(_ref72) { + var node = _ref72.node, frameContext = _objectWithoutProperties(_ref72, _excluded12); + frameContext.initiator = false; + var frameSelector = _getAncestry(node); + return { + frameSelector: frameSelector, + frameContext: frameContext + }; + }); + } + function _getRule(ruleId) { + var rule = axe._audit.rules.find(function(_ref73) { + var id = _ref73.id; + return id === ruleId; + }); + if (!rule) { + throw new Error('Cannot find rule by id: '.concat(ruleId)); + } + return rule; + } + function getScroll(elm) { + var buffer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var overflowX = elm.scrollWidth > elm.clientWidth + buffer; + var overflowY = elm.scrollHeight > elm.clientHeight + buffer; + if (!(overflowX || overflowY)) { + return; + } + var style = window.getComputedStyle(elm); + var scrollableX = isScrollable(style, 'overflow-x'); + var scrollableY = isScrollable(style, 'overflow-y'); + if (overflowX && scrollableX || overflowY && scrollableY) { + return { + elm: elm, + top: elm.scrollTop, + left: elm.scrollLeft + }; + } + } + function isScrollable(style, prop) { + var overflowProp = style.getPropertyValue(prop); + return [ 'scroll', 'auto' ].includes(overflowProp); + } + var get_scroll_default = memoize_default(getScroll); + function getElmScrollRecursive(root) { + return Array.from(root.children || root.childNodes || []).reduce(function(scrolls, elm) { + var scroll = get_scroll_default(elm); + if (scroll) { + scrolls.push(scroll); + } + return scrolls.concat(getElmScrollRecursive(elm)); + }, []); + } + function getScrollState() { + var win = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; + var root = win.document.documentElement; + var windowScroll = [ win.pageXOffset !== void 0 ? { + elm: win, + top: win.pageYOffset, + left: win.pageXOffset + } : { + elm: root, + top: root.scrollTop, + left: root.scrollLeft + } ]; + return windowScroll.concat(getElmScrollRecursive(document.body)); + } + var get_scroll_state_default = getScrollState; + function _getStandards() { + return clone2(standards_default); + } + function getStyleSheetFactory(dynamicDoc) { + if (!dynamicDoc) { + throw new Error('axe.utils.getStyleSheetFactory should be invoked with an argument'); + } + return function(options) { + var data = options.data, _options$isCrossOrigi = options.isCrossOrigin, isCrossOrigin = _options$isCrossOrigi === void 0 ? false : _options$isCrossOrigi, shadowId = options.shadowId, root = options.root, priority = options.priority, _options$isLink = options.isLink, isLink = _options$isLink === void 0 ? false : _options$isLink; + var style = dynamicDoc.createElement('style'); + if (isLink) { + var text = dynamicDoc.createTextNode('@import "'.concat(data.href, '"')); + style.appendChild(text); + } else { + style.appendChild(dynamicDoc.createTextNode(data)); + } + dynamicDoc.head.appendChild(style); + return { + sheet: style.sheet, + isCrossOrigin: isCrossOrigin, + shadowId: shadowId, + root: root, + priority: priority + }; + }; + } + var get_stylesheet_factory_default = getStyleSheetFactory; + var styleSheet; + function injectStyle(style) { + if (styleSheet && styleSheet.parentNode) { + if (styleSheet.styleSheet === void 0) { + styleSheet.appendChild(document.createTextNode(style)); + } else { + styleSheet.styleSheet.cssText += style; + } + return styleSheet; + } + if (!style) { + return; + } + var head = document.head || document.getElementsByTagName('head')[0]; + styleSheet = document.createElement('style'); + styleSheet.type = 'text/css'; + if (styleSheet.styleSheet === void 0) { + styleSheet.appendChild(document.createTextNode(style)); + } else { + styleSheet.styleSheet.cssText = style; + } + head.appendChild(styleSheet); + return styleSheet; + } + var inject_style_default = injectStyle; + function _isArrayLike(arr) { + return !!arr && _typeof(arr) === 'object' && typeof arr.length === 'number' && arr instanceof window.Node === false; + } + function _objectHasOwn(obj, prop) { + if (!obj || _typeof(obj) !== 'object') { + return false; + } + return Object.prototype.hasOwnProperty.call(obj, prop); + } + function _isContextSpec(contextSpec) { + return _isContextObject(contextSpec) || _isContextProp(contextSpec); + } + function _isContextObject(contextSpec) { + return [ 'include', 'exclude' ].some(function(prop) { + return _objectHasOwn(contextSpec, prop) && _isContextProp(contextSpec[prop]); + }); + } + function _isContextProp(contextList) { + return typeof contextList === 'string' || contextList instanceof window.Node || _isLabelledFramesSelector(contextList) || _isLabelledShadowDomSelector(contextList) || _isArrayLike(contextList); + } + function _isLabelledFramesSelector(selector) { + return _objectHasOwn(selector, 'fromFrames'); + } + function _isLabelledShadowDomSelector(selector) { + return _objectHasOwn(selector, 'fromShadowDom'); + } + function isHidden(el, recursed) { + var node = get_node_from_tree_default(el); + if (el.nodeType === 9) { + return false; + } + if (el.nodeType === 11) { + el = el.host; + } + if (node && node._isHidden !== null) { + return node._isHidden; + } + var style = window.getComputedStyle(el, null); + if (!style || !el.parentNode || style.getPropertyValue('display') === 'none' || !recursed && style.getPropertyValue('visibility') === 'hidden' || el.getAttribute('aria-hidden') === 'true') { + return true; + } + var parent = el.assignedSlot ? el.assignedSlot : el.parentNode; + var hidden = isHidden(parent, true); + if (node) { + node._isHidden = hidden; + } + return hidden; + } + var is_hidden_default = isHidden; + function isHtmlElement(node) { + var _node$props$nodeName, _node$props; + var nodeName2 = (_node$props$nodeName = (_node$props = node.props) === null || _node$props === void 0 ? void 0 : _node$props.nodeName) !== null && _node$props$nodeName !== void 0 ? _node$props$nodeName : node.nodeName.toLowerCase(); + if (node.namespaceURI === 'http://www.w3.org/2000/svg') { + return false; + } + return !!standards_default.htmlElms[nodeName2]; + } + var is_html_element_default = isHtmlElement; + function _isNodeInContext(node, _ref74) { + var _ref74$include = _ref74.include, include = _ref74$include === void 0 ? [] : _ref74$include, _ref74$exclude = _ref74.exclude, exclude = _ref74$exclude === void 0 ? [] : _ref74$exclude; + var filterInclude = include.filter(function(candidate) { + return _contains(candidate, node); + }); + if (filterInclude.length === 0) { + return false; + } + var filterExcluded = exclude.filter(function(candidate) { + return _contains(candidate, node); + }); + if (filterExcluded.length === 0) { + return true; + } + var deepestInclude = getDeepest(filterInclude); + var deepestExclude = getDeepest(filterExcluded); + return _contains(deepestExclude, deepestInclude); + } + function getDeepest(collection) { + var deepest; + var _iterator11 = _createForOfIteratorHelper(collection), _step11; + try { + for (_iterator11.s(); !(_step11 = _iterator11.n()).done; ) { + var node = _step11.value; + if (!deepest || !_contains(node, deepest)) { + deepest = node; + } + } + } catch (err) { + _iterator11.e(err); + } finally { + _iterator11.f(); + } + return deepest; + } + function _matchAncestry(ancestryA, ancestryB) { + if (ancestryA.length !== ancestryB.length) { + return false; + } + return ancestryA.every(function(selectorA, ancestorIndex) { + var selectorB = ancestryB[ancestorIndex]; + if (!Array.isArray(selectorA)) { + return selectorA === selectorB; + } + if (selectorA.length !== selectorB.length) { + return false; + } + return selectorA.every(function(str, selectorIndex) { + return selectorB[selectorIndex] === str; + }); + }); + } + function nodeSorter(nodeA, nodeB) { + nodeA = nodeA.actualNode || nodeA; + nodeB = nodeB.actualNode || nodeB; + if (nodeA === nodeB) { + return 0; + } + if (nodeA.compareDocumentPosition(nodeB) & 4) { + return -1; + } else { + return 1; + } + } + var node_sorter_default = nodeSorter; + function _nodeLookup(node) { + if (node instanceof abstract_virtual_node_default) { + return { + vNode: node, + domNode: node.actualNode + }; + } + return { + vNode: get_node_from_tree_default(node), + domNode: node + }; + } + function parseSameOriginStylesheet(sheet, options, priority, importedUrls) { + var isCrossOrigin = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var rules = Array.from(sheet.cssRules); + if (!rules) { + return Promise.resolve(); + } + var cssImportRules = rules.filter(function(r) { + return r.type === 3; + }); + if (!cssImportRules.length) { + return Promise.resolve({ + isCrossOrigin: isCrossOrigin, + priority: priority, + root: options.rootNode, + shadowId: options.shadowId, + sheet: sheet + }); + } + var cssImportUrlsNotAlreadyImported = cssImportRules.filter(function(rule) { + return rule.href; + }).map(function(rule) { + return rule.href; + }).filter(function(url) { + return !importedUrls.includes(url); + }); + var promises = cssImportUrlsNotAlreadyImported.map(function(importUrl, cssRuleIndex) { + var newPriority = [].concat(_toConsumableArray(priority), [ cssRuleIndex ]); + var isCrossOriginRequest = /^https?:\/\/|^\/\//i.test(importUrl); + return parse_crossorigin_stylesheet_default(importUrl, options, newPriority, importedUrls, isCrossOriginRequest); + }); + var nonImportCSSRules = rules.filter(function(r) { + return r.type !== 3; + }); + if (!nonImportCSSRules.length) { + return Promise.all(promises); + } + promises.push(Promise.resolve(options.convertDataToStylesheet({ + data: nonImportCSSRules.map(function(rule) { + return rule.cssText; + }).join(), + isCrossOrigin: isCrossOrigin, + priority: priority, + root: options.rootNode, + shadowId: options.shadowId + }))); + return Promise.all(promises); + } + var parse_sameorigin_stylesheet_default = parseSameOriginStylesheet; + function parseStylesheet(sheet, options, priority, importedUrls) { + var isCrossOrigin = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var isSameOrigin = isSameOriginStylesheet(sheet); + if (isSameOrigin) { + return parse_sameorigin_stylesheet_default(sheet, options, priority, importedUrls, isCrossOrigin); + } + return parse_crossorigin_stylesheet_default(sheet.href, options, priority, importedUrls, true); + } + function isSameOriginStylesheet(sheet) { + try { + var rules = sheet.cssRules; + if (!rules && sheet.href) { + return false; + } + return true; + } catch (e) { + return false; + } + } + var parse_stylesheet_default = parseStylesheet; + function parseCrossOriginStylesheet(url, options, priority, importedUrls, isCrossOrigin) { + importedUrls.push(url); + return new Promise(function(resolve, reject) { + var request = new window.XMLHttpRequest(); + request.open('GET', url); + request.timeout = constants_default.preload.timeout; + request.addEventListener('error', reject); + request.addEventListener('timeout', reject); + request.addEventListener('loadend', function(event) { + if (event.loaded && request.responseText) { + return resolve(request.responseText); + } + reject(request.responseText); + }); + request.send(); + }).then(function(data) { + var result = options.convertDataToStylesheet({ + data: data, + isCrossOrigin: isCrossOrigin, + priority: priority, + root: options.rootNode, + shadowId: options.shadowId + }); + return parse_stylesheet_default(result.sheet, options, priority, importedUrls, result.isCrossOrigin); + }); + } + var parse_crossorigin_stylesheet_default = parseCrossOriginStylesheet; + function parseTabindex(value) { + if (typeof value !== 'string') { + return null; + } + var match = value.trim().match(/^([-+]?\d+)/); + if (match) { + return Number(match[1]); + } + return null; + } + var parse_tabindex_default = parseTabindex; + var performanceTimer = function() { + function now() { + if (window.performance && window.performance) { + return window.performance.now(); + } + } + var axeStartTime = now(); + var axeStarted = false; + return { + start: function start() { + this.reset(); + axeStarted = true; + this.mark('mark_axe_start'); + }, + end: function end() { + this.mark('mark_axe_end'); + this.measure('axe', 'mark_axe_start', 'mark_axe_end', true); + this.logMeasures('axe'); + this.clearMark('mark_axe_start', 'mark_axe_end'); + axeStarted = false; + }, + auditStart: function auditStart() { + if (!axeStarted) { + this.reset(); + } + this.mark('mark_audit_start'); + }, + auditEnd: function auditEnd() { + this.mark('mark_audit_end'); + this.measure('audit_start_to_end', 'mark_audit_start', 'mark_audit_end', true); + this.logMeasures(); + this.clearMark('mark_audit_start', 'mark_audit_end'); + }, + mark: function mark(markName) { + var _window$performance; + if ((_window$performance = window.performance) !== null && _window$performance !== void 0 && _window$performance.mark) { + window.performance.mark(markName); + } + }, + measure: function measure(measureName, startMark, endMark) { + var _window$performance2; + var keepMarks = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + if (!((_window$performance2 = window.performance) !== null && _window$performance2 !== void 0 && _window$performance2.measure)) { + return; + } + try { + window.performance.measure(measureName, startMark, endMark); + } catch (e) { + this._log(e); + } + if (!keepMarks) { + this.clearMark(startMark, endMark); + } + }, + logMeasures: function logMeasures(measureName) { + var _this6 = this, _window$performance3, _window$performance4; + var last2 = function last2(arr) { + return Array.isArray(arr) ? arr[arr.length - 1] : arr; + }; + var logMeasure = function logMeasure(req) { + _this6._log('Measure ' + req.name + ' took ' + req.duration + 'ms'); + }; + if (!((_window$performance3 = window.performance) !== null && _window$performance3 !== void 0 && _window$performance3.getEntriesByType) || !((_window$performance4 = window.performance) !== null && _window$performance4 !== void 0 && _window$performance4.getEntriesByName)) { + return; + } + var axeStart = last2(window.performance.getEntriesByName('mark_axe_start')) || last2(window.performance.getEntriesByName('mark_audit_start')); + if (!axeStart) { + this._log('Axe must be started before using performanceTimer'); + return; + } + var measures = window.performance.getEntriesByType('measure').filter(function(measure) { + return measure.startTime >= axeStart.startTime; + }); + for (var _i19 = 0; _i19 < measures.length; ++_i19) { + var req = measures[_i19]; + if (req.name === measureName) { + logMeasure(req); + return; + } else if (!measureName) { + logMeasure(req); + } + } + }, + timeElapsed: function timeElapsed() { + var currentTime = now(); + return currentTime - axeStartTime; + }, + clearMark: function clearMark() { + var _window$performance5; + if (!((_window$performance5 = window.performance) !== null && _window$performance5 !== void 0 && _window$performance5.clearMarks)) { + return; + } + for (var _len7 = arguments.length, markNames = new Array(_len7), _key0 = 0; _key0 < _len7; _key0++) { + markNames[_key0] = arguments[_key0]; + } + for (var _i20 = 0, _markNames = markNames; _i20 < _markNames.length; _i20++) { + var markName = _markNames[_i20]; + window.performance.clearMarks(markName); + } + }, + reset: function reset() { + axeStartTime = now(); + }, + _log: function _log(message) { + log_default(message); + } + }; + }(); + var performance_timer_default = performanceTimer; + function _pollyfillElementsFromPoint() { + if (document.elementsFromPoint) { + return document.elementsFromPoint; + } + if (document.msElementsFromPoint) { + return document.msElementsFromPoint; + } + var usePointer = function() { + var element = document.createElement('x'); + element.style.cssText = 'pointer-events:auto'; + return element.style.pointerEvents === 'auto'; + }(); + var cssProp = usePointer ? 'pointer-events' : 'visibility'; + var cssDisableVal = usePointer ? 'none' : 'hidden'; + var style = document.createElement('style'); + style.innerHTML = usePointer ? '* { pointer-events: all }' : '* { visibility: visible }'; + return function(x, y) { + var current, i, d2; + var elements = []; + var previousPointerEvents = []; + document.head.appendChild(style); + while ((current = document.elementFromPoint(x, y)) && elements.indexOf(current) === -1) { + elements.push(current); + previousPointerEvents.push({ + value: current.style.getPropertyValue(cssProp), + priority: current.style.getPropertyPriority(cssProp) + }); + current.style.setProperty(cssProp, cssDisableVal, 'important'); + } + if (elements.indexOf(document.documentElement) < elements.length - 1) { + elements.splice(elements.indexOf(document.documentElement), 1); + elements.push(document.documentElement); + } + for (i = previousPointerEvents.length; !!(d2 = previousPointerEvents[--i]); ) { + elements[i].style.setProperty(cssProp, d2.value ? d2.value : '', d2.priority); + } + document.head.removeChild(style); + return elements; + }; + } + if (typeof window.addEventListener === 'function') { + document.elementsFromPoint = _pollyfillElementsFromPoint(); + } + function uniqueArray(arr1, arr2) { + return arr1.concat(arr2).filter(function(elem, pos, arr) { + return arr.indexOf(elem) === pos; + }); + } + var unique_array_default = uniqueArray; + function createLocalVariables(vNodes, anyLevel, thisLevel, parentShadowId, recycledLocalVariable) { + var retVal = recycledLocalVariable || {}; + retVal.vNodes = vNodes; + retVal.vNodesIndex = 0; + retVal.anyLevel = anyLevel; + retVal.thisLevel = thisLevel; + retVal.parentShadowId = parentShadowId; + return retVal; + } + function matchExpressions(domTree, expressions, filter) { + var recycledLocalVariables = cache_default.get('qsa.recycledLocalVariables', function() { + return []; + }); + var stack = []; + var vNodes = Array.isArray(domTree) ? domTree : [ domTree ]; + var currentLevel = createLocalVariables(vNodes, expressions, null, domTree[0].shadowId, recycledLocalVariables.pop()); + var result = []; + while (currentLevel.vNodesIndex < currentLevel.vNodes.length) { + var _currentLevel$anyLeve, _currentLevel$thisLev; + var vNode = currentLevel.vNodes[currentLevel.vNodesIndex++]; + var childOnly = null; + var childAny = null; + var combinedLength = (((_currentLevel$anyLeve = currentLevel.anyLevel) === null || _currentLevel$anyLeve === void 0 ? void 0 : _currentLevel$anyLeve.length) || 0) + (((_currentLevel$thisLev = currentLevel.thisLevel) === null || _currentLevel$thisLev === void 0 ? void 0 : _currentLevel$thisLev.length) || 0); + var added = false; + for (var _i21 = 0; _i21 < combinedLength; _i21++) { + var _currentLevel$anyLeve2, _currentLevel$anyLeve3, _currentLevel$anyLeve4; + var exp = _i21 < (((_currentLevel$anyLeve2 = currentLevel.anyLevel) === null || _currentLevel$anyLeve2 === void 0 ? void 0 : _currentLevel$anyLeve2.length) || 0) ? currentLevel.anyLevel[_i21] : currentLevel.thisLevel[_i21 - (((_currentLevel$anyLeve3 = currentLevel.anyLevel) === null || _currentLevel$anyLeve3 === void 0 ? void 0 : _currentLevel$anyLeve3.length) || 0)]; + if ((!exp[0].id || vNode.shadowId === currentLevel.parentShadowId) && _matchesExpression(vNode, exp[0])) { + if (exp.length === 1) { + if (!added && (!filter || filter(vNode))) { + result.push(vNode); + added = true; + } + } else { + var rest = exp.slice(1); + if ([ ' ', '>' ].includes(rest[0].combinator) === false) { + throw new Error('axe.utils.querySelectorAll does not support the combinator: ' + exp[1].combinator); + } + if (rest[0].combinator === '>') { + (childOnly = childOnly || []).push(rest); + } else { + (childAny = childAny || []).push(rest); + } + } + } + if ((!exp[0].id || vNode.shadowId === currentLevel.parentShadowId) && (_currentLevel$anyLeve4 = currentLevel.anyLevel) !== null && _currentLevel$anyLeve4 !== void 0 && _currentLevel$anyLeve4.includes(exp)) { + (childAny = childAny || []).push(exp); + } + } + if (vNode.children && vNode.children.length) { + stack.push(currentLevel); + currentLevel = createLocalVariables(vNode.children, childAny, childOnly, vNode.shadowId, recycledLocalVariables.pop()); + } + while (currentLevel.vNodesIndex === currentLevel.vNodes.length && stack.length) { + recycledLocalVariables.push(currentLevel); + currentLevel = stack.pop(); + } + } + return result; + } + function querySelectorAllFilter(domTree, selector, filter) { + domTree = Array.isArray(domTree) ? domTree : [ domTree ]; + var expressions = _convertSelector(selector); + var nodes = getNodesMatchingExpression(domTree, expressions, filter); + if (nodes) { + return nodes; + } + return matchExpressions(domTree, expressions, filter); + } + var query_selector_all_filter_default = querySelectorAllFilter; + function preloadCssom(_ref75) { + var _ref75$treeRoot = _ref75.treeRoot, treeRoot = _ref75$treeRoot === void 0 ? axe._tree[0] : _ref75$treeRoot; + var rootNodes = getAllRootNodesInTree(treeRoot); + if (!rootNodes.length) { + return Promise.resolve(); + } + var dynamicDoc = document.implementation.createHTMLDocument('Dynamic document for loading cssom'); + var convertDataToStylesheet = get_stylesheet_factory_default(dynamicDoc); + return getCssomForAllRootNodes(rootNodes, convertDataToStylesheet).then(function(assets) { + return flattenAssets(assets); + }); + } + var preload_cssom_default = preloadCssom; + function getAllRootNodesInTree(tree) { + var ids = []; + var rootNodes = query_selector_all_filter_default(tree, '*', function(node) { + if (ids.includes(node.shadowId)) { + return false; + } + ids.push(node.shadowId); + return true; + }).map(function(node) { + return { + shadowId: node.shadowId, + rootNode: get_root_node_default(node.actualNode) + }; + }); + return unique_array_default(rootNodes, []); + } + function getCssomForAllRootNodes(rootNodes, convertDataToStylesheet) { + var promises = []; + rootNodes.forEach(function(_ref76, index) { + var rootNode = _ref76.rootNode, shadowId = _ref76.shadowId; + var sheets = getStylesheetsOfRootNode(rootNode, shadowId, convertDataToStylesheet); + if (!sheets) { + return Promise.all(promises); + } + var rootIndex = index + 1; + var parseOptions = { + rootNode: rootNode, + shadowId: shadowId, + convertDataToStylesheet: convertDataToStylesheet, + rootIndex: rootIndex + }; + var importedUrls = []; + var p2 = Promise.all(sheets.map(function(sheet, sheetIndex) { + var priority = [ rootIndex, sheetIndex ]; + return parse_stylesheet_default(sheet, parseOptions, priority, importedUrls); + })); + promises.push(p2); + }); + return Promise.all(promises); + } + function flattenAssets(assets) { + return assets.reduce(function(acc, val) { + return Array.isArray(val) ? acc.concat(flattenAssets(val)) : acc.concat(val); + }, []); + } + function getStylesheetsOfRootNode(rootNode, shadowId, convertDataToStylesheet) { + var sheets; + if (rootNode.nodeType === 11 && shadowId) { + sheets = getStylesheetsFromDocumentFragment(rootNode, convertDataToStylesheet); + } else { + sheets = getStylesheetsFromDocument(rootNode); + } + return filterStylesheetsWithSameHref(sheets); + } + function getStylesheetsFromDocumentFragment(rootNode, convertDataToStylesheet) { + return Array.from(rootNode.children).filter(filerStyleAndLinkAttributesInDocumentFragment).reduce(function(out, node) { + var nodeName2 = node.nodeName.toUpperCase(); + var data = nodeName2 === 'STYLE' ? node.textContent : node; + var isLink = nodeName2 === 'LINK'; + var stylesheet = convertDataToStylesheet({ + data: data, + isLink: isLink, + root: rootNode + }); + if (stylesheet.sheet) { + out.push(stylesheet.sheet); + } + return out; + }, []); + } + function getStylesheetsFromDocument(rootNode) { + return Array.from(rootNode.styleSheets).filter(function(sheet) { + if (!sheet.media) { + return false; + } + return filterMediaIsPrint(sheet.media.mediaText); + }); + } + function filerStyleAndLinkAttributesInDocumentFragment(node) { + var nodeName2 = node.nodeName.toUpperCase(); + var linkHref = node.getAttribute('href'); + var linkRel = node.getAttribute('rel'); + var isLink = nodeName2 === 'LINK' && linkHref && linkRel && node.rel.toUpperCase().includes('STYLESHEET'); + var isStyle = nodeName2 === 'STYLE'; + return isStyle || isLink && filterMediaIsPrint(node.media); + } + function filterMediaIsPrint(media) { + if (!media) { + return true; + } + return !media.toUpperCase().includes('PRINT'); + } + function filterStylesheetsWithSameHref(sheets) { + var hrefs = []; + return sheets.filter(function(sheet) { + if (!sheet.href) { + return true; + } + if (hrefs.includes(sheet.href)) { + return false; + } + hrefs.push(sheet.href); + return true; + }); + } + function preloadMedia(_ref77) { + var _ref77$treeRoot = _ref77.treeRoot, treeRoot = _ref77$treeRoot === void 0 ? axe._tree[0] : _ref77$treeRoot; + var mediaVirtualNodes = query_selector_all_filter_default(treeRoot, 'video[autoplay], audio[autoplay]', function(_ref78) { + var actualNode = _ref78.actualNode; + if (actualNode.preload === 'none' && actualNode.readyState === 0 && actualNode.networkState !== actualNode.NETWORK_LOADING) { + return false; + } + if (actualNode.hasAttribute('paused') || actualNode.hasAttribute('muted')) { + return false; + } + if (actualNode.hasAttribute('src')) { + return !!actualNode.getAttribute('src'); + } + var sourceWithSrc = Array.from(actualNode.getElementsByTagName('source')).filter(function(source) { + return !!source.getAttribute('src'); + }); + if (sourceWithSrc.length <= 0) { + return false; + } + return true; + }); + return Promise.all(mediaVirtualNodes.map(function(_ref79) { + var actualNode = _ref79.actualNode; + return isMediaElementReady(actualNode); + })); + } + var preload_media_default = preloadMedia; + function isMediaElementReady(elm) { + return new Promise(function(resolve) { + if (elm.readyState > 0) { + resolve(elm); + } + function onMediaReady() { + elm.removeEventListener('loadedmetadata', onMediaReady); + resolve(elm); + } + elm.addEventListener('loadedmetadata', onMediaReady); + }); + } + function _preload(options) { + var preloadFunctionsMap = { + cssom: preload_cssom_default, + media: preload_media_default + }; + if (!_shouldPreload(options)) { + return Promise.resolve(); + } + return new Promise(function(resolve, reject) { + var _getPreloadConfig2 = _getPreloadConfig(options), assets = _getPreloadConfig2.assets, timeout = _getPreloadConfig2.timeout; + var preloadTimeout = setTimeout(function() { + return reject(new Error('Preload assets timed out.')); + }, timeout); + Promise.all(assets.map(function(asset) { + return preloadFunctionsMap[asset](options).then(function(results) { + return _defineProperty({}, asset, results); + }); + })).then(function(results) { + var preloadAssets = results.reduce(function(out, result) { + return _extends({}, out, result); + }, {}); + clearTimeout(preloadTimeout); + resolve(preloadAssets); + })['catch'](function(err2) { + clearTimeout(preloadTimeout); + reject(err2); + }); + }); + } + function isValidPreloadObject(preloadObj) { + return _typeof(preloadObj) === 'object' && Array.isArray(preloadObj.assets); + } + function _shouldPreload(options) { + if (!options || options.preload === void 0 || options.preload === null) { + return true; + } + if (typeof options.preload === 'boolean') { + return options.preload; + } + return isValidPreloadObject(options.preload); + } + function _getPreloadConfig(options) { + var _constants_default$pr = constants_default.preload, assets = _constants_default$pr.assets, timeout = _constants_default$pr.timeout; + var config = { + assets: assets, + timeout: timeout + }; + if (!options.preload) { + return config; + } + if (typeof options.preload === 'boolean') { + return config; + } + var areRequestedAssetsValid = options.preload.assets.every(function(a2) { + return assets.includes(a2.toLowerCase()); + }); + if (!areRequestedAssetsValid) { + throw new Error('Requested assets, not supported. Supported assets are: '.concat(assets.join(', '), '.')); + } + config.assets = unique_array_default(options.preload.assets.map(function(a2) { + return a2.toLowerCase(); + }), []); + if (options.preload.timeout && typeof options.preload.timeout === 'number' && !isNaN(options.preload.timeout)) { + config.timeout = options.preload.timeout; + } + return config; + } + function _publishMetaData(ruleResult) { + var checksData = axe._audit.data.checks || {}; + var rulesData = axe._audit.data.rules || {}; + var rule = find_by_default(axe._audit.rules, 'id', ruleResult.id) || {}; + ruleResult.tags = clone2(rule.tags || []); + var shouldBeTrue = extender(checksData, true, rule); + var shouldBeFalse = extender(checksData, false, rule); + ruleResult.nodes.forEach(function(detail) { + detail.any.forEach(shouldBeTrue); + detail.all.forEach(shouldBeTrue); + detail.none.forEach(shouldBeFalse); + }); + extend_meta_data_default(ruleResult, clone2(rulesData[ruleResult.id] || {})); + } + function getIncompleteReason(checkData, messages) { + function getDefaultMsg(message) { + if (message.incomplete && message.incomplete['default']) { + return message.incomplete['default']; + } else { + return incompleteFallbackMessage(); + } + } + if (checkData && checkData.missingData) { + try { + var msg = messages.incomplete[checkData.missingData[0].reason]; + if (!msg) { + throw new Error(); + } + return msg; + } catch (_unused5) { + if (typeof checkData.missingData === 'string') { + return messages.incomplete[checkData.missingData]; + } else { + return getDefaultMsg(messages); + } + } + } else if (checkData && checkData.messageKey) { + return messages.incomplete[checkData.messageKey]; + } else { + return getDefaultMsg(messages); + } + } + function extender(checksData, shouldBeTrue, rule) { + return function(check) { + var sourceData = checksData[check.id] || {}; + var messages = sourceData.messages || {}; + var data = Object.assign({}, sourceData); + delete data.messages; + if (!rule.reviewOnFail && check.result === void 0) { + if (_typeof(messages.incomplete) === 'object' && !Array.isArray(check.data)) { + data.message = getIncompleteReason(check.data, messages); + } + if (!data.message) { + data.message = messages.incomplete; + } + } else { + data.message = check.result === shouldBeTrue ? messages.pass : messages.fail; + } + if (typeof data.message !== 'function') { + data.message = process_message_default(data.message, check.data); + } + extend_meta_data_default(check, data); + }; + } + function querySelectorAll(domTree, selector) { + return query_selector_all_filter_default(domTree, selector); + } + var query_selector_all_default = querySelectorAll; + function matchTags(rule, runOnly) { + var include, exclude; + var defaultExclude = axe._audit && axe._audit.tagExclude ? axe._audit.tagExclude : []; + if (runOnly.hasOwnProperty('include') || runOnly.hasOwnProperty('exclude')) { + include = runOnly.include || []; + include = Array.isArray(include) ? include : [ include ]; + exclude = runOnly.exclude || []; + exclude = Array.isArray(exclude) ? exclude : [ exclude ]; + exclude = exclude.concat(defaultExclude.filter(function(tag) { + return include.indexOf(tag) === -1; + })); + } else { + include = Array.isArray(runOnly) ? runOnly : [ runOnly ]; + exclude = defaultExclude.filter(function(tag) { + return include.indexOf(tag) === -1; + }); + } + var matching = include.some(function(tag) { + return rule.tags.indexOf(tag) !== -1; + }); + if (matching || include.length === 0 && rule.enabled !== false) { + return exclude.every(function(tag) { + return rule.tags.indexOf(tag) === -1; + }); + } else { + return false; + } + } + function ruleShouldRun(rule, context, options) { + var runOnly = options.runOnly || {}; + var ruleOptions = (options.rules || {})[rule.id]; + if (rule.pageLevel && !context.page) { + return false; + } else if (runOnly.type === 'rule') { + return runOnly.values.indexOf(rule.id) !== -1; + } else if (ruleOptions && typeof ruleOptions.enabled === 'boolean') { + return ruleOptions.enabled; + } else if (runOnly.type === 'tag' && runOnly.values) { + return matchTags(rule, runOnly.values); + } else { + return matchTags(rule, []); + } + } + var rule_should_run_default = ruleShouldRun; + function _filterHtmlAttrs(element, filterAttrs) { + if (!filterAttrs) { + return element; + } + var node = element.cloneNode(false); + var attributes2 = get_node_attributes_default(node); + if (node.nodeType === 1) { + var outerHTML = node.outerHTML; + node = cache_default.get(outerHTML, function() { + return setNodeAttributes(node, attributes2, element, filterAttrs); + }); + } else { + node = setNodeAttributes(node, attributes2, element, filterAttrs); + } + Array.from(element.childNodes).forEach(function(child) { + node.appendChild(_filterHtmlAttrs(child, filterAttrs)); + }); + return node; + } + function setNodeAttributes(node, attributes2, element, filterAttrs) { + if (!attributes2) { + return node; + } + node = document.createElement(node.nodeName); + Array.from(attributes2).forEach(function(attr) { + if (!attributeMatches(element, attr.name, filterAttrs)) { + node.setAttribute(attr.name, attr.value); + } + }); + return node; + } + function attributeMatches(node, attrName, filterAttrs) { + if (typeof filterAttrs[attrName] === 'undefined') { + return false; + } + if (filterAttrs[attrName] === true) { + return true; + } + return element_matches_default(node, filterAttrs[attrName]); + } + function _select(selector, context) { + var result = []; + var candidate; + if (axe._selectCache) { + for (var j = 0, l = axe._selectCache.length; j < l; j++) { + var item = axe._selectCache[j]; + if (item.selector === selector) { + return item.result; + } + } + } + var outerIncludes = getOuterIncludes(context.include); + var isInContext = getContextFilter(context); + for (var _i22 = 0; _i22 < outerIncludes.length; _i22++) { + candidate = outerIncludes[_i22]; + var nodes = query_selector_all_filter_default(candidate, selector, isInContext); + result = mergeArrayUniques(result, nodes); + } + if (axe._selectCache) { + axe._selectCache.push({ + selector: selector, + result: result + }); + } + return result; + } + function getOuterIncludes(includes) { + return includes.reduce(function(res, el) { + if (!res.length || !_contains(res[res.length - 1], el)) { + res.push(el); + } + return res; + }, []); + } + function getContextFilter(context) { + if (!context.exclude || context.exclude.length === 0) { + return null; + } + return function(node) { + return _isNodeInContext(node, context); + }; + } + function mergeArrayUniques(arr1, arr2) { + if (arr1.length === 0) { + return arr2; + } + if (arr1.length < arr2.length) { + var temp = arr1; + arr1 = arr2; + arr2 = temp; + } + for (var _i23 = 0, l = arr2.length; _i23 < l; _i23++) { + if (!arr1.includes(arr2[_i23])) { + arr1.push(arr2[_i23]); + } + } + return arr1; + } + function _serializeError(err2) { + var iteration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (_typeof(err2) !== 'object' || err2 === null) { + return { + message: String(err2) + }; + } + var serial = {}; + var _iterator12 = _createForOfIteratorHelper(constants_default.serializableErrorProps), _step12; + try { + for (_iterator12.s(); !(_step12 = _iterator12.n()).done; ) { + var prop = _step12.value; + if ([ 'string', 'number', 'boolean' ].includes(_typeof(err2[prop]))) { + serial[prop] = err2[prop]; + } + } + } catch (err) { + _iterator12.e(err); + } finally { + _iterator12.f(); + } + if (err2.cause) { + serial.cause = iteration < 10 ? _serializeError(err2.cause, iteration + 1) : '...'; + } + return serial; + } + var RuleError = function(_Error) { + function RuleError(_ref81) { + var _error$name; + var _this7; + var error = _ref81.error, ruleId = _ref81.ruleId, method = _ref81.method, errorNode = _ref81.errorNode; + _classCallCheck(this, RuleError); + _this7 = _callSuper(this, RuleError); + _this7.name = (_error$name = error.name) !== null && _error$name !== void 0 ? _error$name : 'RuleError'; + _this7.message = error.message; + _this7.stack = error.stack; + if (error.cause) { + _this7.cause = _serializeError(error.cause); + } + if (ruleId) { + _this7.ruleId = ruleId; + _this7.message += ' Skipping '.concat(_this7.ruleId, ' rule.'); + } + if (method) { + _this7.method = method; + } + if (errorNode) { + _this7.errorNode = errorNode; + } + return _this7; + } + _inherits(RuleError, _Error); + return _createClass(RuleError); + }(_wrapNativeSuper(Error)); + var rule_error_default = RuleError; + function setScroll(elm, top, left) { + if (elm === window) { + return elm.scroll(left, top); + } else { + elm.scrollTop = top; + elm.scrollLeft = left; + } + } + function setScrollState(scrollState) { + scrollState.forEach(function(_ref82) { + var elm = _ref82.elm, top = _ref82.top, left = _ref82.left; + return setScroll(elm, top, left); + }); + } + var set_scroll_state_default = setScrollState; + function _shadowSelect(selectors) { + var selectorArr = Array.isArray(selectors) ? _toConsumableArray(selectors) : [ selectors ]; + return selectRecursive(selectorArr, document); + } + function selectRecursive(selectors, doc) { + var selectorStr = selectors.shift(); + var elm = selectorStr ? doc.querySelector(selectorStr) : null; + if (selectors.length === 0) { + return elm; + } + if (!(elm !== null && elm !== void 0 && elm.shadowRoot)) { + return null; + } + return selectRecursive(selectors, elm.shadowRoot); + } + function _shadowSelectAll(selectors) { + var doc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; + var selectorArr = Array.isArray(selectors) ? _toConsumableArray(selectors) : [ selectors ]; + if (selectors.length === 0) { + return []; + } + return selectAllRecursive(selectorArr, doc); + } + function selectAllRecursive(_ref83, doc) { + var _ref84 = _toArray(_ref83), selectorStr = _ref84[0], restSelector = _arrayLikeToArray(_ref84).slice(1); + var elms = doc.querySelectorAll(selectorStr); + if (restSelector.length === 0) { + return Array.from(elms); + } + var selected = []; + var _iterator13 = _createForOfIteratorHelper(elms), _step13; + try { + for (_iterator13.s(); !(_step13 = _iterator13.n()).done; ) { + var elm = _step13.value; + if (elm !== null && elm !== void 0 && elm.shadowRoot) { + selected.push.apply(selected, _toConsumableArray(selectAllRecursive(restSelector, elm.shadowRoot))); + } + } + } catch (err) { + _iterator13.e(err); + } finally { + _iterator13.f(); + } + return selected; + } + function validInputTypes() { + return [ 'hidden', 'text', 'search', 'tel', 'url', 'email', 'password', 'date', 'month', 'week', 'time', 'datetime-local', 'number', 'range', 'color', 'checkbox', 'radio', 'file', 'submit', 'image', 'reset', 'button' ]; + } + var valid_input_type_default = validInputTypes; + var langs = [ , [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, 1, 1, , 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, , , , , , 1, 1, 1, 1, , , 1, 1, 1, , 1, , 1, , 1, 1 ], [ 1, 1, 1, , 1, 1, , 1, 1, 1, , 1, , , 1, 1, 1, , , 1, 1, 1, , , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , , , , 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1 ], [ , 1, , , , , , 1, , 1, , , , , 1, , 1, , , 1, 1, 1, , 1, , , 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, 1, 1, 1, , , 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, 1, , , 1, , , , 1, 1, 1, 1, , 1, , 1, , 1, , , , , , 1 ], [ 1, , 1, 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, , 1, , 1, , , , , 1, , 1, 1, 1, 1, 1, , , , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, , 1, , 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , 1, , , 1, , 1, , , , 1, 1, 1, , , , , , , , , , , 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1 ], [ 1, 1, 1, 1, 1, , , 1, , , 1, , , 1, 1, 1, , , , , 1, , , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1 ], [ , 1, , 1, 1, 1, , 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, , , 1, 1, , , , , , 1, 1 ], [ 1, 1, 1, , , , , 1, , , , 1, 1, , 1, , , , , , 1, , , , , 1 ], [ , 1, , , 1, , , 1, , , , , , 1 ], [ , 1, , 1, , , , 1, , , , 1 ], [ 1, , 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , , 1, , , 1, , 1, 1, , 1, , 1, , , , , 1, , 1 ], [ , 1, , , , 1, , , 1, 1, , 1, , 1, 1, 1, 1, , 1, 1, , , 1, , , 1 ], [ , 1, 1, , , , , , 1, , , , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], [ , 1, , 1, 1, 1, , , 1, 1, 1, 1, 1, 1, , 1, , , , 1, 1, 1, , 1, , 1 ], [ , 1, , 1, , 1, , 1, , 1, , 1, 1, 1, 1, 1, , , 1, 1, 1 ], [ , 1, 1, 1, , , , 1, 1, 1, , 1, 1, , , 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, , 1, 1, 1, , 1, , , , , 1, 1, 1, , , 1, , 1, , , 1, 1 ], [ , , , , 1, , , , , , , , , , , , , , , , , 1 ], [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, 1, 1, , 1, 1, , , , 1, 1, 1, 1, 1, , , 1, 1, 1, , , , 1, 1 ], [ 1, 1, 1, 1, , , , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , , , , , , 1, , , , , , , 1 ], [ , 1, 1, , 1, 1, , 1, , , , , , , , , , , , , 1 ], [ , , , , , , , , 1 ], [ 1, 1, 1, , , , , , , , , , , , , 1 ], [ , , , , , , , , 1, , , 1, , , 1, 1, , , , , 1 ] ], [ , [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ , , , 1, , , , , , , , , , , , , , , 1 ], [ , 1, , , 1, 1, , 1, , 1, 1, , , , 1, 1, , , 1, 1, , , , 1 ], [ 1, , , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, , , 1, , , , 1 ], , [ , 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, , 1, 1, , , 1, 1, 1, 1, , 1, 1, , 1 ], [ , 1, , , 1, , , 1, , 1, , , 1, 1, 1, 1, , , 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, , , 1, , , 1, , 1 ], [ , 1, , , , , , 1, , , , 1, 1, , , , , , 1, 1, , , , , 1 ], [ , , , , , , , 1, , , , 1, , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, , , , 1, 1, 1, 1, 1, , , 1, 1, , 1, 1, 1, 1, 1 ], [ , 1, , , 1, 1, , 1, , 1, 1, 1, , , 1, 1, , , 1, , 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, , 1, 1, , 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1 ], [ , , , , , , , , , , , , , , , , 1 ], , [ , 1, 1, 1, 1, 1, , 1, 1, 1, , , 1, , 1, 1, , 1, 1, 1, 1, 1, , 1, , 1 ], [ , , 1, , , 1, , , 1, 1, , 1, 1, , 1, 1, , 1, , , , , , , , , 1 ], [ , 1, 1, , 1, , , , 1, 1, , 1, , 1, 1, 1, 1, , 1, 1, 1, 1, , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ 1, 1 ], [ , 1, , , , , , , , , , 1, 1, , , , , , 1, 1, , 1, , 1, , 1, 1 ], , [ , 1, 1, , 1, , , 1, , 1, , , , 1, 1, 1, , , 1, , , 1, , , , 1 ], [ 1, 1, , , 1, 1, , 1, , , , , 1, , 1 ] ], [ , [ , 1 ], [ , , , 1, , , , 1, , , , 1, , , , 1, , , 1, , , 1 ], [ , , , , , , , , , , , , , , , , , , 1, 1, , , , , , 1 ], , [ 1, , , , , 1 ], [ , 1, , , , 1, , , , 1 ], [ , 1, , , , , , , , , , , 1, 1, , 1, , , , , , , , , 1, 1 ], [ , , , , , , , , , , , , , , , , , , , 1, , 1 ], [ , , , , , , , , , , , , , , , , 1, , , , 1, , 1 ], [ , 1 ], [ , 1, , 1, , 1, , 1, , 1, , 1, 1, 1, , 1, 1, , 1, , , , , , , 1 ], [ 1, , , , , 1, , , 1, 1, , 1, , 1, , 1, 1, , , , , 1, , , 1 ], [ , 1, 1, , , 1, , 1, , 1, , 1, , 1, 1, 1, 1, 1, , 1, , 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, , 1, , 1, , , , 1, 1, 1, 1, , 1, 1, , , 1, 1, 1, 1 ], [ 1, , , , , , , , , , , , , , , , , , , , 1 ], [ , , , , , , , , , 1 ], , [ , 1, , , , , , 1, 1, 1, , 1, , , , 1, , , 1, 1, 1, , , 1 ], [ 1, , , , , 1, , 1, 1, 1, , 1, 1, 1, 1, 1, , 1, , 1, , 1, , , 1, 1 ], [ 1, , 1, 1, , , , , 1, , , , , , 1, 1, , , 1, 1, 1, 1, , , 1, , 1 ], [ 1, , , , 1, , , , , , , , , , , , , 1 ], [ , , , , , 1, , , 1, , , , , , 1 ], [ , , , , , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , , 1 ], [ , 1, , , , , , , , , , , , , , 1 ], [ , 1, , , , 1 ] ], [ , [ 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, , 1, 1, , , 1, 1, 1 ], [ , , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , 1 ], , [ , , , , , , , , , , , , , , , , , , 1 ], [ 1, , , , , , , , , 1, , , , 1 ], [ , , , , , , , , , , , , , , , , , , 1 ], , [ 1, 1, , , , 1, 1, , , , , , 1, , , , 1, , 1, , 1, 1, , 1 ], [ 1 ], [ , , , , , , , , , , , 1, , , , , , , , , , , 1 ], [ , 1, , , , , , , 1, 1, , , 1, , 1, , , , 1, , , , , , , 1 ], [ , , , , , , , , , , , , , , , , 1, , , , , 1 ], [ , , 1, , , , , 1, , 1 ], [ 1, , , , 1, , , , , 1, , , , 1, 1, , , , 1, 1, , , , , 1 ], [ , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , 1 ], [ 1, , , 1, 1, , , , , , , 1, , 1, , 1, 1, 1, 1, 1, 1 ], [ , , , , , 1, , , , , , , 1, , , , , , , 1 ], , [ , , 1, 1, 1, 1, 1, , 1, 1, 1, , , 1, 1, , , 1, 1, , 1, 1, 1, , , 1 ], [ , , , , , , , , , , , , , , , , , , 1 ], [ , 1, , , , 1 ], , [ 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , , , 1, 1, 1, 1, , , , , , 1, , 1, , , , 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , , 1 ], [ , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, , 1, , , 1, 1, 1, 1, 1 ], [ , , , , , , , , , , , 1, , , , , , , , , 1, , , , 1 ], [ , 1, 1, , 1, 1, , 1, , , , 1, 1, , 1, 1, , , 1, , 1, 1, , 1 ], [ , 1, , 1, , 1, , , 1, , , 1, 1, , 1, 1, , , 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , , , , , , , , , 1, , 1, , 1, 1, , , , 1, , , 1 ], [ , 1, , , 1, 1, , , , , , , , , 1, 1, 1, , , , , 1 ], [ 1, , 1, 1, 1, , , , 1, 1, 1, 1, 1, , , 1, , , 1, , , 1, , 1, , 1 ], [ , 1, 1, , 1, 1, , 1, 1, , , , 1, 1, 1, , , 1, 1, , , 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, , 1, , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , 1, , , , , , , , , 1 ], [ , 1, , , , , , , , 1, , , , , 1, , , , 1, , , 1 ], [ , 1, 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , , , 1, , 1, , , , , 1, 1, 1, 1, 1, , , 1, , , , 1 ], [ , 1, , , , , , , , 1, , , , , , , , , , , , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ 1, 1, , 1, , 1, 1, , , , 1, , 1, 1, 1, 1, 1, , 1, 1, , , , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, , 1, 1, , , 1, 1, , , , 1, , 1, 1, , 1, 1 ], [ , , , , , , , , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, , 1, 1, 1, 1, , 1, , , 1, 1, 1, 1, , , 1, , , , , , , 1, 1 ], [ , 1, , , , , , , , 1, , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1 ], [ , 1, 1, , , , , , , , , , , , 1, 1, , , , , , 1 ], [ , 1, , , , , , , 1 ], [ , , , , , , , , , , , , , , 1, , , , , 1, , , , , , 1 ], [ 1, 1, , , 1, , , 1, 1, 1, , , , 1 ], , [ , , , , , , , , , , , , , 1, , , , , , , , , , 1 ], [ , , , , , , , , , 1, , , , , , , , , 1, , , , , , , 1 ], [ 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1, , , 1, , 1, , , 1, 1 ], [ , , , , , , , , , 1 ], [ , 1, , , , 1, , , 1, , , 1, , , 1, , , , , 1 ], [ , 1, 1, , 1, 1, , , , , , , , , , , , , , , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , 1, 1, , 1, 1, 1, 1, , , 1, 1, 1, , , , 1, , 1 ], [ 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, , 1, 1, , 1, 1 ], [ , , , , , , , , , , , , , , , 1, , , , 1 ], , [ 1, 1, , 1, , 1, , , , , , 1, , 1, , 1, 1, , 1, , 1, 1, , 1, 1, , 1 ], [ , , 1, , , , , , 1, , , , 1, , 1, , , , , 1 ], [ 1, , , , , , , , , 1, , , , , , 1, , , , 1, , 1, , , 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , 1, , 1, , , , , , 1, , , 1, , , , , , , , 1 ], [ , 1, , 1, , , , , , , , , , , , 1 ], , [ 1, 1, , , , , , , , , , , , , , , , , , , , , , 1, 1 ], [ 1 ] ], [ , [ 1, , , , , , , , , 1, , , , , 1, , 1, , 1 ], [ , 1, 1, , 1, 1, , 1, 1, 1, , , 1, 1, 1, , , , 1, , , 1, , , , 1 ], [ , 1, , , , , , , 1, , , , 1, , , , , , 1 ], [ 1, 1, 1, 1, 1, 1, , , , 1, , , , , , , , , 1, 1, 1, 1 ], [ 1 ], [ , 1, 1, , , 1, 1, , , , , 1, , 1, , , , , , , , 1, , , , 1 ], [ 1, , 1, , , 1, , 1, , , , , 1, 1, 1, 1, , , , 1, , , , 1 ], [ , , 1, , , , , , , 1, , , , , , , 1, , , , , , , 1 ], [ 1, , , , , , , , , , , , , , 1, , , , 1 ], [ , , , 1, , 1, , , , , 1, , , , 1, 1, , , , 1 ], [ 1, , , , , 1, , , 1, 1, , 1, 1, , , 1, 1, , 1, 1, 1, , 1, 1, 1, , 1 ], [ , 1, 1, , , , , 1, , 1, , 1, 1, 1, , 1, 1, , , 1, , 1, 1, 1 ], [ , 1, , , , 1, , , , 1, , , 1, , 1, 1, , , 1, 1, 1, , , , , 1 ], [ 1, , 1, 1, , 1, , 1, 1, , 1, , 1, 1, 1, 1, 1, , , 1, 1, , , , , , 1 ], [ 1, , , , , , , , , , , , , , , , , , 1, , , 1, , 1 ], [ , , , , , , , , , 1, , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , , , 1, , 1 ], [ , 1, , , , 1, , , 1, 1, , 1, , , 1, 1, , , 1, , , 1, , , 1, 1 ], [ 1, 1, , 1, 1, 1, , 1, 1, 1, , 1, , 1, 1, 1, , , 1, , 1, 1, 1 ], [ 1, , 1, 1, 1, 1, , , , 1, , 1, 1, 1, , 1, , , 1, 1, 1, , 1, 1, 1, 1, 1 ], [ 1, , , , , , , , , , , , , 1 ], [ , , 1, , , , , , , , , , , , , , , , , , , , 1 ], [ 1, , , , , , , , , , , 1, , 1, , 1, , , , 1 ], [ , , , 1, , , , , , , , , 1 ], [ , 1, , , , , , , , , , , , , , 1, , , , , , , , , 1 ], [ , , , , , , , , 1, 1, , , , 1, , , , , 1, , , , , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , , 1, 1, 1 ], [ , , , , , 1, , , , 1, 1, 1, , 1, 1, 1, , , 1, , 1, 1, , 1 ], [ , , , , , , , , , , , , , , , , , , , 1, 1 ], [ , 1, , , , , , 1, , , , , , , , , , , , , 1 ], [ , , 1, , , 1, , 1, 1, 1, , 1, 1, , 1, , , , 1, , 1, 1 ], , [ , , 1, , , 1, , , , , , 1, , , , 1 ], [ , , , , , , , , , 1, , , , , , , , , , 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, , , 1, 1, , 1, , 1, , , 1, 1, 1, , , 1 ], [ , , , , , 1, , , , , , , , , , , , , 1 ], [ , 1, , , , , , , , , , , , 1, , 1, 1, , 1, 1, , 1 ], [ , , , , , 1, , , , , , , , , , , , , , 1 ], [ , 1, 1, 1, 1, , , , , 1, , , 1, , 1, , , , 1, 1, , , , 1, 1 ], [ , 1, , , 1, , , 1, , 1, 1, , 1, , , , , , , 1 ], [ , , 1, , 1, , , 1, , , , , , , , , , , 1, 1, , , , 1 ], [ , 1, , , , , , , , , , , , , , , , , 1, , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, , , , , , , , , , , , , , , , 1, , 1, 1 ], [ , , , , , , , , , , , , 1 ], , [ , 1, 1, 1, 1, , , , 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, , 1 ], [ 1, , , , 1, , , , , , , , , , 1 ], [ 1, , , , , , , , , 1 ], , [ , 1, , , , 1, , , , , , , , , , , , , , , , , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, , , , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , 1, 1, 1, 1, , 1, , , , 1, 1, , , 1, 1, , 1 ], [ , 1, 1, , 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , , , , , , , , , , 1 ], [ 1, 1, 1, , , , , 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , , , , 1 ], [ , 1, , , , , , , 1, 1, , , 1, 1, 1, , 1, , , 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, , , , 1, , , , 1, , , 1, , , , 1, , , , , , , 1, 1 ], [ , 1, 1, 1, 1, 1, , , 1, 1, 1, , 1, 1, 1, 1, , , 1, 1, 1, 1, , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, , 1, , , 1, 1, 1, 1, , 1, 1, 1, 1, , , , 1, , 1, , 1, , , 1 ], [ 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , 1, , , , , , , , , 1, 1, , , , , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , 1 ], [ , 1, , 1, , 1, , 1, , 1, , 1, 1, 1, 1, 1, , , 1, , 1, , 1, , , , 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, , 1 ], [ 1, , , 1, , , , 1, 1, 1, , , , , 1, 1, , , , 1, , 1 ], [ 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ 1, 1, , , , , , , , 1, , 1, 1, , , , , , , 1, , 1 ], [ , 1, , , , 1, , 1, 1, , , , 1, 1, , 1, , , , 1, 1, 1, , 1 ], [ , , , , , , , , , , , , , 1 ], [ , 1, , , , , , 1, , , , , , , 1 ], [ , , , , , , , , 1, , , , 1, , 1, , , , , , , , , , , , 1 ] ], [ , [ , 1, 1, , 1, 1, 1, 1, , 1, 1, 1, , 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], [ , 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, , 1 ], [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , 1, , , , , , , , 1, , , , , , 1, , , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, , , , 1, 1, 1, , 1, 1, 1, 1, , , 1, 1, 1, 1, , , 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ 1, 1, , 1, , 1, , 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, , , 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, , , , , 1, 1, 1, , , 1, , 1, 1, , , , 1, , 1, , , 1, 1 ], [ , , , , , , , 1, , , , 1, 1, 1, 1, 1, , 1, , , 1, , , , , 1 ], [ 1, 1, 1, 1, , 1, 1, 1, , 1, , 1, 1, 1, 1, , 1, , 1, , 1, 1, , , 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , , 1, 1, , 1, , 1, 1, 1, , 1, , 1, 1, , 1, 1, , 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , , , , , , , 1, , , , , 1, , 1 ], [ , 1, 1, 1, , 1, , 1, , 1, , , , 1, , 1, , , 1, , , , , 1, 1, 1 ], [ , 1, , , 1, 1, , 1, , 1, , 1, 1, 1, 1, 1, , 1, 1, , , 1, , , 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, , , , , 1, , 1, , 1, , , , , 1, 1, , 1, , , , 1, 1 ] ], [ , [ , 1, , 1, , , , , , , , 1, , , , , , , 1, , , , 1 ], [ , , , , , , , , , 1, , 1, 1, 1, , 1, , , 1, , 1, 1 ], [ 1, 1, , , , , , , 1, , , , , 1, , 1, , , , , , 1 ], [ , 1, , , , , , , , , , 1, , , , , , , , , 1, 1 ], , [ , , , , , , , , , , , , , , , 1, , , , 1, , 1 ], [ , , 1, 1, , 1, , 1, , , , , , , , 1, , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , , 1, 1 ], [ , 1, , , , 1, , , , , , , , , 1 ], [ 1, , 1, 1, , , , 1, , , , , , , , , 1, , , 1, , , 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, , 1, 1, , 1, , 1 ], [ , 1, , , 1, 1, , , , , , 1, , 1, , 1, , , 1, , 1, 1 ], [ 1, 1, 1, 1, , 1, , 1, , 1, , 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , , 1, , 1, , 1, 1, 1, , , 1, 1, 1, , 1, 1, 1, 1, , 1, 1 ], [ , , , , 1, , , 1, , , , , , , 1, , , , 1, 1 ], [ , 1, , , , , , , , , , 1, , 1, , 1, , , , , 1, , , , , 1 ], , [ 1, 1, , 1, , 1, , 1, 1, , , , , , 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, , , , , , 1, , , , , 1, 1, 1, , , , 1, 1, , , 1 ], [ , 1, 1, , 1, 1, , , , 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, , , 1, , , , 1, , , , 1, 1 ], [ , , , , 1 ], [ , , , , , , , , , 1, , , 1 ], , [ , , 1, , 1, , , , , , , , , 1, , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , 1, 1, , 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, , , , , 1 ], [ , 1, , 1, , , , , , 1, , , , , 1, 1, , , , , 1, 1 ], [ , 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, , , 1, , 1, 1, 1 ], [ , 1, , , , 1, , , , , , , 1 ], [ , 1, , , 1, , , 1, , 1, , 1, 1, , 1, , , , , 1, , 1, , , , 1, 1 ], [ , 1, , , 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, 1, , , , 1, 1, , , , , , 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, 1 ], [ , 1, , , , 1, , , , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , 1, , , , , , , , 1, , , , , , , , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, , 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1 ], [ 1, 1, , , , , , , 1, 1, , , , , 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, , 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1 ], , [ , 1, 1, , , , , 1, , 1, , , , 1, 1, 1, , , 1, , , , , 1 ], [ , , , , , , , , , , , , , 1 ], [ , , , , , 1, , , , , , , , 1, 1, , , , , 1, , 1, , , 1, 1 ], [ , , , , , 1, , , 1, , , , , , 1 ] ], [ , [ , 1 ], , , , , , , , , , , , , , , , , , , , [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, , , 1, 1, 1, 1, 1 ], [ , 1, , 1, , 1, , , 1, 1, 1, , 1, 1, 1, 1, 1, , , 1, , , , 1, , 1, 1 ], [ , 1, , 1, , 1, , , 1, , , , , 1, , , , , , 1, 1 ], [ , 1, , 1, , , , , 1, , , , 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ , 1, , , , , , , , , , , , , , , 1 ] ], [ , [ , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , 1, , , , , , , , , 1, 1, , , , 1 ], [ , , , , , , 1 ], [ , , 1 ], [ , 1, 1, , , 1, , 1, , 1, 1, , 1, 1, 1, , , , 1, 1, 1, , , , , 1 ], , [ , 1, , , , 1, , , , , , 1, , , 1, , , , 1, 1, , 1 ], [ , , , , , , , 1, , , , , , , , , 1 ], [ , 1, 1, , , 1, 1, , , , , , 1, 1, 1, , , , 1, , 1, 1 ], [ , , , , , , , 1, , 1, , , , , , , , , , 1 ], [ , 1, 1, , , , , , 1, 1, , , , 1, , , , , , , 1, , , 1 ], , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, , 1, , , 1, , , , , 1, , 1, , 1, , 1, , , , , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , , , , 1, 1, , 1, 1, , 1, , , 1, , 1 ], [ , , , , , , , , , , , , , , 1, , , , , , 1 ], , [ , , , , , , , , , 1, , , , 1, , 1, , , , , 1 ], [ , , 1, , , , , , , 1, , 1, 1, 1, 1, , , , , , , , , 1 ], [ , , , 1, , , , , 1, , , , , 1, , , , , , 1, , , , 1 ], [ 1, , 1, 1, , 1, 1, 1, 1, 1, , 1, , , , 1, 1, 1, , , 1, 1, , , , 1, 1 ], , [ 1, 1, , , , , , , , , , 1, 1, 1, , 1, , , 1 ], [ , , , , 1, , , , , , , , , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , , 1, , , , , 1, , 1 ], [ , , , , , , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , , 1, , , 1, , , , , , , , 1, , , , , , 1, , , , 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, , , , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , , 1, 1, 1, 1, , 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ 1, 1, , , , , , , 1, , 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, , , 1 ], [ 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], [ 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ 1, 1, 1, 1, , 1, , 1, , 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, , 1, , , , , , 1, , 1, , , , , 1, 1, , , , , 1 ], [ 1, , 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , 1, 1, , 1, , 1, , , , 1, 1, 1, 1, 1, , , 1, 1, , 1, , 1 ], [ , 1, 1, 1, 1, , , , , 1, , 1, 1, 1, 1, 1, , , 1, 1, , , , 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, , , , , 1, , 1, , 1, , , 1, , , 1, 1, , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , , , , , , , 1, , , , , 1, 1, , , 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , , 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , , , 1, , 1, 1, , 1, 1, 1, 1, 1, , , 1, , 1, , 1 ], [ 1, 1, 1, , 1, 1, 1, 1, , , , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , , 1, , , , , , , , , , 1, 1, 1, 1, 1, 1, 1, , 1, 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , 1, 1, , , , 1, , 1, 1, 1, 1, 1, , , , 1, 1, 1, , 1, 1, 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1 ], [ , 1, 1, 1, , 1, , 1, 1, 1, 1, , , 1, 1, 1, , 1, 1, 1, 1, 1, , , 1, 1 ], [ 1, 1, , , , 1, , , 1, 1, 1, , 1, , 1, , 1, , 1, 1, 1, 1, 1, , 1, 1, 1 ], [ , 1, , , , , , , 1, , 1, , 1, 1, 1, 1, , , , , , , , , 1 ] ], [ , [ , , , , , , , , , , , , , 1, 1, , , , 1 ], [ , 1, , , , , , , , 1, , , 1, , , , , , 1, , , 1, , , , 1 ], , [ , 1, , , , 1, , 1, , 1, 1, , 1, 1, , , , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , 1 ], [ , , , , , , , , , 1 ], [ 1, 1, 1, , , 1, , , 1, , , , , , 1, 1, , , , , , , , , , 1 ], [ , 1, , , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , , , , , , , 1, , , 1 ], [ , , , , , , , , , 1 ], [ 1, 1, , , , , , 1, 1, 1, , 1, 1, , , , 1, 1, , 1, , 1, 1, 1, , 1 ], [ , 1, 1, 1, , 1, 1, , , 1, , 1, 1, 1, 1, , , , , , , 1, , 1, , 1 ], [ , 1, 1, 1, 1, , , 1, , 1, , , , 1, 1, 1, 1, , 1, 1, , 1 ], [ , 1, , , 1, 1, , 1, , 1, , 1, , 1, 1, , 1, , 1, , , 1, , , 1, , 1 ], [ , , , , , , , , , , , 1, , , 1 ], [ , , , , , , , , , 1, , , , , , , , , , , , , 1 ], , [ 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , , , , 1, 1, , 1, , , , , 1, , , 1, , 1 ], [ , 1, , , , 1, , , 1, , , , , , , , 1, , 1, , , 1 ], [ , , , , , , , , , , , , , 1, 1, , , , 1, , , 1 ], [ , , , , , 1, , , 1, , , , 1 ], [ , 1 ], , [ , 1 ], [ 1, , , , , , , , , , , , , , 1, , , , , 1 ] ], [ , [ , 1, , , , 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, , 1, 1, , 1, 1, , , 1 ], [ , , 1, , , , , , , , , 1 ], , , [ 1, , , 1, 1, , , , , , , , 1, 1, , 1, 1, , 1 ], , [ , , , , , , , , , , , , , , , , , , 1, , 1 ], , [ 1, , , 1, 1, , 1, 1, , , , , 1, , 1, , , , , 1, 1, , 1 ], [ , , , , , , , , , , , 1 ], [ , 1, , , , , , , , 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, 1, , , , , 1 ], [ , , , , , , , , , , , , , , , , 1, , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , , , , , , , , , , , 1, , 1, , , 1 ], [ 1, , , , , , , , , , , , , , , , , , 1, , 1 ], , , [ , 1, , , , , , , , , , , , , , 1, , , , 1, 1 ], [ , , , , , , , , , 1, , , 1, , 1, , , , , , , , 1 ], [ , , , , , , , , , , , , , , , 1 ], [ , , , , , , , , , , , , , 1, 1, , , , , , 1 ], , [ , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , , 1, 1, , 1, 1, 1, 1, 1, 1, , , 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, , , , , , , , 1 ], [ , , , , 1, , , 1, , , 1, 1, , , , , , , , , 1, 1, , , , 1 ], [ , 1, , 1, 1, , , 1, 1, 1, , , , 1, 1, 1, 1, , 1, 1, 1, 1, , 1 ], [ , , , , , , , 1 ], [ , 1, 1, , , , , 1, , 1, , , , , , 1, , , , , , 1, , 1, , 1 ], [ , 1, , , , , , 1, , , , 1, , , , , , , , , , 1 ], [ , , 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, , 1, 1, 1, 1, , 1 ], [ , 1, , , , , , , , 1 ], [ , 1, 1, , 1, , , , , , , , 1, , , , , , 1, , , 1, , 1, , 1 ], [ , 1, , 1, , 1, , 1, 1, 1, , 1, 1, 1, , 1, , , 1, 1, , 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, , , , 1, 1, 1, , , , 1, 1, , , 1, 1 ], [ , , 1, 1, 1, 1, , 1, , 1, , 1, , 1, 1, 1, 1, , , , , 1, , 1, , 1 ], [ 1, 1, 1, 1, 1, 1, 1, 1, , 1, , 1, , 1, 1, 1, , , 1, 1, , , , 1, , 1 ], [ , , , 1 ], , [ , 1, 1, , 1, , , 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, , 1, 1, 1, 1, 1, 1 ], [ , 1, , , , , , 1, , 1, , 1, , , , , , , 1, 1, , 1, 1 ], [ , , 1, , , , 1, , 1, 1, , 1, , 1, , , , , , , , , , 1 ], [ , 1, 1, , 1, , , , 1, , , , 1, 1, 1, , , , 1, , 1, 1, 1, , 1, 1 ], , [ , 1, 1, , , , , , , , , , , , , 1, , , 1, , , , , 1 ], [ , 1, , , , , , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, , , , , , , 1, , , , 1, 1, , , , 1, , , , , , , 1 ] ], [ , [ , 1, 1, 1, 1, 1, , 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, , 1, , 1, 1, , , 1, 1, 1, 1, , 1, , , , , 1, 1, 1 ], [ , , 1, 1, , 1, , 1, 1, , , , 1, 1, 1, 1, , , 1, , 1, 1, 1, 1, , 1 ], [ , 1, , 1, , , , , , , , 1, , 1, , 1, , 1, , , , , , , , 1 ], [ , , 1, , 1, , , 1, , , , , 1, 1, , , 1, , 1, 1, 1, 1 ], [ , 1 ], [ , 1, 1, , 1, , 1, 1, , 1, , , 1, 1, 1, , , , 1, , , 1, , 1 ], [ 1, 1, , 1, 1, 1, , , , , , , , 1, , , , , 1, , 1, 1, 1 ], [ , 1, 1, , , , , , , 1, , , 1, , 1, , 1, , 1, 1, , , 1, , , 1 ], [ , , 1, , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, 1, 1, 1, , 1, , 1, , , , , 1, 1, 1, , , 1, , 1, , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, , , 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, , , , 1, 1 ], [ , , , 1, 1, , , 1, , 1, , 1, , 1, 1, 1, 1, , 1, , , , , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , , , , , , , , , , , , , , , , , 1 ], [ , 1, 1, , 1, 1, , 1, , 1, , , , 1, 1, , , 1, 1, , 1, 1, , 1 ], [ , 1, 1, 1, 1, 1, , , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, , , 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1 ], [ , 1, 1, , 1, , , 1, , , 1, , 1, 1, 1, 1, 1, , 1, , 1, 1 ], [ , , , , , 1, , , , 1, , , , , 1, 1, , , , 1 ], [ , 1, , 1, 1, 1, , 1, , , 1, 1, 1, , , 1, , , 1, , 1, , , 1 ], [ , , 1, , , , , , , , , 1, , 1, , , , , 1, , 1 ], [ , 1, 1, , , , , , , , 1, 1, 1, , , , , , , , 1, , , , , 1 ], [ , , , , , , , , 1, , , , , 1, , , 1 ] ], [ , [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, 1, , 1, 1, , , 1, 1, 1, 1, 1, 1, 1, 1, , , , , , , , , 1, 1 ], [ , , , , , , , , 1, , , , 1, , 1, , 1, , 1 ], [ , 1, , , 1, 1, , 1, , , , 1, , , , , , , , 1 ], [ , 1, , 1, , 1, , , , 1, 1, , 1, , 1, , , , 1, 1, 1, 1, 1, , , 1 ], , [ , 1, , , , , , , , 1, , , 1, 1, , , 1, , 1, 1, , 1, , 1 ], [ , 1, , , 1, , , , , , , , 1, , , , , , , 1 ], [ 1, 1, , , , , 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1 ], , [ , 1, , , , , , 1, 1, 1, , 1, 1, 1, 1, 1, , , 1, , 1, 1, , , , 1 ], [ , 1, 1, , , 1, , 1, , 1, , , 1, 1, 1, 1, , , 1, , , 1, , , , 1 ], [ , 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , , , 1, , 1 ], [ , 1, 1, , 1, 1, , 1, 1, , , 1, 1, , 1, 1, , 1, , 1, , 1 ], [ 1, , 1, , , , , 1, , 1, , 1, 1, 1, 1, , , , , 1, 1, , , , 1, 1 ], [ , 1, 1, , , , , 1, 1, , , 1, , 1, 1, 1, 1, , , , , , , , , , 1 ], , [ , 1, 1, , , 1, , , , 1, , 1, 1, 1, 1, 1, , , , 1, , , , 1, , 1 ], [ , , , 1, 1, , , 1, , , , , 1, 1, 1, 1, 1, , 1, 1, , , , , , 1 ], [ , 1, , , , , , , , , , , 1, , , , 1, , , , , , , 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, , 1, 1, 1, , 1, 1, , 1, 1, 1, 1 ], [ , 1, , , , , , , , , , , , , , , , , , , 1 ], [ , 1, , , , , , 1, , , , , 1, , 1, , , 1, 1, , 1, 1, , 1 ], [ , 1, , , , , , 1, , , , , 1, 1, , , , , , , , 1, , , , 1 ], [ , , , , , , , , , , , , , , , , , , 1, , , 1, , , , , 1 ], [ , , , , , , , 1, , , , 1 ] ], [ , [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , 1, , 1, , , , , , , 1, , , , , , , , 1, 1, , 1 ], [ , 1, , , 1, , , , 1 ], [ , , , , , , , , , , 1 ], [ , 1, , , , , , 1, 1, , , , , 1, 1 ], , [ , 1, 1, , , , , , 1, , , , , 1, 1, , , , 1 ], [ 1, , 1, , 1, , , , , 1, , , , , 1, , , , , , , , , 1, 1 ], [ , 1, 1, , , , , , , , , 1, 1, 1, 1, , , , 1, , , , , 1, , , 1 ], , [ , 1, 1, , 1, , , 1, 1, , , 1, , , 1, 1, 1, , 1, , 1, 1, 1, , , , 1 ], [ , 1, , , , 1, , , , , 1, , , 1, 1, , , 1, , 1, , 1, , 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , 1, , , 1, 1, , 1, , , , 1, , , , , , , , 1 ], [ , , , 1, , , , , 1, , , , , 1, , 1, , 1, 1, 1 ], [ , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [ , , , , , 1 ], [ , 1, , , , , , 1, , , , , , , 1, 1, 1, , , 1 ], [ , 1, , , , , , , , , , 1, 1, 1, , , , , 1, , , 1 ], [ , , , , , 1, , 1, , , , , 1, 1, 1, , 1, 1, , 1, 1, 1, , , 1, 1 ], [ 1, 1, , , , , , , 1, , , , , 1, 1, , , , , , , , , , , 1 ], , [ , 1 ], [ , , , , , , , , , , , , , , , , , , , , , , , , 1 ], [ , , 1, , , , , 1, , , 1, , , , 1, , 1 ], [ , 1, , , , , , , , , 1 ] ] ]; + function isValidLang(lang) { + var array = langs; + while (lang.length < 3) { + lang += '`'; + } + for (var _i24 = 0; _i24 <= lang.length - 1; _i24++) { + var index = lang.charCodeAt(_i24) - 96; + array = array[index]; + if (!array) { + return false; + } + } + return true; + } + function _validLangs(langArray) { + langArray = Array.isArray(langArray) ? langArray : langs; + var codes = []; + langArray.forEach(function(lang, index) { + var _char3 = String.fromCharCode(index + 96).replace('`', ''); + if (Array.isArray(lang)) { + codes = codes.concat(_validLangs(lang).map(function(newLang) { + return _char3 + newLang; + })); + } else { + codes.push(_char3); + } + }); + return codes; + } + var valid_langs_default = isValidLang; + var SerialVirtualNode = function(_abstract_virtual_nod2) { + function SerialVirtualNode(serialNode) { + var _this8; + _classCallCheck(this, SerialVirtualNode); + _this8 = _callSuper(this, SerialVirtualNode); + _this8._props = normaliseProps(serialNode); + _this8._attrs = normaliseAttrs(serialNode); + return _this8; + } + _inherits(SerialVirtualNode, _abstract_virtual_nod2); + return _createClass(SerialVirtualNode, [ { + key: 'props', + get: function get() { + return this._props; + } + }, { + key: 'attr', + value: function attr(attrName) { + var _this$_attrs$attrName; + return (_this$_attrs$attrName = this._attrs[attrName]) !== null && _this$_attrs$attrName !== void 0 ? _this$_attrs$attrName : null; + } + }, { + key: 'hasAttr', + value: function hasAttr(attrName) { + return this._attrs[attrName] !== void 0; + } + }, { + key: 'attrNames', + get: function get() { + return Object.keys(this._attrs); + } + } ]); + }(abstract_virtual_node_default); + var nodeNamesToTypes = { + '#cdata-section': 2, + '#text': 3, + '#comment': 8, + '#document': 9, + '#document-fragment': 11 + }; + var nodeTypeToName = {}; + var nodeNames = Object.keys(nodeNamesToTypes); + nodeNames.forEach(function(nodeName2) { + nodeTypeToName[nodeNamesToTypes[nodeName2]] = nodeName2; + }); + function normaliseProps(serialNode) { + var _serialNode$nodeName, _ref85, _serialNode$nodeType; + var nodeName2 = (_serialNode$nodeName = serialNode.nodeName) !== null && _serialNode$nodeName !== void 0 ? _serialNode$nodeName : nodeTypeToName[serialNode.nodeType]; + var nodeType = (_ref85 = (_serialNode$nodeType = serialNode.nodeType) !== null && _serialNode$nodeType !== void 0 ? _serialNode$nodeType : nodeNamesToTypes[serialNode.nodeName]) !== null && _ref85 !== void 0 ? _ref85 : 1; + assert_default(typeof nodeType === 'number', 'nodeType has to be a number, got \''.concat(nodeType, '\'')); + assert_default(typeof nodeName2 === 'string', 'nodeName has to be a string, got \''.concat(nodeName2, '\'')); + nodeName2 = nodeName2.toLowerCase(); + var type2 = null; + if (nodeName2 === 'input') { + type2 = (serialNode.type || serialNode.attributes && serialNode.attributes.type || '').toLowerCase(); + if (!valid_input_type_default().includes(type2)) { + type2 = 'text'; + } + } + var props = _extends({}, serialNode, { + nodeType: nodeType, + nodeName: nodeName2 + }); + if (type2) { + props.type = type2; + } + delete props.attributes; + return Object.freeze(props); + } + function normaliseAttrs(_ref86) { + var _ref86$attributes = _ref86.attributes, attributes2 = _ref86$attributes === void 0 ? {} : _ref86$attributes; + var attrMap = { + htmlFor: 'for', + className: 'class' + }; + return Object.keys(attributes2).reduce(function(attrs, attrName) { + var value = attributes2[attrName]; + assert_default(_typeof(value) !== 'object' || value === null, 'expects attributes not to be an object, \''.concat(attrName, '\' was')); + if (value !== void 0) { + var mappedName = attrMap[attrName] || attrName; + attrs[mappedName] = value !== null ? String(value) : null; + } + return attrs; + }, {}); + } + var serial_virtual_node_default = SerialVirtualNode; + function cleanup(resolve, reject) { + resolve = resolve || function res() {}; + reject = reject || axe.log; + if (!axe._audit) { + throw new Error('No audit configured'); + } + var q = axe.utils.queue(); + var cleanupErrors = []; + Object.keys(axe.plugins).forEach(function(key) { + q.defer(function(res) { + var rej = function rej2(err2) { + cleanupErrors.push(err2); + res(); + }; + try { + axe.plugins[key].cleanup(res, rej); + } catch (err2) { + rej(err2); + } + }); + }); + var flattenedTree = axe.utils.getFlattenedTree(document.body); + axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function(node) { + q.defer(function(res, rej) { + return axe.utils.sendCommandToFrame(node.actualNode, { + command: 'cleanup-plugin' + }, res, rej); + }); + }); + q.then(function(results) { + if (cleanupErrors.length === 0) { + resolve(results); + } else { + reject(cleanupErrors); + } + })['catch'](reject); + } + var cleanup_default = cleanup; + var reporters = {}; + var defaultReporter; + function hasReporter(reporterName) { + return reporters.hasOwnProperty(reporterName); + } + function getReporter(reporter) { + if (typeof reporter === 'string' && reporters[reporter]) { + return reporters[reporter]; + } + if (typeof reporter === 'function') { + return reporter; + } + return defaultReporter; + } + function addReporter(name, cb, isDefault) { + reporters[name] = cb; + if (isDefault) { + defaultReporter = cb; + } + } + function configure(spec) { + var audit = axe._audit; + if (!audit) { + throw new Error('No audit configured'); + } + if (spec.axeVersion || spec.ver) { + var specVersion = spec.axeVersion || spec.ver; + if (!/^\d+\.\d+\.\d+(-canary)?/.test(specVersion)) { + throw new Error('Invalid configured version '.concat(specVersion)); + } + var _specVersion$split = specVersion.split('-'), _specVersion$split2 = _slicedToArray(_specVersion$split, 2), version = _specVersion$split2[0], canary = _specVersion$split2[1]; + var _version$split$map = version.split('.').map(Number), _version$split$map2 = _slicedToArray(_version$split$map, 3), major = _version$split$map2[0], minor = _version$split$map2[1], patch = _version$split$map2[2]; + var _axe$version$split = axe.version.split('-'), _axe$version$split2 = _slicedToArray(_axe$version$split, 2), axeVersion = _axe$version$split2[0], axeCanary = _axe$version$split2[1]; + var _axeVersion$split$map = axeVersion.split('.').map(Number), _axeVersion$split$map2 = _slicedToArray(_axeVersion$split$map, 3), axeMajor = _axeVersion$split$map2[0], axeMinor = _axeVersion$split$map2[1], axePatch = _axeVersion$split$map2[2]; + if (major !== axeMajor || axeMinor < minor || axeMinor === minor && axePatch < patch || major === axeMajor && minor === axeMinor && patch === axePatch && canary && canary !== axeCanary) { + throw new Error('Configured version '.concat(specVersion, ' is not compatible with current axe version ').concat(axe.version)); + } + } + if (spec.reporter && (typeof spec.reporter === 'function' || hasReporter(spec.reporter))) { + audit.reporter = spec.reporter; + } + if (spec.checks) { + if (!Array.isArray(spec.checks)) { + throw new TypeError('Checks property must be an array'); + } + spec.checks.forEach(function(check) { + if (!check.id) { + throw new TypeError('Configured check '.concat(JSON.stringify(check), ' is invalid. Checks must be an object with at least an id property')); + } + audit.addCheck(check); + }); + } + var modifiedRules = []; + if (spec.rules) { + if (!Array.isArray(spec.rules)) { + throw new TypeError('Rules property must be an array'); + } + spec.rules.forEach(function(rule) { + if (!rule.id) { + throw new TypeError('Configured rule '.concat(JSON.stringify(rule), ' is invalid. Rules must be an object with at least an id property')); + } + modifiedRules.push(rule.id); + audit.addRule(rule); + }); + } + if (spec.disableOtherRules) { + audit.rules.forEach(function(rule) { + if (modifiedRules.includes(rule.id) === false) { + rule.enabled = false; + } + }); + } + if (typeof spec.branding !== 'undefined') { + audit.setBranding(spec.branding); + } else { + audit._constructHelpUrls(); + } + if (spec.tagExclude) { + audit.tagExclude = spec.tagExclude; + } + if (spec.locale) { + audit.applyLocale(spec.locale); + } + if (spec.standards) { + configureStandards(spec.standards); + } + if (spec.noHtml) { + audit.noHtml = true; + } + if (spec.allowedOrigins) { + if (!Array.isArray(spec.allowedOrigins)) { + throw new TypeError('Allowed origins property must be an array'); + } + if (spec.allowedOrigins.includes('*')) { + throw new Error('"*" is not allowed. Use "'.concat(constants_default.allOrigins, '" instead')); + } + audit.setAllowedOrigins(spec.allowedOrigins); + } + } + var configure_default = configure; + function frameMessenger2(frameHandler) { + _respondable.updateMessenger(frameHandler); + } + function getRules(tags) { + tags = tags || []; + var matchingRules = !tags.length ? axe._audit.rules : axe._audit.rules.filter(function(item) { + return !!tags.filter(function(tag) { + return item.tags.indexOf(tag) !== -1; + }).length; + }); + var ruleData = axe._audit.data.rules || {}; + return matchingRules.map(function(matchingRule) { + var rd = ruleData[matchingRule.id] || {}; + return { + ruleId: matchingRule.id, + description: rd.description, + help: rd.help, + helpUrl: rd.helpUrl, + tags: matchingRule.tags, + actIds: matchingRule.actIds + }; + }); + } + var get_rules_default = getRules; + function hiddenContentEvaluate(node, options, virtualNode) { + var allowlist = [ 'SCRIPT', 'HEAD', 'TITLE', 'NOSCRIPT', 'STYLE', 'TEMPLATE' ]; + if (!allowlist.includes(node.nodeName.toUpperCase()) && has_content_virtual_default(virtualNode)) { + var styles = window.getComputedStyle(node); + if (styles.getPropertyValue('display') === 'none') { + return void 0; + } else if (styles.getPropertyValue('visibility') === 'hidden') { + var parent = get_composed_parent_default(node); + var parentStyle = parent && window.getComputedStyle(parent); + if (!parentStyle || parentStyle.getPropertyValue('visibility') !== 'hidden') { + return void 0; + } + } + } + return true; + } + var hidden_content_evaluate_default = hiddenContentEvaluate; + var table_exports = {}; + __export(table_exports, { + getAllCells: function getAllCells() { + return get_all_cells_default; + }, + getCellPosition: function getCellPosition() { + return get_cell_position_default; + }, + getHeaders: function getHeaders() { + return get_headers_default; + }, + getScope: function getScope() { + return _getScope; + }, + isColumnHeader: function isColumnHeader() { + return is_column_header_default; + }, + isDataCell: function isDataCell() { + return is_data_cell_default; + }, + isDataTable: function isDataTable() { + return is_data_table_default; + }, + isHeader: function isHeader() { + return is_header_default; + }, + isRowHeader: function isRowHeader() { + return is_row_header_default; + }, + toArray: function toArray() { + return to_grid_default; + }, + toGrid: function toGrid() { + return to_grid_default; + }, + traverse: function traverse() { + return traverse_default; + } + }); + function getAllCells(tableElm) { + var rowIndex, cellIndex, rowLength, cellLength; + var cells = []; + for (rowIndex = 0, rowLength = tableElm.rows.length; rowIndex < rowLength; rowIndex++) { + for (cellIndex = 0, cellLength = tableElm.rows[rowIndex].cells.length; cellIndex < cellLength; cellIndex++) { + cells.push(tableElm.rows[rowIndex].cells[cellIndex]); + } + } + return cells; + } + var get_all_cells_default = getAllCells; + function traverseForHeaders(headerType, position, tableGrid) { + var property = headerType === 'row' ? '_rowHeaders' : '_colHeaders'; + var predicate = headerType === 'row' ? is_row_header_default : is_column_header_default; + var startCell = tableGrid[position.y][position.x]; + var colspan = startCell.colSpan - 1; + var rowspanAttr = startCell.getAttribute('rowspan'); + var rowspanValue = parseInt(rowspanAttr) === 0 || startCell.rowspan === 0 ? tableGrid.length : startCell.rowSpan; + var rowspan = rowspanValue - 1; + var rowStart = position.y + rowspan; + var colStart = position.x + colspan; + var rowEnd = headerType === 'row' ? position.y : 0; + var colEnd = headerType === 'row' ? 0 : position.x; + var headers; + var cells = []; + for (var row = rowStart; row >= rowEnd && !headers; row--) { + for (var col = colStart; col >= colEnd; col--) { + var cell = tableGrid[row] ? tableGrid[row][col] : void 0; + if (!cell) { + continue; + } + var vNode = axe.utils.getNodeFromTree(cell); + if (vNode[property]) { + headers = vNode[property]; + break; + } + cells.push(cell); + } + } + headers = (headers || []).concat(cells.filter(predicate)); + cells.forEach(function(tableCell) { + var vNode = axe.utils.getNodeFromTree(tableCell); + vNode[property] = headers; + }); + return headers; + } + function getHeaders(cell, tableGrid) { + if (cell.getAttribute('headers')) { + var headers = idrefs_default(cell, 'headers'); + if (headers.filter(function(header) { + return header; + }).length) { + return headers; + } + } + if (!tableGrid) { + tableGrid = to_grid_default(find_up_default(cell, 'table')); + } + var position = get_cell_position_default(cell, tableGrid); + var rowHeaders = traverseForHeaders('row', position, tableGrid); + var colHeaders = traverseForHeaders('col', position, tableGrid); + return [].concat(rowHeaders, colHeaders).reverse(); + } + var get_headers_default = getHeaders; + function isDataCell(cell) { + if (!cell.children.length && !cell.textContent.trim()) { + return false; + } + var role = get_explicit_role_default(cell); + if (role) { + return [ 'cell', 'gridcell' ].includes(role); + } else { + return cell.nodeName.toUpperCase() === 'TD'; + } + } + var is_data_cell_default = isDataCell; + function isDataTable(node) { + var role = get_explicit_role_default(node); + if ((role === 'presentation' || role === 'none') && !_isFocusable(node)) { + return false; + } + if (node.getAttribute('contenteditable') === 'true' || find_up_default(node, '[contenteditable="true"]')) { + return true; + } + if (role === 'grid' || role === 'treegrid' || role === 'table') { + return true; + } + if (get_role_type_default(role) === 'landmark') { + return true; + } + if (node.getAttribute('datatable') === '0') { + return false; + } + if (node.getAttribute('summary')) { + return true; + } + if (node.tHead || node.tFoot || node.caption) { + return true; + } + for (var childIndex = 0, childLength = node.children.length; childIndex < childLength; childIndex++) { + if (node.children[childIndex].nodeName.toUpperCase() === 'COLGROUP') { + return true; + } + } + var cells = 0; + var rowLength = node.rows.length; + var row, cell; + var hasBorder = false; + for (var rowIndex = 0; rowIndex < rowLength; rowIndex++) { + row = node.rows[rowIndex]; + for (var cellIndex = 0, cellLength = row.cells.length; cellIndex < cellLength; cellIndex++) { + cell = row.cells[cellIndex]; + if (cell.nodeName.toUpperCase() === 'TH') { + return true; + } + if (!hasBorder && (cell.offsetWidth !== cell.clientWidth || cell.offsetHeight !== cell.clientHeight)) { + hasBorder = true; + } + if (cell.getAttribute('scope') || cell.getAttribute('headers') || cell.getAttribute('abbr')) { + return true; + } + if ([ 'columnheader', 'rowheader' ].includes(get_explicit_role_default(cell))) { + return true; + } + if (cell.children.length === 1 && cell.children[0].nodeName.toUpperCase() === 'ABBR') { + return true; + } + cells++; + } + } + if (node.getElementsByTagName('table').length) { + return false; + } + if (rowLength < 2) { + return false; + } + var sampleRow = node.rows[Math.ceil(rowLength / 2)]; + if (sampleRow.cells.length === 1 && sampleRow.cells[0].colSpan === 1) { + return false; + } + if (sampleRow.cells.length >= 5) { + return true; + } + if (hasBorder) { + return true; + } + var bgColor, bgImage; + for (var _rowIndex = 0; _rowIndex < rowLength; _rowIndex++) { + row = node.rows[_rowIndex]; + if (bgColor && bgColor !== window.getComputedStyle(row).getPropertyValue('background-color')) { + return true; + } else { + bgColor = window.getComputedStyle(row).getPropertyValue('background-color'); + } + if (bgImage && bgImage !== window.getComputedStyle(row).getPropertyValue('background-image')) { + return true; + } else { + bgImage = window.getComputedStyle(row).getPropertyValue('background-image'); + } + } + if (rowLength >= 20) { + return true; + } + if (get_element_coordinates_default(node).width > get_viewport_size_default(window).width * .95) { + return false; + } + if (cells < 10) { + return false; + } + if (node.querySelector('object, embed, iframe, applet')) { + return false; + } + return true; + } + var is_data_table_default = isDataTable; + function isHeader(cell) { + if (is_column_header_default(cell) || is_row_header_default(cell)) { + return true; + } + if (cell.getAttribute('id')) { + var _id4 = escape_selector_default(cell.getAttribute('id')); + return !!document.querySelector('[headers~="'.concat(_id4, '"]')); + } + return false; + } + var is_header_default = isHeader; + function traverseTable(dir, position, tableGrid, callback) { + var result; + var cell = tableGrid[position.y] ? tableGrid[position.y][position.x] : void 0; + if (!cell) { + return []; + } + if (typeof callback === 'function') { + result = callback(cell, position, tableGrid); + if (result === true) { + return [ cell ]; + } + } + result = traverseTable(dir, { + x: position.x + dir.x, + y: position.y + dir.y + }, tableGrid, callback); + result.unshift(cell); + return result; + } + function traverse(dir, startPos, tableGrid, callback) { + if (Array.isArray(startPos)) { + callback = tableGrid; + tableGrid = startPos; + startPos = { + x: 0, + y: 0 + }; + } + if (typeof dir === 'string') { + switch (dir) { + case 'left': + dir = { + x: -1, + y: 0 + }; + break; + + case 'up': + dir = { + x: 0, + y: -1 + }; + break; + + case 'right': + dir = { + x: 1, + y: 0 + }; + break; + + case 'down': + dir = { + x: 0, + y: 1 + }; + break; + } + } + return traverseTable(dir, { + x: startPos.x + dir.x, + y: startPos.y + dir.y + }, tableGrid, callback); + } + var traverse_default = traverse; + var aria_exports = {}; + __export(aria_exports, { + allowedAttr: function allowedAttr() { + return allowed_attr_default; + }, + arialabelText: function arialabelText() { + return _arialabelText; + }, + arialabelledbyText: function arialabelledbyText() { + return arialabelledby_text_default; + }, + getAccessibleRefs: function getAccessibleRefs() { + return get_accessible_refs_default; + }, + getElementUnallowedRoles: function getElementUnallowedRoles() { + return get_element_unallowed_roles_default; + }, + getExplicitRole: function getExplicitRole() { + return get_explicit_role_default; + }, + getImplicitRole: function getImplicitRole() { + return implicit_role_default; + }, + getOwnedVirtual: function getOwnedVirtual() { + return get_owned_virtual_default; + }, + getRole: function getRole() { + return get_role_default; + }, + getRoleType: function getRoleType() { + return get_role_type_default; + }, + getRolesByType: function getRolesByType() { + return get_roles_by_type_default; + }, + getRolesWithNameFromContents: function getRolesWithNameFromContents() { + return get_roles_with_name_from_contents_default; + }, + implicitNodes: function implicitNodes() { + return implicit_nodes_default; + }, + implicitRole: function implicitRole() { + return implicit_role_default; + }, + isAccessibleRef: function isAccessibleRef() { + return is_accessible_ref_default; + }, + isAriaRoleAllowedOnElement: function isAriaRoleAllowedOnElement() { + return is_aria_role_allowed_on_element_default; + }, + isComboboxPopup: function isComboboxPopup() { + return _isComboboxPopup; + }, + isUnsupportedRole: function isUnsupportedRole() { + return is_unsupported_role_default; + }, + isValidRole: function isValidRole() { + return is_valid_role_default; + }, + label: function label() { + return label_default2; + }, + labelVirtual: function labelVirtual() { + return label_virtual_default; + }, + lookupTable: function lookupTable() { + return lookup_table_default; + }, + namedFromContents: function namedFromContents() { + return named_from_contents_default; + }, + requiredAttr: function requiredAttr() { + return required_attr_default; + }, + requiredContext: function requiredContext() { + return required_context_default; + }, + requiredOwned: function requiredOwned() { + return required_owned_default; + }, + validateAttr: function validateAttr() { + return validate_attr_default; + }, + validateAttrValue: function validateAttrValue() { + return validate_attr_value_default; + } + }); + function allowedAttr(role) { + var roleDef = standards_default.ariaRoles[role]; + var attrs = _toConsumableArray(get_global_aria_attrs_default()); + if (!roleDef) { + return attrs; + } + if (roleDef.allowedAttrs) { + attrs.push.apply(attrs, _toConsumableArray(roleDef.allowedAttrs)); + } + if (roleDef.requiredAttrs) { + attrs.push.apply(attrs, _toConsumableArray(roleDef.requiredAttrs)); + } + return attrs; + } + var allowed_attr_default = allowedAttr; + var idRefsRegex = /^idrefs?$/; + function cacheIdRefs(node, idRefs, refAttrs) { + if (node.hasAttribute) { + if (node.nodeName.toUpperCase() === 'LABEL' && node.hasAttribute('for')) { + var _id5 = node.getAttribute('for'); + if (!idRefs.has(_id5)) { + idRefs.set(_id5, [ node ]); + } else { + idRefs.get(_id5).push(node); + } + } + for (var _i25 = 0; _i25 < refAttrs.length; ++_i25) { + var attr = refAttrs[_i25]; + var attrValue = sanitize_default(node.getAttribute(attr) || ''); + if (!attrValue) { + continue; + } + var _iterator14 = _createForOfIteratorHelper(token_list_default(attrValue)), _step14; + try { + for (_iterator14.s(); !(_step14 = _iterator14.n()).done; ) { + var token = _step14.value; + if (!idRefs.has(token)) { + idRefs.set(token, [ node ]); + } else { + idRefs.get(token).push(node); + } + } + } catch (err) { + _iterator14.e(err); + } finally { + _iterator14.f(); + } + } + } + for (var _i26 = 0; _i26 < node.childNodes.length; _i26++) { + if (node.childNodes[_i26].nodeType === 1) { + cacheIdRefs(node.childNodes[_i26], idRefs, refAttrs); + } + } + } + function getAccessibleRefs(node) { + var _idRefs$get; + node = node.actualNode || node; + var root = get_root_node_default2(node); + root = root.documentElement || root; + var idRefsByRoot = cache_default.get('idRefsByRoot', function() { + return new Map(); + }); + var idRefs = idRefsByRoot.get(root); + if (!idRefs) { + idRefs = new Map(); + idRefsByRoot.set(root, idRefs); + var refAttrs = Object.keys(standards_default.ariaAttrs).filter(function(attr) { + var type2 = standards_default.ariaAttrs[attr].type; + return idRefsRegex.test(type2); + }); + cacheIdRefs(root, idRefs, refAttrs); + } + return (_idRefs$get = idRefs.get(node.id)) !== null && _idRefs$get !== void 0 ? _idRefs$get : []; + } + var get_accessible_refs_default = getAccessibleRefs; + function isAriaRoleAllowedOnElement(node, role) { + var vNode = node instanceof abstract_virtual_node_default ? node : get_node_from_tree_default(node); + var implicitRole3 = implicit_role_default(vNode); + var spec = get_element_spec_default(vNode); + if (Array.isArray(spec.allowedRoles)) { + return spec.allowedRoles.includes(role); + } + if (role === implicitRole3) { + return false; + } + return !!spec.allowedRoles; + } + var is_aria_role_allowed_on_element_default = isAriaRoleAllowedOnElement; + var dpubRoles2 = [ 'doc-backlink', 'doc-biblioentry', 'doc-biblioref', 'doc-cover', 'doc-endnote', 'doc-glossref', 'doc-noteref' ]; + var landmarkRoles = { + header: 'banner', + footer: 'contentinfo' + }; + function getRoleSegments(vNode) { + var roles = []; + if (!vNode) { + return roles; + } + if (vNode.hasAttr('role')) { + var nodeRoles = token_list_default(vNode.attr('role').toLowerCase()); + roles = roles.concat(nodeRoles); + } + return roles.filter(function(role) { + return is_valid_role_default(role); + }); + } + function getElementUnallowedRoles(node) { + var allowImplicit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var _nodeLookup23 = _nodeLookup(node), vNode = _nodeLookup23.vNode; + if (!is_html_element_default(vNode)) { + return []; + } + var nodeName2 = vNode.props.nodeName; + var implicitRole3 = implicit_role_default(vNode) || landmarkRoles[nodeName2]; + var roleSegments = getRoleSegments(vNode); + return roleSegments.filter(function(role) { + return !roleIsAllowed(role, vNode, allowImplicit, implicitRole3); + }); + } + function roleIsAllowed(role, vNode, allowImplicit, implicitRole3) { + if (allowImplicit && role === implicitRole3) { + return true; + } + if (dpubRoles2.includes(role) && get_role_type_default(role) !== implicitRole3) { + return false; + } + return is_aria_role_allowed_on_element_default(vNode, role); + } + var get_element_unallowed_roles_default = getElementUnallowedRoles; + function getAriaRolesByType(type2) { + return Object.keys(standards_default.ariaRoles).filter(function(roleName) { + return standards_default.ariaRoles[roleName].type === type2; + }); + } + var get_aria_roles_by_type_default = getAriaRolesByType; + function getRolesByType(roleType) { + return get_aria_roles_by_type_default(roleType); + } + var get_roles_by_type_default = getRolesByType; + function getAriaRolesSupportingNameFromContent() { + return cache_default.get('ariaRolesNameFromContent', function() { + return Object.keys(standards_default.ariaRoles).filter(function(roleName) { + return standards_default.ariaRoles[roleName].nameFromContent; + }); + }); + } + var get_aria_roles_supporting_name_from_content_default = getAriaRolesSupportingNameFromContent; + function getRolesWithNameFromContents() { + return get_aria_roles_supporting_name_from_content_default(); + } + var get_roles_with_name_from_contents_default = getRolesWithNameFromContents; + var isNull = function isNull(value) { + return value === null; + }; + var isNotNull = function isNotNull(value) { + return value !== null; + }; + var lookupTable = {}; + lookupTable.attributes = { + 'aria-activedescendant': { + type: 'idref', + allowEmpty: true, + unsupported: false + }, + 'aria-atomic': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-autocomplete': { + type: 'nmtoken', + values: [ 'inline', 'list', 'both', 'none' ], + unsupported: false + }, + 'aria-busy': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-checked': { + type: 'nmtoken', + values: [ 'true', 'false', 'mixed', 'undefined' ], + unsupported: false + }, + 'aria-colcount': { + type: 'int', + unsupported: false + }, + 'aria-colindex': { + type: 'int', + unsupported: false + }, + 'aria-colspan': { + type: 'int', + unsupported: false + }, + 'aria-controls': { + type: 'idrefs', + allowEmpty: true, + unsupported: false + }, + 'aria-current': { + type: 'nmtoken', + allowEmpty: true, + values: [ 'page', 'step', 'location', 'date', 'time', 'true', 'false' ], + unsupported: false + }, + 'aria-describedby': { + type: 'idrefs', + allowEmpty: true, + unsupported: false + }, + 'aria-describedat': { + unsupported: true, + unstandardized: true + }, + 'aria-details': { + type: 'idref', + allowEmpty: true, + unsupported: false + }, + 'aria-disabled': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-dropeffect': { + type: 'nmtokens', + values: [ 'copy', 'move', 'reference', 'execute', 'popup', 'none' ], + unsupported: false + }, + 'aria-errormessage': { + type: 'idref', + allowEmpty: true, + unsupported: false + }, + 'aria-expanded': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ], + unsupported: false + }, + 'aria-flowto': { + type: 'idrefs', + allowEmpty: true, + unsupported: false + }, + 'aria-grabbed': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ], + unsupported: false + }, + 'aria-haspopup': { + type: 'nmtoken', + allowEmpty: true, + values: [ 'true', 'false', 'menu', 'listbox', 'tree', 'grid', 'dialog' ], + unsupported: false + }, + 'aria-hidden': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-invalid': { + type: 'nmtoken', + allowEmpty: true, + values: [ 'true', 'false', 'spelling', 'grammar' ], + unsupported: false + }, + 'aria-keyshortcuts': { + type: 'string', + allowEmpty: true, + unsupported: false + }, + 'aria-label': { + type: 'string', + allowEmpty: true, + unsupported: false + }, + 'aria-labelledby': { + type: 'idrefs', + allowEmpty: true, + unsupported: false + }, + 'aria-level': { + type: 'int', + unsupported: false + }, + 'aria-live': { + type: 'nmtoken', + values: [ 'off', 'polite', 'assertive' ], + unsupported: false + }, + 'aria-modal': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-multiline': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-multiselectable': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-orientation': { + type: 'nmtoken', + values: [ 'horizontal', 'vertical' ], + unsupported: false + }, + 'aria-owns': { + type: 'idrefs', + allowEmpty: true, + unsupported: false + }, + 'aria-placeholder': { + type: 'string', + allowEmpty: true, + unsupported: false + }, + 'aria-posinset': { + type: 'int', + unsupported: false + }, + 'aria-pressed': { + type: 'nmtoken', + values: [ 'true', 'false', 'mixed', 'undefined' ], + unsupported: false + }, + 'aria-readonly': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-relevant': { + type: 'nmtokens', + values: [ 'additions', 'removals', 'text', 'all' ], + unsupported: false + }, + 'aria-required': { + type: 'boolean', + values: [ 'true', 'false' ], + unsupported: false + }, + 'aria-roledescription': { + type: 'string', + allowEmpty: true, + unsupported: false + }, + 'aria-rowcount': { + type: 'int', + unsupported: false + }, + 'aria-rowindex': { + type: 'int', + unsupported: false + }, + 'aria-rowspan': { + type: 'int', + unsupported: false + }, + 'aria-selected': { + type: 'nmtoken', + values: [ 'true', 'false', 'undefined' ], + unsupported: false + }, + 'aria-setsize': { + type: 'int', + unsupported: false + }, + 'aria-sort': { + type: 'nmtoken', + values: [ 'ascending', 'descending', 'other', 'none' ], + unsupported: false + }, + 'aria-valuemax': { + type: 'decimal', + unsupported: false + }, + 'aria-valuemin': { + type: 'decimal', + unsupported: false + }, + 'aria-valuenow': { + type: 'decimal', + unsupported: false + }, + 'aria-valuetext': { + type: 'string', + unsupported: false + } + }; + lookupTable.globalAttributes = [ 'aria-atomic', 'aria-busy', 'aria-controls', 'aria-current', 'aria-describedby', 'aria-details', 'aria-disabled', 'aria-dropeffect', 'aria-flowto', 'aria-grabbed', 'aria-haspopup', 'aria-hidden', 'aria-invalid', 'aria-keyshortcuts', 'aria-label', 'aria-labelledby', 'aria-live', 'aria-owns', 'aria-relevant', 'aria-roledescription' ]; + lookupTable.role = { + alert: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + alertdialog: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-modal', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'dialog', 'section' ] + }, + application: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage', 'aria-activedescendant' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'article', 'audio', 'embed', 'iframe', 'object', 'section', 'svg', 'video' ] + }, + article: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'article' ], + unsupported: false + }, + banner: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'header' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + button: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-pressed', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'button', 'input[type="button"]', 'input[type="image"]', 'input[type="reset"]', 'input[type="submit"]', 'summary' ], + unsupported: false, + allowedElements: [ { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + cell: { + type: 'structure', + attributes: { + allowed: [ 'aria-colindex', 'aria-colspan', 'aria-rowindex', 'aria-rowspan', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'row' ], + implicit: [ 'td', 'th' ], + unsupported: false + }, + checkbox: { + type: 'widget', + attributes: { + allowed: [ 'aria-checked', 'aria-required', 'aria-readonly', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'input[type="checkbox"]' ], + unsupported: false, + allowedElements: [ 'button' ] + }, + columnheader: { + type: 'structure', + attributes: { + allowed: [ 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-rowindex', 'aria-rowspan', 'aria-required', 'aria-readonly', 'aria-selected', 'aria-sort', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'row' ], + implicit: [ 'th' ], + unsupported: false + }, + combobox: { + type: 'composite', + attributes: { + allowed: [ 'aria-autocomplete', 'aria-required', 'aria-activedescendant', 'aria-orientation', 'aria-errormessage' ], + required: [ 'aria-expanded' ] + }, + owned: { + all: [ 'listbox', 'tree', 'grid', 'dialog', 'textbox' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: 'input', + properties: { + type: [ 'text', 'search', 'tel', 'url', 'email' ] + } + } ] + }, + command: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + complementary: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'aside' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + composite: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + contentinfo: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'footer' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + definition: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'dd', 'dfn' ], + unsupported: false + }, + dialog: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-modal', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'dialog' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + directory: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + document: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'body' ], + unsupported: false, + allowedElements: [ 'article', 'embed', 'iframe', 'object', 'section', 'svg' ] + }, + 'doc-abstract': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-acknowledgments': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-afterword': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-appendix': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-backlink': { + type: 'link', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + 'doc-biblioentry': { + type: 'listitem', + attributes: { + allowed: [ 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: [ 'doc-bibliography' ], + unsupported: false, + allowedElements: [ 'li' ] + }, + 'doc-bibliography': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: { + one: [ 'doc-biblioentry' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-biblioref': { + type: 'link', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + 'doc-chapter': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-colophon': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-conclusion': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-cover': { + type: 'img', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false + }, + 'doc-credit': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-credits': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-dedication': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-endnote': { + type: 'listitem', + attributes: { + allowed: [ 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: [ 'doc-endnotes' ], + unsupported: false, + allowedElements: [ 'li' ] + }, + 'doc-endnotes': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: { + one: [ 'doc-endnote' ] + }, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-epigraph': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false + }, + 'doc-epilogue': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-errata': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-example': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'aside', 'section' ] + }, + 'doc-footnote': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'aside', 'footer', 'header' ] + }, + 'doc-foreword': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-glossary': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: [ 'term', 'definition' ], + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'dl' ] + }, + 'doc-glossref': { + type: 'link', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + 'doc-index': { + type: 'navigation', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'nav', 'section' ] + }, + 'doc-introduction': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-noteref': { + type: 'link', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + 'doc-notice': { + type: 'note', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-pagebreak': { + type: 'separator', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'hr' ] + }, + 'doc-pagelist': { + type: 'navigation', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'nav', 'section' ] + }, + 'doc-part': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-preface': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-prologue': { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-pullquote': { + type: 'none', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'aside', 'section' ] + }, + 'doc-qna': { + type: 'section', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + 'doc-subtitle': { + type: 'sectionhead', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: { + nodeName: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ] + } + }, + 'doc-tip': { + type: 'note', + attributes: { + allowed: [ 'aria-expanded' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'aside' ] + }, + 'doc-toc': { + type: 'navigation', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + namefrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'nav', 'section' ] + }, + feed: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: { + one: [ 'article' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'article', 'aside', 'section' ] + }, + figure: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'figure' ], + unsupported: false + }, + form: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'form' ], + unsupported: false + }, + grid: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-colcount', 'aria-level', 'aria-multiselectable', 'aria-readonly', 'aria-rowcount', 'aria-errormessage' ] + }, + owned: { + one: [ 'rowgroup', 'row' ] + }, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'table' ], + unsupported: false + }, + gridcell: { + type: 'widget', + attributes: { + allowed: [ 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-rowindex', 'aria-rowspan', 'aria-selected', 'aria-readonly', 'aria-required', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'row' ], + implicit: [ 'td', 'th' ], + unsupported: false + }, + group: { + type: 'structure', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'details', 'optgroup' ], + unsupported: false, + allowedElements: [ 'dl', 'figcaption', 'fieldset', 'figure', 'footer', 'header', 'ol', 'ul' ] + }, + heading: { + type: 'structure', + attributes: { + required: [ 'aria-level' ], + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ], + unsupported: false + }, + img: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'img' ], + unsupported: false, + allowedElements: [ 'embed', 'iframe', 'object', 'svg' ] + }, + input: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + landmark: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + link: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'a[href]', 'area[href]' ], + unsupported: false, + allowedElements: [ 'button', { + nodeName: 'input', + properties: { + type: [ 'image', 'button' ] + } + } ] + }, + list: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: { + all: [ 'listitem' ] + }, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'ol', 'ul', 'dl' ], + unsupported: false + }, + listbox: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-multiselectable', 'aria-readonly', 'aria-required', 'aria-expanded', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + all: [ 'option' ] + }, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'select' ], + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + listitem: { + type: 'structure', + attributes: { + allowed: [ 'aria-level', 'aria-posinset', 'aria-setsize', 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'list' ], + implicit: [ 'li', 'dt' ], + unsupported: false + }, + log: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + main: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'main' ], + unsupported: false, + allowedElements: [ 'article', 'section' ] + }, + marquee: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + math: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'math' ], + unsupported: false + }, + menu: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + one: [ 'menuitem', 'menuitemradio', 'menuitemcheckbox' ] + }, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'menu[type="context"]' ], + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + menubar: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + one: [ 'menuitem', 'menuitemradio', 'menuitemcheckbox' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + menuitem: { + type: 'widget', + attributes: { + allowed: [ 'aria-posinset', 'aria-setsize', 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'menu', 'menubar' ], + implicit: [ 'menuitem[type="command"]' ], + unsupported: false, + allowedElements: [ 'button', 'li', { + nodeName: 'iput', + properties: { + type: [ 'image', 'button' ] + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + menuitemcheckbox: { + type: 'widget', + attributes: { + allowed: [ 'aria-checked', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'menu', 'menubar' ], + implicit: [ 'menuitem[type="checkbox"]' ], + unsupported: false, + allowedElements: [ { + nodeName: [ 'button', 'li' ] + }, { + nodeName: 'input', + properties: { + type: [ 'checkbox', 'image', 'button' ] + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + menuitemradio: { + type: 'widget', + attributes: { + allowed: [ 'aria-checked', 'aria-selected', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'menu', 'menubar' ], + implicit: [ 'menuitem[type="radio"]' ], + unsupported: false, + allowedElements: [ { + nodeName: [ 'button', 'li' ] + }, { + nodeName: 'input', + properties: { + type: [ 'image', 'button', 'radio' ] + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + navigation: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'nav' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + none: { + type: 'structure', + attributes: null, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: [ 'article', 'aside', 'dl', 'embed', 'figcaption', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'iframe', 'li', 'ol', 'section', 'ul' ] + }, { + nodeName: 'img', + attributes: { + alt: isNotNull + } + } ] + }, + note: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'aside' ] + }, + option: { + type: 'widget', + attributes: { + allowed: [ 'aria-selected', 'aria-posinset', 'aria-setsize', 'aria-checked', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'listbox' ], + implicit: [ 'option' ], + unsupported: false, + allowedElements: [ { + nodeName: [ 'button', 'li' ] + }, { + nodeName: 'input', + properties: { + type: [ 'checkbox', 'button' ] + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + presentation: { + type: 'structure', + attributes: null, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ { + nodeName: [ 'article', 'aside', 'dl', 'embed', 'figcaption', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'iframe', 'li', 'ol', 'section', 'ul' ] + }, { + nodeName: 'img', + attributes: { + alt: isNotNull + } + } ] + }, + progressbar: { + type: 'widget', + attributes: { + allowed: [ 'aria-valuetext', 'aria-valuenow', 'aria-valuemax', 'aria-valuemin', 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'progress' ], + unsupported: false + }, + radio: { + type: 'widget', + attributes: { + allowed: [ 'aria-selected', 'aria-posinset', 'aria-setsize', 'aria-required', 'aria-errormessage', 'aria-checked' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'input[type="radio"]' ], + unsupported: false, + allowedElements: [ { + nodeName: [ 'button', 'li' ] + }, { + nodeName: 'input', + properties: { + type: [ 'image', 'button' ] + } + } ] + }, + radiogroup: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-required', 'aria-expanded', 'aria-readonly', 'aria-errormessage', 'aria-orientation' ] + }, + owned: { + all: [ 'radio' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: { + nodeName: [ 'ol', 'ul', 'fieldset' ] + } + }, + range: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + region: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'section[aria-label]', 'section[aria-labelledby]', 'section[title]' ], + unsupported: false, + allowedElements: { + nodeName: [ 'article', 'aside' ] + } + }, + roletype: { + type: 'abstract', + unsupported: false + }, + row: { + type: 'structure', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-colindex', 'aria-expanded', 'aria-level', 'aria-selected', 'aria-rowindex', 'aria-errormessage' ] + }, + owned: { + one: [ 'cell', 'columnheader', 'rowheader', 'gridcell' ] + }, + nameFrom: [ 'author', 'contents' ], + context: [ 'rowgroup', 'grid', 'treegrid', 'table' ], + implicit: [ 'tr' ], + unsupported: false + }, + rowgroup: { + type: 'structure', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-errormessage' ] + }, + owned: { + all: [ 'row' ] + }, + nameFrom: [ 'author', 'contents' ], + context: [ 'grid', 'table', 'treegrid' ], + implicit: [ 'tbody', 'thead', 'tfoot' ], + unsupported: false + }, + rowheader: { + type: 'structure', + attributes: { + allowed: [ 'aria-colindex', 'aria-colspan', 'aria-expanded', 'aria-rowindex', 'aria-rowspan', 'aria-required', 'aria-readonly', 'aria-selected', 'aria-sort', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'row' ], + implicit: [ 'th' ], + unsupported: false + }, + scrollbar: { + type: 'widget', + attributes: { + required: [ 'aria-controls', 'aria-valuenow' ], + allowed: [ 'aria-valuetext', 'aria-orientation', 'aria-errormessage', 'aria-valuemax', 'aria-valuemin' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false + }, + search: { + type: 'landmark', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: { + nodeName: [ 'aside', 'form', 'section' ] + } + }, + searchbox: { + type: 'widget', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-autocomplete', 'aria-multiline', 'aria-readonly', 'aria-required', 'aria-placeholder', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'input[type="search"]' ], + unsupported: false, + allowedElements: { + nodeName: 'input', + properties: { + type: 'text' + } + } + }, + section: { + nameFrom: [ 'author', 'contents' ], + type: 'abstract', + unsupported: false + }, + sectionhead: { + nameFrom: [ 'author', 'contents' ], + type: 'abstract', + unsupported: false + }, + select: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + }, + separator: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-orientation', 'aria-valuenow', 'aria-valuemax', 'aria-valuemin', 'aria-valuetext', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'hr' ], + unsupported: false, + allowedElements: [ 'li' ] + }, + slider: { + type: 'widget', + attributes: { + allowed: [ 'aria-valuetext', 'aria-orientation', 'aria-readonly', 'aria-errormessage', 'aria-valuemax', 'aria-valuemin' ], + required: [ 'aria-valuenow' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'input[type="range"]' ], + unsupported: false + }, + spinbutton: { + type: 'widget', + attributes: { + allowed: [ 'aria-valuetext', 'aria-required', 'aria-readonly', 'aria-errormessage', 'aria-valuemax', 'aria-valuemin' ], + required: [ 'aria-valuenow' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'input[type="number"]' ], + unsupported: false, + allowedElements: { + nodeName: 'input', + properties: { + type: [ 'text', 'tel' ] + } + } + }, + status: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'output' ], + unsupported: false, + allowedElements: [ 'section' ] + }, + structure: { + type: 'abstract', + unsupported: false + }, + switch: { + type: 'widget', + attributes: { + allowed: [ 'aria-errormessage' ], + required: [ 'aria-checked' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + unsupported: false, + allowedElements: [ 'button', { + nodeName: 'input', + properties: { + type: [ 'checkbox', 'image', 'button' ] + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + tab: { + type: 'widget', + attributes: { + allowed: [ 'aria-selected', 'aria-expanded', 'aria-setsize', 'aria-posinset', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'tablist' ], + unsupported: false, + allowedElements: [ { + nodeName: [ 'button', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li' ] + }, { + nodeName: 'input', + properties: { + type: 'button' + } + }, { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + table: { + type: 'structure', + attributes: { + allowed: [ 'aria-colcount', 'aria-rowcount', 'aria-errormessage' ] + }, + owned: { + one: [ 'rowgroup', 'row' ] + }, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'table' ], + unsupported: false + }, + tablist: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-level', 'aria-multiselectable', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + all: [ 'tab' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + tabpanel: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'section' ] + }, + term: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + implicit: [ 'dt' ], + unsupported: false + }, + textbox: { + type: 'widget', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-autocomplete', 'aria-multiline', 'aria-readonly', 'aria-required', 'aria-placeholder', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'input[type="text"]', 'input[type="email"]', 'input[type="password"]', 'input[type="tel"]', 'input[type="url"]', 'input:not([type])', 'textarea' ], + unsupported: false + }, + timer: { + type: 'widget', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + unsupported: false + }, + toolbar: { + type: 'structure', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-expanded', 'aria-orientation', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author' ], + context: null, + implicit: [ 'menu[type="toolbar"]' ], + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + tooltip: { + type: 'structure', + attributes: { + allowed: [ 'aria-expanded', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: null, + unsupported: false + }, + tree: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-multiselectable', 'aria-required', 'aria-expanded', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + all: [ 'treeitem' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false, + allowedElements: [ 'ol', 'ul' ] + }, + treegrid: { + type: 'composite', + attributes: { + allowed: [ 'aria-activedescendant', 'aria-colcount', 'aria-expanded', 'aria-level', 'aria-multiselectable', 'aria-readonly', 'aria-required', 'aria-rowcount', 'aria-orientation', 'aria-errormessage' ] + }, + owned: { + one: [ 'rowgroup', 'row' ] + }, + nameFrom: [ 'author' ], + context: null, + unsupported: false + }, + treeitem: { + type: 'widget', + attributes: { + allowed: [ 'aria-checked', 'aria-selected', 'aria-expanded', 'aria-level', 'aria-posinset', 'aria-setsize', 'aria-errormessage' ] + }, + owned: null, + nameFrom: [ 'author', 'contents' ], + context: [ 'group', 'tree' ], + unsupported: false, + allowedElements: [ 'li', { + nodeName: 'a', + attributes: { + href: isNotNull + } + } ] + }, + widget: { + type: 'abstract', + unsupported: false + }, + window: { + nameFrom: [ 'author' ], + type: 'abstract', + unsupported: false + } + }; + lookupTable.implicitHtmlRole = implicit_html_roles_default; + lookupTable.elementsAllowedNoRole = [ { + nodeName: [ 'base', 'body', 'caption', 'col', 'colgroup', 'datalist', 'dd', 'details', 'dt', 'head', 'html', 'keygen', 'label', 'legend', 'main', 'map', 'math', 'meta', 'meter', 'noscript', 'optgroup', 'param', 'picture', 'progress', 'script', 'source', 'style', 'template', 'textarea', 'title', 'track' ] + }, { + nodeName: 'area', + attributes: { + href: isNotNull + } + }, { + nodeName: 'input', + properties: { + type: [ 'color', 'data', 'datatime', 'file', 'hidden', 'month', 'number', 'password', 'range', 'reset', 'submit', 'time', 'week' ] + } + }, { + nodeName: 'link', + attributes: { + href: isNotNull + } + }, { + nodeName: 'menu', + attributes: { + type: 'context' + } + }, { + nodeName: 'menuitem', + attributes: { + type: [ 'command', 'checkbox', 'radio' ] + } + }, { + nodeName: 'select', + condition: function condition(vNode) { + if (!(vNode instanceof axe.AbstractVirtualNode)) { + vNode = axe.utils.getNodeFromTree(vNode); + } + return Number(vNode.attr('size')) > 1; + }, + properties: { + multiple: true + } + }, { + nodeName: [ 'clippath', 'cursor', 'defs', 'desc', 'feblend', 'fecolormatrix', 'fecomponenttransfer', 'fecomposite', 'feconvolvematrix', 'fediffuselighting', 'fedisplacementmap', 'fedistantlight', 'fedropshadow', 'feflood', 'fefunca', 'fefuncb', 'fefuncg', 'fefuncr', 'fegaussianblur', 'feimage', 'femerge', 'femergenode', 'femorphology', 'feoffset', 'fepointlight', 'fespecularlighting', 'fespotlight', 'fetile', 'feturbulence', 'filter', 'hatch', 'hatchpath', 'lineargradient', 'marker', 'mask', 'meshgradient', 'meshpatch', 'meshrow', 'metadata', 'mpath', 'pattern', 'radialgradient', 'solidcolor', 'stop', 'switch', 'view' ] + } ]; + lookupTable.elementsAllowedAnyRole = [ { + nodeName: 'a', + attributes: { + href: isNull + } + }, { + nodeName: 'img', + attributes: { + alt: isNull + } + }, { + nodeName: [ 'abbr', 'address', 'canvas', 'div', 'p', 'pre', 'blockquote', 'ins', 'del', 'output', 'span', 'table', 'tbody', 'thead', 'tfoot', 'td', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'br', 'wbr', 'th', 'tr' ] + } ]; + lookupTable.evaluateRoleForElement = { + A: function A(_ref87) { + var node = _ref87.node, out = _ref87.out; + if (node.namespaceURI === 'http://www.w3.org/2000/svg') { + return true; + } + if (node.href.length) { + return out; + } + return true; + }, + AREA: function AREA(_ref88) { + var node = _ref88.node; + return !node.href; + }, + BUTTON: function BUTTON(_ref89) { + var node = _ref89.node, role = _ref89.role, out = _ref89.out; + if (node.getAttribute('type') === 'menu') { + return role === 'menuitem'; + } + return out; + }, + IMG: function IMG(_ref90) { + var node = _ref90.node, role = _ref90.role, out = _ref90.out; + switch (node.alt) { + case null: + return out; + + case '': + return role === 'presentation' || role === 'none'; + + default: + return role !== 'presentation' && role !== 'none'; + } + }, + INPUT: function INPUT(_ref91) { + var node = _ref91.node, role = _ref91.role, out = _ref91.out; + switch (node.type) { + case 'button': + case 'image': + return out; + + case 'checkbox': + if (role === 'button' && node.hasAttribute('aria-pressed')) { + return true; + } + return out; + + case 'radio': + return role === 'menuitemradio'; + + case 'text': + return role === 'combobox' || role === 'searchbox' || role === 'spinbutton'; + + case 'tel': + return role === 'combobox' || role === 'spinbutton'; + + case 'url': + case 'search': + case 'email': + return role === 'combobox'; + + default: + return false; + } + }, + LI: function LI(_ref92) { + var node = _ref92.node, out = _ref92.out; + var hasImplicitListitemRole = axe.utils.matchesSelector(node, 'ol li, ul li'); + if (hasImplicitListitemRole) { + return out; + } + return true; + }, + MENU: function MENU(_ref93) { + var node = _ref93.node; + if (node.getAttribute('type') === 'context') { + return false; + } + return true; + }, + OPTION: function OPTION(_ref94) { + var node = _ref94.node; + var withinOptionList = axe.utils.matchesSelector(node, 'select > option, datalist > option, optgroup > option'); + return !withinOptionList; + }, + SELECT: function SELECT(_ref95) { + var node = _ref95.node, role = _ref95.role; + return !node.multiple && node.size <= 1 && role === 'menu'; + }, + SVG: function SVG(_ref96) { + var node = _ref96.node, out = _ref96.out; + if (node.parentNode && node.parentNode.namespaceURI === 'http://www.w3.org/2000/svg') { + return true; + } + return out; + } + }; + lookupTable.rolesOfType = { + widget: [ 'button', 'checkbox', 'dialog', 'gridcell', 'link', 'log', 'marquee', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'progressbar', 'radio', 'scrollbar', 'searchbox', 'slider', 'spinbutton', 'status', 'switch', 'tab', 'tabpanel', 'textbox', 'timer', 'tooltip', 'tree', 'treeitem' ] + }; + var lookup_table_default = lookupTable; + function implicitNodes(role) { + var implicit = null; + var roles = lookup_table_default.role[role]; + if (roles && roles.implicit) { + implicit = clone2(roles.implicit); + } + return implicit; + } + var implicit_nodes_default = implicitNodes; + function isAccessibleRef(node) { + return !!get_accessible_refs_default(node).length; + } + var is_accessible_ref_default = isAccessibleRef; + function _isComboboxPopup(virtualNode) { + var _ref97 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, popupRoles = _ref97.popupRoles; + var role = get_role_default(virtualNode); + popupRoles !== null && popupRoles !== void 0 ? popupRoles : popupRoles = aria_attrs_default['aria-haspopup'].values; + if (!popupRoles.includes(role)) { + return false; + } + var vParent = nearestParentWithRole(virtualNode); + if (isCombobox(vParent)) { + return true; + } + var id = virtualNode.props.id; + if (!id) { + return false; + } + if (!virtualNode.actualNode) { + throw new Error('Unable to determine combobox popup without an actualNode'); + } + var root = get_root_node_default(virtualNode.actualNode); + var ownedCombobox = root.querySelectorAll('[aria-owns~="'.concat(id, '"][role~="combobox"]:not(select),\n [aria-controls~="').concat(id, '"][role~="combobox"]:not(select)')); + return Array.from(ownedCombobox).some(isCombobox); + } + var isCombobox = function isCombobox(node) { + return node && get_role_default(node) === 'combobox'; + }; + function nearestParentWithRole(vNode) { + while (vNode = vNode.parent) { + if (get_role_default(vNode, { + noPresentational: true + }) !== null) { + return vNode; + } + } + return null; + } + function label2(node) { + node = get_node_from_tree_default(node); + return label_virtual_default(node); + } + var label_default2 = label2; + function requiredAttr(role) { + var roleDef = standards_default.ariaRoles[role]; + if (!roleDef || !Array.isArray(roleDef.requiredAttrs)) { + return []; + } + return _toConsumableArray(roleDef.requiredAttrs); + } + var required_attr_default = requiredAttr; + function requiredContext(role) { + var roleDef = standards_default.ariaRoles[role]; + if (!roleDef || !Array.isArray(roleDef.requiredContext)) { + return null; + } + return _toConsumableArray(roleDef.requiredContext); + } + var required_context_default = requiredContext; + function requiredOwned(role) { + var roleDef = standards_default.ariaRoles[role]; + if (!roleDef || !Array.isArray(roleDef.requiredOwned)) { + return null; + } + return _toConsumableArray(roleDef.requiredOwned); + } + var required_owned_default = requiredOwned; + function validateAttrValue(vNode, attr) { + vNode = vNode instanceof abstract_virtual_node_default ? vNode : get_node_from_tree_default(vNode); + var matches4; + var list; + var value = vNode.attr(attr); + var attrInfo = standards_default.ariaAttrs[attr]; + if (!attrInfo) { + return true; + } + if (attrInfo.allowEmpty && (!value || value.trim() === '')) { + return true; + } + switch (attrInfo.type) { + case 'boolean': + return [ 'true', 'false' ].includes(value.toLowerCase()); + + case 'nmtoken': + return typeof value === 'string' && attrInfo.values.includes(value.toLowerCase()); + + case 'nmtokens': + list = token_list_default(value); + return list.reduce(function(result, token) { + return result && attrInfo.values.includes(token); + }, list.length !== 0); + + case 'idref': + try { + var doc = get_root_node_default2(vNode.actualNode); + return !!(value && doc.getElementById(value)); + } catch (_unused6) { + throw new TypeError('Cannot resolve id references for partial DOM'); + } + + case 'idrefs': + return idrefs_default(vNode, attr).some(function(node) { + return !!node; + }); + + case 'string': + return value.trim() !== ''; + + case 'decimal': + matches4 = value.match(/^[-+]?([0-9]*)\.?([0-9]*)$/); + return !!(matches4 && (matches4[1] || matches4[2])); + + case 'int': + var minValue = typeof attrInfo.minValue !== 'undefined' ? attrInfo.minValue : -Infinity; + return /^[-+]?[0-9]+$/.test(value) && parseInt(value) >= minValue; + } + } + var validate_attr_value_default = validateAttrValue; + function validateAttr(att) { + var attrDefinition = standards_default.ariaAttrs[att]; + return !!attrDefinition; + } + var validate_attr_default = validateAttr; + function thHasDataCellsEvaluate(node) { + var cells = get_all_cells_default(node); + var checkResult = this; + var reffedHeaders = []; + cells.forEach(function(cell) { + var headers2 = cell.getAttribute('headers'); + if (headers2) { + reffedHeaders = reffedHeaders.concat(headers2.split(/\s+/)); + } + var ariaLabel = cell.getAttribute('aria-labelledby'); + if (ariaLabel) { + reffedHeaders = reffedHeaders.concat(ariaLabel.split(/\s+/)); + } + }); + var headers = cells.filter(function(cell) { + if (sanitize_default(cell.textContent) === '') { + return false; + } + return cell.nodeName.toUpperCase() === 'TH' || [ 'rowheader', 'columnheader' ].indexOf(get_explicit_role_default(cell)) !== -1; + }); + var tableGrid = to_grid_default(node); + var out = true; + headers.forEach(function(header) { + if (header.getAttribute('id') && reffedHeaders.includes(header.getAttribute('id'))) { + return; + } + var pos = get_cell_position_default(header, tableGrid); + var hasCell = false; + if (is_column_header_default(header)) { + hasCell = traverse_default('down', pos, tableGrid).find(function(cell) { + return !is_column_header_default(cell) && get_headers_default(cell, tableGrid).includes(header); + }); + } + if (!hasCell && is_row_header_default(header)) { + hasCell = traverse_default('right', pos, tableGrid).find(function(cell) { + return !is_row_header_default(cell) && get_headers_default(cell, tableGrid).includes(header); + }); + } + if (!hasCell) { + checkResult.relatedNodes(header); + } + out = out && hasCell; + }); + return out ? true : void 0; + } + var th_has_data_cells_evaluate_default = thHasDataCellsEvaluate; + var messageKeys = [ 'cell-header-not-in-table', 'cell-header-not-th', 'header-refs-self', 'empty-hdrs' ]; + var notInTable = messageKeys[0], notTh = messageKeys[1], selfRef = messageKeys[2], emptyHdrs = messageKeys[3]; + function tdHeadersAttrEvaluate(node) { + var cells = []; + var cellRoleById = {}; + for (var rowIndex = 0; rowIndex < node.rows.length; rowIndex++) { + var row = node.rows[rowIndex]; + for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) { + var cell = row.cells[cellIndex]; + cells.push(cell); + var cellId = cell.getAttribute('id'); + if (cellId) { + cellRoleById[cellId] = get_role_default(cell); + } + } + } + var badCells = _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, selfRef, new Set()), notInTable, new Set()), notTh, new Set()), emptyHdrs, new Set()); + cells.forEach(function(cell) { + if (!cell.hasAttribute('headers') || !_isVisibleToScreenReaders(cell)) { + return; + } + var headersAttr = cell.getAttribute('headers').trim(); + if (!headersAttr) { + badCells[emptyHdrs].add(cell); + return; + } + var cellId = cell.getAttribute('id'); + var headers = token_list_default(headersAttr); + headers.forEach(function(headerId) { + if (cellId && headerId === cellId) { + badCells[selfRef].add(cell); + } else if (!cellRoleById[headerId]) { + badCells[notInTable].add(cell); + } else if (![ 'columnheader', 'rowheader' ].includes(cellRoleById[headerId])) { + badCells[notTh].add(cell); + } + }); + }); + var _iterator15 = _createForOfIteratorHelper(messageKeys), _step15; + try { + for (_iterator15.s(); !(_step15 = _iterator15.n()).done; ) { + var messageKey = _step15.value; + if (badCells[messageKey].size > 0) { + this.relatedNodes(_toConsumableArray(badCells[messageKey])); + if (messageKey === emptyHdrs) { + return void 0; + } + this.data({ + messageKey: messageKey + }); + return false; + } + } + } catch (err) { + _iterator15.e(err); + } finally { + _iterator15.f(); + } + return true; + } + function tdHasHeaderEvaluate(node) { + var badCells = []; + var cells = get_all_cells_default(node); + var tableGrid = to_grid_default(node); + cells.forEach(function(cell) { + if (has_content_default(cell) && is_data_cell_default(cell) && !label_default2(cell)) { + var hasHeaders = get_headers_default(cell, tableGrid).some(function(header) { + return header !== null && !!has_content_default(header); + }); + if (!hasHeaders) { + badCells.push(cell); + } + } + }); + if (badCells.length) { + this.relatedNodes(badCells); + return false; + } + return true; + } + var td_has_header_evaluate_default = tdHasHeaderEvaluate; + function scopeValueEvaluate(node, options) { + var value = node.getAttribute('scope').toLowerCase(); + return options.values.indexOf(value) !== -1; + } + var scope_value_evaluate_default = scopeValueEvaluate; + var same_caption_summary_evaluate_default = sameCaptionSummaryEvaluate; + function sameCaptionSummaryEvaluate(node, options, virtualNode) { + if (virtualNode.children === void 0) { + return void 0; + } + var summary = virtualNode.attr('summary'); + var captionNode = virtualNode.children.find(isCaptionNode); + var caption = captionNode ? sanitize_default(subtree_text_default(captionNode)) : false; + if (!caption || !summary) { + return false; + } + return sanitize_default(summary).toLowerCase() === sanitize_default(caption).toLowerCase(); + } + function isCaptionNode(virtualNode) { + return virtualNode.props.nodeName === 'caption'; + } + function html5ScopeEvaluate(node) { + if (!is_html5_default(document)) { + return true; + } + return node.nodeName.toUpperCase() === 'TH'; + } + var html5_scope_evaluate_default = html5ScopeEvaluate; + function captionFakedEvaluate(node) { + var table = to_grid_default(node); + var firstRow = table[0]; + if (table.length <= 1 || firstRow.length <= 1 || node.rows.length <= 1) { + return true; + } + return firstRow.reduce(function(out, curr, i) { + return out || curr !== firstRow[i + 1] && firstRow[i + 1] !== void 0; + }, false); + } + var caption_faked_evaluate_default = captionFakedEvaluate; + function svgNonEmptyTitleEvaluate(node, options, virtualNode) { + if (!virtualNode.children) { + return void 0; + } + var titleNode = virtualNode.children.find(function(_ref98) { + var props = _ref98.props; + return props.nodeName === 'title'; + }); + if (!titleNode) { + this.data({ + messageKey: 'noTitle' + }); + return false; + } + try { + var titleText2 = subtree_text_default(titleNode, { + includeHidden: true + }).trim(); + if (titleText2 === '') { + this.data({ + messageKey: 'emptyTitle' + }); + return false; + } + } catch (_unused7) { + return void 0; + } + return true; + } + var svg_non_empty_title_evaluate_default = svgNonEmptyTitleEvaluate; + var standards_exports = {}; + __export(standards_exports, { + getAriaRolesByType: function getAriaRolesByType() { + return get_aria_roles_by_type_default; + }, + getAriaRolesSupportingNameFromContent: function getAriaRolesSupportingNameFromContent() { + return get_aria_roles_supporting_name_from_content_default; + }, + getElementSpec: function getElementSpec() { + return get_element_spec_default; + }, + getElementsByContentType: function getElementsByContentType() { + return get_elements_by_content_type_default; + }, + getGlobalAriaAttrs: function getGlobalAriaAttrs() { + return get_global_aria_attrs_default; + }, + implicitHtmlRoles: function implicitHtmlRoles() { + return implicit_html_roles_default; + } + }); + function presentationalRoleEvaluate(node, options, virtualNode) { + var explicitRole2 = get_explicit_role_default(virtualNode); + if ([ 'presentation', 'none' ].includes(explicitRole2) && [ 'iframe', 'frame' ].includes(virtualNode.props.nodeName) && virtualNode.hasAttr('title')) { + this.data({ + messageKey: 'iframe', + nodeName: virtualNode.props.nodeName + }); + return false; + } + var role = get_role_default(virtualNode); + if ([ 'presentation', 'none' ].includes(role)) { + this.data({ + role: role + }); + return true; + } + if (![ 'presentation', 'none' ].includes(explicitRole2)) { + return false; + } + var hasGlobalAria = get_global_aria_attrs_default().some(function(attr) { + return virtualNode.hasAttr(attr); + }); + var focusable = _isFocusable(virtualNode); + var messageKey; + if (hasGlobalAria && !focusable) { + messageKey = 'globalAria'; + } else if (!hasGlobalAria && focusable) { + messageKey = 'focusable'; + } else { + messageKey = 'both'; + } + this.data({ + messageKey: messageKey, + role: role + }); + return false; + } + function nonEmptyIfPresentEvaluate(node, options, virtualNode) { + var nodeName2 = virtualNode.props.nodeName; + var type2 = (virtualNode.attr('type') || '').toLowerCase(); + var label3 = virtualNode.attr('value'); + if (label3) { + this.data({ + messageKey: 'has-label' + }); + } + if (nodeName2 === 'input' && [ 'submit', 'reset' ].includes(type2)) { + return label3 === null; + } + return false; + } + var non_empty_if_present_evaluate_default = nonEmptyIfPresentEvaluate; + function isOnScreenEvaluate(node) { + return _isVisibleOnScreen(node); + } + var is_on_screen_evaluate_default = isOnScreenEvaluate; + function inlineStyleProperty(node, options) { + var cssProperty = options.cssProperty, absoluteValues = options.absoluteValues, minValue = options.minValue, maxValue = options.maxValue, _options$normalValue = options.normalValue, normalValue = _options$normalValue === void 0 ? 0 : _options$normalValue, noImportant = options.noImportant, multiLineOnly = options.multiLineOnly; + if (!noImportant && node.style.getPropertyPriority(cssProperty) !== 'important' || multiLineOnly && !_isMultiline(node)) { + return true; + } + var data = {}; + if (typeof minValue === 'number') { + data.minValue = minValue; + } + if (typeof maxValue === 'number') { + data.maxValue = maxValue; + } + var declaredPropValue = node.style.getPropertyValue(cssProperty); + if ([ 'inherit', 'unset', 'revert', 'revert-layer' ].includes(declaredPropValue)) { + this.data(_extends({ + value: declaredPropValue + }, data)); + return true; + } + var value = getNumberValue(node, { + absoluteValues: absoluteValues, + cssProperty: cssProperty, + normalValue: normalValue + }); + this.data(_extends({ + value: value + }, data)); + if (typeof value !== 'number') { + return void 0; + } + if ((typeof minValue !== 'number' || value >= minValue) && (typeof maxValue !== 'number' || value <= maxValue)) { + return true; + } + return false; + } + function getNumberValue(domNode, _ref99) { + var cssProperty = _ref99.cssProperty, absoluteValues = _ref99.absoluteValues, normalValue = _ref99.normalValue; + var computedStyle = window.getComputedStyle(domNode); + var cssPropValue = computedStyle.getPropertyValue(cssProperty); + if (cssPropValue === 'normal') { + return normalValue; + } + var parsedValue = parseFloat(cssPropValue); + if (absoluteValues) { + return parsedValue; + } + var fontSize = parseFloat(computedStyle.getPropertyValue('font-size')); + var value = Math.round(parsedValue / fontSize * 100) / 100; + if (isNaN(value)) { + return cssPropValue; + } + return value; + } + function hasAltEvaluate(node, options, virtualNode) { + var nodeName2 = virtualNode.props.nodeName; + if (![ 'img', 'input', 'area' ].includes(nodeName2)) { + return false; + } + return virtualNode.hasAttr('alt'); + } + var has_alt_evaluate_default = hasAltEvaluate; + function existsEvaluate() { + return void 0; + } + var exists_evaluate_default = existsEvaluate; + function docHasTitleEvaluate() { + var title = document.title; + return !!sanitize_default(title); + } + var doc_has_title_evaluate_default = docHasTitleEvaluate; + function avoidInlineSpacingEvaluate(node, options) { + var overriddenProperties = options.cssProperties.filter(function(property) { + if (node.style.getPropertyPriority(property) === 'important') { + return property; + } + }); + if (overriddenProperties.length > 0) { + this.data(overriddenProperties); + return false; + } + return true; + } + var avoid_inline_spacing_evaluate_default = avoidInlineSpacingEvaluate; + function ariaLabelledbyEvaluate(node, options, virtualNode) { + try { + return !!sanitize_default(arialabelledby_text_default(virtualNode)); + } catch (_unused8) { + return void 0; + } + } + var aria_labelledby_evaluate_default = ariaLabelledbyEvaluate; + function ariaLabelEvaluate(node, options, virtualNode) { + return !!sanitize_default(_arialabelText(virtualNode)); + } + var aria_label_evaluate_default = ariaLabelEvaluate; + function duplicateIdEvaluate(node) { + var id = node.getAttribute('id').trim(); + if (!id) { + return true; + } + var root = get_root_node_default2(node); + var matchingNodes = Array.from(root.querySelectorAll('[id="'.concat(escape_selector_default(id), '"]'))).filter(function(foundNode) { + return foundNode !== node; + }); + if (matchingNodes.length) { + this.relatedNodes(matchingNodes); + } + this.data(id); + return matchingNodes.length === 0; + } + var duplicate_id_evaluate_default = duplicateIdEvaluate; + function duplicateIdAfter(results) { + var uniqueIds = []; + return results.filter(function(r) { + if (uniqueIds.indexOf(r.data) === -1) { + uniqueIds.push(r.data); + return true; + } + return false; + }); + } + var duplicate_id_after_default = duplicateIdAfter; + function uniqueFrameTitleEvaluate(node, options, vNode) { + var title = sanitize_default(vNode.attr('title')).toLowerCase(); + this.data(title); + return true; + } + var unique_frame_title_evaluate_default = uniqueFrameTitleEvaluate; + function uniqueFrameTitleAfter(results) { + var titles = {}; + results.forEach(function(r) { + titles[r.data] = titles[r.data] !== void 0 ? ++titles[r.data] : 0; + }); + results.forEach(function(r) { + r.result = !!titles[r.data]; + }); + return results; + } + var unique_frame_title_after_default = uniqueFrameTitleAfter; + function skipLinkEvaluate(node) { + var target = get_element_by_reference_default(node, 'href'); + if (target) { + return _isVisibleToScreenReaders(target) || void 0; + } + return false; + } + var skip_link_evaluate_default = skipLinkEvaluate; + var implicitAriaLiveRoles = [ 'alert', 'log', 'status' ]; + function regionEvaluate(node, options, virtualNode) { + this.data({ + isIframe: [ 'iframe', 'frame' ].includes(virtualNode.props.nodeName) + }); + var regionlessNodes = cache_default.get('regionlessNodes', function() { + return getRegionlessNodes(options); + }); + return !regionlessNodes.includes(virtualNode); + } + function getRegionlessNodes(options) { + var regionlessNodes = findRegionlessElms(axe._tree[0], options).map(function(vNode) { + while (vNode.parent && !vNode.parent._hasRegionDescendant && vNode.parent.actualNode !== document.body) { + vNode = vNode.parent; + } + return vNode; + }).filter(function(vNode, index, array) { + return array.indexOf(vNode) === index; + }); + return regionlessNodes; + } + function findRegionlessElms(virtualNode, options) { + var node = virtualNode.actualNode; + if (get_role_default(virtualNode) === 'button' || isRegion(virtualNode, options) || [ 'iframe', 'frame' ].includes(virtualNode.props.nodeName) || _isSkipLink(virtualNode.actualNode) && get_element_by_reference_default(virtualNode.actualNode, 'href') || !_isVisibleToScreenReaders(node)) { + var vNode = virtualNode; + while (vNode) { + vNode._hasRegionDescendant = true; + vNode = vNode.parent; + } + if ([ 'iframe', 'frame' ].includes(virtualNode.props.nodeName)) { + return [ virtualNode ]; + } + return []; + } else if (node !== document.body && has_content_default(node, true) && !isShallowlyHidden(virtualNode)) { + return [ virtualNode ]; + } else { + return virtualNode.children.filter(function(_ref100) { + var actualNode = _ref100.actualNode; + return actualNode.nodeType === 1; + }).map(function(vNode) { + return findRegionlessElms(vNode, options); + }).reduce(function(a2, b2) { + return a2.concat(b2); + }, []); + } + } + function isShallowlyHidden(virtualNode) { + return [ 'none', 'presentation' ].includes(get_role_default(virtualNode)) && !hasChildTextNodes(virtualNode); + } + function isRegion(virtualNode, options) { + var node = virtualNode.actualNode; + var role = get_role_default(virtualNode); + var ariaLive = (node.getAttribute('aria-live') || '').toLowerCase().trim(); + var landmarkRoles2 = get_aria_roles_by_type_default('landmark'); + if ([ 'assertive', 'polite' ].includes(ariaLive) || implicitAriaLiveRoles.includes(role)) { + return true; + } + if (landmarkRoles2.includes(role)) { + return true; + } + if (options.regionMatcher && matches_default2(virtualNode, options.regionMatcher)) { + return true; + } + return false; + } + function regionAfter(results) { + var iframeResults = results.filter(function(r) { + return r.data.isIframe; + }); + results.forEach(function(r) { + if (r.result || r.node.ancestry.length === 1) { + return; + } + var frameAncestry = r.node.ancestry.slice(0, -1); + var _iterator16 = _createForOfIteratorHelper(iframeResults), _step16; + try { + for (_iterator16.s(); !(_step16 = _iterator16.n()).done; ) { + var iframeResult = _step16.value; + if (_matchAncestry(frameAncestry, iframeResult.node.ancestry)) { + r.result = iframeResult.result; + break; + } + } + } catch (err) { + _iterator16.e(err); + } finally { + _iterator16.f(); + } + }); + iframeResults.forEach(function(r) { + if (!r.result) { + r.result = true; + } + }); + return results; + } + var region_after_default = regionAfter; + function normalizeFontWeight(weight) { + switch (weight) { + case 'lighter': + return 100; + + case 'normal': + return 400; + + case 'bold': + return 700; + + case 'bolder': + return 900; + } + weight = parseInt(weight); + return !isNaN(weight) ? weight : 400; + } + function getTextContainer(elm) { + var nextNode = elm; + var outerText = elm.textContent.trim(); + var innerText = outerText; + while (innerText === outerText && nextNode !== void 0) { + var _i27 = -1; + elm = nextNode; + if (elm.children.length === 0) { + return elm; + } + do { + _i27++; + innerText = elm.children[_i27].textContent.trim(); + } while (innerText === '' && _i27 + 1 < elm.children.length); + nextNode = elm.children[_i27]; + } + return elm; + } + function getStyleValues(node) { + var style = window.getComputedStyle(getTextContainer(node)); + return { + fontWeight: normalizeFontWeight(style.getPropertyValue('font-weight')), + fontSize: parseInt(style.getPropertyValue('font-size')), + isItalic: style.getPropertyValue('font-style') === 'italic' + }; + } + function isHeaderStyle(styleA, styleB, margins) { + return margins.reduce(function(out, margin) { + return out || (!margin.size || styleA.fontSize / margin.size > styleB.fontSize) && (!margin.weight || styleA.fontWeight - margin.weight > styleB.fontWeight) && (!margin.italic || styleA.isItalic && !styleB.isItalic); + }, false); + } + function pAsHeadingEvaluate(node, options, virtualNode) { + var siblings = Array.from(node.parentNode.children); + var currentIndex = siblings.indexOf(node); + options = options || {}; + var margins = options.margins || []; + var nextSibling = siblings.slice(currentIndex + 1).find(function(elm) { + return elm.nodeName.toUpperCase() === 'P'; + }); + var prevSibling = siblings.slice(0, currentIndex).reverse().find(function(elm) { + return elm.nodeName.toUpperCase() === 'P'; + }); + var currStyle = getStyleValues(node); + var nextStyle = nextSibling ? getStyleValues(nextSibling) : null; + var prevStyle = prevSibling ? getStyleValues(prevSibling) : null; + var optionsPassLength = options.passLength; + var optionsFailLength = options.failLength; + var headingLength = node.textContent.trim().length; + var paragraphLength = nextSibling === null || nextSibling === void 0 ? void 0 : nextSibling.textContent.trim().length; + if (headingLength > paragraphLength * optionsPassLength) { + return true; + } + if (!nextStyle || !isHeaderStyle(currStyle, nextStyle, margins)) { + return true; + } + var blockquote = find_up_virtual_default(virtualNode, 'blockquote'); + if (blockquote && blockquote.nodeName.toUpperCase() === 'BLOCKQUOTE') { + return void 0; + } + if (prevStyle && !isHeaderStyle(currStyle, prevStyle, margins)) { + return void 0; + } + if (headingLength > paragraphLength * optionsFailLength) { + return void 0; + } + return false; + } + var p_as_heading_evaluate_default = pAsHeadingEvaluate; + var separatorRegex = /[;,\s]/; + var validRedirectNumRegex = /^[0-9.]+$/; + function metaRefreshEvaluate(node, options, virtualNode) { + var _ref101 = options || {}, minDelay = _ref101.minDelay, maxDelay = _ref101.maxDelay; + var content = (virtualNode.attr('content') || '').trim(); + var _content$split = content.split(separatorRegex), _content$split2 = _slicedToArray(_content$split, 1), redirectStr = _content$split2[0]; + if (!redirectStr.match(validRedirectNumRegex)) { + return true; + } + var redirectDelay = parseFloat(redirectStr); + this.data({ + redirectDelay: redirectDelay + }); + if (typeof minDelay === 'number' && redirectDelay <= options.minDelay) { + return true; + } + if (typeof maxDelay === 'number' && redirectDelay > options.maxDelay) { + return true; + } + return false; + } + function internalLinkPresentEvaluate(node, options, virtualNode) { + var links = query_selector_all_default(virtualNode, 'a[href]'); + return links.some(function(vLink) { + return /^#[^/!]/.test(vLink.attr('href')); + }); + } + var internal_link_present_evaluate_default = internalLinkPresentEvaluate; + var commons_exports = {}; + __export(commons_exports, { + aria: function aria() { + return aria_exports; + }, + color: function color() { + return color_exports; + }, + dom: function dom() { + return dom_exports; + }, + forms: function forms() { + return forms_exports; + }, + matches: function matches() { + return matches_default2; + }, + math: function math() { + return math_exports; + }, + standards: function standards() { + return standards_exports; + }, + table: function table() { + return table_exports; + }, + text: function text() { + return text_exports; + }, + utils: function utils() { + return utils_exports; + } + }); + var color_exports = {}; + __export(color_exports, { + Color: function Color() { + return color_default; + }, + centerPointOfRect: function centerPointOfRect() { + return center_point_of_rect_default; + }, + elementHasImage: function elementHasImage() { + return element_has_image_default; + }, + elementIsDistinct: function elementIsDistinct() { + return element_is_distinct_default; + }, + filteredRectStack: function filteredRectStack() { + return filtered_rect_stack_default; + }, + flattenColors: function flattenColors() { + return _flattenColors; + }, + flattenShadowColors: function flattenShadowColors() { + return _flattenShadowColors; + }, + getBackgroundColor: function getBackgroundColor() { + return _getBackgroundColor2; + }, + getBackgroundStack: function getBackgroundStack() { + return _getBackgroundStack; + }, + getContrast: function getContrast() { + return get_contrast_default; + }, + getForegroundColor: function getForegroundColor() { + return _getForegroundColor; + }, + getOwnBackgroundColor: function getOwnBackgroundColor() { + return get_own_background_color_default; + }, + getRectStack: function getRectStack() { + return get_rect_stack_default; + }, + getStackingContext: function getStackingContext() { + return _getStackingContext; + }, + getStrokeColorsFromShadows: function getStrokeColorsFromShadows() { + return _getStrokeColorsFromShadows; + }, + getTextShadowColors: function getTextShadowColors() { + return _getTextShadowColors; + }, + hasValidContrastRatio: function hasValidContrastRatio() { + return has_valid_contrast_ratio_default; + }, + incompleteData: function incompleteData() { + return incomplete_data_default; + }, + parseTextShadows: function parseTextShadows() { + return _parseTextShadows; + }, + stackingContextToColor: function stackingContextToColor() { + return _stackingContextToColor; + } + }); + function centerPointOfRect(rect) { + if (rect.left > window.innerWidth) { + return void 0; + } + if (rect.top > window.innerHeight) { + return void 0; + } + var x = Math.min(Math.ceil(rect.left + rect.width / 2), window.innerWidth - 1); + var y = Math.min(Math.ceil(rect.top + rect.height / 2), window.innerHeight - 1); + return { + x: x, + y: y + }; + } + var center_point_of_rect_default = centerPointOfRect; + function _getFonts(style) { + return style.getPropertyValue('font-family').split(/[,;]/g).map(function(font) { + return font.trim().toLowerCase(); + }); + } + function elementIsDistinct(node, ancestorNode) { + var nodeStyle = window.getComputedStyle(node); + if (nodeStyle.getPropertyValue('background-image') !== 'none') { + return true; + } + var hasBorder = [ 'border-bottom', 'border-top', 'outline' ].reduce(function(result, edge) { + var borderClr = new color_default(); + borderClr.parseString(nodeStyle.getPropertyValue(edge + '-color')); + return result || nodeStyle.getPropertyValue(edge + '-style') !== 'none' && parseFloat(nodeStyle.getPropertyValue(edge + '-width')) > 0 && borderClr.alpha !== 0; + }, false); + if (hasBorder) { + return true; + } + var parentStyle = window.getComputedStyle(ancestorNode); + if (_getFonts(nodeStyle)[0] !== _getFonts(parentStyle)[0]) { + return true; + } + var hasStyle = [ 'text-decoration-line', 'text-decoration-style', 'font-weight', 'font-style', 'font-size' ].reduce(function(result, cssProp) { + return result || nodeStyle.getPropertyValue(cssProp) !== parentStyle.getPropertyValue(cssProp); + }, false); + var tDec = nodeStyle.getPropertyValue('text-decoration'); + if (tDec.split(' ').length < 3) { + hasStyle = hasStyle || tDec !== parentStyle.getPropertyValue('text-decoration'); + } + return hasStyle; + } + var element_is_distinct_default = elementIsDistinct; + function getRectStack2(elm) { + var boundingStack = get_element_stack_default(elm); + var filteredArr = get_text_element_stack_default(elm); + if (!filteredArr || filteredArr.length <= 1) { + return [ boundingStack ]; + } + if (filteredArr.some(function(stack) { + return stack === void 0; + })) { + return null; + } + filteredArr.splice(0, 0, boundingStack); + return filteredArr; + } + var get_rect_stack_default = getRectStack2; + function filteredRectStack(elm) { + var rectStack = get_rect_stack_default(elm); + if (rectStack && rectStack.length === 1) { + return rectStack[0]; + } + if (rectStack && rectStack.length > 1) { + var boundingStack = rectStack.shift(); + var isSame; + rectStack.forEach(function(rectList, index) { + if (index === 0) { + return; + } + var rectA = rectStack[index - 1], rectB = rectStack[index]; + isSame = rectA.every(function(element, elementIndex) { + return element === rectB[elementIndex]; + }) || boundingStack.includes(elm); + }); + if (!isSame) { + incomplete_data_default.set('bgColor', 'elmPartiallyObscuring'); + return null; + } + return rectStack[0]; + } + incomplete_data_default.set('bgColor', 'outsideViewport'); + return null; + } + var filtered_rect_stack_default = filteredRectStack; + var nonSeparableBlendModes = [ 'hue', 'saturation', 'color', 'luminosity' ]; + var blendFunctions = { + normal: function normal(Cb, Cs) { + return Cs; + }, + multiply: function multiply(Cb, Cs) { + return Cs * Cb; + }, + screen: function screen(Cb, Cs) { + return Cb + Cs - Cb * Cs; + }, + overlay: function overlay(Cb, Cs) { + return this['hard-light'](Cs, Cb); + }, + darken: function darken(Cb, Cs) { + return Math.min(Cb, Cs); + }, + lighten: function lighten(Cb, Cs) { + return Math.max(Cb, Cs); + }, + 'color-dodge': function colorDodge(Cb, Cs) { + return Cb === 0 ? 0 : Cs === 1 ? 1 : Math.min(1, Cb / (1 - Cs)); + }, + 'color-burn': function colorBurn(Cb, Cs) { + return Cb === 1 ? 1 : Cs === 0 ? 0 : 1 - Math.min(1, (1 - Cb) / Cs); + }, + 'hard-light': function hardLight(Cb, Cs) { + return Cs <= .5 ? this.multiply(Cb, 2 * Cs) : this.screen(Cb, 2 * Cs - 1); + }, + 'soft-light': function softLight(Cb, Cs) { + if (Cs <= .5) { + return Cb - (1 - 2 * Cs) * Cb * (1 - Cb); + } else { + var D = Cb <= .25 ? ((16 * Cb - 12) * Cb + 4) * Cb : Math.sqrt(Cb); + return Cb + (2 * Cs - 1) * (D - Cb); + } + }, + difference: function difference(Cb, Cs) { + return Math.abs(Cb - Cs); + }, + exclusion: function exclusion(Cb, Cs) { + return Cb + Cs - 2 * Cb * Cs; + }, + hue: function hue(Cb, Cs) { + return Cs.setSaturation(Cb.getSaturation()).setLuminosity(Cb.getLuminosity()); + }, + saturation: function saturation(Cb, Cs) { + return Cb.setSaturation(Cs.getSaturation()).setLuminosity(Cb.getLuminosity()); + }, + color: function color(Cb, Cs) { + return Cs.setLuminosity(Cb.getLuminosity()); + }, + luminosity: function luminosity(Cb, Cs) { + return Cb.setLuminosity(Cs.getLuminosity()); + } + }; + function _flattenColors(sourceColor, backdrop) { + var blendMode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'normal'; + var blendingResult = blend(backdrop, sourceColor, blendMode); + var r = simpleAlphaCompositing(sourceColor.red, sourceColor.alpha, backdrop.red, backdrop.alpha, blendingResult.r * 255); + var g2 = simpleAlphaCompositing(sourceColor.green, sourceColor.alpha, backdrop.green, backdrop.alpha, blendingResult.g * 255); + var b2 = simpleAlphaCompositing(sourceColor.blue, sourceColor.alpha, backdrop.blue, backdrop.alpha, blendingResult.b * 255); + var \u03b1o = clamp2(sourceColor.alpha + backdrop.alpha * (1 - sourceColor.alpha), 0, 1); + if (\u03b1o === 0) { + return new color_default(r, g2, b2, \u03b1o); + } + var Cr = Math.round(r / \u03b1o); + var Cg = Math.round(g2 / \u03b1o); + var Cb = Math.round(b2 / \u03b1o); + return new color_default(Cr, Cg, Cb, \u03b1o); + } + function simpleAlphaCompositing(Cs, \u03b1s, Cb, \u03b1b, blendingResult) { + return \u03b1s * (1 - \u03b1b) * Cs + \u03b1s * \u03b1b * blendingResult + (1 - \u03b1s) * \u03b1b * Cb; + } + function clamp2(value, min, max2) { + return Math.min(Math.max(min, value), max2); + } + function blend(Cb, Cs, blendMode) { + if (nonSeparableBlendModes.includes(blendMode)) { + return blendFunctions[blendMode](Cb, Cs); + } + var C = new color_default(); + [ 'r', 'g', 'b' ].forEach(function(channel) { + C[channel] = blendFunctions[blendMode](Cb[channel], Cs[channel]); + }); + return C; + } + function _flattenShadowColors(fgColor, bgColor) { + var alpha = fgColor.alpha; + var r = (1 - alpha) * bgColor.red + alpha * fgColor.red; + var g2 = (1 - alpha) * bgColor.green + alpha * fgColor.green; + var b2 = (1 - alpha) * bgColor.blue + alpha * fgColor.blue; + var a2 = fgColor.alpha + bgColor.alpha * (1 - fgColor.alpha); + return new color_default(r, g2, b2, a2); + } + function _getBackgroundStack(node) { + var stacks = get_text_element_stack_default(node).map(function(stack) { + stack = reduce_to_elements_below_floating_default(stack, node); + stack = sortPageBackground(stack); + return stack; + }); + for (var index = 0; index < stacks.length; index++) { + var stack = stacks[index]; + if (stack[0] !== node) { + incomplete_data_default.set('bgColor', 'bgOverlap'); + return null; + } + if (index !== 0 && !shallowArraysEqual(stack, stacks[0])) { + incomplete_data_default.set('bgColor', 'elmPartiallyObscuring'); + return null; + } + } + return stacks[0] || null; + } + function sortPageBackground(elmStack) { + var bodyIndex = elmStack.indexOf(document.body); + var bgNodes = elmStack; + var htmlBgColor = get_own_background_color_default(window.getComputedStyle(document.documentElement)); + if (bodyIndex > 1 && htmlBgColor.alpha === 0 && !element_has_image_default(document.documentElement)) { + if (bodyIndex > 1) { + bgNodes.splice(bodyIndex, 1); + bgNodes.push(document.body); + } + var htmlIndex = bgNodes.indexOf(document.documentElement); + if (htmlIndex > 0) { + bgNodes.splice(htmlIndex, 1); + bgNodes.push(document.documentElement); + } + } + return bgNodes; + } + function shallowArraysEqual(a2, b2) { + if (a2 === b2) { + return true; + } + if (a2 === null || b2 === null) { + return false; + } + if (a2.length !== b2.length) { + return false; + } + for (var _i28 = 0; _i28 < a2.length; ++_i28) { + if (a2[_i28] !== b2[_i28]) { + return false; + } + } + return true; + } + var SHADOW_STROKE_ALPHA = .54; + var VISIBLE_SHADOW_MIN_PX = .5; + var OPAQUE_STROKE_OFFSET_MIN_PX = 1.5; + var edges = [ 'top', 'right', 'bottom', 'left' ]; + function _getStrokeColorsFromShadows(parsedShadows) { + var _ref102 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref102$ignoreEdgeCou = _ref102.ignoreEdgeCount, ignoreEdgeCount = _ref102$ignoreEdgeCou === void 0 ? false : _ref102$ignoreEdgeCou; + var shadowMap = getShadowColorsMap(parsedShadows); + var shadowsByColor = Object.entries(shadowMap).map(function(_ref103) { + var _ref104 = _slicedToArray(_ref103, 2), colorStr = _ref104[0], sides = _ref104[1]; + var edgeCount = edges.filter(function(side) { + return sides[side].length !== 0; + }).length; + return { + colorStr: colorStr, + sides: sides, + edgeCount: edgeCount + }; + }); + if (!ignoreEdgeCount && shadowsByColor.some(function(_ref105) { + var edgeCount = _ref105.edgeCount; + return edgeCount > 1 && edgeCount < 4; + })) { + return null; + } + return shadowsByColor.map(shadowGroupToColor).filter(function(shadow) { + return shadow !== null; + }); + } + function getShadowColorsMap(parsedShadows) { + var colorMap = {}; + var _iterator17 = _createForOfIteratorHelper(parsedShadows), _step17; + try { + for (_iterator17.s(); !(_step17 = _iterator17.n()).done; ) { + var _colorMap$colorStr; + var _step17$value = _step17.value, colorStr = _step17$value.colorStr, pixels = _step17$value.pixels; + (_colorMap$colorStr = colorMap[colorStr]) !== null && _colorMap$colorStr !== void 0 ? _colorMap$colorStr : colorMap[colorStr] = { + top: [], + right: [], + bottom: [], + left: [] + }; + var borders = colorMap[colorStr]; + var _pixels = _slicedToArray(pixels, 2), offsetX = _pixels[0], offsetY = _pixels[1]; + if (offsetX > VISIBLE_SHADOW_MIN_PX) { + borders.right.push(offsetX); + } else if (-offsetX > VISIBLE_SHADOW_MIN_PX) { + borders.left.push(-offsetX); + } + if (offsetY > VISIBLE_SHADOW_MIN_PX) { + borders.bottom.push(offsetY); + } else if (-offsetY > VISIBLE_SHADOW_MIN_PX) { + borders.top.push(-offsetY); + } + } + } catch (err) { + _iterator17.e(err); + } finally { + _iterator17.f(); + } + return colorMap; + } + function shadowGroupToColor(_ref106) { + var colorStr = _ref106.colorStr, sides = _ref106.sides, edgeCount = _ref106.edgeCount; + if (edgeCount !== 4) { + return null; + } + var strokeColor = new color_default(); + strokeColor.parseString(colorStr); + var density = 0; + var isSolid = true; + edges.forEach(function(edge) { + density += sides[edge].length / 4; + isSolid && (isSolid = sides[edge].every(function(offset) { + return offset > OPAQUE_STROKE_OFFSET_MIN_PX; + })); + }); + if (!isSolid) { + strokeColor.alpha = 1 - Math.pow(SHADOW_STROKE_ALPHA, density); + } + return strokeColor; + } + function _parseTextShadows(textShadow) { + var current = { + pixels: [] + }; + var str = textShadow.trim(); + var shadows = [ current ]; + if (!str) { + return []; + } + while (str) { + var colorMatch = str.match(/^[a-z]+(\([^)]+\))?/i) || str.match(/^#[0-9a-f]+/i); + var pixelMatch = str.match(/^([0-9.-]+)px/i) || str.match(/^(0)/); + if (colorMatch) { + assert_default(!current.colorStr, 'Multiple colors identified in text-shadow: '.concat(textShadow)); + str = str.replace(colorMatch[0], '').trim(); + current.colorStr = colorMatch[0]; + } else if (pixelMatch) { + assert_default(current.pixels.length < 3, 'Too many pixel units in text-shadow: '.concat(textShadow)); + str = str.replace(pixelMatch[0], '').trim(); + var pixelUnit = parseFloat((pixelMatch[1][0] === '.' ? '0' : '') + pixelMatch[1]); + current.pixels.push(pixelUnit); + } else if (str[0] === ',') { + assert_default(current.pixels.length >= 2, 'Missing pixel value in text-shadow: '.concat(textShadow)); + current = { + pixels: [] + }; + shadows.push(current); + str = str.substr(1).trim(); + } else { + throw new Error('Unable to process text-shadows: '.concat(str)); + } + } + shadows.forEach(function(_ref107) { + var pixels = _ref107.pixels; + if (pixels.length === 2) { + pixels.push(0); + } + }); + return shadows; + } + function _getTextShadowColors(node) { + var _ref108 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, minRatio = _ref108.minRatio, maxRatio = _ref108.maxRatio, ignoreEdgeCount = _ref108.ignoreEdgeCount; + var shadowColors = []; + var style = window.getComputedStyle(node); + var textShadow = style.getPropertyValue('text-shadow'); + if (textShadow === 'none') { + return shadowColors; + } + var fontSizeStr = style.getPropertyValue('font-size'); + var fontSize = parseInt(fontSizeStr); + assert_default(isNaN(fontSize) === false, 'Unable to determine font-size value '.concat(fontSizeStr)); + var thinShadows = []; + var shadows = _parseTextShadows(textShadow); + var _iterator18 = _createForOfIteratorHelper(shadows), _step18; + try { + for (_iterator18.s(); !(_step18 = _iterator18.n()).done; ) { + var shadow = _step18.value; + var colorStr = shadow.colorStr || style.getPropertyValue('color'); + var _shadow$pixels = _slicedToArray(shadow.pixels, 3), offsetX = _shadow$pixels[0], offsetY = _shadow$pixels[1], _shadow$pixels$ = _shadow$pixels[2], blurRadius = _shadow$pixels$ === void 0 ? 0 : _shadow$pixels$; + if (maxRatio && blurRadius >= fontSize * maxRatio) { + continue; + } + if (minRatio && blurRadius < fontSize * minRatio) { + thinShadows.push({ + colorStr: colorStr, + pixels: shadow.pixels + }); + continue; + } + if (thinShadows.length > 0) { + var _strokeColors = _getStrokeColorsFromShadows(thinShadows, { + ignoreEdgeCount: ignoreEdgeCount + }); + if (_strokeColors === null) { + return null; + } + shadowColors.push.apply(shadowColors, _toConsumableArray(_strokeColors)); + thinShadows.splice(0, thinShadows.length); + } + var _color3 = textShadowColor({ + colorStr: colorStr, + offsetX: offsetX, + offsetY: offsetY, + blurRadius: blurRadius, + fontSize: fontSize + }); + shadowColors.push(_color3); + } + } catch (err) { + _iterator18.e(err); + } finally { + _iterator18.f(); + } + if (thinShadows.length > 0) { + var strokeColors = _getStrokeColorsFromShadows(thinShadows, { + ignoreEdgeCount: ignoreEdgeCount + }); + if (strokeColors === null) { + return null; + } + shadowColors.push.apply(shadowColors, _toConsumableArray(strokeColors)); + } + return shadowColors; + } + function textShadowColor(_ref109) { + var colorStr = _ref109.colorStr, offsetX = _ref109.offsetX, offsetY = _ref109.offsetY, blurRadius = _ref109.blurRadius, fontSize = _ref109.fontSize; + if (offsetX > blurRadius || offsetY > blurRadius) { + return new color_default(0, 0, 0, 0); + } + var shadowColor = new color_default(); + shadowColor.parseString(colorStr); + shadowColor.alpha *= blurRadiusToAlpha(blurRadius, fontSize); + return shadowColor; + } + function blurRadiusToAlpha(blurRadius, fontSize) { + if (blurRadius === 0) { + return 1; + } + var relativeBlur = blurRadius / fontSize; + return .185 / (relativeBlur + .4); + } + function _getStackingContext(elm, elmStack) { + var virtualNode = get_node_from_tree_default(elm); + if (virtualNode._stackingContext) { + return virtualNode._stackingContext; + } + var stackingContext = []; + var contextMap = new Map(); + elmStack = elmStack !== null && elmStack !== void 0 ? elmStack : _getBackgroundStack(elm); + elmStack.forEach(function(bgElm) { + var _stackingOrder2; + var bgVNode = get_node_from_tree_default(bgElm); + var bgColor = getOwnBackgroundColor2(bgVNode); + var stackingOrder = bgVNode._stackingOrder.filter(function(_ref110) { + var vNode = _ref110.vNode; + return !!vNode; + }); + stackingOrder.forEach(function(_ref111, index) { + var _stackingOrder; + var vNode = _ref111.vNode; + var ancestorVNode2 = (_stackingOrder = stackingOrder[index - 1]) === null || _stackingOrder === void 0 ? void 0 : _stackingOrder.vNode; + var context2 = addToStackingContext(contextMap, vNode, ancestorVNode2); + if (index === 0 && !contextMap.get(vNode)) { + stackingContext.unshift(context2); + } + contextMap.set(vNode, context2); + }); + var ancestorVNode = (_stackingOrder2 = stackingOrder[stackingOrder.length - 1]) === null || _stackingOrder2 === void 0 ? void 0 : _stackingOrder2.vNode; + var context = addToStackingContext(contextMap, bgVNode, ancestorVNode); + if (!stackingOrder.length) { + stackingContext.unshift(context); + } + context.bgColor = bgColor; + }); + virtualNode._stackingContext = stackingContext; + return stackingContext; + } + function _stackingContextToColor(context) { + var _context$descendants; + if (!((_context$descendants = context.descendants) !== null && _context$descendants !== void 0 && _context$descendants.length)) { + var color2 = context.bgColor; + color2.alpha *= context.opacity; + return { + color: color2, + blendMode: context.blendMode + }; + } + var sourceColor = context.descendants.reduce(reduceToColor, createStackingContext2()); + var color = _flattenColors(sourceColor, context.bgColor, context.descendants[0].blendMode); + color.alpha *= context.opacity; + return { + color: color, + blendMode: context.blendMode + }; + } + function reduceToColor(backdropContext, sourceContext) { + var backdrop; + if (backdropContext instanceof color_default) { + backdrop = backdropContext; + } else { + backdrop = _stackingContextToColor(backdropContext).color; + } + var sourceColor = _stackingContextToColor(sourceContext).color; + return _flattenColors(sourceColor, backdrop, sourceContext.blendMode); + } + function createStackingContext2(vNode, ancestorContext) { + var _vNode$getComputedSty; + return { + vNode: vNode, + ancestor: ancestorContext, + opacity: parseFloat((_vNode$getComputedSty = vNode === null || vNode === void 0 ? void 0 : vNode.getComputedStylePropertyValue('opacity')) !== null && _vNode$getComputedSty !== void 0 ? _vNode$getComputedSty : 1), + bgColor: new color_default(0, 0, 0, 0), + blendMode: normalizeBlendMode(vNode === null || vNode === void 0 ? void 0 : vNode.getComputedStylePropertyValue('mix-blend-mode')), + descendants: [] + }; + } + function normalizeBlendMode(blendmode) { + return !!blendmode ? blendmode : void 0; + } + function addToStackingContext(contextMap, vNode, ancestorVNode) { + var _contextMap$get; + var ancestorContext = contextMap.get(ancestorVNode); + var context = (_contextMap$get = contextMap.get(vNode)) !== null && _contextMap$get !== void 0 ? _contextMap$get : createStackingContext2(vNode, ancestorContext); + if (ancestorContext && ancestorVNode !== vNode && !ancestorContext.descendants.includes(context)) { + ancestorContext.descendants.unshift(context); + } + return context; + } + function getOwnBackgroundColor2(vNode) { + var bgColor = new color_default(); + bgColor.parseString(vNode.getComputedStylePropertyValue('background-color')); + return bgColor; + } + function _getBackgroundColor2(elm) { + var bgElms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var shadowOutlineEmMax = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : .1; + var vNode = get_node_from_tree_default(elm); + var bgColorCache = vNode._cache.getBackgroundColor; + if (bgColorCache) { + bgElms.push.apply(bgElms, _toConsumableArray(bgColorCache.bgElms)); + incomplete_data_default.set('bgColor', bgColorCache.incompleteData); + return bgColorCache.bgColor; + } + var bgColor = _getBackgroundColor(elm, bgElms, shadowOutlineEmMax); + vNode._cache.getBackgroundColor = { + bgColor: bgColor, + bgElms: bgElms, + incompleteData: incomplete_data_default.get('bgColor') + }; + return bgColor; + } + function _getBackgroundColor(elm, bgElms, shadowOutlineEmMax) { + var _getTextShadowColors2, _bgColors; + var elmStack = _getBackgroundStack(elm); + if (!elmStack) { + return null; + } + var textRects = get_visible_child_text_rects_default(elm); + var bgColors = (_getTextShadowColors2 = _getTextShadowColors(elm, { + minRatio: shadowOutlineEmMax, + ignoreEdgeCount: true + })) !== null && _getTextShadowColors2 !== void 0 ? _getTextShadowColors2 : []; + if (bgColors.length) { + bgColors = [ { + color: bgColors.reduce(_flattenShadowColors) + } ]; + } + for (var _i29 = 0; _i29 < elmStack.length; _i29++) { + var bgElm = elmStack[_i29]; + var bgElmStyle = window.getComputedStyle(bgElm); + if (element_has_image_default(bgElm, bgElmStyle)) { + bgElms.push(bgElm); + return null; + } + var bgColor = void 0; + try { + bgColor = get_own_background_color_default(bgElmStyle); + if (bgColor.alpha === 0) { + continue; + } + } catch (error) { + if (error && incomplete_data_default.get('colorParse')) { + return null; + } + throw error; + } + if (bgElmStyle.getPropertyValue('display') !== 'inline' && !fullyEncompasses(bgElm, textRects)) { + bgElms.push(bgElm); + incomplete_data_default.set('bgColor', 'elmPartiallyObscured'); + return null; + } + bgElms.push(bgElm); + if (bgColor.alpha === 1) { + break; + } + } + var stackingContext = _getStackingContext(elm, elmStack); + bgColors = stackingContext.map(_stackingContextToColor).concat(bgColors); + var pageBgs = getPageBackgroundColors(elm, elmStack.includes(document.body)); + (_bgColors = bgColors).unshift.apply(_bgColors, _toConsumableArray(pageBgs)); + if (bgColors.length === 0) { + return new color_default(255, 255, 255, 1); + } + var blendedColor = bgColors.reduce(function(bgColor, fgColor) { + return _flattenColors(fgColor.color, bgColor.color instanceof color_default ? bgColor.color : bgColor, fgColor.blendMode); + }); + return _flattenColors(blendedColor.color instanceof color_default ? blendedColor.color : blendedColor, new color_default(255, 255, 255, 1)); + } + function fullyEncompasses(node, rects) { + rects = Array.isArray(rects) ? rects : [ rects ]; + var nodeRect = node.getBoundingClientRect(); + var right = nodeRect.right, bottom = nodeRect.bottom; + var style = window.getComputedStyle(node); + var overflow = style.getPropertyValue('overflow'); + var paddingLeft = parseInt(style.getPropertyValue('padding-left'), 10); + var paddingRight = parseInt(style.getPropertyValue('padding-right'), 10); + var paddingTop = parseInt(style.getPropertyValue('padding-top'), 10); + var paddingBottom = parseInt(style.getPropertyValue('padding-bottom'), 10); + if ([ 'scroll', 'auto' ].includes(overflow) || node instanceof window.HTMLHtmlElement) { + right = nodeRect.left + node.scrollWidth + paddingLeft + paddingRight; + bottom = nodeRect.top + node.scrollHeight + paddingTop + paddingBottom; + } + return rects.every(function(rect) { + return rect.top >= nodeRect.top && rect.bottom <= bottom && rect.left >= nodeRect.left && rect.right <= right; + }); + } + function normalizeBlendMode2(blendmode) { + return !!blendmode ? blendmode : void 0; + } + function getPageBackgroundColors(elm, stackContainsBody) { + var pageColors = []; + if (!stackContainsBody) { + var html = document.documentElement; + var body = document.body; + var htmlStyle = window.getComputedStyle(html); + var bodyStyle = window.getComputedStyle(body); + var htmlBgColor = get_own_background_color_default(htmlStyle); + var bodyBgColor = get_own_background_color_default(bodyStyle); + var bodyBgColorApplies = bodyBgColor.alpha !== 0 && fullyEncompasses(body, elm.getBoundingClientRect()); + if (bodyBgColor.alpha !== 0 && htmlBgColor.alpha === 0 || bodyBgColorApplies && bodyBgColor.alpha !== 1) { + pageColors.unshift({ + color: bodyBgColor, + blendMode: normalizeBlendMode2(bodyStyle.getPropertyValue('mix-blend-mode')) + }); + } + if (htmlBgColor.alpha !== 0 && (!bodyBgColorApplies || bodyBgColorApplies && bodyBgColor.alpha !== 1)) { + pageColors.unshift({ + color: htmlBgColor, + blendMode: normalizeBlendMode2(htmlStyle.getPropertyValue('mix-blend-mode')) + }); + } + } + return pageColors; + } + function getContrast(bgColor, fgColor) { + if (!fgColor || !bgColor) { + return null; + } + if (fgColor.alpha < 1) { + fgColor = _flattenColors(fgColor, bgColor); + } + var bL = bgColor.getRelativeLuminance(); + var fL = fgColor.getRelativeLuminance(); + return (Math.max(fL, bL) + .05) / (Math.min(fL, bL) + .05); + } + var get_contrast_default = getContrast; + function _getForegroundColor(node, _, bgColor) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var nodeStyle = window.getComputedStyle(node); + var colorStack = [ function() { + return getStrokeColor(nodeStyle, options); + }, function() { + return getTextColor(nodeStyle); + }, function() { + return _getTextShadowColors(node, { + minRatio: 0 + }); + } ]; + var fgColors = []; + try { + for (var _i30 = 0, _colorStack = colorStack; _i30 < _colorStack.length; _i30++) { + var colorFn = _colorStack[_i30]; + var _color4 = colorFn(); + if (!_color4) { + continue; + } + fgColors = fgColors.concat(_color4); + if (_color4.alpha === 1) { + break; + } + } + } catch (error) { + if (error && incomplete_data_default.get('colorParse')) { + return null; + } + throw error; + } + var fgColor = fgColors.reduce(function(source, backdrop) { + return _flattenColors(source, backdrop); + }); + bgColor !== null && bgColor !== void 0 ? bgColor : bgColor = _getBackgroundColor2(node, []); + if (bgColor === null) { + var reason = incomplete_data_default.get('bgColor'); + incomplete_data_default.set('fgColor', reason); + return null; + } + var stackingContexts = _getStackingContext(node); + var context = findNodeInContexts(stackingContexts, node); + return _flattenColors(calculateBlendedForegroundColor(fgColor, context, stackingContexts), new color_default(255, 255, 255, 1)); + } + function getTextColor(nodeStyle) { + return new color_default().parseString(nodeStyle.getPropertyValue('-webkit-text-fill-color') || nodeStyle.getPropertyValue('color')); + } + function getStrokeColor(nodeStyle, _ref112) { + var _ref112$textStrokeEmM = _ref112.textStrokeEmMin, textStrokeEmMin = _ref112$textStrokeEmM === void 0 ? 0 : _ref112$textStrokeEmM; + var strokeWidth = parseFloat(nodeStyle.getPropertyValue('-webkit-text-stroke-width')); + if (strokeWidth === 0) { + return null; + } + var fontSize = nodeStyle.getPropertyValue('font-size'); + var relativeStrokeWidth = strokeWidth / parseFloat(fontSize); + if (isNaN(relativeStrokeWidth) || relativeStrokeWidth < textStrokeEmMin) { + return null; + } + var strokeColor = nodeStyle.getPropertyValue('-webkit-text-stroke-color'); + return new color_default().parseString(strokeColor); + } + function calculateBlendedForegroundColor(fgColor, context, stackingContexts) { + while (context) { + var _context$ancestor; + if (context.opacity === 1 && context.ancestor) { + context = context.ancestor; + continue; + } + fgColor.alpha *= context.opacity; + var stack = ((_context$ancestor = context.ancestor) === null || _context$ancestor === void 0 ? void 0 : _context$ancestor.descendants) || stackingContexts; + if (context.opacity !== 1) { + stack = stack.slice(0, stack.indexOf(context)); + } + var bgColors = stack.map(_stackingContextToColor); + if (!bgColors.length) { + context = context.ancestor; + continue; + } + var bgColor = bgColors.reduce(function(backdrop, source) { + return _flattenColors(source.color, backdrop.color instanceof color_default ? backdrop.color : backdrop); + }, { + color: new color_default(0, 0, 0, 0), + blendMode: 'normal' + }); + fgColor = _flattenColors(fgColor, bgColor); + context = context.ancestor; + } + return fgColor; + } + function findNodeInContexts(contexts, node) { + var _iterator19 = _createForOfIteratorHelper(contexts), _step19; + try { + for (_iterator19.s(); !(_step19 = _iterator19.n()).done; ) { + var _context$vNode; + var context = _step19.value; + if (((_context$vNode = context.vNode) === null || _context$vNode === void 0 ? void 0 : _context$vNode.actualNode) === node) { + return context; + } + var found = findNodeInContexts(context.descendants, node); + if (found) { + return found; + } + } + } catch (err) { + _iterator19.e(err); + } finally { + _iterator19.f(); + } + } + function hasValidContrastRatio(bg, fg, fontSize, isBold) { + var contrast2 = get_contrast_default(bg, fg); + var isSmallFont = isBold && Math.ceil(fontSize * 72) / 96 < 14 || !isBold && Math.ceil(fontSize * 72) / 96 < 18; + var expectedContrastRatio = isSmallFont ? 4.5 : 3; + return { + isValid: contrast2 > expectedContrastRatio, + contrastRatio: contrast2, + expectedContrastRatio: expectedContrastRatio + }; + } + var has_valid_contrast_ratio_default = hasValidContrastRatio; + var forms_exports = {}; + __export(forms_exports, { + isAriaCombobox: function isAriaCombobox() { + return is_aria_combobox_default; + }, + isAriaListbox: function isAriaListbox() { + return is_aria_listbox_default; + }, + isAriaRange: function isAriaRange() { + return is_aria_range_default; + }, + isAriaTextbox: function isAriaTextbox() { + return is_aria_textbox_default; + }, + isDisabled: function isDisabled() { + return is_disabled_default; + }, + isNativeSelect: function isNativeSelect() { + return is_native_select_default; + }, + isNativeTextbox: function isNativeTextbox() { + return is_native_textbox_default; + } + }); + var disabledNodeNames = [ 'fieldset', 'button', 'select', 'input', 'textarea' ]; + function isDisabled(virtualNode) { + var disabledState = virtualNode._isDisabled; + if (typeof disabledState === 'boolean') { + return disabledState; + } + var nodeName2 = virtualNode.props.nodeName; + var ariaDisabled = virtualNode.attr('aria-disabled'); + if (disabledNodeNames.includes(nodeName2) && virtualNode.hasAttr('disabled')) { + disabledState = true; + } else if (ariaDisabled) { + disabledState = ariaDisabled.toLowerCase() === 'true'; + } else if (virtualNode.parent) { + disabledState = isDisabled(virtualNode.parent); + } else { + disabledState = false; + } + virtualNode._isDisabled = disabledState; + return disabledState; + } + var is_disabled_default = isDisabled; + function identicalLinksSamePurposeEvaluate(node, options, virtualNode) { + var accText = text_exports.accessibleTextVirtual(virtualNode); + var name = text_exports.sanitize(text_exports.removeUnicode(accText, { + emoji: true, + nonBmp: true, + punctuations: true + })).toLowerCase(); + if (!name) { + return void 0; + } + var afterData = { + name: name, + urlProps: dom_exports.urlPropsFromAttribute(node, 'href') + }; + this.data(afterData); + this.relatedNodes([ node ]); + return true; + } + var identical_links_same_purpose_evaluate_default = identicalLinksSamePurposeEvaluate; + function isIdenticalObject(a2, b2) { + if (!a2 || !b2) { + return false; + } + var aProps = Object.getOwnPropertyNames(a2); + var bProps = Object.getOwnPropertyNames(b2); + if (aProps.length !== bProps.length) { + return false; + } + var result = aProps.every(function(propName) { + var aValue = a2[propName]; + var bValue = b2[propName]; + if (_typeof(aValue) !== _typeof(bValue)) { + return false; + } + if (_typeof(aValue) === 'object' || _typeof(bValue) === 'object') { + return isIdenticalObject(aValue, bValue); + } + return aValue === bValue; + }); + return result; + } + function identicalLinksSamePurposeAfter(results) { + if (results.length < 2) { + return results; + } + var incompleteResults = results.filter(function(_ref113) { + var result = _ref113.result; + return result !== void 0; + }); + var uniqueResults = []; + var nameMap = {}; + var _loop8 = function _loop8(index) { + var _currentResult$relate; + var currentResult = incompleteResults[index]; + var _currentResult$data = currentResult.data, name = _currentResult$data.name, urlProps = _currentResult$data.urlProps; + if (nameMap[name]) { + return 1; + } + var sameNameResults = incompleteResults.filter(function(_ref114, resultNum) { + var data = _ref114.data; + return data.name === name && resultNum !== index; + }); + var isSameUrl = sameNameResults.every(function(_ref115) { + var data = _ref115.data; + return isIdenticalObject(data.urlProps, urlProps); + }); + if (sameNameResults.length && !isSameUrl) { + currentResult.result = void 0; + } + currentResult.relatedNodes = []; + (_currentResult$relate = currentResult.relatedNodes).push.apply(_currentResult$relate, _toConsumableArray(sameNameResults.map(function(node) { + return node.relatedNodes[0]; + }))); + nameMap[name] = sameNameResults; + uniqueResults.push(currentResult); + }; + for (var index = 0; index < incompleteResults.length; index++) { + if (_loop8(index)) { + continue; + } + } + return uniqueResults; + } + var identical_links_same_purpose_after_default = identicalLinksSamePurposeAfter; + function getLevel(vNode) { + var role = get_role_default(vNode); + var headingRole = role && role.includes('heading'); + var ariaHeadingLevel = vNode.attr('aria-level'); + var ariaLevel = parseInt(ariaHeadingLevel, 10); + var _ref116 = vNode.props.nodeName.match(/h(\d)/) || [], _ref117 = _slicedToArray(_ref116, 2), headingLevel = _ref117[1]; + if (!headingRole) { + return -1; + } + if (headingLevel && !ariaHeadingLevel) { + return parseInt(headingLevel, 10); + } + if (isNaN(ariaLevel) || ariaLevel < 1) { + if (headingLevel) { + return parseInt(headingLevel, 10); + } + return 2; + } + if (ariaLevel) { + return ariaLevel; + } + return -1; + } + function headingOrderEvaluate() { + var headingOrder = cache_default.get('headingOrder'); + if (headingOrder) { + return true; + } + var selector = 'h1, h2, h3, h4, h5, h6, [role=heading], iframe, frame'; + var vNodes = query_selector_all_filter_default(axe._tree[0], selector, _isVisibleToScreenReaders); + headingOrder = vNodes.map(function(vNode) { + return { + ancestry: [ _getAncestry(vNode.actualNode) ], + level: getLevel(vNode) + }; + }); + this.data({ + headingOrder: headingOrder + }); + cache_default.set('headingOrder', vNodes); + return true; + } + var heading_order_evaluate_default = headingOrderEvaluate; + function headingOrderAfter(results) { + var headingOrder = getHeadingOrder(results); + results.forEach(function(result) { + result.result = getHeadingOrderOutcome(result, headingOrder); + }); + return results; + } + function getHeadingOrderOutcome(result, headingOrder) { + var _headingOrder$index$l, _headingOrder$index, _headingOrder$level, _headingOrder; + var index = findHeadingOrderIndex(headingOrder, result.node.ancestry); + var currLevel = (_headingOrder$index$l = (_headingOrder$index = headingOrder[index]) === null || _headingOrder$index === void 0 ? void 0 : _headingOrder$index.level) !== null && _headingOrder$index$l !== void 0 ? _headingOrder$index$l : -1; + var prevLevel = (_headingOrder$level = (_headingOrder = headingOrder[index - 1]) === null || _headingOrder === void 0 ? void 0 : _headingOrder.level) !== null && _headingOrder$level !== void 0 ? _headingOrder$level : -1; + if (index === 0) { + return true; + } + if (currLevel === -1) { + return void 0; + } + return currLevel - prevLevel <= 1; + } + function getHeadingOrder(results) { + results = _toConsumableArray(results); + results.sort(function(_ref118, _ref119) { + var nodeA = _ref118.node; + var nodeB = _ref119.node; + return nodeA.ancestry.length - nodeB.ancestry.length; + }); + var headingOrder = results.reduce(mergeHeadingOrder, []); + return headingOrder.filter(function(_ref120) { + var level = _ref120.level; + return level !== -1; + }); + } + function mergeHeadingOrder(mergedHeadingOrder, result) { + var _result$data; + var frameHeadingOrder = (_result$data = result.data) === null || _result$data === void 0 ? void 0 : _result$data.headingOrder; + var frameAncestry = shortenArray(result.node.ancestry, 1); + if (!frameHeadingOrder) { + return mergedHeadingOrder; + } + var normalizedHeadingOrder = frameHeadingOrder.map(function(heading) { + return addFrameToHeadingAncestry(heading, frameAncestry); + }); + var index = getFrameIndex(mergedHeadingOrder, frameAncestry); + if (index === -1) { + mergedHeadingOrder.push.apply(mergedHeadingOrder, _toConsumableArray(normalizedHeadingOrder)); + } else { + mergedHeadingOrder.splice.apply(mergedHeadingOrder, [ index, 0 ].concat(_toConsumableArray(normalizedHeadingOrder))); + } + return mergedHeadingOrder; + } + function getFrameIndex(headingOrder, frameAncestry) { + while (frameAncestry.length) { + var index = findHeadingOrderIndex(headingOrder, frameAncestry); + if (index !== -1) { + return index; + } + frameAncestry = shortenArray(frameAncestry, 1); + } + return -1; + } + function findHeadingOrderIndex(headingOrder, ancestry) { + return headingOrder.findIndex(function(heading) { + return _matchAncestry(heading.ancestry, ancestry); + }); + } + function addFrameToHeadingAncestry(heading, frameAncestry) { + var ancestry = frameAncestry.concat(heading.ancestry); + return _extends({}, heading, { + ancestry: ancestry + }); + } + function shortenArray(arr, spliceLength) { + return arr.slice(0, arr.length - spliceLength); + } + function targetSizeEvaluate(node, options, vNode) { + var minSize = (options === null || options === void 0 ? void 0 : options.minSize) || 24; + var nodeRect = vNode.boundingClientRect; + if (_rectHasMinimumSize(minSize * 10, nodeRect)) { + this.data({ + messageKey: 'large', + minSize: minSize + }); + return true; + } + var hasMinimumSize = _rectHasMinimumSize.bind(null, minSize); + var nearbyElms = _findNearbyElms(vNode); + var overflowingContent = filterOverflowingContent(vNode, nearbyElms); + var _filterByElmsOverlap = filterByElmsOverlap(vNode, nearbyElms), fullyObscuringElms = _filterByElmsOverlap.fullyObscuringElms, partialObscuringElms = _filterByElmsOverlap.partialObscuringElms; + if (overflowingContent.length && (fullyObscuringElms.length || !hasMinimumSize(nodeRect))) { + this.data({ + minSize: minSize, + messageKey: 'contentOverflow' + }); + this.relatedNodes(mapActualNodes(overflowingContent)); + return void 0; + } + if (fullyObscuringElms.length) { + this.relatedNodes(mapActualNodes(fullyObscuringElms)); + this.data({ + messageKey: 'obscured' + }); + return true; + } + var negativeOutcome = _isInTabOrder(vNode) ? false : void 0; + if (!hasMinimumSize(nodeRect)) { + this.data(_extends({ + minSize: minSize + }, toDecimalSize(nodeRect))); + return negativeOutcome; + } + var obscuredWidgets = filterFocusableWidgets(partialObscuringElms); + if (!obscuredWidgets.length) { + this.data(_extends({ + minSize: minSize + }, toDecimalSize(nodeRect))); + return true; + } + var largestInnerRect = getLargestUnobscuredArea(vNode, obscuredWidgets, minSize); + if (!largestInnerRect) { + this.data({ + minSize: minSize, + messageKey: 'tooManyRects' + }); + return void 0; + } + if (!hasMinimumSize(largestInnerRect)) { + if (overflowingContent.length) { + this.data({ + minSize: minSize, + messageKey: 'contentOverflow' + }); + this.relatedNodes(mapActualNodes(overflowingContent)); + return void 0; + } + var allTabbable = obscuredWidgets.every(_isInTabOrder); + var messageKey = 'partiallyObscured'.concat(allTabbable ? '' : 'NonTabbable'); + this.data(_extends({ + messageKey: messageKey, + minSize: minSize + }, toDecimalSize(largestInnerRect))); + this.relatedNodes(mapActualNodes(obscuredWidgets)); + return allTabbable ? negativeOutcome : void 0; + } + this.data(_extends({ + minSize: minSize + }, toDecimalSize(largestInnerRect || nodeRect))); + this.relatedNodes(mapActualNodes(obscuredWidgets)); + return true; + } + function filterOverflowingContent(vNode, nearbyElms) { + return nearbyElms.filter(function(nearbyElm) { + return !isEnclosedRect2(nearbyElm, vNode) && isDescendantNotInTabOrder2(vNode, nearbyElm); + }); + } + function filterByElmsOverlap(vNode, nearbyElms) { + var fullyObscuringElms = []; + var partialObscuringElms = []; + var _iterator20 = _createForOfIteratorHelper(nearbyElms), _step20; + try { + for (_iterator20.s(); !(_step20 = _iterator20.n()).done; ) { + var vNeighbor = _step20.value; + if (!isDescendantNotInTabOrder2(vNode, vNeighbor) && _hasVisualOverlap(vNode, vNeighbor) && getCssPointerEvents(vNeighbor) !== 'none') { + if (isEnclosedRect2(vNode, vNeighbor)) { + fullyObscuringElms.push(vNeighbor); + } else { + partialObscuringElms.push(vNeighbor); + } + } + } + } catch (err) { + _iterator20.e(err); + } finally { + _iterator20.f(); + } + return { + fullyObscuringElms: fullyObscuringElms, + partialObscuringElms: partialObscuringElms + }; + } + function getLargestUnobscuredArea(vNode, obscuredNodes, minSize) { + var nodeRect = vNode.boundingClientRect; + var obscuringRects = obscuredNodes.map(function(obscuredNode) { + var display2 = obscuredNode.getComputedStylePropertyValue('display'); + return display2 === 'inline' ? obscuredNode.clientRects : obscuredNode.boundingClientRect; + }).flat(Infinity); + var unobscuredRects; + try { + unobscuredRects = _splitRects(nodeRect, obscuringRects); + } catch (_unused9) { + return null; + } + return getLargestRect2(unobscuredRects, minSize); + } + function getLargestRect2(rects, minSize) { + return rects.reduce(function(rectA, rectB) { + var rectAisMinimum = _rectHasMinimumSize(minSize, rectA); + var rectBisMinimum = _rectHasMinimumSize(minSize, rectB); + if (rectAisMinimum !== rectBisMinimum) { + return rectAisMinimum ? rectA : rectB; + } + var areaA = rectA.width * rectA.height; + var areaB = rectB.width * rectB.height; + return areaA > areaB ? rectA : rectB; + }); + } + function filterFocusableWidgets(vNodes) { + return vNodes.filter(function(vNode) { + return get_role_type_default(vNode) === 'widget' && _isFocusable(vNode); + }); + } + function isEnclosedRect2(vNodeA, vNodeB) { + var rectA = vNodeA.boundingClientRect; + var rectB = vNodeB.boundingClientRect; + return rectA.top >= rectB.top && rectA.left >= rectB.left && rectA.bottom <= rectB.bottom && rectA.right <= rectB.right; + } + function getCssPointerEvents(vNode) { + return vNode.getComputedStylePropertyValue('pointer-events'); + } + function toDecimalSize(rect) { + return { + width: Math.round(rect.width * 10) / 10, + height: Math.round(rect.height * 10) / 10 + }; + } + function isDescendantNotInTabOrder2(vAncestor, vNode) { + return _contains(vAncestor, vNode) && !_isInTabOrder(vNode); + } + function mapActualNodes(vNodes) { + return vNodes.map(function(_ref121) { + var actualNode = _ref121.actualNode; + return actualNode; + }); + } + var roundingMargin2 = .05; + function targetOffsetEvaluate(node, options, vNode) { + var minOffset = (options === null || options === void 0 ? void 0 : options.minOffset) || 24; + if (_rectHasMinimumSize(minOffset * 10, vNode.boundingClientRect)) { + this.data({ + messageKey: 'large', + minOffset: minOffset + }); + return true; + } + var closeNeighbors = []; + var closestOffset = minOffset; + var _iterator21 = _createForOfIteratorHelper(_findNearbyElms(vNode, minOffset)), _step21; + try { + for (_iterator21.s(); !(_step21 = _iterator21.n()).done; ) { + var vNeighbor = _step21.value; + if (get_role_type_default(vNeighbor) !== 'widget' || !_isFocusable(vNeighbor)) { + continue; + } + var offset = null; + try { + offset = _getOffset(vNode, vNeighbor, minOffset / 2); + } catch (err2) { + if (err2.message.startsWith('splitRects')) { + this.data({ + messageKey: 'tooManyRects', + closestOffset: 0, + minOffset: minOffset + }); + return void 0; + } + throw err2; + } + if (offset === null) { + continue; + } + offset = roundToSingleDecimal(offset) * 2; + if (offset + roundingMargin2 >= minOffset) { + continue; + } + closestOffset = Math.min(closestOffset, offset); + closeNeighbors.push(vNeighbor); + } + } catch (err) { + _iterator21.e(err); + } finally { + _iterator21.f(); + } + if (closeNeighbors.length === 0) { + this.data({ + closestOffset: closestOffset, + minOffset: minOffset + }); + return true; + } + this.relatedNodes(closeNeighbors.map(function(_ref122) { + var actualNode = _ref122.actualNode; + return actualNode; + })); + if (!closeNeighbors.some(_isInTabOrder)) { + this.data({ + messageKey: 'nonTabbableNeighbor', + closestOffset: closestOffset, + minOffset: minOffset + }); + return void 0; + } + this.data({ + closestOffset: closestOffset, + minOffset: minOffset + }); + return _isInTabOrder(vNode) ? false : void 0; + } + function roundToSingleDecimal(num) { + return Math.round(num * 10) / 10; + } + function metaViewportScaleEvaluate(node, options, virtualNode) { + var _ref123 = options || {}, _ref123$scaleMinimum = _ref123.scaleMinimum, scaleMinimum = _ref123$scaleMinimum === void 0 ? 2 : _ref123$scaleMinimum, _ref123$lowerBound = _ref123.lowerBound, lowerBound = _ref123$lowerBound === void 0 ? false : _ref123$lowerBound; + var content = virtualNode.attr('content') || ''; + if (!content) { + return true; + } + var result = content.split(/[;,]/).reduce(function(out, item) { + var contentValue = item.trim(); + if (!contentValue) { + return out; + } + var _contentValue$split = contentValue.split('='), _contentValue$split2 = _slicedToArray(_contentValue$split, 2), key = _contentValue$split2[0], value = _contentValue$split2[1]; + if (!key || !value) { + return out; + } + var curatedKey = key.toLowerCase().trim(); + var curatedValue = value.toLowerCase().trim(); + if (curatedKey === 'maximum-scale' && curatedValue === 'yes') { + curatedValue = 1; + } + if (curatedKey === 'maximum-scale' && parseFloat(curatedValue) < 0) { + return out; + } + out[curatedKey] = curatedValue; + return out; + }, {}); + if (lowerBound && result['maximum-scale'] && parseFloat(result['maximum-scale']) < lowerBound) { + return true; + } + if (!lowerBound && result['user-scalable'] === 'no') { + this.data('user-scalable=no'); + return false; + } + var userScalableAsFloat = parseFloat(result['user-scalable']); + if (!lowerBound && result['user-scalable'] && (userScalableAsFloat || userScalableAsFloat === 0) && userScalableAsFloat > -1 && userScalableAsFloat < 1) { + this.data('user-scalable'); + return false; + } + if (result['maximum-scale'] && parseFloat(result['maximum-scale']) < scaleMinimum) { + this.data('maximum-scale'); + return false; + } + return true; + } + var meta_viewport_scale_evaluate_default = metaViewportScaleEvaluate; + function cssOrientationLockEvaluate(node, options, virtualNode, context) { + var _ref124 = context || {}, _ref124$cssom = _ref124.cssom, cssom = _ref124$cssom === void 0 ? void 0 : _ref124$cssom; + var _ref125 = options || {}, _ref125$degreeThresho = _ref125.degreeThreshold, degreeThreshold = _ref125$degreeThresho === void 0 ? 0 : _ref125$degreeThresho; + if (!cssom || !cssom.length) { + return void 0; + } + var isLocked = false; + var relatedElements = []; + var rulesGroupByDocumentFragment = groupCssomByDocument(cssom); + var _loop9 = function _loop9() { + var key = _Object$keys3[_i31]; + var _rulesGroupByDocument = rulesGroupByDocumentFragment[key], root = _rulesGroupByDocument.root, rules = _rulesGroupByDocument.rules; + var orientationRules = rules.filter(isMediaRuleWithOrientation); + if (!orientationRules.length) { + return 1; + } + orientationRules.forEach(function(_ref126) { + var cssRules = _ref126.cssRules; + Array.from(cssRules).forEach(function(cssRule) { + var locked = getIsOrientationLocked(cssRule); + if (locked && cssRule.selectorText.toUpperCase() !== 'HTML') { + var elms = Array.from(root.querySelectorAll(cssRule.selectorText)) || []; + relatedElements = relatedElements.concat(elms); + } + isLocked = isLocked || locked; + }); + }); + }; + for (var _i31 = 0, _Object$keys3 = Object.keys(rulesGroupByDocumentFragment); _i31 < _Object$keys3.length; _i31++) { + if (_loop9()) { + continue; + } + } + if (!isLocked) { + return true; + } + if (relatedElements.length) { + this.relatedNodes(relatedElements); + } + return false; + function groupCssomByDocument(cssObjectModel) { + return cssObjectModel.reduce(function(out, _ref127) { + var sheet = _ref127.sheet, root = _ref127.root, shadowId = _ref127.shadowId; + var key = shadowId ? shadowId : 'topDocument'; + if (!out[key]) { + out[key] = { + root: root, + rules: [] + }; + } + if (!sheet || !sheet.cssRules) { + return out; + } + var rules = Array.from(sheet.cssRules); + out[key].rules = out[key].rules.concat(rules); + return out; + }, {}); + } + function isMediaRuleWithOrientation(_ref128) { + var type2 = _ref128.type, cssText = _ref128.cssText; + if (type2 !== 4) { + return false; + } + return /orientation:\s*landscape/i.test(cssText) || /orientation:\s*portrait/i.test(cssText); + } + function getIsOrientationLocked(_ref129) { + var selectorText = _ref129.selectorText, style = _ref129.style; + if (!selectorText || style.length <= 0) { + return false; + } + var transformStyle = style.transform || style.webkitTransform || style.msTransform || false; + if (!transformStyle && !style.rotate) { + return false; + } + var transformDegrees = getTransformDegrees(transformStyle); + var rotateDegrees = getRotationInDegrees('rotate', style.rotate); + var degrees = transformDegrees + rotateDegrees; + if (!degrees) { + return false; + } + degrees = Math.abs(degrees); + if (Math.abs(degrees - 180) % 180 <= degreeThreshold) { + return false; + } + return Math.abs(degrees - 90) % 90 <= degreeThreshold; + } + function getTransformDegrees(transformStyle) { + if (!transformStyle) { + return 0; + } + var matches4 = transformStyle.match(/(rotate|rotateZ|rotate3d|matrix|matrix3d)\(([^)]+)\)(?!.*(rotate|rotateZ|rotate3d|matrix|matrix3d))/); + if (!matches4) { + return 0; + } + var _matches2 = _slicedToArray(matches4, 3), transformFn = _matches2[1], transformFnValue = _matches2[2]; + return getRotationInDegrees(transformFn, transformFnValue); + } + function getRotationInDegrees(transformFunction, transformFnValue) { + switch (transformFunction) { + case 'rotate': + case 'rotateZ': + return getAngleInDegrees(transformFnValue); + + case 'rotate3d': + var _transformFnValue$spl = transformFnValue.split(',').map(function(value) { + return value.trim(); + }), _transformFnValue$spl2 = _slicedToArray(_transformFnValue$spl, 4), z = _transformFnValue$spl2[2], angleWithUnit = _transformFnValue$spl2[3]; + if (parseInt(z) === 0) { + return; + } + return getAngleInDegrees(angleWithUnit); + + case 'matrix': + case 'matrix3d': + return getAngleInDegreesFromMatrixTransform(transformFnValue); + + default: + return 0; + } + } + function getAngleInDegrees(angleWithUnit) { + var _ref130 = angleWithUnit.match(/(deg|grad|rad|turn)/) || [], _ref131 = _slicedToArray(_ref130, 1), unit = _ref131[0]; + if (!unit) { + return 0; + } + var angle = parseFloat(angleWithUnit.replace(unit, '')); + switch (unit) { + case 'rad': + return convertRadToDeg(angle); + + case 'grad': + return convertGradToDeg(angle); + + case 'turn': + return convertTurnToDeg(angle); + + case 'deg': + default: + return parseInt(angle); + } + } + function getAngleInDegreesFromMatrixTransform(transformFnValue) { + var values2 = transformFnValue.split(','); + if (values2.length <= 6) { + var _values = _slicedToArray(values2, 2), a2 = _values[0], b3 = _values[1]; + var radians = Math.atan2(parseFloat(b3), parseFloat(a2)); + return convertRadToDeg(radians); + } + var sinB = parseFloat(values2[8]); + var b2 = Math.asin(sinB); + var cosB = Math.cos(b2); + var rotateZRadians = Math.acos(parseFloat(values2[0]) / cosB); + return convertRadToDeg(rotateZRadians); + } + function convertRadToDeg(radians) { + return Math.round(radians * (180 / Math.PI)); + } + function convertGradToDeg(grad) { + grad = grad % 400; + if (grad < 0) { + grad += 400; + } + return Math.round(grad / 400 * 360); + } + function convertTurnToDeg(turn) { + return Math.round(360 / (1 / turn)); + } + } + var css_orientation_lock_evaluate_default = cssOrientationLockEvaluate; + function noAutoplayAudioEvaluate(node, options) { + var hasControls = node.hasAttribute('controls'); + if (node.hasAttribute('loop')) { + return hasControls; + } + if (!node.duration) { + console.warn('axe.utils.preloadMedia did not load metadata'); + return void 0; + } + var _options$allowedDurat = options.allowedDuration, allowedDuration = _options$allowedDurat === void 0 ? 3 : _options$allowedDurat; + var playableDuration = getPlayableDuration(node); + if (playableDuration <= allowedDuration) { + return true; + } + if (!hasControls) { + return false; + } + return true; + function getPlayableDuration(elm) { + if (!elm.currentSrc) { + return 0; + } + var playbackRange = getPlaybackRange(elm.currentSrc); + if (!playbackRange) { + return Math.abs(elm.duration - (elm.currentTime || 0)); + } + if (playbackRange.length === 1) { + return Math.abs(elm.duration - playbackRange[0]); + } + return Math.abs(playbackRange[1] - playbackRange[0]); + } + function getPlaybackRange(src) { + var match = src.match(/#t=(.*)/); + if (!match) { + return; + } + var _match = _slicedToArray(match, 2), value = _match[1]; + var ranges = value.split(','); + return ranges.map(function(range2) { + if (/:/.test(range2)) { + return convertHourMinSecToSeconds(range2); + } + return parseFloat(range2); + }); + } + function convertHourMinSecToSeconds(hhMmSs) { + var parts = hhMmSs.split(':'); + var secs = 0; + var mins = 1; + while (parts.length > 0) { + secs += mins * parseInt(parts.pop(), 10); + mins *= 60; + } + return parseFloat(secs); + } + } + var no_autoplay_audio_evaluate_default = noAutoplayAudioEvaluate; + function frameTestedEvaluate(node, options) { + return options.isViolation ? false : void 0; + } + var frame_tested_evaluate_default = frameTestedEvaluate; + var joinStr = ' > '; + function frameTestedAfter(results) { + var iframes = {}; + return results.filter(function(result) { + var frameResult = result.node.ancestry[result.node.ancestry.length - 1] !== 'html'; + if (frameResult) { + var ancestry2 = result.node.ancestry.flat(Infinity).join(joinStr); + iframes[ancestry2] = result; + return true; + } + var ancestry = result.node.ancestry.slice(0, result.node.ancestry.length - 1).flat(Infinity).join(joinStr); + if (iframes[ancestry]) { + iframes[ancestry].result = true; + } + return false; + }); + } + var frame_tested_after_default = frameTestedAfter; + function captionEvaluate(node, options, virtualNode) { + var tracks = query_selector_all_default(virtualNode, 'track'); + var hasCaptions = tracks.some(function(vNode) { + return (vNode.attr('kind') || '').toLowerCase() === 'captions'; + }); + return hasCaptions ? false : void 0; + } + var caption_evaluate_default = captionEvaluate; + function structuredDlitemsEvaluate(node, options, virtualNode) { + var children = virtualNode.children; + if (!children || !children.length) { + return false; + } + var hasDt = false, hasDd = false, nodeName2; + for (var _i32 = 0; _i32 < children.length; _i32++) { + nodeName2 = children[_i32].props.nodeName.toUpperCase(); + if (nodeName2 === 'DT') { + hasDt = true; + } + if (hasDt && nodeName2 === 'DD') { + return false; + } + if (nodeName2 === 'DD') { + hasDd = true; + } + } + return hasDt || hasDd; + } + var structured_dlitems_evaluate_default = structuredDlitemsEvaluate; + function onlyListitemsEvaluate(node, options, virtualNode) { + var hasNonEmptyTextNode = false; + var atLeastOneListitem = false; + var isEmpty2 = true; + var badNodes = []; + var badRoleNodes = []; + var badRoles = []; + virtualNode.children.forEach(function(vNode) { + var actualNode = vNode.actualNode; + if (actualNode.nodeType === 3 && actualNode.nodeValue.trim() !== '') { + hasNonEmptyTextNode = true; + return; + } + if (actualNode.nodeType !== 1 || !_isVisibleToScreenReaders(actualNode)) { + return; + } + isEmpty2 = false; + var isLi = actualNode.nodeName.toUpperCase() === 'LI'; + var role = get_role_default(vNode); + var isListItemRole = role === 'listitem'; + if (!isLi && !isListItemRole) { + badNodes.push(actualNode); + } + if (isLi && !isListItemRole) { + badRoleNodes.push(actualNode); + if (!badRoles.includes(role)) { + badRoles.push(role); + } + } + if (isListItemRole) { + atLeastOneListitem = true; + } + }); + if (hasNonEmptyTextNode || badNodes.length) { + this.relatedNodes(badNodes); + return true; + } + if (isEmpty2 || atLeastOneListitem) { + return false; + } + this.relatedNodes(badRoleNodes); + this.data({ + messageKey: 'roleNotValid', + roles: badRoles.join(', ') + }); + return true; + } + var only_listitems_evaluate_default = onlyListitemsEvaluate; + function onlyDlitemsEvaluate(node, options, virtualNode) { + var ALLOWED_ROLES = [ 'definition', 'term', 'list' ]; + var base = { + badNodes: [], + hasNonEmptyTextNode: false + }; + var content = virtualNode.children.reduce(function(vNodes, child) { + var actualNode = child.actualNode; + if (actualNode.nodeName.toUpperCase() === 'DIV' && get_role_default(actualNode) === null) { + return vNodes.concat(child.children); + } + return vNodes.concat(child); + }, []); + var result = content.reduce(function(out, childNode) { + var actualNode = childNode.actualNode; + var tagName = actualNode.nodeName.toUpperCase(); + if (actualNode.nodeType === 1 && _isVisibleToScreenReaders(actualNode)) { + var explicitRole2 = get_explicit_role_default(actualNode); + if (tagName !== 'DT' && tagName !== 'DD' || explicitRole2) { + if (!ALLOWED_ROLES.includes(explicitRole2)) { + out.badNodes.push(actualNode); + } + } + } else if (actualNode.nodeType === 3 && actualNode.nodeValue.trim() !== '') { + out.hasNonEmptyTextNode = true; + } + return out; + }, base); + if (result.badNodes.length) { + this.relatedNodes(result.badNodes); + } + return !!result.badNodes.length || result.hasNonEmptyTextNode; + } + function listitemEvaluate(node, options, virtualNode) { + var parent = virtualNode.parent; + if (!parent) { + return void 0; + } + var parentNodeName = parent.props.nodeName; + var parentRole = get_explicit_role_default(parent); + if ([ 'presentation', 'none', 'list' ].includes(parentRole)) { + return true; + } + if (parentRole && is_valid_role_default(parentRole)) { + this.data({ + messageKey: 'roleNotValid' + }); + return false; + } + return [ 'ul', 'ol', 'menu' ].includes(parentNodeName); + } + function invalidChildrenEvaluate(node) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var relatedNodes = []; + var issues = []; + if (!virtualNode.children) { + return void 0; + } + var vChildren = mapWithNested(virtualNode.children); + while (vChildren.length) { + var _vChild$actualNode; + var _vChildren$shift = vChildren.shift(), vChild = _vChildren$shift.vChild, nested = _vChildren$shift.nested; + if (options.divGroups && !nested && isDivGroup(vChild)) { + if (!vChild.children) { + return void 0; + } + var vGrandChildren = mapWithNested(vChild.children, true); + vChildren.push.apply(vChildren, _toConsumableArray(vGrandChildren)); + continue; + } + var issue = getInvalidSelector(vChild, nested, options); + if (!issue) { + continue; + } + if (!issues.includes(issue)) { + issues.push(issue); + } + if ((vChild === null || vChild === void 0 || (_vChild$actualNode = vChild.actualNode) === null || _vChild$actualNode === void 0 ? void 0 : _vChild$actualNode.nodeType) === 1) { + relatedNodes.push(vChild.actualNode); + } + } + if (issues.length === 0) { + return false; + } + this.data({ + values: issues.join(', ') + }); + this.relatedNodes(relatedNodes); + return true; + } + function getInvalidSelector(vChild, nested, _ref132) { + var _ref132$validRoles = _ref132.validRoles, validRoles = _ref132$validRoles === void 0 ? [] : _ref132$validRoles, _ref132$validNodeName = _ref132.validNodeNames, validNodeNames = _ref132$validNodeName === void 0 ? [] : _ref132$validNodeName; + var _vChild$props = vChild.props, nodeName2 = _vChild$props.nodeName, nodeType = _vChild$props.nodeType, nodeValue = _vChild$props.nodeValue; + var selector = nested ? 'div > ' : ''; + if (nodeType === 3 && nodeValue.trim() !== '') { + return selector + '#text'; + } + if (nodeType !== 1 || !_isVisibleToScreenReaders(vChild)) { + return false; + } + var role = get_explicit_role_default(vChild); + if (role) { + return validRoles.includes(role) ? false : selector + '[role='.concat(role, ']'); + } else { + return validNodeNames.includes(nodeName2) ? false : selector + nodeName2; + } + } + function isDivGroup(vNode) { + return vNode.props.nodeName === 'div' && get_explicit_role_default(vNode) === null; + } + function mapWithNested(vNodes) { + var nested = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return vNodes.map(function(vChild) { + return { + vChild: vChild, + nested: nested + }; + }); + } + function dlitemEvaluate(node) { + var parent = get_composed_parent_default(node); + var parentTagName = parent.nodeName.toUpperCase(); + var parentRole = get_explicit_role_default(parent); + if (parentTagName === 'DIV' && [ 'presentation', 'none', null ].includes(parentRole)) { + parent = get_composed_parent_default(parent); + parentTagName = parent.nodeName.toUpperCase(); + parentRole = get_explicit_role_default(parent); + } + if (parentTagName !== 'DL') { + return false; + } + if (!parentRole || [ 'presentation', 'none', 'list' ].includes(parentRole)) { + return true; + } + return false; + } + var dlitem_evaluate_default = dlitemEvaluate; + function xmlLangMismatchEvaluate(node, options, vNode) { + var primaryLangValue = get_base_lang_default(vNode.attr('lang')); + var primaryXmlLangValue = get_base_lang_default(vNode.attr('xml:lang')); + return primaryLangValue === primaryXmlLangValue; + } + var xml_lang_mismatch_evaluate_default = xmlLangMismatchEvaluate; + function validLangEvaluate(node, options, virtualNode) { + var invalid = []; + options.attributes.forEach(function(langAttr) { + var langVal = virtualNode.attr(langAttr); + if (typeof langVal !== 'string') { + return; + } + var baselangVal = get_base_lang_default(langVal); + var invalidLang = options.value ? !options.value.map(get_base_lang_default).includes(baselangVal) : !valid_langs_default(baselangVal); + if (baselangVal !== '' && invalidLang || langVal !== '' && !sanitize_default(langVal)) { + invalid.push(langAttr + '="' + virtualNode.attr(langAttr) + '"'); + } + }); + if (!invalid.length) { + return false; + } + if (virtualNode.props.nodeName !== 'html' && !_hasLangText(virtualNode)) { + return false; + } + this.data(invalid); + return true; + } + var valid_lang_evaluate_default = validLangEvaluate; + function hasValue(value) { + return (value || '').trim() !== ''; + } + function hasLangEvaluate(node, options, virtualNode) { + var xhtml = typeof document !== 'undefined' ? is_xhtml_default(document) : false; + if (options.attributes.includes('xml:lang') && options.attributes.includes('lang') && hasValue(virtualNode.attr('xml:lang')) && !hasValue(virtualNode.attr('lang')) && !xhtml) { + this.data({ + messageKey: 'noXHTML' + }); + return false; + } + var hasLang = options.attributes.some(function(name) { + return hasValue(virtualNode.attr(name)); + }); + if (!hasLang) { + this.data({ + messageKey: 'noLang' + }); + return false; + } + return true; + } + var has_lang_evaluate_default = hasLangEvaluate; + function landmarkIsUniqueEvaluate(node, options, virtualNode) { + var role = get_role_default(node); + var accessibleText2 = _accessibleTextVirtual(virtualNode); + accessibleText2 = accessibleText2 ? accessibleText2.toLowerCase() : null; + this.data({ + role: role, + accessibleText: accessibleText2 + }); + this.relatedNodes([ node ]); + return true; + } + var landmark_is_unique_evaluate_default = landmarkIsUniqueEvaluate; + function landmarkIsUniqueAfter(results) { + var uniqueLandmarks = []; + return results.filter(function(currentResult) { + var findMatch = function findMatch(someResult) { + return currentResult.data.role === someResult.data.role && currentResult.data.accessibleText === someResult.data.accessibleText; + }; + var matchedResult = uniqueLandmarks.find(findMatch); + if (matchedResult) { + matchedResult.result = false; + matchedResult.relatedNodes.push(currentResult.relatedNodes[0]); + return false; + } + uniqueLandmarks.push(currentResult); + currentResult.relatedNodes = []; + return true; + }); + } + var landmark_is_unique_after_default = landmarkIsUniqueAfter; + function titleOnlyEvaluate(node, options, virtualNode) { + var labelText2 = label_virtual_default2(virtualNode); + var title = title_text_default(virtualNode); + var ariaDescribedBy = virtualNode.attr('aria-describedby'); + return !labelText2 && !!(title || ariaDescribedBy); + } + var title_only_evaluate_default = titleOnlyEvaluate; + function multipleLabelEvaluate(node) { + var id = escape_selector_default(node.getAttribute('id')); + var parent = node.parentNode; + var root = get_root_node_default2(node); + root = root.documentElement || root; + var labels = Array.from(root.querySelectorAll('label[for="'.concat(id, '"]'))); + if (labels.length) { + labels = labels.filter(function(label3) { + return !_isHiddenForEveryone(label3); + }); + } + while (parent) { + if (parent.nodeName.toUpperCase() === 'LABEL' && labels.indexOf(parent) === -1) { + labels.push(parent); + } + parent = parent.parentNode; + } + this.relatedNodes(labels); + if (labels.length > 1) { + var ATVisibleLabels = labels.filter(function(label3) { + return _isVisibleToScreenReaders(label3); + }); + if (ATVisibleLabels.length > 1) { + return void 0; + } + var labelledby = idrefs_default(node, 'aria-labelledby'); + return !labelledby.includes(ATVisibleLabels[0]) ? void 0 : false; + } + return false; + } + var multiple_label_evaluate_default = multipleLabelEvaluate; + function isStringContained(compare, compareWith) { + var curatedCompareWith = curateString(compareWith); + var curatedCompare = curateString(compare); + if (!curatedCompareWith || !curatedCompare) { + return false; + } + return curatedCompareWith.includes(curatedCompare); + } + function curateString(str) { + var noUnicodeStr = remove_unicode_default(str, { + emoji: true, + nonBmp: true, + punctuations: true + }); + return sanitize_default(noUnicodeStr); + } + function labelContentNameMismatchEvaluate(node, options, virtualNode) { + var _options$occurrenceTh; + var pixelThreshold = options === null || options === void 0 ? void 0 : options.pixelThreshold; + var occurrenceThreshold = (_options$occurrenceTh = options === null || options === void 0 ? void 0 : options.occurrenceThreshold) !== null && _options$occurrenceTh !== void 0 ? _options$occurrenceTh : options === null || options === void 0 ? void 0 : options.occuranceThreshold; + var accText = accessible_text_default(node).toLowerCase(); + var visibleText = sanitize_default(subtree_text_default(virtualNode, { + subtreeDescendant: true, + ignoreIconLigature: true, + pixelThreshold: pixelThreshold, + occurrenceThreshold: occurrenceThreshold + })).toLowerCase(); + if (!visibleText) { + return true; + } + if (is_human_interpretable_default(accText) < 1 || is_human_interpretable_default(visibleText) < 1) { + return void 0; + } + return isStringContained(visibleText, accText); + } + var label_content_name_mismatch_evaluate_default = labelContentNameMismatchEvaluate; + function implicitEvaluate(node, options, virtualNode) { + try { + var label3 = closest_default(virtualNode, 'label'); + if (label3) { + var implicitLabel = sanitize_default(_accessibleTextVirtual(label3, { + inControlContext: true, + startNode: virtualNode + })); + if (label3.actualNode) { + this.relatedNodes([ label3.actualNode ]); + } + this.data({ + implicitLabel: implicitLabel + }); + return !!implicitLabel; + } + return false; + } catch (_unused0) { + return void 0; + } + } + var implicit_evaluate_default = implicitEvaluate; + function hiddenExplicitLabelEvaluate(node, options, virtualNode) { + if (virtualNode.hasAttr('id')) { + if (!virtualNode.actualNode) { + return void 0; + } + var root = get_root_node_default2(node); + var _id6 = escape_selector_default(node.getAttribute('id')); + var label3 = root.querySelector('label[for="'.concat(_id6, '"]')); + if (label3 && !_isVisibleToScreenReaders(label3)) { + var name; + try { + name = _accessibleTextVirtual(virtualNode).trim(); + } catch (_unused1) { + return void 0; + } + var isNameEmpty = name === ''; + return isNameEmpty; + } + } + return false; + } + var hidden_explicit_label_evaluate_default = hiddenExplicitLabelEvaluate; + function helpSameAsLabelEvaluate(node, options, virtualNode) { + var labelText2 = label_virtual_default2(virtualNode); + var check = node.getAttribute('title'); + if (!labelText2) { + return false; + } + if (!check) { + check = ''; + if (node.getAttribute('aria-describedby')) { + var ref = idrefs_default(node, 'aria-describedby'); + check = ref.map(function(thing) { + return thing ? accessible_text_default(thing) : ''; + }).join(''); + } + } + return sanitize_default(check) === sanitize_default(labelText2); + } + var help_same_as_label_evaluate_default = helpSameAsLabelEvaluate; + function explicitEvaluate(node, options, virtualNode) { + var _this9 = this; + if (!virtualNode.attr('id')) { + return false; + } + if (!virtualNode.actualNode) { + return void 0; + } + var root = get_root_node_default2(virtualNode.actualNode); + var id = escape_selector_default(virtualNode.attr('id')); + var labels = Array.from(root.querySelectorAll('label[for="'.concat(id, '"]'))); + this.relatedNodes(labels); + if (!labels.length) { + return false; + } + try { + return labels.some(function(label3) { + if (!_isVisibleOnScreen(label3)) { + return true; + } else { + var explicitLabel = sanitize_default(accessible_text_default(label3, { + inControlContext: true, + startNode: virtualNode + })); + _this9.data({ + explicitLabel: explicitLabel + }); + return !!explicitLabel; + } + }); + } catch (_unused10) { + return void 0; + } + } + var explicit_evaluate_default = explicitEvaluate; + function duplicateImgLabelEvaluate(node, options, virtualNode) { + if ([ 'none', 'presentation' ].includes(get_role_default(virtualNode))) { + return false; + } + var parentVNode = closest_default(virtualNode, options.parentSelector); + if (!parentVNode) { + return false; + } + var visibleText = visible_virtual_default(parentVNode, true).toLowerCase(); + if (visibleText === '') { + return false; + } + return visibleText === _accessibleTextVirtual(virtualNode).toLowerCase(); + } + var duplicate_img_label_evaluate_default = duplicateImgLabelEvaluate; + function altSpaceValueEvaluate(node, options, virtualNode) { + var alt = virtualNode.attr('alt'); + var isOnlySpace = /^\s+$/; + return typeof alt === 'string' && isOnlySpace.test(alt); + } + var alt_space_value_evaluate_default = altSpaceValueEvaluate; + function tabindexEvaluate(node, options, virtualNode) { + var tabIndex = parse_tabindex_default(virtualNode.attr('tabindex')); + return tabIndex === null || tabIndex <= 0; + } + var tabindex_evaluate_default = tabindexEvaluate; + function noFocusableContentEvaluate(node, options, virtualNode) { + if (!virtualNode.children) { + return void 0; + } + try { + var focusableDescendants2 = getFocusableDescendants(virtualNode); + if (!focusableDescendants2.length) { + return true; + } + var notHiddenElements = focusableDescendants2.filter(usesUnreliableHidingStrategy); + if (notHiddenElements.length > 0) { + this.data({ + messageKey: 'notHidden' + }); + this.relatedNodes(notHiddenElements); + } else { + this.relatedNodes(focusableDescendants2); + } + return false; + } catch (_unused11) { + return void 0; + } + } + function getFocusableDescendants(vNode) { + if (!vNode.children) { + if (vNode.props.nodeType === 1) { + throw new Error('Cannot determine children'); + } + return []; + } + var retVal = []; + vNode.children.forEach(function(child) { + if (get_role_type_default(child) === 'widget' && _isFocusable(child)) { + retVal.push(child); + } else { + retVal.push.apply(retVal, _toConsumableArray(getFocusableDescendants(child))); + } + }); + return retVal; + } + function usesUnreliableHidingStrategy(vNode) { + var tabIndex = parse_tabindex_default(vNode.attr('tabindex')); + return tabIndex !== null && tabIndex < 0; + } + function landmarkIsTopLevelEvaluate(node) { + var landmarks = get_aria_roles_by_type_default('landmark'); + var parent = get_composed_parent_default(node); + var nodeRole = get_role_default(node); + this.data({ + role: nodeRole + }); + while (parent) { + var role = get_explicit_role_default(parent); + if (!role && parent.nodeName.toUpperCase() !== 'FORM') { + role = implicit_role_default(parent); + } + if (role && landmarks.includes(role) && !(role === 'main' && nodeRole === 'complementary')) { + return false; + } + parent = get_composed_parent_default(parent); + } + return true; + } + var landmark_is_top_level_evaluate_default = landmarkIsTopLevelEvaluate; + function frameFocusableContentEvaluate(node, options, virtualNode) { + if (!virtualNode.children) { + return void 0; + } + try { + return !virtualNode.children.some(function(child) { + return focusableDescendants(child); + }); + } catch (_unused12) { + return void 0; + } + } + function focusableDescendants(vNode) { + if (_isInTabOrder(vNode)) { + return true; + } + if (!vNode.children) { + if (vNode.props.nodeType === 1) { + throw new Error('Cannot determine children'); + } + return false; + } + return vNode.children.some(function(child) { + return focusableDescendants(child); + }); + } + function focusableNotTabbableEvaluate(node, options, virtualNode) { + var elementsThatCanBeDisabled = [ 'button', 'fieldset', 'input', 'select', 'textarea' ]; + var tabbableElements = virtualNode.tabbableElements; + if (!tabbableElements || !tabbableElements.length) { + return true; + } + var relatedNodes = tabbableElements.filter(function(vNode) { + return !elementsThatCanBeDisabled.includes(vNode.props.nodeName); + }); + this.relatedNodes(relatedNodes.map(function(vNode) { + return vNode.actualNode; + })); + if (relatedNodes.length === 0 || is_modal_open_default()) { + return true; + } + return relatedNodes.every(function(vNode) { + var pointerEvents = vNode.getComputedStylePropertyValue('pointer-events'); + var width = parseInt(vNode.getComputedStylePropertyValue('width')); + var height = parseInt(vNode.getComputedStylePropertyValue('height')); + return vNode.actualNode.onfocus || (width === 0 || height === 0) && pointerEvents === 'none'; + }) ? void 0 : false; + } + var focusable_not_tabbable_evaluate_default = focusableNotTabbableEvaluate; + function focusableNoNameEvaluate(node, options, virtualNode) { + if (!_isInTabOrder(virtualNode)) { + return false; + } + try { + return !_accessibleTextVirtual(virtualNode); + } catch (_unused13) { + return void 0; + } + } + var focusable_no_name_evaluate_default = focusableNoNameEvaluate; + function focusableModalOpenEvaluate(node, options, virtualNode) { + var tabbableElements = virtualNode.tabbableElements.map(function(_ref133) { + var actualNode = _ref133.actualNode; + return actualNode; + }); + if (!tabbableElements || !tabbableElements.length) { + return true; + } + if (is_modal_open_default()) { + this.relatedNodes(tabbableElements); + return void 0; + } + return true; + } + var focusable_modal_open_evaluate_default = focusableModalOpenEvaluate; + function focusableElementEvaluate(node, options, virtualNode) { + if (virtualNode.hasAttr('contenteditable') && isContenteditable(virtualNode)) { + return true; + } + return _isInTabOrder(virtualNode); + function isContenteditable(vNode) { + var contenteditable = vNode.attr('contenteditable'); + if (contenteditable === 'true' || contenteditable === '') { + return true; + } + if (contenteditable === 'false') { + return false; + } + var ancestor = closest_default(virtualNode.parent, '[contenteditable]'); + if (!ancestor) { + return false; + } + return isContenteditable(ancestor); + } + } + var focusable_element_evaluate_default = focusableElementEvaluate; + function focusableDisabledEvaluate(node, options, virtualNode) { + var elementsThatCanBeDisabled = [ 'button', 'fieldset', 'input', 'select', 'textarea' ]; + var tabbableElements = virtualNode.tabbableElements; + if (!tabbableElements || !tabbableElements.length) { + return true; + } + var relatedNodes = tabbableElements.filter(function(vNode) { + return elementsThatCanBeDisabled.includes(vNode.props.nodeName); + }); + this.relatedNodes(relatedNodes.map(function(vNode) { + return vNode.actualNode; + })); + if (relatedNodes.length === 0 || is_modal_open_default()) { + return true; + } + return relatedNodes.every(function(vNode) { + var pointerEvents = vNode.getComputedStylePropertyValue('pointer-events'); + var width = parseInt(vNode.getComputedStylePropertyValue('width')); + var height = parseInt(vNode.getComputedStylePropertyValue('height')); + return vNode.actualNode.onfocus || (width === 0 || height === 0) && pointerEvents === 'none'; + }) ? void 0 : false; + } + var focusable_disabled_evaluate_default = focusableDisabledEvaluate; + function focusableContentEvaluate(node, options, virtualNode) { + var tabbableElements = virtualNode.tabbableElements; + if (!tabbableElements) { + return false; + } + var tabbableContentElements = tabbableElements.filter(function(el) { + return el !== virtualNode; + }); + return tabbableContentElements.length > 0; + } + var focusable_content_evaluate_default = focusableContentEvaluate; + function accesskeysEvaluate(node, options, vNode) { + if (!_isHiddenForEveryone(vNode)) { + this.data(vNode.attr('accesskey')); + this.relatedNodes([ node ]); + } + return true; + } + var accesskeys_evaluate_default = accesskeysEvaluate; + function accesskeysAfter(results) { + var seen = {}; + return results.filter(function(r) { + if (!r.data) { + return false; + } + var key = r.data.toUpperCase(); + if (!seen[key]) { + seen[key] = r; + r.relatedNodes = []; + return true; + } + seen[key].relatedNodes.push(r.relatedNodes[0]); + return false; + }).map(function(r) { + r.result = !!r.relatedNodes.length; + return r; + }); + } + var accesskeys_after_default = accesskeysAfter; + function pageNoDuplicateEvaluate(node, options, virtualNode) { + if (!options || !options.selector || typeof options.selector !== 'string') { + throw new TypeError('page-no-duplicate requires options.selector to be a string'); + } + var key = 'page-no-duplicate;' + options.selector; + if (cache_default.get(key)) { + this.data('ignored'); + return; + } + cache_default.set(key, true); + var elms = query_selector_all_filter_default(axe._tree[0], options.selector, function(elm) { + return _isVisibleToScreenReaders(elm); + }); + if (typeof options.nativeScopeFilter === 'string') { + elms = elms.filter(function(elm) { + return elm.actualNode.hasAttribute('role') || !find_up_virtual_default(elm, options.nativeScopeFilter); + }); + } + if (typeof options.role === 'string') { + elms = elms.filter(function(elm) { + return get_role_default(elm) === options.role; + }); + } + this.relatedNodes(elms.filter(function(elm) { + return elm !== virtualNode; + }).map(function(elm) { + return elm.actualNode; + })); + return elms.length <= 1; + } + var page_no_duplicate_evaluate_default = pageNoDuplicateEvaluate; + function pageNoDuplicateAfter(results) { + return results.filter(function(checkResult) { + return checkResult.data !== 'ignored'; + }); + } + var page_no_duplicate_after_default = pageNoDuplicateAfter; + function matchesDefinitionEvaluate(_, options, virtualNode) { + return matches_default2(virtualNode, options.matcher); + } + var matches_definition_evaluate_default = matchesDefinitionEvaluate; + function hasTextContentEvaluate(node, options, virtualNode) { + try { + return sanitize_default(subtree_text_default(virtualNode)) !== ''; + } catch (_unused14) { + return void 0; + } + } + function hasDescendant(node, options, virtualNode) { + if (!options || !options.selector || typeof options.selector !== 'string') { + throw new TypeError('has-descendant requires options.selector to be a string'); + } + if (options.passForModal && is_modal_open_default()) { + return true; + } + var matchingElms = query_selector_all_filter_default(virtualNode, options.selector, function(vNode) { + return _isVisibleToScreenReaders(vNode); + }); + this.relatedNodes(matchingElms.map(function(vNode) { + return vNode.actualNode; + })); + return matchingElms.length > 0; + } + var has_descendant_evaluate_default = hasDescendant; + function pageHasElmAfter(results) { + var elmUsedAnywhere = results.some(function(frameResult) { + return frameResult.result === true; + }); + if (elmUsedAnywhere) { + results.forEach(function(result) { + result.result = true; + }); + } + return results; + } + var has_descendant_after_default = pageHasElmAfter; + function attrNonSpaceContentEvaluate(node) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var vNode = arguments.length > 2 ? arguments[2] : undefined; + if (!options.attribute || typeof options.attribute !== 'string') { + throw new TypeError('attr-non-space-content requires options.attribute to be a string'); + } + if (!vNode.hasAttr(options.attribute)) { + this.data({ + messageKey: 'noAttr' + }); + return false; + } + var attribute = vNode.attr(options.attribute); + var attributeIsEmpty = !sanitize_default(attribute); + if (attributeIsEmpty) { + this.data({ + messageKey: 'emptyAttr' + }); + return false; + } + return true; + } + var attr_non_space_content_evaluate_default = attrNonSpaceContentEvaluate; + function autocompleteValidEvaluate(_node, options, virtualNode) { + var autocomplete2 = virtualNode.attr('autocomplete') || ''; + return is_valid_autocomplete_default(autocomplete2, options); + } + var autocomplete_valid_evaluate_default = autocompleteValidEvaluate; + function autocompleteAppropriateEvaluate(node, options, virtualNode) { + if (virtualNode.props.nodeName !== 'input') { + return true; + } + var number = [ 'text', 'search', 'number', 'tel' ]; + var url = [ 'text', 'search', 'url' ]; + var allowedTypesMap = { + bday: [ 'text', 'search', 'date' ], + email: [ 'text', 'search', 'email' ], + username: [ 'text', 'search', 'email' ], + 'street-address': [ 'text' ], + tel: [ 'text', 'search', 'tel' ], + 'tel-country-code': [ 'text', 'search', 'tel' ], + 'tel-national': [ 'text', 'search', 'tel' ], + 'tel-area-code': [ 'text', 'search', 'tel' ], + 'tel-local': [ 'text', 'search', 'tel' ], + 'tel-local-prefix': [ 'text', 'search', 'tel' ], + 'tel-local-suffix': [ 'text', 'search', 'tel' ], + 'tel-extension': [ 'text', 'search', 'tel' ], + 'cc-number': number, + 'cc-exp': [ 'text', 'search', 'month', 'tel' ], + 'cc-exp-month': number, + 'cc-exp-year': number, + 'cc-csc': number, + 'transaction-amount': number, + 'bday-day': number, + 'bday-month': number, + 'bday-year': number, + 'new-password': [ 'text', 'search', 'password' ], + 'current-password': [ 'text', 'search', 'password' ], + url: url, + photo: url, + impp: url + }; + if (_typeof(options) === 'object') { + Object.keys(options).forEach(function(key) { + if (!allowedTypesMap[key]) { + allowedTypesMap[key] = []; + } + allowedTypesMap[key] = allowedTypesMap[key].concat(options[key]); + }); + } + var autocompleteAttr = virtualNode.attr('autocomplete'); + var autocompleteTerms = autocompleteAttr.split(/\s+/g).map(function(term) { + return term.toLowerCase(); + }); + var purposeTerm = autocompleteTerms[autocompleteTerms.length - 1]; + if (_autocomplete.stateTerms.includes(purposeTerm)) { + return true; + } + var allowedTypes = allowedTypesMap[purposeTerm]; + var type2 = virtualNode.hasAttr('type') ? sanitize_default(virtualNode.attr('type')).toLowerCase() : 'text'; + type2 = valid_input_type_default().includes(type2) ? type2 : 'text'; + if (typeof allowedTypes === 'undefined') { + return type2 === 'text'; + } + return allowedTypes.includes(type2); + } + var autocomplete_appropriate_evaluate_default = autocompleteAppropriateEvaluate; + var blockLike2 = [ 'block', 'list-item', 'table', 'flex', 'grid', 'inline-block' ]; + function linkInTextBlockStyleEvaluate(node) { + if (isBlock2(node)) { + return false; + } + var parentBlock = get_composed_parent_default(node); + while (parentBlock && parentBlock.nodeType === 1 && !isBlock2(parentBlock)) { + parentBlock = get_composed_parent_default(parentBlock); + } + if (!parentBlock) { + return void 0; + } + this.relatedNodes([ parentBlock ]); + if (element_is_distinct_default(node, parentBlock)) { + return true; + } + if (hasPseudoContent(node)) { + this.data({ + messageKey: 'pseudoContent' + }); + return void 0; + } + return false; + } + function isBlock2(elm) { + var display2 = window.getComputedStyle(elm).getPropertyValue('display'); + return blockLike2.indexOf(display2) !== -1 || display2.substr(0, 6) === 'table-'; + } + function hasPseudoContent(node) { + for (var _i33 = 0, _arr3 = [ 'before', 'after' ]; _i33 < _arr3.length; _i33++) { + var pseudo = _arr3[_i33]; + var style = window.getComputedStyle(node, ':'.concat(pseudo)); + var content = style.getPropertyValue('content'); + if (content !== 'none') { + return true; + } + } + return false; + } + function getContrast2(color1, color2) { + var c1lum = color1.getRelativeLuminance(); + var c2lum = color2.getRelativeLuminance(); + return (Math.max(c1lum, c2lum) + .05) / (Math.min(c1lum, c2lum) + .05); + } + var blockLike3 = [ 'block', 'list-item', 'table', 'flex', 'grid', 'inline-block' ]; + function isBlock3(elm) { + var display2 = window.getComputedStyle(elm).getPropertyValue('display'); + return blockLike3.indexOf(display2) !== -1 || display2.substr(0, 6) === 'table-'; + } + function linkInTextBlockEvaluate(node, options) { + var requiredContrastRatio = options.requiredContrastRatio, allowSameColor = options.allowSameColor; + if (isBlock3(node)) { + return false; + } + var parentBlock = get_composed_parent_default(node); + while (parentBlock && parentBlock.nodeType === 1 && !isBlock3(parentBlock)) { + parentBlock = get_composed_parent_default(parentBlock); + } + if (!parentBlock) { + return void 0; + } + this.relatedNodes([ parentBlock ]); + var nodeColor = _getForegroundColor(node); + var parentColor = _getForegroundColor(parentBlock); + var nodeBackgroundColor = _getBackgroundColor2(node); + var parentBackgroundColor = _getBackgroundColor2(parentBlock); + var textContrast = nodeColor && parentColor ? getContrast2(nodeColor, parentColor) : void 0; + if (textContrast) { + textContrast = Math.floor(textContrast * 100) / 100; + } + if (textContrast && textContrast >= requiredContrastRatio) { + return true; + } + var backgroundContrast = nodeBackgroundColor && parentBackgroundColor ? getContrast2(nodeBackgroundColor, parentBackgroundColor) : void 0; + if (backgroundContrast) { + backgroundContrast = Math.floor(backgroundContrast * 100) / 100; + } + if (backgroundContrast && backgroundContrast >= requiredContrastRatio) { + return true; + } + if (!backgroundContrast) { + var _incomplete_data_defa; + var reason = (_incomplete_data_defa = incomplete_data_default.get('bgColor')) !== null && _incomplete_data_defa !== void 0 ? _incomplete_data_defa : 'bgContrast'; + this.data({ + messageKey: reason + }); + incomplete_data_default.clear(); + return void 0; + } + if (!textContrast) { + return void 0; + } + if (allowSameColor && textContrast === 1 && backgroundContrast === 1) { + return true; + } + if (textContrast === 1 && backgroundContrast > 1) { + this.data({ + messageKey: 'bgContrast', + contrastRatio: backgroundContrast, + requiredContrastRatio: requiredContrastRatio, + nodeBackgroundColor: nodeBackgroundColor ? nodeBackgroundColor.toHexString() : void 0, + parentBackgroundColor: parentBackgroundColor ? parentBackgroundColor.toHexString() : void 0 + }); + return false; + } + this.data({ + messageKey: 'fgContrast', + contrastRatio: textContrast, + requiredContrastRatio: requiredContrastRatio, + nodeColor: nodeColor ? nodeColor.toHexString() : void 0, + parentColor: parentColor ? parentColor.toHexString() : void 0 + }); + return false; + } + var link_in_text_block_evaluate_default = linkInTextBlockEvaluate; + function colorContrastEvaluate(node, options, virtualNode) { + var ignoreUnicode = options.ignoreUnicode, ignoreLength = options.ignoreLength, ignorePseudo = options.ignorePseudo, boldValue = options.boldValue, boldTextPt = options.boldTextPt, largeTextPt = options.largeTextPt, contrastRatio = options.contrastRatio, shadowOutlineEmMax = options.shadowOutlineEmMax, pseudoSizeThreshold = options.pseudoSizeThreshold; + if (!_isVisibleOnScreen(node)) { + this.data({ + messageKey: 'hidden' + }); + return true; + } + var visibleText = visible_virtual_default(virtualNode, false, true); + if (ignoreUnicode && textIsEmojis(visibleText)) { + this.data({ + messageKey: 'nonBmp' + }); + return void 0; + } + var nodeStyle = window.getComputedStyle(node); + var fontSize = parseFloat(nodeStyle.getPropertyValue('font-size')); + var fontWeight = nodeStyle.getPropertyValue('font-weight'); + var bold = parseFloat(fontWeight) >= boldValue || fontWeight === 'bold'; + var ptSize = Math.ceil(fontSize * 72) / 96; + var isSmallFont = bold && ptSize < boldTextPt || !bold && ptSize < largeTextPt; + var _ref134 = isSmallFont ? contrastRatio.normal : contrastRatio.large, expected = _ref134.expected, minThreshold = _ref134.minThreshold, maxThreshold = _ref134.maxThreshold; + var pseudoElm = findPseudoElement(virtualNode, { + ignorePseudo: ignorePseudo, + pseudoSizeThreshold: pseudoSizeThreshold + }); + if (pseudoElm) { + this.data({ + fontSize: ''.concat((fontSize * 72 / 96).toFixed(1), 'pt (').concat(fontSize, 'px)'), + fontWeight: bold ? 'bold' : 'normal', + messageKey: 'pseudoContent', + expectedContrastRatio: expected + ':1' + }); + this.relatedNodes(pseudoElm.actualNode); + return void 0; + } + var shadowColors = _getTextShadowColors(node, { + minRatio: .001, + maxRatio: shadowOutlineEmMax + }); + if (shadowColors === null) { + this.data({ + messageKey: 'complexTextShadows' + }); + return void 0; + } + var bgNodes = []; + var bgColor = _getBackgroundColor2(node, bgNodes, shadowOutlineEmMax); + var fgColor = _getForegroundColor(node, false, bgColor, options); + var contrast2 = null; + var contrastContributor = null; + var shadowColor = null; + if (shadowColors.length === 0) { + contrast2 = get_contrast_default(bgColor, fgColor); + } else if (fgColor && bgColor) { + shadowColor = [].concat(_toConsumableArray(shadowColors), [ bgColor ]).reduce(_flattenShadowColors); + var fgBgContrast = get_contrast_default(bgColor, fgColor); + var bgShContrast = get_contrast_default(bgColor, shadowColor); + var fgShContrast = get_contrast_default(shadowColor, fgColor); + contrast2 = Math.max(fgBgContrast, bgShContrast, fgShContrast); + if (contrast2 !== fgBgContrast) { + contrastContributor = bgShContrast > fgShContrast ? 'shadowOnBgColor' : 'fgOnShadowColor'; + } + } + var isValid = contrast2 > expected; + if (typeof minThreshold === 'number' && (typeof contrast2 !== 'number' || contrast2 < minThreshold) || typeof maxThreshold === 'number' && (typeof contrast2 !== 'number' || contrast2 > maxThreshold)) { + this.data({ + contrastRatio: contrast2 + }); + return true; + } + var truncatedResult = Math.floor(contrast2 * 100) / 100; + var missing; + var colorParse; + if (bgColor === null) { + if (incomplete_data_default.get('colorParse')) { + missing = 'colorParse'; + colorParse = incomplete_data_default.get('colorParse'); + } else { + missing = incomplete_data_default.get('bgColor'); + } + } else if (!isValid) { + missing = contrastContributor; + } + if (fgColor === null && incomplete_data_default.get('colorParse')) { + missing = 'colorParse'; + colorParse = incomplete_data_default.get('colorParse'); + } + var equalRatio = truncatedResult === 1; + var shortTextContent = visibleText.length === 1; + if (equalRatio) { + missing = incomplete_data_default.set('bgColor', 'equalRatio'); + } else if (!isValid && shortTextContent && !ignoreLength) { + missing = 'shortTextContent'; + } + this.data({ + fgColor: fgColor ? fgColor.toHexString() : void 0, + bgColor: bgColor ? bgColor.toHexString() : void 0, + contrastRatio: truncatedResult, + fontSize: ''.concat((fontSize * 72 / 96).toFixed(1), 'pt (').concat(fontSize, 'px)'), + fontWeight: bold ? 'bold' : 'normal', + messageKey: missing, + expectedContrastRatio: expected + ':1', + shadowColor: shadowColor ? shadowColor.toHexString() : void 0, + colorParse: colorParse + }); + if (fgColor === null || bgColor === null || equalRatio || shortTextContent && !ignoreLength && !isValid) { + missing = null; + incomplete_data_default.clear(); + this.relatedNodes(bgNodes); + return void 0; + } + if (!isValid) { + this.relatedNodes(bgNodes); + } + return isValid; + } + function findPseudoElement(vNode, _ref135) { + var _ref135$pseudoSizeThr = _ref135.pseudoSizeThreshold, pseudoSizeThreshold = _ref135$pseudoSizeThr === void 0 ? .25 : _ref135$pseudoSizeThr, _ref135$ignorePseudo = _ref135.ignorePseudo, ignorePseudo = _ref135$ignorePseudo === void 0 ? false : _ref135$ignorePseudo; + if (ignorePseudo) { + return; + } + var rect = vNode.boundingClientRect; + var minimumSize = rect.width * rect.height * pseudoSizeThreshold; + do { + var beforeSize = getPseudoElementArea(vNode.actualNode, ':before'); + var afterSize = getPseudoElementArea(vNode.actualNode, ':after'); + if (beforeSize + afterSize > minimumSize) { + return vNode; + } + } while (vNode = vNode.parent); + } + var getPseudoElementArea = memoize_default(function getPseudoElementArea2(node, pseudo) { + var style = window.getComputedStyle(node, pseudo); + var matchPseudoStyle = function matchPseudoStyle(prop, value) { + return style.getPropertyValue(prop) === value; + }; + if (matchPseudoStyle('content', 'none') || matchPseudoStyle('display', 'none') || matchPseudoStyle('visibility', 'hidden') || matchPseudoStyle('position', 'absolute') === false) { + return 0; + } + if (get_own_background_color_default(style).alpha === 0 && matchPseudoStyle('background-image', 'none')) { + return 0; + } + var pseudoWidth = parseUnit(style.getPropertyValue('width')); + var pseudoHeight = parseUnit(style.getPropertyValue('height')); + if (pseudoWidth.unit !== 'px' || pseudoHeight.unit !== 'px') { + return pseudoWidth.value === 0 || pseudoHeight.value === 0 ? 0 : Infinity; + } + return pseudoWidth.value * pseudoHeight.value; + }); + function textIsEmojis(visibleText) { + var options = { + nonBmp: true + }; + var hasUnicodeChars = has_unicode_default(visibleText, options); + var hasNonUnicodeChars = sanitize_default(remove_unicode_default(visibleText, options)) === ''; + return hasUnicodeChars && hasNonUnicodeChars; + } + function parseUnit(str) { + var unitRegex = /^([0-9.]+)([a-z]+)$/i; + var _ref136 = str.match(unitRegex) || [], _ref137 = _slicedToArray(_ref136, 3), _ref137$ = _ref137[1], value = _ref137$ === void 0 ? '' : _ref137$, _ref137$2 = _ref137[2], unit = _ref137$2 === void 0 ? '' : _ref137$2; + return { + value: parseFloat(value), + unit: unit.toLowerCase() + }; + } + var VALID_TAG_NAMES_FOR_SCROLLABLE_REGIONS = { + ARTICLE: true, + ASIDE: true, + NAV: true, + SECTION: true + }; + var VALID_ROLES_FOR_SCROLLABLE_REGIONS = { + alert: true, + alertdialog: true, + application: true, + article: true, + banner: false, + complementary: true, + contentinfo: true, + dialog: true, + form: true, + log: true, + main: true, + navigation: true, + region: true, + search: false, + status: true, + tabpanel: true + }; + function validScrollableTagName(node) { + var nodeName2 = node.nodeName.toUpperCase(); + return VALID_TAG_NAMES_FOR_SCROLLABLE_REGIONS[nodeName2] || false; + } + function validScrollableRole(node, options) { + var role = get_explicit_role_default(node); + if (!role) { + return false; + } + return VALID_ROLES_FOR_SCROLLABLE_REGIONS[role] || options.roles.includes(role) || false; + } + function validScrollableSemanticsEvaluate(node, options) { + return validScrollableRole(node, options) || validScrollableTagName(node); + } + var valid_scrollable_semantics_evaluate_default = validScrollableSemanticsEvaluate; + function unsupportedroleEvaluate(node, options, virtualNode) { + var role = get_role_default(virtualNode, { + dpub: true, + fallback: true + }); + var isUnsupported = is_unsupported_role_default(role); + if (isUnsupported) { + this.data(role); + } + return isUnsupported; + } + var unsupportedrole_evaluate_default = unsupportedroleEvaluate; + function noImplicitExplicitLabelEvaluate(node, options, virtualNode) { + var role = get_role_default(virtualNode, { + noImplicit: true + }); + this.data(role); + var label3; + var accText; + try { + label3 = sanitize_default(label_text_default(virtualNode)).toLowerCase(); + accText = sanitize_default(_accessibleTextVirtual(virtualNode)).toLowerCase(); + } catch (_unused15) { + return void 0; + } + if (!accText && !label3) { + return false; + } + if (!accText && label3) { + return void 0; + } + if (!accText.includes(label3)) { + return void 0; + } + return false; + } + var no_implicit_explicit_label_evaluate_default = noImplicitExplicitLabelEvaluate; + function isElementFocusableEvaluate(node, options, virtualNode) { + return _isFocusable(virtualNode); + } + var is_element_focusable_evaluate_default = isElementFocusableEvaluate; + function invalidroleEvaluate(node, options, virtualNode) { + var allRoles = token_list_default(virtualNode.attr('role')); + var allInvalid = allRoles.every(function(role) { + return !is_valid_role_default(role.toLowerCase(), { + allowAbstract: true + }); + }); + if (allInvalid) { + this.data(allRoles); + return true; + } + return false; + } + var invalidrole_evaluate_default = invalidroleEvaluate; + function hasWidgetRoleEvaluate(node, options, virtualNode) { + var role = get_explicit_role_default(virtualNode); + if (role === null) { + return false; + } + var roleType = get_role_type_default(role); + return roleType === 'widget' || roleType === 'composite'; + } + var has_widget_role_evaluate_default = hasWidgetRoleEvaluate; + function hasGlobalAriaAttributeEvaluate(node, options, virtualNode) { + var globalAttrs = get_global_aria_attrs_default().filter(function(attr) { + return virtualNode.hasAttr(attr); + }); + this.data(globalAttrs); + return globalAttrs.length > 0; + } + var has_global_aria_attribute_evaluate_default = hasGlobalAriaAttributeEvaluate; + function nonePresentationOnElementWithNoImplicitRole(virtualNode, explicitRoles) { + var hasImplicitRole = implicit_role_default(virtualNode); + return !hasImplicitRole && explicitRoles.length === 2 && explicitRoles.includes('none') && explicitRoles.includes('presentation'); + } + function fallbackroleEvaluate(node, options, virtualNode) { + var explicitRoles = token_list_default(virtualNode.attr('role')); + if (explicitRoles.length <= 1) { + return false; + } + return nonePresentationOnElementWithNoImplicitRole(virtualNode, explicitRoles) ? void 0 : true; + } + var fallbackrole_evaluate_default = fallbackroleEvaluate; + function deprecatedroleEvaluate(node, options, virtualNode) { + var role = get_role_default(virtualNode, { + dpub: true, + fallback: true + }); + var roleDefinition = standards_default.ariaRoles[role]; + if (!(roleDefinition !== null && roleDefinition !== void 0 && roleDefinition.deprecated)) { + return false; + } + this.data(role); + return true; + } + function brailleRoleDescriptionEquivalentEvaluate(node, options, virtualNode) { + var _virtualNode$attr; + var brailleRoleDesc = (_virtualNode$attr = virtualNode.attr('aria-brailleroledescription')) !== null && _virtualNode$attr !== void 0 ? _virtualNode$attr : ''; + if (sanitize_default(brailleRoleDesc) === '') { + return true; + } + var roleDesc = virtualNode.attr('aria-roledescription'); + if (typeof roleDesc !== 'string') { + this.data({ + messageKey: 'noRoleDescription' + }); + return false; + } + if (sanitize_default(roleDesc) === '') { + this.data({ + messageKey: 'emptyRoleDescription' + }); + return false; + } + return true; + } + function brailleLabelEquivalentEvaluate(node, options, virtualNode) { + var _virtualNode$attr2; + var brailleLabel = (_virtualNode$attr2 = virtualNode.attr('aria-braillelabel')) !== null && _virtualNode$attr2 !== void 0 ? _virtualNode$attr2 : ''; + if (!brailleLabel.trim()) { + return true; + } + try { + return sanitize_default(_accessibleTextVirtual(virtualNode)) !== ''; + } catch (_unused16) { + return void 0; + } + } + function ariaValidAttrValueEvaluate(node, options, virtualNode) { + options = Array.isArray(options.value) ? options.value : []; + var needsReview = ''; + var messageKey = ''; + var invalid = []; + var aria = /^aria-/; + var skipAttrs = [ 'aria-errormessage' ]; + var preChecks = { + 'aria-controls': function ariaControls() { + var hasPopup = [ 'false', null ].includes(virtualNode.attr('aria-haspopup')) === false; + if (hasPopup) { + needsReview = 'aria-controls="'.concat(virtualNode.attr('aria-controls'), '"'); + messageKey = 'controlsWithinPopup'; + } + return virtualNode.attr('aria-expanded') !== 'false' && virtualNode.attr('aria-selected') !== 'false' && hasPopup === false; + }, + 'aria-current': function ariaCurrent(validValue) { + if (!validValue) { + needsReview = 'aria-current="'.concat(virtualNode.attr('aria-current'), '"'); + messageKey = 'ariaCurrent'; + } + return; + }, + 'aria-owns': function ariaOwns() { + return virtualNode.attr('aria-expanded') !== 'false'; + }, + 'aria-describedby': function ariaDescribedby(validValue) { + if (!validValue) { + needsReview = 'aria-describedby="'.concat(virtualNode.attr('aria-describedby'), '"'); + messageKey = axe._tree && axe._tree[0]._hasShadowRoot ? 'noIdShadow' : 'noId'; + } + return; + }, + 'aria-labelledby': function ariaLabelledby(validValue) { + if (!validValue) { + needsReview = 'aria-labelledby="'.concat(virtualNode.attr('aria-labelledby'), '"'); + messageKey = axe._tree && axe._tree[0]._hasShadowRoot ? 'noIdShadow' : 'noId'; + } + } + }; + virtualNode.attrNames.forEach(function(attrName) { + if (skipAttrs.includes(attrName) || options.includes(attrName) || !aria.test(attrName)) { + return; + } + var validValue; + var attrValue = virtualNode.attr(attrName); + try { + validValue = validate_attr_value_default(virtualNode, attrName); + } catch (_unused17) { + needsReview = ''.concat(attrName, '="').concat(attrValue, '"'); + messageKey = 'idrefs'; + return; + } + if ((preChecks[attrName] ? preChecks[attrName](validValue) : true) && !validValue) { + if (attrValue === '' && !isStringType(attrName)) { + needsReview = attrName; + messageKey = 'empty'; + } else { + invalid.push(''.concat(attrName, '="').concat(attrValue, '"')); + } + } + }); + if (invalid.length) { + this.data(invalid); + return false; + } + if (needsReview) { + this.data({ + messageKey: messageKey, + needsReview: needsReview + }); + return void 0; + } + return true; + } + function isStringType(attrName) { + var _standards_default$ar; + return ((_standards_default$ar = standards_default.ariaAttrs[attrName]) === null || _standards_default$ar === void 0 ? void 0 : _standards_default$ar.type) === 'string'; + } + function ariaValidAttrEvaluate(node, options, virtualNode) { + options = Array.isArray(options.value) ? options.value : []; + var invalid = []; + var aria = /^aria-/; + virtualNode.attrNames.forEach(function(attr) { + if (options.indexOf(attr) === -1 && aria.test(attr) && !validate_attr_default(attr)) { + invalid.push(attr); + } + }); + if (invalid.length) { + this.data(invalid); + return false; + } + return true; + } + var aria_valid_attr_evaluate_default = ariaValidAttrEvaluate; + function ariaUnsupportedAttrEvaluate(node, options, virtualNode) { + var unsupportedAttrs = virtualNode.attrNames.filter(function(name) { + var attribute = standards_default.ariaAttrs[name]; + if (!validate_attr_default(name)) { + return false; + } + var unsupported = attribute.unsupported; + if (_typeof(unsupported) !== 'object') { + return !!unsupported; + } + return !matches_default2(node, unsupported.exceptions); + }); + if (unsupportedAttrs.length) { + this.data(unsupportedAttrs); + return true; + } + return false; + } + var aria_unsupported_attr_evaluate_default = ariaUnsupportedAttrEvaluate; + function ariaRoledescriptionEvaluate(node) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var role = get_role_default(virtualNode); + var supportedRoles = options.supportedRoles || []; + if (supportedRoles.includes(role)) { + return true; + } + if (role && role !== 'presentation' && role !== 'none') { + return void 0; + } + return false; + } + var aria_roledescription_evaluate_default = ariaRoledescriptionEvaluate; + function getMissingContext(virtualNode, ownGroupRoles, reqContext, includeElement) { + var explicitRole2 = get_explicit_role_default(virtualNode); + if (!reqContext) { + reqContext = required_context_default(explicitRole2); + } + if (!reqContext) { + return null; + } + var allowsGroup = reqContext.includes('group'); + var vNode = includeElement ? virtualNode : virtualNode.parent; + while (vNode) { + var role = get_role_default(vNode, { + noPresentational: true + }); + if (!role) { + vNode = vNode.parent; + } else if (role === 'group' && allowsGroup) { + if (ownGroupRoles.includes(explicitRole2)) { + reqContext.push(explicitRole2); + } + reqContext = reqContext.filter(function(r) { + return r !== 'group'; + }); + vNode = vNode.parent; + } else if (reqContext.includes(role)) { + return null; + } else { + return reqContext; + } + } + return reqContext; + } + function getAriaOwners(element) { + var owners = []; + var o = null; + while (element) { + if (element.getAttribute('id')) { + var _id7 = escape_selector_default(element.getAttribute('id')); + var doc = get_root_node_default2(element); + o = doc.querySelector('[aria-owns~='.concat(_id7, ']')); + if (o) { + owners.push(o); + } + } + element = element.parentElement; + } + return owners.length ? owners : null; + } + function ariaRequiredParentEvaluate(node, options, virtualNode) { + var ownGroupRoles = options && Array.isArray(options.ownGroupRoles) ? options.ownGroupRoles : []; + var missingParents = getMissingContext(virtualNode, ownGroupRoles); + if (!missingParents) { + return true; + } + var owners = getAriaOwners(node); + if (owners) { + for (var _i34 = 0, l = owners.length; _i34 < l; _i34++) { + missingParents = getMissingContext(get_node_from_tree_default(owners[_i34]), ownGroupRoles, missingParents, true); + if (!missingParents) { + return true; + } + } + } + this.data(missingParents); + return false; + } + var aria_required_parent_evaluate_default = ariaRequiredParentEvaluate; + function ariaRequiredChildrenEvaluate(node, options, virtualNode) { + var reviewEmpty = options && Array.isArray(options.reviewEmpty) ? options.reviewEmpty : []; + var explicitRole2 = get_explicit_role_default(virtualNode, { + dpub: true + }); + var required = required_owned_default(explicitRole2); + if (required === null) { + return true; + } + var ownedRoles = getOwnedRoles(virtualNode, required); + var unallowed = ownedRoles.filter(function(_ref138) { + var role = _ref138.role, vNode = _ref138.vNode; + return vNode.props.nodeType === 1 && !required.includes(role); + }); + if (unallowed.length) { + this.relatedNodes(unallowed.map(function(_ref139) { + var vNode = _ref139.vNode; + return vNode; + })); + var messageKey = virtualNode.attr('aria-busy') === 'true' ? 'aria-busy-fail' : 'unallowed'; + this.data({ + messageKey: messageKey, + values: unallowed.map(function(_ref140) { + var vNode = _ref140.vNode, attr = _ref140.attr; + return getUnallowedSelector(vNode, attr); + }).filter(function(selector, index, array) { + return array.indexOf(selector) === index; + }).join(', ') + }); + return false; + } + if (hasRequiredChildren(required, ownedRoles)) { + return true; + } + if (virtualNode.attr('aria-busy') === 'true') { + this.data({ + messageKey: 'aria-busy' + }); + return true; + } + this.data(required); + if (reviewEmpty.includes(explicitRole2) && !ownedRoles.some(isContent)) { + return void 0; + } + return false; + } + function getOwnedRoles(virtualNode, required) { + var vNode; + var ownedRoles = []; + var ownedVirtual = get_owned_virtual_default(virtualNode); + var _loop0 = function _loop0() { + if (vNode.props.nodeType === 3) { + ownedRoles.push({ + vNode: vNode, + role: null + }); + } + if (vNode.props.nodeType !== 1 || !_isVisibleToScreenReaders(vNode)) { + return 1; + } + var role = get_role_default(vNode, { + noPresentational: true + }); + var globalAriaAttr = getGlobalAriaAttr(vNode); + var hasGlobalAriaOrFocusable = !!globalAriaAttr || _isFocusable(vNode); + if (!role && !hasGlobalAriaOrFocusable || [ 'group', 'rowgroup' ].includes(role) && required.some(function(requiredRole) { + return requiredRole === role; + })) { + ownedVirtual.push.apply(ownedVirtual, _toConsumableArray(vNode.children)); + } else if (role || hasGlobalAriaOrFocusable) { + var attr = globalAriaAttr || 'tabindex'; + ownedRoles.push({ + role: role, + attr: attr, + vNode: vNode + }); + } + }; + while (vNode = ownedVirtual.shift()) { + if (_loop0()) { + continue; + } + } + return ownedRoles; + } + function hasRequiredChildren(required, ownedRoles) { + return ownedRoles.some(function(_ref141) { + var role = _ref141.role; + return role && required.includes(role); + }); + } + function getGlobalAriaAttr(vNode) { + return get_global_aria_attrs_default().find(function(attr) { + return vNode.hasAttr(attr); + }); + } + function getUnallowedSelector(vNode, attr) { + var _vNode$props = vNode.props, nodeName2 = _vNode$props.nodeName, nodeType = _vNode$props.nodeType; + if (nodeType === 3) { + return '#text'; + } + var role = get_explicit_role_default(vNode, { + dpub: true + }); + if (role) { + return '[role='.concat(role, ']'); + } + if (attr) { + return nodeName2 + '['.concat(attr, ']'); + } + return nodeName2; + } + function isContent(_ref142) { + var vNode = _ref142.vNode; + if (vNode.props.nodeType === 3) { + return vNode.props.nodeValue.trim().length > 0; + } + return has_content_virtual_default(vNode, false, true); + } + function ariaRequiredAttrEvaluate(node) { + var _virtualNode$attr3; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var role = get_explicit_role_default(virtualNode); + var attrs = virtualNode.attrNames; + var requiredAttrs = required_attr_default(role); + if (Array.isArray(options[role])) { + requiredAttrs = unique_array_default(options[role], requiredAttrs); + } + if (!role || !attrs.length || !requiredAttrs.length) { + return true; + } + if (isStaticSeparator(virtualNode, role) || isClosedCombobox(virtualNode, role)) { + return true; + } + if (role === 'slider' && (_virtualNode$attr3 = virtualNode.attr('aria-valuetext')) !== null && _virtualNode$attr3 !== void 0 && _virtualNode$attr3.trim()) { + return true; + } + var elmSpec = get_element_spec_default(virtualNode); + var missingAttrs = requiredAttrs.filter(function(requiredAttr2) { + return !virtualNode.attr(requiredAttr2) && !hasImplicitAttr(elmSpec, requiredAttr2); + }); + if (missingAttrs.length) { + this.data(missingAttrs); + return false; + } + return true; + } + function isStaticSeparator(vNode, role) { + return role === 'separator' && !_isFocusable(vNode); + } + function hasImplicitAttr(elmSpec, attr) { + var _elmSpec$implicitAttr; + return ((_elmSpec$implicitAttr = elmSpec.implicitAttrs) === null || _elmSpec$implicitAttr === void 0 ? void 0 : _elmSpec$implicitAttr[attr]) !== void 0; + } + function isClosedCombobox(vNode, role) { + return role === 'combobox' && vNode.attr('aria-expanded') === 'false'; + } + function ariaProhibitedAttrEvaluate(node) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var elementsAllowedAriaLabel = (options === null || options === void 0 ? void 0 : options.elementsAllowedAriaLabel) || []; + var nodeName2 = virtualNode.props.nodeName; + var role = get_role_default(virtualNode, { + chromium: true, + fallback: true + }); + var prohibitedList = listProhibitedAttrs(virtualNode, role, nodeName2, elementsAllowedAriaLabel); + var prohibited = prohibitedList.filter(function(attrName) { + if (!virtualNode.attrNames.includes(attrName)) { + return false; + } + return sanitize_default(virtualNode.attr(attrName)) !== ''; + }); + if (prohibited.length === 0) { + return false; + } + var messageKey = role !== null ? 'hasRole' : 'noRole'; + messageKey += prohibited.length > 1 ? 'Plural' : 'Singular'; + this.data({ + role: role, + nodeName: nodeName2, + messageKey: messageKey, + prohibited: prohibited + }); + var textContent = subtree_text_default(virtualNode, { + subtreeDescendant: true + }); + if (sanitize_default(textContent) !== '') { + return void 0; + } + return true; + } + function listProhibitedAttrs(vNode, role, nodeName2, elementsAllowedAriaLabel) { + var roleSpec = standards_default.ariaRoles[role]; + if (roleSpec) { + return roleSpec.prohibitedAttrs || []; + } + if (!!role || elementsAllowedAriaLabel.includes(nodeName2) || getClosestAncestorRoleType(vNode) === 'widget') { + return []; + } + return [ 'aria-label', 'aria-labelledby' ]; + } + var getClosestAncestorRoleType = memoize_default(function getClosestAncestorRoleTypeMemoized(vNode) { + if (!vNode) { + return; + } + var role = get_role_default(vNode, { + noPresentational: true, + chromium: true + }); + if (role) { + return get_role_type_default(role); + } + return getClosestAncestorRoleType(vNode.parent); + }); + function ariaLevelEvaluate(node, options, virtualNode) { + var ariaHeadingLevel = virtualNode.attr('aria-level'); + var ariaLevel = parseInt(ariaHeadingLevel, 10); + if (ariaLevel > 6) { + return void 0; + } + return true; + } + var aria_level_evaluate_default = ariaLevelEvaluate; + function ariaHiddenBodyEvaluate(node, options, virtualNode) { + return virtualNode.attr('aria-hidden') !== 'true'; + } + var aria_hidden_body_evaluate_default = ariaHiddenBodyEvaluate; + function ariaErrormessageEvaluate(node, options, virtualNode) { + options = Array.isArray(options) ? options : []; + var errorMessageAttr = virtualNode.attr('aria-errormessage'); + var hasAttr = virtualNode.hasAttr('aria-errormessage'); + var invaid = virtualNode.attr('aria-invalid'); + var hasInvallid = virtualNode.hasAttr('aria-invalid'); + if (!hasInvallid || invaid === 'false') { + return true; + } + function validateAttrValue2(attr) { + if (attr.trim() === '') { + return standards_default.ariaAttrs['aria-errormessage'].allowEmpty; + } + var errormessageTokens = token_list_default(attr); + if (errormessageTokens.length > 1) { + this.data({ + messageKey: 'unsupported', + values: errormessageTokens + }); + return false; + } + var idref; + try { + idref = attr && idrefs_default(virtualNode, 'aria-errormessage')[0]; + } catch (_unused18) { + this.data({ + messageKey: 'idrefs', + values: errormessageTokens + }); + return void 0; + } + if (idref) { + if (!_isVisibleToScreenReaders(idref)) { + this.data({ + messageKey: 'hidden', + values: errormessageTokens + }); + return false; + } + var describedbyTokens = token_list_default(virtualNode.attr('aria-describedby')); + return get_explicit_role_default(idref) === 'alert' || idref.getAttribute('aria-live') === 'assertive' || idref.getAttribute('aria-live') === 'polite' || errormessageTokens.some(function(token) { + return describedbyTokens.includes(token); + }); + } + return; + } + if (options.indexOf(errorMessageAttr) === -1 && hasAttr) { + this.data(token_list_default(errorMessageAttr)); + return validateAttrValue2.call(this, errorMessageAttr); + } + return true; + } + function ariaConditionalRowAttr(node) { + var _invalidTableRowAttrs, _invalidTableRowAttrs2; + var _ref143 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, invalidTableRowAttrs = _ref143.invalidTableRowAttrs; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var invalidAttrs = (_invalidTableRowAttrs = invalidTableRowAttrs === null || invalidTableRowAttrs === void 0 || (_invalidTableRowAttrs2 = invalidTableRowAttrs.filter) === null || _invalidTableRowAttrs2 === void 0 ? void 0 : _invalidTableRowAttrs2.call(invalidTableRowAttrs, function(invalidAttr) { + return virtualNode.hasAttr(invalidAttr); + })) !== null && _invalidTableRowAttrs !== void 0 ? _invalidTableRowAttrs : []; + if (invalidAttrs.length === 0) { + return true; + } + var owner = getRowOwner(virtualNode); + var ownerRole = owner && get_role_default(owner); + if (!ownerRole || ownerRole === 'treegrid') { + return true; + } + var messageKey = 'row'.concat(invalidAttrs.length > 1 ? 'Plural' : 'Singular'); + this.data({ + messageKey: messageKey, + invalidAttrs: invalidAttrs, + ownerRole: ownerRole + }); + return false; + } + function getRowOwner(virtualNode) { + if (!virtualNode.parent) { + return; + } + var rowOwnerQuery = 'table:not([role]), [role~="treegrid"], [role~="table"], [role~="grid"]'; + return closest_default(virtualNode, rowOwnerQuery); + } + function ariaConditionalCheckboxAttr(node, options, virtualNode) { + var _virtualNode$props = virtualNode.props, nodeName2 = _virtualNode$props.nodeName, type2 = _virtualNode$props.type; + var ariaChecked = normalizeAriaChecked(virtualNode.attr('aria-checked')); + if (nodeName2 !== 'input' || type2 !== 'checkbox' || !ariaChecked) { + return true; + } + var checkState = getCheckState(virtualNode); + if (ariaChecked === checkState) { + return true; + } + this.data({ + messageKey: 'checkbox', + checkState: checkState + }); + return false; + } + function getCheckState(vNode) { + if (vNode.props.indeterminate) { + return 'mixed'; + } + return vNode.props.checked ? 'true' : 'false'; + } + function normalizeAriaChecked(ariaCheckedVal) { + if (!ariaCheckedVal) { + return ''; + } + ariaCheckedVal = ariaCheckedVal.toLowerCase(); + if ([ 'mixed', 'true' ].includes(ariaCheckedVal)) { + return ariaCheckedVal; + } + return 'false'; + } + var conditionalRoleMap = { + row: ariaConditionalRowAttr, + checkbox: ariaConditionalCheckboxAttr + }; + function ariaConditionalAttrEvaluate(node, options, virtualNode) { + var role = get_role_default(virtualNode); + if (!conditionalRoleMap[role]) { + return true; + } + return conditionalRoleMap[role].call(this, node, options, virtualNode); + } + function ariaBusyEvaluate(node, options, virtualNode) { + return virtualNode.attr('aria-busy') === 'true'; + } + function ariaAllowedRoleEvaluate(node) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var virtualNode = arguments.length > 2 ? arguments[2] : undefined; + var _options$allowImplici = options.allowImplicit, allowImplicit = _options$allowImplici === void 0 ? true : _options$allowImplici, _options$ignoredTags = options.ignoredTags, ignoredTags = _options$ignoredTags === void 0 ? [] : _options$ignoredTags; + var nodeName2 = virtualNode.props.nodeName; + if (ignoredTags.map(function(tag) { + return tag.toLowerCase(); + }).includes(nodeName2)) { + return true; + } + var unallowedRoles = get_element_unallowed_roles_default(virtualNode, allowImplicit); + if (unallowedRoles.length) { + this.data(unallowedRoles); + if (!_isVisibleToScreenReaders(virtualNode)) { + return void 0; + } + return false; + } + return true; + } + var aria_allowed_role_evaluate_default = ariaAllowedRoleEvaluate; + function ariaAllowedAttrEvaluate(node, options, virtualNode) { + var invalid = []; + var role = get_role_default(virtualNode); + var allowed = allowed_attr_default(role); + if (Array.isArray(options[role])) { + allowed = unique_array_default(options[role].concat(allowed)); + } + var _iterator22 = _createForOfIteratorHelper(virtualNode.attrNames), _step22; + try { + for (_iterator22.s(); !(_step22 = _iterator22.n()).done; ) { + var attrName = _step22.value; + if (validate_attr_default(attrName) && !allowed.includes(attrName) && !ignoredAttrs(attrName, virtualNode.attr(attrName), virtualNode)) { + invalid.push(attrName); + } + } + } catch (err) { + _iterator22.e(err); + } finally { + _iterator22.f(); + } + if (!invalid.length) { + return true; + } + this.data(invalid.map(function(attrName) { + return attrName + '="' + virtualNode.attr(attrName) + '"'; + })); + if (!role && !is_html_element_default(virtualNode) && !_isFocusable(virtualNode)) { + return void 0; + } + return false; + } + function ignoredAttrs(attrName, attrValue, vNode) { + if (attrName === 'aria-required' && attrValue === 'false') { + return true; + } + if (attrName === 'aria-multiline' && attrValue === 'false' && vNode.hasAttr('contenteditable')) { + return true; + } + return false; + } + function ariaAllowedAttrElmEvaluate(node, options, virtualNode) { + var elmSpec = get_element_spec_default(virtualNode); + if (!elmSpec.allowedAriaAttrs) { + return true; + } + var explicitRole2 = get_explicit_role_default(virtualNode); + if (explicitRole2) { + return true; + } + var allowedAriaAttrs = elmSpec.allowedAriaAttrs; + var globalAriaAttrs = get_global_aria_attrs_default(); + var invalid = []; + var _iterator23 = _createForOfIteratorHelper(virtualNode.attrNames), _step23; + try { + for (_iterator23.s(); !(_step23 = _iterator23.n()).done; ) { + var attrName = _step23.value; + if (globalAriaAttrs.includes(attrName) && !allowedAriaAttrs.includes(attrName)) { + invalid.push(attrName); + } + } + } catch (err) { + _iterator23.e(err); + } finally { + _iterator23.f(); + } + if (!invalid.length) { + return true; + } + var messageKey = invalid.length > 1 ? 'plural' : 'singular'; + this.data({ + messageKey: messageKey, + nodeName: virtualNode.props.nodeName, + values: invalid.map(function(attrName) { + return attrName + '="' + virtualNode.attr(attrName) + '"'; + }).join(', ') + }); + return false; + } + function abstractroleEvaluate(node, options, virtualNode) { + var abstractRoles = token_list_default(virtualNode.attr('role')).filter(function(role) { + return get_role_type_default(role) === 'abstract'; + }); + if (abstractRoles.length > 0) { + this.data(abstractRoles); + return true; + } + return false; + } + var abstractrole_evaluate_default = abstractroleEvaluate; + function xmlLangMismatchMatches(node) { + var primaryLangValue = get_base_lang_default(node.getAttribute('lang')); + var primaryXmlLangValue = get_base_lang_default(node.getAttribute('xml:lang')); + return valid_langs_default(primaryLangValue) && valid_langs_default(primaryXmlLangValue); + } + var xml_lang_mismatch_matches_default = xmlLangMismatchMatches; + function windowIsTopMatches(node) { + return node.ownerDocument.defaultView.self === node.ownerDocument.defaultView.top; + } + var window_is_top_matches_default = windowIsTopMatches; + function svgNamespaceMatches(node, virtualNode) { + try { + var nodeName2 = virtualNode.props.nodeName; + if (nodeName2 === 'svg') { + return true; + } + return !!closest_default(virtualNode, 'svg'); + } catch (_unused19) { + return false; + } + } + var svg_namespace_matches_default = svgNamespaceMatches; + function widgetNotInline(node, vNode) { + return matchesFns.every(function(fn) { + return fn(node, vNode); + }); + } + var matchesFns = [ function(node, vNode) { + return isWidgetType(vNode); + }, function(node, vNode) { + return isNotAreaElement(vNode); + }, function(node, vNode) { + return !svg_namespace_matches_default(node, vNode); + }, function(node, vNode) { + return _isFocusable(vNode); + }, function(node, vNode) { + return _isInTabOrder(vNode) || !hasWidgetAncestorInTabOrder(vNode); + }, function(node) { + return !is_in_text_block_default(node, { + noLengthCompare: true, + includeInlineBlock: true + }); + } ]; + function isWidgetType(vNode) { + return get_role_type_default(vNode) === 'widget'; + } + function isNotAreaElement(vNode) { + return vNode.props.nodeName !== 'area'; + } + var hasWidgetAncestorInTabOrder = memoize_default(function hasWidgetAncestorInTabOrderMemoized(vNode) { + if (!(vNode !== null && vNode !== void 0 && vNode.parent)) { + return false; + } + if (isWidgetType(vNode.parent) && _isInTabOrder(vNode.parent)) { + return true; + } + return hasWidgetAncestorInTabOrderMemoized(vNode.parent); + }); + function tableOrGridRoleMatches(_, vNode) { + var role = get_role_default(vNode); + return [ 'treegrid', 'grid', 'table' ].includes(role); + } + function summaryIsInteractiveMatches(_, virtualNode) { + var parent = virtualNode.parent; + if (parent.props.nodeName !== 'details' || isSlottedElm(virtualNode)) { + return false; + } + var firstSummary = parent.children.find(function(child) { + return child.props.nodeName === 'summary'; + }); + if (firstSummary !== virtualNode) { + return false; + } + return true; + } + function isSlottedElm(vNode) { + var _vNode$actualNode; + var domParent = (_vNode$actualNode = vNode.actualNode) === null || _vNode$actualNode === void 0 ? void 0 : _vNode$actualNode.parentElement; + return domParent && domParent !== vNode.parent.actualNode; + } + function skipLinkMatches(node) { + return _isSkipLink(node) && is_offscreen_default(node); + } + var skip_link_matches_default = skipLinkMatches; + function scrollableRegionFocusableMatches(node, virtualNode) { + return get_scroll_default(node, 13) !== void 0 && _isComboboxPopup(virtualNode) === false && isNonEmptyElementOutsideViewableRect(virtualNode); + } + function isNonEmptyElementOutsideViewableRect(vNode) { + var boundingRect = vNode.boundingClientRect; + return query_selector_all_default(vNode, '*').some(function(elm) { + if (!has_content_virtual_default(elm, true, true)) { + return false; + } + var rects = []; + if (hasChildTextNodes(elm)) { + var _rects; + (_rects = rects).push.apply(_rects, _toConsumableArray(getContentRects2(elm))); + } else { + rects = [ elm.boundingClientRect ]; + } + return rects.some(function(rect) { + return rect.left < boundingRect.left || rect.right > boundingRect.right || rect.top < boundingRect.top || rect.bottom > boundingRect.bottom; + }); + }); + } + function getContentRects2(vNode) { + var range2 = document.createRange(); + range2.selectNodeContents(vNode.actualNode); + return Array.from(range2.getClientRects()); + } + function presentationRoleConflictMatches(node, virtualNode) { + return implicit_role_default(virtualNode, { + chromiumRoles: true + }) !== null; + } + var presentation_role_conflict_matches_default = presentationRoleConflictMatches; + function pAsHeadingMatches(node) { + var children = Array.from(node.parentNode.childNodes); + var nodeText = node.textContent.trim(); + var isSentence = /[.!?:;](?![.!?:;])/g; + if (nodeText.length === 0 || (nodeText.match(isSentence) || []).length >= 2) { + return false; + } + var siblingsAfter = children.slice(children.indexOf(node) + 1).filter(function(elm) { + return elm.nodeName.toUpperCase() === 'P' && elm.textContent.trim() !== ''; + }); + return siblingsAfter.length !== 0; + } + var p_as_heading_matches_default = pAsHeadingMatches; + function noExplicitNameRequired(node, virtualNode) { + var role = get_explicit_role_default(virtualNode); + if (!role || [ 'none', 'presentation' ].includes(role)) { + return true; + } + var _ref144 = aria_roles_default[role] || {}, accessibleNameRequired = _ref144.accessibleNameRequired; + if (accessibleNameRequired || _isFocusable(virtualNode)) { + return true; + } + return false; + } + var no_explicit_name_required_matches_default = noExplicitNameRequired; + var object_is_loaded_matches_default = function object_is_loaded_matches_default(node, vNode) { + return [ no_explicit_name_required_matches_default, objectHasLoaded ].every(function(fn) { + return fn(node, vNode); + }); + }; + function objectHasLoaded(node) { + var _node$ownerDocument; + if (!(node !== null && node !== void 0 && (_node$ownerDocument = node.ownerDocument) !== null && _node$ownerDocument !== void 0 && _node$ownerDocument.createRange)) { + return true; + } + var range2 = node.ownerDocument.createRange(); + range2.setStart(node, 0); + range2.setEnd(node, node.childNodes.length); + return range2.getClientRects().length === 0; + } + function notHtmlMatches(node, virtualNode) { + return virtualNode.props.nodeName !== 'html'; + } + var not_html_matches_default = notHtmlMatches; + function noRoleMatches(node, vNode) { + return !vNode.attr('role'); + } + var no_role_matches_default = noRoleMatches; + function noNegativeTabindexMatches(node, virtualNode) { + var tabindex = parse_tabindex_default(virtualNode.attr('tabindex')); + return tabindex === null || tabindex >= 0; + } + var no_negative_tabindex_matches_default = noNegativeTabindexMatches; + function noNamingMethodMatches(node, virtualNode) { + var _get_element_spec_def3 = get_element_spec_default(virtualNode), namingMethods = _get_element_spec_def3.namingMethods; + if (namingMethods && namingMethods.length !== 0) { + return false; + } + if (get_explicit_role_default(virtualNode) === 'combobox' && query_selector_all_default(virtualNode, 'input:not([type="hidden"])').length) { + return false; + } + if (_isComboboxPopup(virtualNode, { + popupRoles: [ 'listbox' ] + })) { + return false; + } + return true; + } + var no_naming_method_matches_default = noNamingMethodMatches; + function noEmptyRoleMatches(node, virtualNode) { + if (!virtualNode.hasAttr('role')) { + return false; + } + if (!virtualNode.attr('role').trim()) { + return false; + } + return true; + } + var no_empty_role_matches_default = noEmptyRoleMatches; + function noAutoplayAudioMatches(node) { + if (!node.currentSrc) { + return false; + } + if (node.hasAttribute('paused') || node.hasAttribute('muted')) { + return false; + } + return true; + } + var no_autoplay_audio_matches_default = noAutoplayAudioMatches; + function nestedInteractiveMatches(node, virtualNode) { + var role = get_role_default(virtualNode); + if (!role) { + return false; + } + return !!standards_default.ariaRoles[role].childrenPresentational; + } + var nested_interactive_matches_default = nestedInteractiveMatches; + function linkInTextBlockMatches(node) { + var text = sanitize_default(node.innerText); + var role = get_explicit_role_default(node); + if (role && role !== 'link') { + return false; + } + if (!text) { + return false; + } + if (!_isVisibleOnScreen(node)) { + return false; + } + return is_in_text_block_default(node); + } + var link_in_text_block_matches_default = linkInTextBlockMatches; + function dataTableMatches(node) { + return !is_data_table_default(node) && !_isFocusable(node); + } + var layout_table_matches_default = dataTableMatches; + function landmarkUniqueMatches(node, virtualNode) { + return isLandmarkVirtual(virtualNode) && _isVisibleToScreenReaders(virtualNode); + } + function isLandmarkVirtual(vNode) { + var landmarkRoles2 = get_aria_roles_by_type_default('landmark'); + var role = get_role_default(vNode); + if (!role) { + return false; + } + var nodeName2 = vNode.props.nodeName; + if (nodeName2 === 'section' || nodeName2 === 'form') { + var accessibleText2 = _accessibleTextVirtual(vNode); + return !!accessibleText2; + } + return landmarkRoles2.indexOf(role) >= 0 || role === 'region'; + } + function landmarkHasBodyContextMatches(node, virtualNode) { + var nativeScopeFilter = 'article, aside, main, nav, section'; + return node.hasAttribute('role') || !find_up_virtual_default(virtualNode, nativeScopeFilter); + } + var landmark_has_body_context_matches_default = landmarkHasBodyContextMatches; + function labelMatches(node, virtualNode) { + if (virtualNode.props.nodeName !== 'input' || virtualNode.hasAttr('type') === false) { + return true; + } + var type2 = virtualNode.attr('type').toLowerCase(); + return [ 'hidden', 'image', 'button', 'submit', 'reset' ].includes(type2) === false; + } + var label_matches_default = labelMatches; + function labelContentNameMismatchMatches(node, virtualNode) { + var role = get_role_default(node); + if (!role) { + return false; + } + var widgetRoles = get_aria_roles_by_type_default('widget'); + var isWidgetType2 = widgetRoles.includes(role); + if (!isWidgetType2) { + return false; + } + var rolesWithNameFromContents = get_aria_roles_supporting_name_from_content_default(); + if (!rolesWithNameFromContents.includes(role)) { + return false; + } + if (!sanitize_default(_arialabelText(virtualNode)) && !sanitize_default(arialabelledby_text_default(node))) { + return false; + } + if (!sanitize_default(visible_virtual_default(virtualNode))) { + return false; + } + return true; + } + var label_content_name_mismatch_matches_default = labelContentNameMismatchMatches; + function isVisibleOnScreenMatches(node, virtualNode) { + return _isVisibleOnScreen(virtualNode); + } + function hasVisibleTextMatches(node) { + return _isVisibleOnScreen(node); + } + function isInitiatorMatches(node, virtualNode, context) { + return context.initiator; + } + var is_initiator_matches_default = isInitiatorMatches; + function insertedIntoFocusOrderMatches(node) { + return inserted_into_focus_order_default(node); + } + var inserted_into_focus_order_matches_default = insertedIntoFocusOrderMatches; + function identicalLinksSamePurposeMatches(node, virtualNode) { + var hasAccName = !!_accessibleTextVirtual(virtualNode); + if (!hasAccName) { + return false; + } + var role = get_role_default(node); + if (role && role !== 'link') { + return false; + } + return true; + } + var identical_links_same_purpose_matches_default = identicalLinksSamePurposeMatches; + function htmlNamespaceMatches(node, virtualNode) { + return !svg_namespace_matches_default(node, virtualNode); + } + var html_namespace_matches_default = htmlNamespaceMatches; + function headingMatches(node, virtualNode) { + return get_role_default(virtualNode) === 'heading'; + } + function hasImplicitChromiumRoleMatches(node, virtualNode) { + return implicit_role_default(virtualNode, { + chromium: true + }) !== null; + } + var has_implicit_chromium_role_matches_default = hasImplicitChromiumRoleMatches; + function frameTitleHasTextMatches(node) { + var title = node.getAttribute('title'); + return !!sanitize_default(title); + } + var frame_title_has_text_matches_default = frameTitleHasTextMatches; + function frameFocusableContentMatches(node, virtualNode, context) { + var _context$size, _context$size2; + return !context.initiator && !context.focusable && ((_context$size = context.size) === null || _context$size === void 0 ? void 0 : _context$size.width) * ((_context$size2 = context.size) === null || _context$size2 === void 0 ? void 0 : _context$size2.height) > 1; + } + var frame_focusable_content_matches_default = frameFocusableContentMatches; + function duplicateIdMiscMatches(node) { + var id = node.getAttribute('id').trim(); + var idSelector = '*[id="'.concat(escape_selector_default(id), '"]'); + var idMatchingElms = Array.from(get_root_node_default2(node).querySelectorAll(idSelector)); + return !is_accessible_ref_default(node) && idMatchingElms.every(function(elm) { + return !_isFocusable(elm); + }); + } + var duplicate_id_misc_matches_default = duplicateIdMiscMatches; + function duplicateIdAriaMatches(node) { + return is_accessible_ref_default(node); + } + var duplicate_id_aria_matches_default = duplicateIdAriaMatches; + function duplicateIdActiveMatches(node) { + var id = node.getAttribute('id').trim(); + var idSelector = '*[id="'.concat(escape_selector_default(id), '"]'); + var idMatchingElms = Array.from(get_root_node_default2(node).querySelectorAll(idSelector)); + return !is_accessible_ref_default(node) && idMatchingElms.some(_isFocusable); + } + var duplicate_id_active_matches_default = duplicateIdActiveMatches; + function dataTableMatches2(node) { + return is_data_table_default(node); + } + var data_table_matches_default = dataTableMatches2; + function dataTableLargeMatches(node) { + if (is_data_table_default(node)) { + var tableArray = to_grid_default(node); + return tableArray.length >= 3 && tableArray[0].length >= 3 && tableArray[1].length >= 3 && tableArray[2].length >= 3; + } + return false; + } + var data_table_large_matches_default = dataTableLargeMatches; + function colorContrastMatches(node, virtualNode) { + var _virtualNode$props2 = virtualNode.props, nodeName2 = _virtualNode$props2.nodeName, inputType = _virtualNode$props2.type; + if (nodeName2 === 'option') { + return false; + } + if (nodeName2 === 'select' && !node.options.length) { + return false; + } + var nonTextInput = [ 'hidden', 'range', 'color', 'checkbox', 'radio', 'image' ]; + if (nodeName2 === 'input' && nonTextInput.includes(inputType)) { + return false; + } + if (is_disabled_default(virtualNode) || _isInert(virtualNode)) { + return false; + } + var formElements = [ 'input', 'select', 'textarea' ]; + if (formElements.includes(nodeName2)) { + var style = window.getComputedStyle(node); + var textIndent = parseInt(style.getPropertyValue('text-indent'), 10); + if (textIndent) { + var rect = node.getBoundingClientRect(); + rect = { + top: rect.top, + bottom: rect.bottom, + left: rect.left + textIndent, + right: rect.right + textIndent + }; + if (!visually_overlaps_default(rect, node)) { + return false; + } + } + return true; + } + var nodeParentLabel = find_up_virtual_default(virtualNode, 'label'); + if (nodeName2 === 'label' || nodeParentLabel) { + var labelNode = nodeParentLabel || node; + var labelVirtual3 = nodeParentLabel ? get_node_from_tree_default(nodeParentLabel) : virtualNode; + if (labelNode.htmlFor) { + var doc = get_root_node_default2(labelNode); + var explicitControl = doc.getElementById(labelNode.htmlFor); + var explicitControlVirtual = explicitControl && get_node_from_tree_default(explicitControl); + if (explicitControlVirtual && is_disabled_default(explicitControlVirtual)) { + return false; + } + } + var query = 'input:not([type="hidden"],[type="image"],[type="button"],[type="submit"],[type="reset"]), select, textarea'; + var implicitControl = query_selector_all_default(labelVirtual3, query)[0]; + if (implicitControl && is_disabled_default(implicitControl)) { + return false; + } + } + var ariaLabelledbyControls = []; + var ancestorNode = virtualNode; + while (ancestorNode) { + if (ancestorNode.props.id) { + var virtualControls = get_accessible_refs_default(ancestorNode).filter(function(control) { + return token_list_default(control.getAttribute('aria-labelledby') || '').includes(ancestorNode.props.id); + }).map(function(control) { + return get_node_from_tree_default(control); + }); + ariaLabelledbyControls.push.apply(ariaLabelledbyControls, _toConsumableArray(virtualControls)); + } + ancestorNode = ancestorNode.parent; + } + if (ariaLabelledbyControls.length > 0 && ariaLabelledbyControls.every(is_disabled_default)) { + return false; + } + if (!hasRealTextChildren(virtualNode)) { + return false; + } + if (!parseFloat(virtualNode.getComputedStylePropertyValue('font-size'))) { + return false; + } + var range2 = document.createRange(); + var childNodes = virtualNode.children; + for (var index = 0; index < childNodes.length; index++) { + var child = childNodes[index]; + if (child.actualNode.nodeType === 3 && sanitize_default(child.actualNode.nodeValue) !== '') { + range2.selectNodeContents(child.actualNode); + } + } + var rects = Array.from(range2.getClientRects()); + var clippingAncestors = get_overflow_hidden_ancestors_default(virtualNode); + return rects.some(function(rect) { + var overlaps = visually_overlaps_default(rect, node); + if (!clippingAncestors.length) { + return overlaps; + } + var withinOverflow = clippingAncestors.some(function(overflowNode) { + return _rectsOverlap(rect, overflowNode.boundingClientRect); + }); + return overlaps && withinOverflow; + }); + } + var color_contrast_matches_default = colorContrastMatches; + var removeUnicodeOptions = { + emoji: true, + nonBmp: false, + punctuations: true + }; + function hasRealTextChildren(virtualNode) { + var visibleText = visible_virtual_default(virtualNode, false, true); + if (visibleText === '' || remove_unicode_default(visibleText, removeUnicodeOptions) === '') { + return false; + } + return virtualNode.children.some(function(vChild) { + return vChild.props.nodeName === '#text' && !_isIconLigature(vChild); + }); + } + function bypassMatches(node, virtualNode, context) { + if (is_initiator_matches_default(node, virtualNode, context)) { + return !!node.querySelector('a[href]'); + } + return true; + } + var bypass_matches_default = bypassMatches; + function autocompleteMatches(node, virtualNode) { + var autocomplete2 = virtualNode.attr('autocomplete'); + if (!autocomplete2 || sanitize_default(autocomplete2) === '') { + return false; + } + var nodeName2 = virtualNode.props.nodeName; + if ([ 'textarea', 'input', 'select' ].includes(nodeName2) === false) { + return false; + } + var ariaReadonly = virtualNode.attr('aria-readonly') || 'false'; + if (virtualNode.hasAttr('readonly') || ariaReadonly.toLowerCase() === 'true') { + return false; + } + var excludedInputTypes = [ 'submit', 'reset', 'button', 'hidden' ]; + if (nodeName2 === 'input' && excludedInputTypes.includes(virtualNode.props.type)) { + return false; + } + var ariaDisabled = virtualNode.attr('aria-disabled') || 'false'; + if (virtualNode.hasAttr('disabled') || ariaDisabled.toLowerCase() === 'true') { + return false; + } + var role = get_explicit_role_default(virtualNode); + var tabIndex = parse_tabindex_default(virtualNode.attr('tabindex')); + if (tabIndex < 0 && virtualNode.hasAttr('role')) { + var roleDef = standards_default.ariaRoles[role]; + if (roleDef === void 0 || roleDef.type !== 'widget') { + return false; + } + } + if (tabIndex < 0 && virtualNode.actualNode && !_isVisibleOnScreen(virtualNode) && !_isVisibleToScreenReaders(virtualNode)) { + return false; + } + return true; + } + var autocomplete_matches_default = autocompleteMatches; + function ariaRequiredParentMatches(node, virtualNode) { + var role = get_explicit_role_default(virtualNode); + return !!required_context_default(role); + } + var aria_required_parent_matches_default = ariaRequiredParentMatches; + function ariaRequiredChildrenMatches(node, virtualNode) { + var role = get_explicit_role_default(virtualNode, { + dpub: true + }); + return !!required_owned_default(role); + } + var aria_required_children_matches_default = ariaRequiredChildrenMatches; + function shouldMatchElement(el) { + if (!el) { + return true; + } + if (el.getAttribute('aria-hidden') === 'true') { + return false; + } + return shouldMatchElement(get_composed_parent_default(el)); + } + function ariaHiddenFocusMatches(node) { + return shouldMatchElement(get_composed_parent_default(node)); + } + var aria_hidden_focus_matches_default = ariaHiddenFocusMatches; + function ariaHasAttrMatches(node, virtualNode) { + var aria = /^aria-/; + return virtualNode.attrNames.some(function(attr) { + return aria.test(attr); + }); + } + var aria_has_attr_matches_default = ariaHasAttrMatches; + function ariaAllowedRoleMatches(node, virtualNode) { + return get_explicit_role_default(virtualNode, { + dpub: true, + fallback: true + }) !== null; + } + var aria_allowed_role_matches_default = ariaAllowedRoleMatches; + function ariaAllowedAttrMatches(node, virtualNode) { + var aria = /^aria-/; + var attrs = virtualNode.attrNames; + if (attrs.length) { + for (var _i35 = 0, l = attrs.length; _i35 < l; _i35++) { + if (aria.test(attrs[_i35])) { + return true; + } + } + } + return false; + } + var aria_allowed_attr_matches_default = ariaAllowedAttrMatches; + var metadataFunctionMap = { + 'abstractrole-evaluate': abstractrole_evaluate_default, + 'accesskeys-after': accesskeys_after_default, + 'accesskeys-evaluate': accesskeys_evaluate_default, + 'alt-space-value-evaluate': alt_space_value_evaluate_default, + 'aria-allowed-attr-elm-evaluate': ariaAllowedAttrElmEvaluate, + 'aria-allowed-attr-evaluate': ariaAllowedAttrEvaluate, + 'aria-allowed-attr-matches': aria_allowed_attr_matches_default, + 'aria-allowed-role-evaluate': aria_allowed_role_evaluate_default, + 'aria-allowed-role-matches': aria_allowed_role_matches_default, + 'aria-busy-evaluate': ariaBusyEvaluate, + 'aria-conditional-attr-evaluate': ariaConditionalAttrEvaluate, + 'aria-conditional-checkbox-attr-evaluate': ariaConditionalCheckboxAttr, + 'aria-conditional-row-attr-evaluate': ariaConditionalRowAttr, + 'aria-errormessage-evaluate': ariaErrormessageEvaluate, + 'aria-has-attr-matches': aria_has_attr_matches_default, + 'aria-hidden-body-evaluate': aria_hidden_body_evaluate_default, + 'aria-hidden-focus-matches': aria_hidden_focus_matches_default, + 'aria-label-evaluate': aria_label_evaluate_default, + 'aria-labelledby-evaluate': aria_labelledby_evaluate_default, + 'aria-level-evaluate': aria_level_evaluate_default, + 'aria-prohibited-attr-evaluate': ariaProhibitedAttrEvaluate, + 'aria-required-attr-evaluate': ariaRequiredAttrEvaluate, + 'aria-required-children-evaluate': ariaRequiredChildrenEvaluate, + 'aria-required-children-matches': aria_required_children_matches_default, + 'aria-required-parent-evaluate': aria_required_parent_evaluate_default, + 'aria-required-parent-matches': aria_required_parent_matches_default, + 'aria-roledescription-evaluate': aria_roledescription_evaluate_default, + 'aria-unsupported-attr-evaluate': aria_unsupported_attr_evaluate_default, + 'aria-valid-attr-evaluate': aria_valid_attr_evaluate_default, + 'aria-valid-attr-value-evaluate': ariaValidAttrValueEvaluate, + 'attr-non-space-content-evaluate': attr_non_space_content_evaluate_default, + 'autocomplete-appropriate-evaluate': autocomplete_appropriate_evaluate_default, + 'autocomplete-matches': autocomplete_matches_default, + 'autocomplete-valid-evaluate': autocomplete_valid_evaluate_default, + 'avoid-inline-spacing-evaluate': avoid_inline_spacing_evaluate_default, + 'braille-label-equivalent-evaluate': brailleLabelEquivalentEvaluate, + 'braille-roledescription-equivalent-evaluate': brailleRoleDescriptionEquivalentEvaluate, + 'bypass-matches': bypass_matches_default, + 'caption-evaluate': caption_evaluate_default, + 'caption-faked-evaluate': caption_faked_evaluate_default, + 'color-contrast-evaluate': colorContrastEvaluate, + 'color-contrast-matches': color_contrast_matches_default, + 'css-orientation-lock-evaluate': css_orientation_lock_evaluate_default, + 'data-table-large-matches': data_table_large_matches_default, + 'data-table-matches': data_table_matches_default, + 'deprecatedrole-evaluate': deprecatedroleEvaluate, + 'dlitem-evaluate': dlitem_evaluate_default, + 'doc-has-title-evaluate': doc_has_title_evaluate_default, + 'duplicate-id-active-matches': duplicate_id_active_matches_default, + 'duplicate-id-after': duplicate_id_after_default, + 'duplicate-id-aria-matches': duplicate_id_aria_matches_default, + 'duplicate-id-evaluate': duplicate_id_evaluate_default, + 'duplicate-id-misc-matches': duplicate_id_misc_matches_default, + 'duplicate-img-label-evaluate': duplicate_img_label_evaluate_default, + 'exists-evaluate': exists_evaluate_default, + 'explicit-evaluate': explicit_evaluate_default, + 'fallbackrole-evaluate': fallbackrole_evaluate_default, + 'focusable-content-evaluate': focusable_content_evaluate_default, + 'focusable-disabled-evaluate': focusable_disabled_evaluate_default, + 'focusable-element-evaluate': focusable_element_evaluate_default, + 'focusable-modal-open-evaluate': focusable_modal_open_evaluate_default, + 'focusable-no-name-evaluate': focusable_no_name_evaluate_default, + 'focusable-not-tabbable-evaluate': focusable_not_tabbable_evaluate_default, + 'frame-focusable-content-evaluate': frameFocusableContentEvaluate, + 'frame-focusable-content-matches': frame_focusable_content_matches_default, + 'frame-tested-after': frame_tested_after_default, + 'frame-tested-evaluate': frame_tested_evaluate_default, + 'frame-title-has-text-matches': frame_title_has_text_matches_default, + 'has-alt-evaluate': has_alt_evaluate_default, + 'has-descendant-after': has_descendant_after_default, + 'has-descendant-evaluate': has_descendant_evaluate_default, + 'has-global-aria-attribute-evaluate': has_global_aria_attribute_evaluate_default, + 'has-implicit-chromium-role-matches': has_implicit_chromium_role_matches_default, + 'has-lang-evaluate': has_lang_evaluate_default, + 'has-text-content-evaluate': hasTextContentEvaluate, + 'has-widget-role-evaluate': has_widget_role_evaluate_default, + 'heading-matches': headingMatches, + 'heading-order-after': headingOrderAfter, + 'heading-order-evaluate': heading_order_evaluate_default, + 'help-same-as-label-evaluate': help_same_as_label_evaluate_default, + 'hidden-content-evaluate': hidden_content_evaluate_default, + 'hidden-explicit-label-evaluate': hidden_explicit_label_evaluate_default, + 'html-namespace-matches': html_namespace_matches_default, + 'html5-scope-evaluate': html5_scope_evaluate_default, + 'identical-links-same-purpose-after': identical_links_same_purpose_after_default, + 'identical-links-same-purpose-evaluate': identical_links_same_purpose_evaluate_default, + 'identical-links-same-purpose-matches': identical_links_same_purpose_matches_default, + 'implicit-evaluate': implicit_evaluate_default, + 'inline-style-property-evaluate': inlineStyleProperty, + 'inserted-into-focus-order-matches': inserted_into_focus_order_matches_default, + 'internal-link-present-evaluate': internal_link_present_evaluate_default, + 'invalid-children-evaluate': invalidChildrenEvaluate, + 'invalidrole-evaluate': invalidrole_evaluate_default, + 'is-element-focusable-evaluate': is_element_focusable_evaluate_default, + 'is-initiator-matches': is_initiator_matches_default, + 'is-on-screen-evaluate': is_on_screen_evaluate_default, + 'is-visible-matches': hasVisibleTextMatches, + 'is-visible-on-screen-matches': isVisibleOnScreenMatches, + 'label-content-name-mismatch-evaluate': label_content_name_mismatch_evaluate_default, + 'label-content-name-mismatch-matches': label_content_name_mismatch_matches_default, + 'label-matches': label_matches_default, + 'landmark-has-body-context-matches': landmark_has_body_context_matches_default, + 'landmark-is-top-level-evaluate': landmark_is_top_level_evaluate_default, + 'landmark-is-unique-after': landmark_is_unique_after_default, + 'landmark-is-unique-evaluate': landmark_is_unique_evaluate_default, + 'landmark-unique-matches': landmarkUniqueMatches, + 'layout-table-matches': layout_table_matches_default, + 'link-in-text-block-evaluate': link_in_text_block_evaluate_default, + 'link-in-text-block-matches': link_in_text_block_matches_default, + 'link-in-text-block-style-evaluate': linkInTextBlockStyleEvaluate, + 'listitem-evaluate': listitemEvaluate, + 'matches-definition-evaluate': matches_definition_evaluate_default, + 'meta-refresh-evaluate': metaRefreshEvaluate, + 'meta-viewport-scale-evaluate': meta_viewport_scale_evaluate_default, + 'multiple-label-evaluate': multiple_label_evaluate_default, + 'nested-interactive-matches': nested_interactive_matches_default, + 'no-autoplay-audio-evaluate': no_autoplay_audio_evaluate_default, + 'no-autoplay-audio-matches': no_autoplay_audio_matches_default, + 'no-empty-role-matches': no_empty_role_matches_default, + 'no-explicit-name-required-matches': no_explicit_name_required_matches_default, + 'no-focusable-content-evaluate': noFocusableContentEvaluate, + 'no-implicit-explicit-label-evaluate': no_implicit_explicit_label_evaluate_default, + 'no-naming-method-matches': no_naming_method_matches_default, + 'no-negative-tabindex-matches': no_negative_tabindex_matches_default, + 'no-role-matches': no_role_matches_default, + 'non-empty-if-present-evaluate': non_empty_if_present_evaluate_default, + 'not-html-matches': not_html_matches_default, + 'object-is-loaded-matches': object_is_loaded_matches_default, + 'only-dlitems-evaluate': onlyDlitemsEvaluate, + 'only-listitems-evaluate': only_listitems_evaluate_default, + 'p-as-heading-evaluate': p_as_heading_evaluate_default, + 'p-as-heading-matches': p_as_heading_matches_default, + 'page-no-duplicate-after': page_no_duplicate_after_default, + 'page-no-duplicate-evaluate': page_no_duplicate_evaluate_default, + 'presentation-role-conflict-matches': presentation_role_conflict_matches_default, + 'presentational-role-evaluate': presentationalRoleEvaluate, + 'region-after': region_after_default, + 'region-evaluate': regionEvaluate, + 'same-caption-summary-evaluate': same_caption_summary_evaluate_default, + 'scope-value-evaluate': scope_value_evaluate_default, + 'scrollable-region-focusable-matches': scrollableRegionFocusableMatches, + 'skip-link-evaluate': skip_link_evaluate_default, + 'skip-link-matches': skip_link_matches_default, + 'structured-dlitems-evaluate': structured_dlitems_evaluate_default, + 'summary-interactive-matches': summaryIsInteractiveMatches, + 'svg-namespace-matches': svg_namespace_matches_default, + 'svg-non-empty-title-evaluate': svg_non_empty_title_evaluate_default, + 'tabindex-evaluate': tabindex_evaluate_default, + 'table-or-grid-role-matches': tableOrGridRoleMatches, + 'target-offset-evaluate': targetOffsetEvaluate, + 'target-size-evaluate': targetSizeEvaluate, + 'td-has-header-evaluate': td_has_header_evaluate_default, + 'td-headers-attr-evaluate': tdHeadersAttrEvaluate, + 'th-has-data-cells-evaluate': th_has_data_cells_evaluate_default, + 'title-only-evaluate': title_only_evaluate_default, + 'unique-frame-title-after': unique_frame_title_after_default, + 'unique-frame-title-evaluate': unique_frame_title_evaluate_default, + 'unsupportedrole-evaluate': unsupportedrole_evaluate_default, + 'valid-lang-evaluate': valid_lang_evaluate_default, + 'valid-scrollable-semantics-evaluate': valid_scrollable_semantics_evaluate_default, + 'widget-not-inline-matches': widgetNotInline, + 'window-is-top-matches': window_is_top_matches_default, + 'xml-lang-mismatch-evaluate': xml_lang_mismatch_evaluate_default, + 'xml-lang-mismatch-matches': xml_lang_mismatch_matches_default + }; + var metadata_function_map_default = metadataFunctionMap; + function CheckResult(check) { + this.id = check.id; + this.data = null; + this.relatedNodes = []; + this.result = null; + } + var check_result_default = CheckResult; + function createExecutionContext(spec) { + if (typeof spec === 'string') { + if (metadata_function_map_default[spec]) { + return metadata_function_map_default[spec]; + } + if (/^\s*function[\s\w]*\(/.test(spec)) { + return new Function('return ' + spec + ';')(); + } + throw new ReferenceError('Function ID does not exist in the metadata-function-map: '.concat(spec)); + } + return spec; + } + function normalizeOptions() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (Array.isArray(options) || _typeof(options) !== 'object') { + options = { + value: options + }; + } + return options; + } + function Check(spec) { + if (spec) { + this.id = spec.id; + this.configure(spec); + } + } + Check.prototype.enabled = true; + Check.prototype.run = function run(node, options, context, resolve, reject) { + options = options || {}; + var enabled = options.hasOwnProperty('enabled') ? options.enabled : this.enabled; + var checkOptions = this.getOptions(options.options); + if (enabled) { + var checkResult = new check_result_default(this); + var helper = check_helper_default(checkResult, options, resolve, reject); + var result; + try { + result = this.evaluate.call(helper, node.actualNode, checkOptions, node, context); + } catch (e) { + if (node && node.actualNode) { + e.errorNode = node_serializer_default.toSpec(node); + } + reject(e); + return; + } + if (!helper.isAsync) { + checkResult.result = result; + resolve(checkResult); + } + } else { + resolve(null); + } + }; + Check.prototype.runSync = function runSync(node, options, context) { + options = options || {}; + var _options2 = options, _options2$enabled = _options2.enabled, enabled = _options2$enabled === void 0 ? this.enabled : _options2$enabled; + if (!enabled) { + return null; + } + var checkOptions = this.getOptions(options.options); + var checkResult = new check_result_default(this); + var helper = check_helper_default(checkResult, options); + helper.async = function async() { + throw new Error('Cannot run async check while in a synchronous run'); + }; + var result; + try { + result = this.evaluate.call(helper, node.actualNode, checkOptions, node, context); + } catch (e) { + if (node && node.actualNode) { + e.errorNode = node_serializer_default.toSpec(node); + } + throw e; + } + checkResult.result = result; + return checkResult; + }; + Check.prototype.configure = function configure2(spec) { + var _this0 = this; + if (!spec.evaluate || metadata_function_map_default[spec.evaluate]) { + this._internalCheck = true; + } + if (spec.hasOwnProperty('enabled')) { + this.enabled = spec.enabled; + } + if (spec.hasOwnProperty('options')) { + if (this._internalCheck) { + this.options = normalizeOptions(spec.options); + } else { + this.options = spec.options; + } + } + [ 'evaluate', 'after' ].filter(function(prop) { + return spec.hasOwnProperty(prop); + }).forEach(function(prop) { + return _this0[prop] = createExecutionContext(spec[prop]); + }); + }; + Check.prototype.getOptions = function getOptions(options) { + if (this._internalCheck) { + return deep_merge_default(this.options, normalizeOptions(options || {})); + } else { + return options || this.options; + } + }; + var check_default = Check; + function RuleResult(rule) { + this.id = rule.id; + this.result = constants_default.NA; + this.pageLevel = rule.pageLevel; + this.impact = null; + this.nodes = []; + } + var rule_result_default = RuleResult; + function Rule(spec, parentAudit) { + this._audit = parentAudit; + this.id = spec.id; + this.selector = spec.selector || '*'; + if (spec.impact) { + assert_default(constants_default.impact.includes(spec.impact), 'Impact '.concat(spec.impact, ' is not a valid impact')); + this.impact = spec.impact; + } + this.excludeHidden = typeof spec.excludeHidden === 'boolean' ? spec.excludeHidden : true; + this.enabled = typeof spec.enabled === 'boolean' ? spec.enabled : true; + this.pageLevel = typeof spec.pageLevel === 'boolean' ? spec.pageLevel : false; + this.reviewOnFail = typeof spec.reviewOnFail === 'boolean' ? spec.reviewOnFail : false; + this.any = spec.any || []; + this.all = spec.all || []; + this.none = spec.none || []; + this.tags = spec.tags || []; + this.preload = spec.preload ? true : false; + this.actIds = spec.actIds; + if (spec.matches) { + this.matches = createExecutionContext(spec.matches); + } + } + Rule.prototype.matches = function matches3() { + return true; + }; + Rule.prototype.gather = function gather(context) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var markStart = 'mark_gather_start_' + this.id; + var markEnd = 'mark_gather_end_' + this.id; + var markHiddenStart = 'mark_isVisibleToScreenReaders_start_' + this.id; + var markHiddenEnd = 'mark_isVisibleToScreenReaders_end_' + this.id; + if (options.performanceTimer) { + performance_timer_default.mark(markStart); + } + var elements = _select(this.selector, context); + if (this.excludeHidden) { + if (options.performanceTimer) { + performance_timer_default.mark(markHiddenStart); + } + elements = elements.filter(function(element) { + return _isVisibleToScreenReaders(element); + }); + if (options.performanceTimer) { + performance_timer_default.mark(markHiddenEnd); + performance_timer_default.measure('rule_' + this.id + '#gather_axe.utils.isVisibleToScreenReaders', markHiddenStart, markHiddenEnd); + } + } + if (options.performanceTimer) { + performance_timer_default.mark(markEnd); + performance_timer_default.measure('rule_' + this.id + '#gather', markStart, markEnd); + } + return elements; + }; + Rule.prototype.runChecks = function runChecks(type2, node, options, context, resolve, reject) { + var self2 = this; + var checkQueue = queue_default(); + this[type2].forEach(function(c4) { + var check = self2._audit.checks[c4.id || c4]; + var option = get_check_option_default(check, self2.id, options); + checkQueue.defer(function(res, rej) { + check.run(node, option, context, res, function(error) { + rej(new rule_error_default({ + ruleId: self2.id, + method: ''.concat(check.id, '#evaluate'), + errorNode: new dq_element_default(node), + error: error + })); + }); + }); + }); + checkQueue.then(function(results) { + results = results.filter(function(check) { + return check; + }); + resolve({ + type: type2, + results: results + }); + })['catch'](reject); + }; + Rule.prototype.runChecksSync = function runChecksSync(type2, node, options, context) { + var self2 = this; + var results = []; + this[type2].forEach(function(c4) { + var check = self2._audit.checks[c4.id || c4]; + var option = get_check_option_default(check, self2.id, options); + results.push(check.runSync(node, option, context)); + }); + results = results.filter(function(check) { + return check; + }); + return { + type: type2, + results: results + }; + }; + Rule.prototype.run = function run2(context) { + var _this1 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var resolve = arguments.length > 2 ? arguments[2] : undefined; + var reject = arguments.length > 3 ? arguments[3] : undefined; + if (options.performanceTimer) { + this._trackPerformance(); + } + var q = queue_default(); + var ruleResult = new rule_result_default(this); + var nodes; + try { + nodes = this.gatherAndMatchNodes(context, options); + } catch (error) { + reject(error); + return; + } + if (options.performanceTimer) { + this._logGatherPerformance(nodes); + } + nodes.forEach(function(node) { + q.defer(function(resolveNode, rejectNode) { + var checkQueue = queue_default(); + [ 'any', 'all', 'none' ].forEach(function(type2) { + checkQueue.defer(function(res, rej) { + _this1.runChecks(type2, node, options, context, res, rej); + }); + }); + checkQueue.then(function(results) { + var result = getResult(results); + if (result) { + result.node = new dq_element_default(node); + ruleResult.nodes.push(result); + if (_this1.reviewOnFail) { + [ 'any', 'all' ].forEach(function(type2) { + result[type2].forEach(function(checkResult) { + if (checkResult.result === false) { + checkResult.result = void 0; + } + }); + }); + result.none.forEach(function(checkResult) { + if (checkResult.result === true) { + checkResult.result = void 0; + } + }); + } + } + resolveNode(); + })['catch'](function(err2) { + return rejectNode(err2); + }); + }); + }); + q.then(function() { + if (options.performanceTimer) { + _this1._logRulePerformance(); + } + setTimeout(function() { + resolve(ruleResult); + }, 0); + })['catch'](function(error) { + if (options.performanceTimer) { + _this1._logRulePerformance(); + } + reject(error); + }); + }; + Rule.prototype.runSync = function runSync2(context) { + var _this10 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (options.performanceTimer) { + this._trackPerformance(); + } + var ruleResult = new rule_result_default(this); + var nodes = this.gatherAndMatchNodes(context, options); + if (options.performanceTimer) { + this._logGatherPerformance(nodes); + } + nodes.forEach(function(node) { + var results = []; + [ 'any', 'all', 'none' ].forEach(function(type2) { + results.push(_this10.runChecksSync(type2, node, options, context)); + }); + var result = getResult(results); + if (result) { + result.node = node.actualNode ? new dq_element_default(node) : null; + ruleResult.nodes.push(result); + if (_this10.reviewOnFail) { + [ 'any', 'all' ].forEach(function(type2) { + result[type2].forEach(function(checkResult) { + if (checkResult.result === false) { + checkResult.result = void 0; + } + }); + }); + result.none.forEach(function(checkResult) { + if (checkResult.result === true) { + checkResult.result = void 0; + } + }); + } + } + }); + if (options.performanceTimer) { + this._logRulePerformance(); + } + return ruleResult; + }; + Rule.prototype._trackPerformance = function _trackPerformance() { + this._markStart = 'mark_rule_start_' + this.id; + this._markEnd = 'mark_rule_end_' + this.id; + this._markChecksStart = 'mark_runchecks_start_' + this.id; + this._markChecksEnd = 'mark_runchecks_end_' + this.id; + }; + Rule.prototype._logGatherPerformance = function _logGatherPerformance(nodes) { + log_default('gather for '.concat(this.id, ' (').concat(nodes.length, ' nodes): ').concat(performance_timer_default.timeElapsed(), 'ms')); + performance_timer_default.mark(this._markChecksStart); + }; + Rule.prototype._logRulePerformance = function _logRulePerformance() { + performance_timer_default.mark(this._markChecksEnd); + performance_timer_default.mark(this._markEnd); + performance_timer_default.measure('runchecks_' + this.id, this._markChecksStart, this._markChecksEnd); + performance_timer_default.measure('rule_' + this.id, this._markStart, this._markEnd); + }; + function getResult(results) { + if (results.length) { + var hasResults = false; + var result = {}; + results.forEach(function(r) { + var res = r.results.filter(function(_result) { + return _result; + }); + result[r.type] = res; + if (res.length) { + hasResults = true; + } + }); + if (hasResults) { + return result; + } + return null; + } + } + Rule.prototype.gatherAndMatchNodes = function gatherAndMatchNodes(context, options) { + var _this11 = this; + var markMatchesStart = 'mark_matches_start_' + this.id; + var markMatchesEnd = 'mark_matches_end_' + this.id; + var nodes = this.gather(context, options); + if (options.performanceTimer) { + performance_timer_default.mark(markMatchesStart); + } + nodes = nodes.filter(function(node) { + try { + return _this11.matches(node.actualNode, node, context); + } catch (error) { + throw new rule_error_default({ + ruleId: _this11.id, + method: '#matches', + errorNode: new dq_element_default(node), + error: error + }); + } + }); + if (options.performanceTimer) { + performance_timer_default.mark(markMatchesEnd); + performance_timer_default.measure('rule_' + this.id + '#matches', markMatchesStart, markMatchesEnd); + } + return nodes; + }; + function findAfterChecks(rule) { + return get_all_checks_default(rule).map(function(c4) { + var check = rule._audit.checks[c4.id || c4]; + return check && typeof check.after === 'function' ? check : null; + }).filter(Boolean); + } + function findCheckResults(nodes, checkID) { + var checkResults = []; + nodes.forEach(function(nodeResult) { + var checks = get_all_checks_default(nodeResult); + checks.forEach(function(checkResult) { + if (checkResult.id === checkID) { + checkResult.node = nodeResult.node; + checkResults.push(checkResult); + } + }); + }); + return checkResults; + } + function filterChecks(checks) { + return checks.filter(function(check) { + return check.filtered !== true; + }); + } + function sanitizeNodes(result) { + var checkTypes2 = [ 'any', 'all', 'none' ]; + var nodes = result.nodes.filter(function(detail) { + var length = 0; + checkTypes2.forEach(function(type2) { + detail[type2] = filterChecks(detail[type2]); + length += detail[type2].length; + }); + return length > 0; + }); + if (result.pageLevel && nodes.length) { + nodes = [ nodes.reduce(function(a2, b2) { + if (a2) { + checkTypes2.forEach(function(type2) { + a2[type2].push.apply(a2[type2], b2[type2]); + }); + return a2; + } + }) ]; + } + return nodes; + } + Rule.prototype.after = function after(result, options) { + var _this12 = this; + var afterChecks = findAfterChecks(this); + afterChecks.forEach(function(check) { + var beforeResults = findCheckResults(result.nodes, check.id); + var checkOption = get_check_option_default(check, _this12.id, options); + var afterResults; + try { + afterResults = check.after(beforeResults, checkOption.options); + } catch (error) { + var _result$nodes; + throw new rule_error_default({ + ruleId: _this12.id, + method: ''.concat(check.id, '#after'), + errorNode: (_result$nodes = result.nodes) === null || _result$nodes === void 0 || (_result$nodes = _result$nodes[0]) === null || _result$nodes === void 0 ? void 0 : _result$nodes.node, + error: error + }); + } + if (_this12.reviewOnFail) { + afterResults.forEach(function(checkResult) { + var changeAnyAllResults = (_this12.any.includes(checkResult.id) || _this12.all.includes(checkResult.id)) && checkResult.result === false; + var changeNoneResult = _this12.none.includes(checkResult.id) && checkResult.result === true; + if (changeAnyAllResults || changeNoneResult) { + checkResult.result = void 0; + } + }); + } + beforeResults.forEach(function(item) { + delete item.node; + if (afterResults.indexOf(item) === -1) { + item.filtered = true; + } + }); + }); + result.nodes = sanitizeNodes(result); + return result; + }; + Rule.prototype.configure = function configure3(spec) { + if (spec.hasOwnProperty('selector')) { + this.selector = spec.selector; + } + if (spec.hasOwnProperty('excludeHidden')) { + this.excludeHidden = typeof spec.excludeHidden === 'boolean' ? spec.excludeHidden : true; + } + if (spec.hasOwnProperty('enabled')) { + this.enabled = typeof spec.enabled === 'boolean' ? spec.enabled : true; + } + if (spec.hasOwnProperty('pageLevel')) { + this.pageLevel = typeof spec.pageLevel === 'boolean' ? spec.pageLevel : false; + } + if (spec.hasOwnProperty('reviewOnFail')) { + this.reviewOnFail = typeof spec.reviewOnFail === 'boolean' ? spec.reviewOnFail : false; + } + if (spec.hasOwnProperty('any')) { + this.any = spec.any; + } + if (spec.hasOwnProperty('all')) { + this.all = spec.all; + } + if (spec.hasOwnProperty('none')) { + this.none = spec.none; + } + if (spec.hasOwnProperty('tags')) { + this.tags = spec.tags; + } + if (spec.hasOwnProperty('actIds')) { + this.actIds = spec.actIds; + } + if (spec.hasOwnProperty('matches')) { + this.matches = createExecutionContext(spec.matches); + } + if (spec.impact) { + assert_default(constants_default.impact.includes(spec.impact), 'Impact '.concat(spec.impact, ' is not a valid impact')); + this.impact = spec.impact; + } + }; + var dotRegex = /\{\{.+?\}\}/g; + var Audit = function() { + function Audit(audit) { + _classCallCheck(this, Audit); + this.lang = 'en'; + this.defaultConfig = audit; + this.standards = standards_default; + this._init(); + this._defaultLocale = null; + } + return _createClass(Audit, [ { + key: '_setDefaultLocale', + value: function _setDefaultLocale() { + if (this._defaultLocale) { + return; + } + var locale = { + checks: {}, + rules: {}, + failureSummaries: {}, + incompleteFallbackMessage: '', + lang: this.lang + }; + var checkIDs = Object.keys(this.data.checks); + for (var _i36 = 0; _i36 < checkIDs.length; _i36++) { + var _id8 = checkIDs[_i36]; + var check = this.data.checks[_id8]; + var _check$messages = check.messages, pass = _check$messages.pass, fail = _check$messages.fail, incomplete = _check$messages.incomplete; + locale.checks[_id8] = { + pass: pass, + fail: fail, + incomplete: incomplete + }; + } + var ruleIDs = Object.keys(this.data.rules); + for (var _i37 = 0; _i37 < ruleIDs.length; _i37++) { + var _id9 = ruleIDs[_i37]; + var rule = this.data.rules[_id9]; + var description = rule.description, help = rule.help; + locale.rules[_id9] = { + description: description, + help: help + }; + } + var failureSummaries = Object.keys(this.data.failureSummaries); + for (var _i38 = 0; _i38 < failureSummaries.length; _i38++) { + var type2 = failureSummaries[_i38]; + var failureSummary2 = this.data.failureSummaries[type2]; + var failureMessage = failureSummary2.failureMessage; + locale.failureSummaries[type2] = { + failureMessage: failureMessage + }; + } + locale.incompleteFallbackMessage = this.data.incompleteFallbackMessage; + this._defaultLocale = locale; + } + }, { + key: '_resetLocale', + value: function _resetLocale() { + var defaultLocale = this._defaultLocale; + if (!defaultLocale) { + return; + } + this.applyLocale(defaultLocale); + } + }, { + key: '_applyCheckLocale', + value: function _applyCheckLocale(checks) { + var keys = Object.keys(checks); + for (var _i39 = 0; _i39 < keys.length; _i39++) { + var _id0 = keys[_i39]; + if (!this.data.checks[_id0]) { + throw new Error('Locale provided for unknown check: "'.concat(_id0, '"')); + } + this.data.checks[_id0] = mergeCheckLocale(this.data.checks[_id0], checks[_id0]); + } + } + }, { + key: '_applyRuleLocale', + value: function _applyRuleLocale(rules) { + var keys = Object.keys(rules); + for (var _i40 = 0; _i40 < keys.length; _i40++) { + var _id1 = keys[_i40]; + if (!this.data.rules[_id1]) { + throw new Error('Locale provided for unknown rule: "'.concat(_id1, '"')); + } + this.data.rules[_id1] = mergeRuleLocale(this.data.rules[_id1], rules[_id1]); + } + } + }, { + key: '_applyFailureSummaries', + value: function _applyFailureSummaries(messages) { + var keys = Object.keys(messages); + for (var _i41 = 0; _i41 < keys.length; _i41++) { + var _key1 = keys[_i41]; + if (!this.data.failureSummaries[_key1]) { + throw new Error('Locale provided for unknown failureMessage: "'.concat(_key1, '"')); + } + this.data.failureSummaries[_key1] = mergeFailureMessage(this.data.failureSummaries[_key1], messages[_key1]); + } + } + }, { + key: 'applyLocale', + value: function applyLocale(locale) { + this._setDefaultLocale(); + if (locale.checks) { + this._applyCheckLocale(locale.checks); + } + if (locale.rules) { + this._applyRuleLocale(locale.rules); + } + if (locale.failureSummaries) { + this._applyFailureSummaries(locale.failureSummaries, 'failureSummaries'); + } + if (locale.incompleteFallbackMessage) { + this.data.incompleteFallbackMessage = mergeFallbackMessage(this.data.incompleteFallbackMessage, locale.incompleteFallbackMessage); + } + if (locale.lang) { + this.lang = locale.lang; + } + } + }, { + key: 'setAllowedOrigins', + value: function setAllowedOrigins(allowedOrigins) { + var defaultOrigin = getDefaultOrigin(); + this.allowedOrigins = []; + var _iterator24 = _createForOfIteratorHelper(allowedOrigins), _step24; + try { + for (_iterator24.s(); !(_step24 = _iterator24.n()).done; ) { + var origin = _step24.value; + if (origin === constants_default.allOrigins) { + this.allowedOrigins = [ '*' ]; + return; + } else if (origin !== constants_default.sameOrigin) { + this.allowedOrigins.push(origin); + } else if (defaultOrigin) { + this.allowedOrigins.push(defaultOrigin); + } + } + } catch (err) { + _iterator24.e(err); + } finally { + _iterator24.f(); + } + } + }, { + key: '_init', + value: function _init() { + var audit = getDefaultConfiguration(this.defaultConfig); + this.lang = audit.lang || 'en'; + this.reporter = audit.reporter; + this.commands = {}; + this.rules = []; + this.checks = {}; + this.brand = 'axe'; + this.application = 'axeAPI'; + this.tagExclude = [ 'experimental', 'deprecated' ]; + this.noHtml = audit.noHtml; + this.allowedOrigins = audit.allowedOrigins; + unpackToObject(audit.rules, this, 'addRule'); + unpackToObject(audit.checks, this, 'addCheck'); + this.data = {}; + this.data.checks = audit.data && audit.data.checks || {}; + this.data.rules = audit.data && audit.data.rules || {}; + this.data.failureSummaries = audit.data && audit.data.failureSummaries || {}; + this.data.incompleteFallbackMessage = audit.data && audit.data.incompleteFallbackMessage || ''; + this._constructHelpUrls(); + } + }, { + key: 'registerCommand', + value: function registerCommand(command) { + this.commands[command.id] = command.callback; + } + }, { + key: 'addRule', + value: function addRule(spec) { + if (spec.metadata) { + this.data.rules[spec.id] = spec.metadata; + } + var rule = this.getRule(spec.id); + if (rule) { + rule.configure(spec); + } else { + this.rules.push(new Rule(spec, this)); + } + } + }, { + key: 'addCheck', + value: function addCheck(spec) { + var metadata = spec.metadata; + if (_typeof(metadata) === 'object') { + this.data.checks[spec.id] = metadata; + if (_typeof(metadata.messages) === 'object') { + Object.keys(metadata.messages).filter(function(prop) { + return metadata.messages.hasOwnProperty(prop) && typeof metadata.messages[prop] === 'string'; + }).forEach(function(prop) { + if (metadata.messages[prop].indexOf('function') === 0) { + metadata.messages[prop] = new Function('return ' + metadata.messages[prop] + ';')(); + } + }); + } + } + if (this.checks[spec.id]) { + this.checks[spec.id].configure(spec); + } else { + this.checks[spec.id] = new check_default(spec); + } + } + }, { + key: 'run', + value: function run(context, options, resolve, reject) { + this.normalizeOptions(options); + dq_element_default.setRunOptions(options); + axe._selectCache = []; + var allRulesToRun = getRulesToRun(this.rules, context, options); + var runNowRules = allRulesToRun.now; + var runLaterRules = allRulesToRun.later; + var nowRulesQueue = queue_default(); + runNowRules.forEach(function(rule) { + nowRulesQueue.defer(getDefferedRule(rule, context, options)); + }); + var preloaderQueue = queue_default(); + if (runLaterRules.length) { + preloaderQueue.defer(function(res) { + _preload(options).then(function(assets) { + return res(assets); + })['catch'](function(err2) { + console.warn('Couldn\'t load preload assets: ', err2); + res(void 0); + }); + }); + } + var queueForNowRulesAndPreloader = queue_default(); + queueForNowRulesAndPreloader.defer(nowRulesQueue); + queueForNowRulesAndPreloader.defer(preloaderQueue); + queueForNowRulesAndPreloader.then(function(nowRulesAndPreloaderResults) { + var assetsFromQueue = nowRulesAndPreloaderResults.pop(); + if (assetsFromQueue && assetsFromQueue.length) { + var assets = assetsFromQueue[0]; + if (assets) { + context = _extends({}, context, assets); + } + } + var nowRulesResults = nowRulesAndPreloaderResults[0]; + if (!runLaterRules.length) { + axe._selectCache = void 0; + resolve(nowRulesResults.filter(function(result) { + return !!result; + })); + return; + } + var laterRulesQueue = queue_default(); + runLaterRules.forEach(function(rule) { + var deferredRule = getDefferedRule(rule, context, options); + laterRulesQueue.defer(deferredRule); + }); + laterRulesQueue.then(function(laterRuleResults) { + axe._selectCache = void 0; + resolve(nowRulesResults.concat(laterRuleResults).filter(function(result) { + return !!result; + })); + })['catch'](reject); + })['catch'](reject); + } + }, { + key: 'after', + value: function after(results, options) { + var rules = this.rules; + return results.map(function(ruleResult) { + if (ruleResult.error) { + return ruleResult; + } + var rule = find_by_default(rules, 'id', ruleResult.id); + if (!rule) { + throw new Error('Result for unknown rule. You may be running mismatch axe-core versions'); + } + try { + return rule.after(ruleResult, options); + } catch (err2) { + if (options.debug) { + throw err2; + } + return createIncompleteErrorResult(rule, err2); + } + }); + } + }, { + key: 'getRule', + value: function getRule(ruleId) { + return this.rules.find(function(rule) { + return rule.id === ruleId; + }); + } + }, { + key: 'normalizeOptions', + value: function normalizeOptions(options) { + var audit = this; + var tags = []; + var ruleIds = []; + audit.rules.forEach(function(rule) { + ruleIds.push(rule.id); + rule.tags.forEach(function(tag) { + if (!tags.includes(tag)) { + tags.push(tag); + } + }); + }); + if ([ 'object', 'string' ].includes(_typeof(options.runOnly))) { + if (typeof options.runOnly === 'string') { + options.runOnly = [ options.runOnly ]; + } + if (Array.isArray(options.runOnly)) { + var hasTag = options.runOnly.find(function(value) { + return tags.includes(value); + }); + var hasRule = options.runOnly.find(function(value) { + return ruleIds.includes(value); + }); + if (hasTag && hasRule) { + throw new Error('runOnly cannot be both rules and tags'); + } + if (hasRule) { + options.runOnly = { + type: 'rule', + values: options.runOnly + }; + } else { + options.runOnly = { + type: 'tag', + values: options.runOnly + }; + } + } + var only = options.runOnly; + if (only.value && !only.values) { + only.values = only.value; + delete only.value; + } + if (!Array.isArray(only.values) || only.values.length === 0) { + throw new Error('runOnly.values must be a non-empty array'); + } + if ([ 'rule', 'rules' ].includes(only.type)) { + only.type = 'rule'; + only.values.forEach(function(ruleId) { + if (!ruleIds.includes(ruleId)) { + throw new Error('unknown rule `' + ruleId + '` in options.runOnly'); + } + }); + } else if ([ 'tag', 'tags', void 0 ].includes(only.type)) { + only.type = 'tag'; + var unmatchedTags = only.values.filter(function(tag) { + return !tags.includes(tag) && !/wcag2[1-3]a{1,3}/.test(tag); + }); + if (unmatchedTags.length !== 0) { + axe.log('Could not find tags `' + unmatchedTags.join('`, `') + '`'); + } + } else { + throw new Error('Unknown runOnly type \''.concat(only.type, '\'')); + } + } + if (_typeof(options.rules) === 'object') { + Object.keys(options.rules).forEach(function(ruleId) { + if (!ruleIds.includes(ruleId)) { + throw new Error('unknown rule `' + ruleId + '` in options.rules'); + } + }); + } + return options; + } + }, { + key: 'setBranding', + value: function setBranding(branding) { + var previous = { + brand: this.brand, + application: this.application + }; + if (typeof branding === 'string') { + this.application = branding; + } + if (branding && branding.hasOwnProperty('brand') && branding.brand && typeof branding.brand === 'string') { + this.brand = branding.brand; + } + if (branding && branding.hasOwnProperty('application') && branding.application && typeof branding.application === 'string') { + this.application = branding.application; + } + this._constructHelpUrls(previous); + } + }, { + key: '_constructHelpUrls', + value: function _constructHelpUrls() { + var _this13 = this; + var previous = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var version = (axe.version.match(/^[1-9][0-9]*\.[0-9]+/) || [ 'x.y' ])[0]; + this.rules.forEach(function(rule) { + if (!_this13.data.rules[rule.id]) { + _this13.data.rules[rule.id] = {}; + } + var metaData = _this13.data.rules[rule.id]; + if (typeof metaData.helpUrl !== 'string' || previous && metaData.helpUrl === getHelpUrl(previous, rule.id, version)) { + metaData.helpUrl = getHelpUrl(_this13, rule.id, version); + } + }); + } + }, { + key: 'resetRulesAndChecks', + value: function resetRulesAndChecks() { + this._init(); + this._resetLocale(); + } + } ]); + }(); + var audit_default = Audit; + function getDefaultOrigin() { + if (window.origin && window.origin !== 'null') { + return window.origin; + } + if (window.location && window.location.origin && window.location.origin !== 'null') { + return window.location.origin; + } + } + function getDefaultConfiguration(audit) { + var config; + if (audit) { + config = clone2(audit); + config.commons = audit.commons; + } else { + config = {}; + } + config.reporter = config.reporter || null; + config.noHtml = config.noHtml || false; + if (!config.allowedOrigins) { + var defaultOrigin = getDefaultOrigin(); + config.allowedOrigins = defaultOrigin ? [ defaultOrigin ] : []; + } + config.rules = config.rules || []; + config.checks = config.checks || []; + config.data = _extends({ + checks: {}, + rules: {} + }, config.data); + return config; + } + function unpackToObject(collection, audit, method) { + var i, l; + for (i = 0, l = collection.length; i < l; i++) { + audit[method](collection[i]); + } + } + var mergeCheckLocale = function mergeCheckLocale(a2, b2) { + var pass = b2.pass, fail = b2.fail; + if (typeof pass === 'string' && dotRegex.test(pass)) { + pass = import_dot['default'].compile(pass); + } + if (typeof fail === 'string' && dotRegex.test(fail)) { + fail = import_dot['default'].compile(fail); + } + return _extends({}, a2, { + messages: { + pass: pass || a2.messages.pass, + fail: fail || a2.messages.fail, + incomplete: _typeof(a2.messages.incomplete) === 'object' ? _extends({}, a2.messages.incomplete, b2.incomplete) : b2.incomplete + } + }); + }; + var mergeRuleLocale = function mergeRuleLocale(a2, b2) { + var help = b2.help, description = b2.description; + if (typeof help === 'string' && dotRegex.test(help)) { + help = import_dot['default'].compile(help); + } + if (typeof description === 'string' && dotRegex.test(description)) { + description = import_dot['default'].compile(description); + } + return _extends({}, a2, { + help: help || a2.help, + description: description || a2.description + }); + }; + var mergeFailureMessage = function mergeFailureMessage(a2, b2) { + var failureMessage = b2.failureMessage; + if (typeof failureMessage === 'string' && dotRegex.test(failureMessage)) { + failureMessage = import_dot['default'].compile(failureMessage); + } + return _extends({}, a2, { + failureMessage: failureMessage || a2.failureMessage + }); + }; + var mergeFallbackMessage = function mergeFallbackMessage(a2, b2) { + if (typeof b2 === 'string' && dotRegex.test(b2)) { + b2 = import_dot['default'].compile(b2); + } + return b2 || a2; + }; + function getRulesToRun(rules, context, options) { + var base = { + now: [], + later: [] + }; + var splitRules = rules.reduce(function(out, rule) { + if (!rule_should_run_default(rule, context, options)) { + return out; + } + if (rule.preload) { + out.later.push(rule); + return out; + } + out.now.push(rule); + return out; + }, base); + return splitRules; + } + function getDefferedRule(rule, context, options) { + if (options.performanceTimer) { + performance_timer_default.mark('mark_rule_start_' + rule.id); + } + return function(resolve, reject) { + rule.run(context, options, function(ruleResult) { + return resolve(ruleResult); + }, function(err2) { + if (options.debug) { + reject(err2); + } else { + resolve(createIncompleteErrorResult(rule, err2)); + } + }); + }; + } + function createIncompleteErrorResult(rule, error) { + var errorNode = error.errorNode; + var serialError = _serializeError(error); + var none = [ { + id: 'error-occurred', + result: void 0, + data: serialError, + relatedNodes: [] + } ]; + var node = errorNode || new dq_element_default(document.documentElement); + return Object.assign(new rule_result_default(rule), { + error: serialError, + result: constants_default.CANTTELL, + nodes: [ { + any: [], + all: [], + none: none, + node: node + } ] + }); + } + function getHelpUrl(_ref145, ruleId, version) { + var brand = _ref145.brand, application = _ref145.application, lang = _ref145.lang; + return constants_default.helpUrlBase + brand + '/' + (version || axe.version.substring(0, axe.version.lastIndexOf('.'))) + '/' + ruleId + '?application=' + encodeURIComponent(application) + (lang && lang !== 'en' ? '&lang=' + encodeURIComponent(lang) : ''); + } + function setupGlobals(context) { + var hasWindow = window && 'Node' in window && 'NodeList' in window; + var hasDoc = !!document; + if (hasWindow && hasDoc) { + return; + } + if (!context || !context.ownerDocument) { + throw new Error('Required "window" or "document" globals not defined and cannot be deduced from the context. Either set the globals before running or pass in a valid Element.'); + } + if (!hasDoc) { + cache_default.set('globalDocumentSet', true); + document = context.ownerDocument; + } + if (!hasWindow) { + cache_default.set('globalWindowSet', true); + window = document.defaultView; + } + } + function resetGlobals() { + if (cache_default.get('globalDocumentSet')) { + cache_default.set('globalDocumentSet', false); + document = null; + } + if (cache_default.get('globalWindowSet')) { + cache_default.set('globalWindowSet', false); + window = null; + } + } + function teardown() { + resetGlobals(); + axe._memoizedFns.forEach(function(fn) { + return fn.clear(); + }); + cache_default.clear(); + axe._tree = void 0; + axe._selectorData = void 0; + axe._selectCache = void 0; + } + var teardown_default = teardown; + function runRules(context, options, resolve, reject) { + try { + context = new Context(context); + axe._tree = context.flatTree; + axe._selectorData = _getSelectorData(context.flatTree); + } catch (e) { + teardown_default(); + return reject(e); + } + var q = queue_default(); + var audit = axe._audit; + if (options.performanceTimer) { + performance_timer_default.auditStart(); + } + if (context.frames.length && options.iframes !== false) { + q.defer(function(res, rej) { + _collectResultsFromFrames(context, options, 'rules', null, res, rej); + }); + } + q.defer(function(res, rej) { + audit.run(context, options, res, rej); + }); + q.then(function(data) { + try { + if (options.performanceTimer) { + performance_timer_default.auditEnd(); + } + var results = merge_results_default(data.map(function(res) { + return { + results: res + }; + })); + if (context.initiator) { + if (options.performanceTimer) { + performance_timer_default.mark('auditAfterStart'); + } + results = audit.after(results, options); + if (options.performanceTimer) { + performance_timer_default.mark('auditAfterEnd'); + performance_timer_default.measure('audit.after', 'auditAfterStart', 'auditAfterEnd'); + performance_timer_default.logMeasures('audit.after'); + } + results.forEach(_publishMetaData); + results = results.map(_finalizeRuleResult); + } + try { + resolve(results, teardown_default); + } catch (e) { + teardown_default(); + log_default(e); + } + } catch (e) { + teardown_default(); + reject(e); + } + })['catch'](function(e) { + teardown_default(); + reject(e); + }); + } + function load(audit) { + axe._audit = new audit_default(audit); + } + function runCommand(data, keepalive, callback) { + var resolve = callback; + var reject = function reject2(err2) { + if (err2 instanceof Error === false) { + err2 = new Error(err2); + } + callback(err2); + }; + var context = data && data.context || {}; + if (context.hasOwnProperty('include') && !context.include.length) { + context.include = [ document ]; + } + var options = data && data.options || {}; + switch (data.command) { + case 'rules': + return runRules(context, options, function(results, cleanupFn) { + results = node_serializer_default.mapRawResults(results); + resolve(results); + cleanupFn(); + }, reject); + + case 'cleanup-plugin': + return cleanup_default(resolve, reject); + + default: + if (axe._audit && axe._audit.commands && axe._audit.commands[data.command]) { + return axe._audit.commands[data.command](data, callback); + } + } + } + if (window.top !== window) { + _respondable.subscribe('axe.start', runCommand); + _respondable.subscribe('axe.ping', function(data, keepalive, respond) { + respond({ + axe: true + }); + }); + } + function Plugin(spec) { + this._run = spec.run; + this._collect = spec.collect; + this._registry = {}; + spec.commands.forEach(function(command) { + axe._audit.registerCommand(command); + }); + } + Plugin.prototype.run = function run3() { + return this._run.apply(this, arguments); + }; + Plugin.prototype.collect = function collect() { + return this._collect.apply(this, arguments); + }; + Plugin.prototype.cleanup = function cleanup2(done) { + var q = axe.utils.queue(); + var that = this; + Object.keys(this._registry).forEach(function(key) { + q.defer(function(_done) { + that._registry[key].cleanup(_done); + }); + }); + q.then(done); + }; + Plugin.prototype.add = function add(impl) { + this._registry[impl.id] = impl; + }; + function registerPlugin(plugin) { + axe.plugins[plugin.id] = new Plugin(plugin); + } + var plugins_default = registerPlugin; + function reset() { + var audit = axe._audit; + if (!audit) { + throw new Error('No audit configured'); + } + audit.resetRulesAndChecks(); + resetStandards(); + } + var reset_default = reset; + function runVirtualRule(ruleId, vNode) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + options.reporter = options.reporter || axe._audit.reporter || 'v1'; + axe._selectorData = {}; + if (!(vNode instanceof abstract_virtual_node_default)) { + vNode = new serial_virtual_node_default(vNode); + } + var rule = _getRule(ruleId); + if (!rule) { + throw new Error('unknown rule `' + ruleId + '`'); + } + rule = Object.create(rule, { + excludeHidden: { + value: false + } + }); + var context = { + initiator: true, + include: [ vNode ], + exclude: [], + frames: [], + page: false, + focusable: true, + size: {}, + flatTree: [] + }; + var rawResults = rule.runSync(context, options); + _publishMetaData(rawResults); + _finalizeRuleResult(rawResults); + var results = aggregate_result_default([ rawResults ]); + results.violations.forEach(function(result) { + return result.nodes.forEach(function(nodeResult) { + nodeResult.failureSummary = failure_summary_default(nodeResult); + }); + }); + return _extends({}, _getEnvironmentData(), results, { + toolOptions: options + }); + } + function normalizeRunParams(_ref146) { + var _ref148, _options$reporter, _axe$_audit; + var _ref147 = _slicedToArray(_ref146, 3), context = _ref147[0], options = _ref147[1], callback = _ref147[2]; + var typeErr = new TypeError('axe.run arguments are invalid'); + if (!_isContextSpec(context)) { + if (callback !== void 0) { + throw typeErr; + } + callback = options; + options = context; + context = document; + } + if (_typeof(options) !== 'object') { + if (callback !== void 0) { + throw typeErr; + } + callback = options; + options = {}; + } + if (typeof callback !== 'function' && callback !== void 0) { + throw typeErr; + } + options = clone2(options); + options.reporter = (_ref148 = (_options$reporter = options.reporter) !== null && _options$reporter !== void 0 ? _options$reporter : (_axe$_audit = axe._audit) === null || _axe$_audit === void 0 ? void 0 : _axe$_audit.reporter) !== null && _ref148 !== void 0 ? _ref148 : 'v1'; + return { + context: context, + options: options, + callback: callback + }; + } + var noop2 = function noop2() {}; + function run4() { + for (var _len8 = arguments.length, args = new Array(_len8), _key10 = 0; _key10 < _len8; _key10++) { + args[_key10] = arguments[_key10]; + } + setupGlobals(args[0]); + var _normalizeRunParams = normalizeRunParams(args), context = _normalizeRunParams.context, options = _normalizeRunParams.options, _normalizeRunParams$c = _normalizeRunParams.callback, callback = _normalizeRunParams$c === void 0 ? noop2 : _normalizeRunParams$c; + var _getPromiseHandlers = getPromiseHandlers(callback), thenable = _getPromiseHandlers.thenable, resolve = _getPromiseHandlers.resolve, reject = _getPromiseHandlers.reject; + try { + assert_default(axe._audit, 'No audit configured'); + assert_default(!axe._running, 'Axe is already running. Use `await axe.run()` to wait for the previous run to finish before starting a new run.'); + } catch (e) { + return handleError(e, callback); + } + axe._running = true; + if (options.performanceTimer) { + performance_timer_default.start(); + } + function handleRunRules(rawResults, teardown2) { + var respond = function respond(results) { + if (options.performanceTimer) { + performance_timer_default.mark('reporterEnd'); + performance_timer_default.measure('reporter', 'reporterStart', 'reporterEnd'); + performance_timer_default.logMeasures('reporter'); + performance_timer_default.end(); + } + axe._running = false; + teardown2(); + try { + resolve(results); + } catch (e) { + axe.log(e); + } + }; + var wrappedReject = function wrappedReject(err2) { + axe._running = false; + teardown2(); + try { + reject(err2); + } catch (e) { + axe.log(e); + } + }; + try { + if (options.performanceTimer) { + performance_timer_default.mark('reporterStart'); + } + createReport(rawResults, options, respond, wrappedReject); + } catch (err2) { + wrappedReject(err2); + } + } + function errorRunRules(err2) { + if (options.performanceTimer) { + performance_timer_default.end(); + } + axe._running = false; + callback(err2); + reject(err2); + } + axe._runRules(context, options, handleRunRules, errorRunRules); + return thenable; + } + function getPromiseHandlers(callback) { + var thenable, reject, resolve; + if (typeof Promise === 'function' && callback === noop2) { + thenable = new Promise(function(_resolve, _reject) { + reject = _reject; + resolve = _resolve; + }); + } else { + resolve = function resolve(result) { + return callback(null, result); + }; + reject = function reject(err2) { + return callback(err2); + }; + } + return { + thenable: thenable, + reject: reject, + resolve: resolve + }; + } + function createReport(rawResults, options, respond, reject) { + var reporter = getReporter(options.reporter); + var results = reporter(rawResults, options, respond, reject); + if (results !== void 0) { + respond(results); + } + } + function handleError(err2, callback) { + if (typeof callback === 'function' && callback !== noop2) { + callback(err2.message); + return; + } + throw err2; + } + function runPartial() { + for (var _len9 = arguments.length, args = new Array(_len9), _key11 = 0; _key11 < _len9; _key11++) { + args[_key11] = arguments[_key11]; + } + var _normalizeRunParams2 = normalizeRunParams(args), options = _normalizeRunParams2.options, context = _normalizeRunParams2.context; + assert_default(axe._audit, 'Axe is not configured. Audit is missing.'); + assert_default(!axe._running, 'Axe is already running. Use `await axe.run()` to wait for the previous run to finish before starting a new run.'); + var contextObj = new Context(context, axe._tree); + axe._tree = contextObj.flatTree; + axe._selectorData = _getSelectorData(contextObj.flatTree); + axe._running = true; + options.elementRef = false; + return new Promise(function(res, rej) { + axe._audit.run(contextObj, options, res, rej); + }).then(function(results) { + results = node_serializer_default.mapRawResults(results); + var frames = contextObj.frames.map(function(_ref149) { + var node = _ref149.node; + return node_serializer_default.toSpec(node); + }); + var environmentData; + if (contextObj.initiator) { + environmentData = _getEnvironmentData(); + } + axe._running = false; + teardown_default(); + return { + results: results, + frames: frames, + environmentData: environmentData + }; + })['catch'](function(err2) { + axe._running = false; + teardown_default(); + return Promise.reject(err2); + }); + } + function finishRun(partialResults) { + var _ref151, _options$reporter2, _axe$_audit2; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options = clone2(options); + var _ref150 = partialResults.find(function(r) { + return r.environmentData; + }) || {}, environmentData = _ref150.environmentData; + axe._audit.normalizeOptions(options); + options.reporter = (_ref151 = (_options$reporter2 = options.reporter) !== null && _options$reporter2 !== void 0 ? _options$reporter2 : (_axe$_audit2 = axe._audit) === null || _axe$_audit2 === void 0 ? void 0 : _axe$_audit2.reporter) !== null && _ref151 !== void 0 ? _ref151 : 'v1'; + setFrameSpec(partialResults); + var results = merge_results_default(partialResults); + results = axe._audit.after(results, options); + results.forEach(_publishMetaData); + results = results.map(_finalizeRuleResult); + return createReport2(results, _extends({ + environmentData: environmentData + }, options)); + } + function setFrameSpec(partialResults) { + var frameStack = []; + var _iterator25 = _createForOfIteratorHelper(partialResults), _step25; + try { + for (_iterator25.s(); !(_step25 = _iterator25.n()).done; ) { + var partialResult = _step25.value; + var frameSpec = frameStack.shift(); + if (!partialResult) { + continue; + } + partialResult.frameSpec = frameSpec !== null && frameSpec !== void 0 ? frameSpec : null; + var frameSpecs = getMergedFrameSpecs(partialResult); + frameStack.unshift.apply(frameStack, _toConsumableArray(frameSpecs)); + } + } catch (err) { + _iterator25.e(err); + } finally { + _iterator25.f(); + } + } + function getMergedFrameSpecs(_ref152) { + var childFrameSpecs = _ref152.frames, parentFrameSpec = _ref152.frameSpec; + if (!parentFrameSpec) { + return childFrameSpecs; + } + return childFrameSpecs.map(function(childFrameSpec) { + return node_serializer_default.mergeSpecs(childFrameSpec, parentFrameSpec); + }); + } + function createReport2(results, options) { + return new Promise(function(resolve, reject) { + var reporter = getReporter(options.reporter); + reporter(results, options, resolve, reject); + }); + } + function setup(node) { + if (axe._tree) { + throw new Error('Axe is already setup. Call `axe.teardown()` before calling `axe.setup` again.'); + } + if (node && _typeof(node.documentElement) === 'object' && _typeof(node.defaultView) === 'object') { + node = node.documentElement; + } + setupGlobals(node); + axe._tree = _getFlattenedTree(node); + axe._selectorData = _getSelectorData(axe._tree); + return axe._tree[0]; + } + var setup_default = setup; + var naReporter = function naReporter(results, options, callback) { + console.warn('"na" reporter will be deprecated in axe v4.0. Use the "v2" reporter instead.'); + if (typeof options === 'function') { + callback = options; + options = {}; + } + var _options3 = options, environmentData = _options3.environmentData, toolOptions = _objectWithoutProperties(_options3, _excluded13); + callback(_extends({}, _getEnvironmentData(environmentData), { + toolOptions: toolOptions + }, processAggregate(results, options))); + }; + var na_default = naReporter; + var noPassesReporter = function noPassesReporter(results, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + var _options4 = options, environmentData = _options4.environmentData, toolOptions = _objectWithoutProperties(_options4, _excluded14); + options.resultTypes = [ 'violations' ]; + var _processAggregate = processAggregate(results, options), violations = _processAggregate.violations; + callback(_extends({}, _getEnvironmentData(environmentData), { + toolOptions: toolOptions, + violations: violations + })); + }; + var no_passes_default = noPassesReporter; + var rawReporter = function rawReporter(results, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (!results || !Array.isArray(results)) { + return callback(results); + } + var transformedResults = results.map(function(result) { + var transformedResult = _extends({}, result); + var types = [ 'passes', 'violations', 'incomplete', 'inapplicable' ]; + for (var _i42 = 0, _types = types; _i42 < _types.length; _i42++) { + var type2 = _types[_i42]; + transformedResult[type2] = node_serializer_default.mapRawNodeResults(transformedResult[type2]); + } + return transformedResult; + }); + callback(transformedResults); + }; + var raw_default = rawReporter; + var rawEnvReporter = function rawEnvReporter(results, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + var _options5 = options, environmentData = _options5.environmentData, toolOptions = _objectWithoutProperties(_options5, _excluded15); + raw_default(results, toolOptions, function(raw) { + var env = _getEnvironmentData(environmentData); + callback({ + raw: raw, + env: env + }); + }); + }; + var raw_env_default = rawEnvReporter; + var v1Reporter = function v1Reporter(results, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + var _options6 = options, environmentData = _options6.environmentData, toolOptions = _objectWithoutProperties(_options6, _excluded16); + var out = processAggregate(results, options); + var addFailureSummaries = function addFailureSummaries(result) { + result.nodes.forEach(function(nodeResult) { + nodeResult.failureSummary = failure_summary_default(nodeResult); + }); + }; + out.incomplete.forEach(addFailureSummaries); + out.violations.forEach(addFailureSummaries); + callback(_extends({}, _getEnvironmentData(environmentData), { + toolOptions: toolOptions + }, out)); + }; + var v1_default = v1Reporter; + var v2Reporter = function v2Reporter(results, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + var _options7 = options, environmentData = _options7.environmentData, toolOptions = _objectWithoutProperties(_options7, _excluded17); + var out = processAggregate(results, options); + callback(_extends({}, _getEnvironmentData(environmentData), { + toolOptions: toolOptions + }, out)); + }; + var v2_default = v2Reporter; + var _thisWillBeDeletedDoNotUse = { + base: { + Audit: audit_default, + CheckResult: check_result_default, + Check: check_default, + Context: Context, + RuleResult: rule_result_default, + Rule: Rule, + metadataFunctionMap: metadata_function_map_default + }, + public: { + reporters: reporters + }, + helpers: { + failureSummary: failure_summary_default, + incompleteFallbackMessage: incompleteFallbackMessage, + processAggregate: processAggregate + }, + utils: { + setDefaultFrameMessenger: setDefaultFrameMessenger, + cacheNodeSelectors: cacheNodeSelectors, + getNodesMatchingExpression: getNodesMatchingExpression, + convertSelector: _convertSelector + }, + commons: { + dom: { + nativelyHidden: nativelyHidden, + displayHidden: displayHidden, + visibilityHidden: visibilityHidden, + contentVisibiltyHidden: contentVisibiltyHidden, + ariaHidden: ariaHidden, + opacityHidden: opacityHidden, + scrollHidden: scrollHidden, + overflowHidden: overflowHidden, + clipHidden: clipHidden, + areaHidden: areaHidden, + detailsHidden: detailsHidden + } + } + }; + var exposed_for_testing_default = _thisWillBeDeletedDoNotUse; + axe._thisWillBeDeletedDoNotUse = exposed_for_testing_default; + axe.constants = constants_default; + axe.log = log_default; + axe.AbstractVirtualNode = abstract_virtual_node_default; + axe.SerialVirtualNode = serial_virtual_node_default; + axe.VirtualNode = virtual_node_default; + axe._cache = cache_default; + axe.imports = imports_exports; + axe.cleanup = cleanup_default; + axe.configure = configure_default; + axe.frameMessenger = frameMessenger2; + axe.getRules = get_rules_default; + axe._load = load; + axe.plugins = {}; + axe.registerPlugin = plugins_default; + axe.hasReporter = hasReporter; + axe.getReporter = getReporter; + axe.addReporter = addReporter; + axe.reset = reset_default; + axe._runRules = runRules; + axe.runVirtualRule = runVirtualRule; + axe.run = run4; + axe.setup = setup_default; + axe.teardown = teardown_default; + axe.runPartial = runPartial; + axe.finishRun = finishRun; + axe.commons = commons_exports; + axe.utils = utils_exports; + axe.addReporter('na', na_default); + axe.addReporter('no-passes', no_passes_default); + axe.addReporter('rawEnv', raw_env_default); + axe.addReporter('raw', raw_default); + axe.addReporter('v1', v1_default); + axe.addReporter('v2', v2_default, true); + })(); + 'use strict'; + axe._load({ + lang: 'en', + data: { + rules: { + accesskeys: { + description: 'Ensure every accesskey attribute value is unique', + help: 'accesskey attribute value should be unique' + }, + 'area-alt': { + description: 'Ensure elements of image maps have alternative text', + help: 'Active elements must have alternative text' + }, + 'aria-allowed-attr': { + description: 'Ensure an element\'s role supports its ARIA attributes', + help: 'Elements must only use supported ARIA attributes' + }, + 'aria-allowed-role': { + description: 'Ensure role attribute has an appropriate value for the element', + help: 'ARIA role should be appropriate for the element' + }, + 'aria-braille-equivalent': { + description: 'Ensure aria-braillelabel and aria-brailleroledescription have a non-braille equivalent', + help: 'aria-braille attributes must have a non-braille equivalent' + }, + 'aria-command-name': { + description: 'Ensure every ARIA button, link and menuitem has an accessible name', + help: 'ARIA commands must have an accessible name' + }, + 'aria-conditional-attr': { + description: 'Ensure ARIA attributes are used as described in the specification of the element\'s role', + help: 'ARIA attributes must be used as specified for the element\'s role' + }, + 'aria-deprecated-role': { + description: 'Ensure elements do not use deprecated roles', + help: 'Deprecated ARIA roles must not be used' + }, + 'aria-dialog-name': { + description: 'Ensure every ARIA dialog and alertdialog node has an accessible name', + help: 'ARIA dialog and alertdialog nodes should have an accessible name' + }, + 'aria-hidden-body': { + description: 'Ensure aria-hidden="true" is not present on the document body.', + help: 'aria-hidden="true" must not be present on the document body' + }, + 'aria-hidden-focus': { + description: 'Ensure aria-hidden elements are not focusable nor contain focusable elements', + help: 'ARIA hidden element must not be focusable or contain focusable elements' + }, + 'aria-input-field-name': { + description: 'Ensure every ARIA input field has an accessible name', + help: 'ARIA input fields must have an accessible name' + }, + 'aria-meter-name': { + description: 'Ensure every ARIA meter node has an accessible name', + help: 'ARIA meter nodes must have an accessible name' + }, + 'aria-progressbar-name': { + description: 'Ensure every ARIA progressbar node has an accessible name', + help: 'ARIA progressbar nodes must have an accessible name' + }, + 'aria-prohibited-attr': { + description: 'Ensure ARIA attributes are not prohibited for an element\'s role', + help: 'Elements must only use permitted ARIA attributes' + }, + 'aria-required-attr': { + description: 'Ensure elements with ARIA roles have all required ARIA attributes', + help: 'Required ARIA attributes must be provided' + }, + 'aria-required-children': { + description: 'Ensure elements with an ARIA role that require child roles contain them', + help: 'Certain ARIA roles must contain particular children' + }, + 'aria-required-parent': { + description: 'Ensure elements with an ARIA role that require parent roles are contained by them', + help: 'Certain ARIA roles must be contained by particular parents' + }, + 'aria-roledescription': { + description: 'Ensure aria-roledescription is only used on elements with an implicit or explicit role', + help: 'aria-roledescription must be on elements with a semantic role' + }, + 'aria-roles': { + description: 'Ensure all elements with a role attribute use a valid value', + help: 'ARIA roles used must conform to valid values' + }, + 'aria-text': { + description: 'Ensure role="text" is used on elements with no focusable descendants', + help: '"role=text" should have no focusable descendants' + }, + 'aria-toggle-field-name': { + description: 'Ensure every ARIA toggle field has an accessible name', + help: 'ARIA toggle fields must have an accessible name' + }, + 'aria-tooltip-name': { + description: 'Ensure every ARIA tooltip node has an accessible name', + help: 'ARIA tooltip nodes must have an accessible name' + }, + 'aria-treeitem-name': { + description: 'Ensure every ARIA treeitem node has an accessible name', + help: 'ARIA treeitem nodes should have an accessible name' + }, + 'aria-valid-attr-value': { + description: 'Ensure all ARIA attributes have valid values', + help: 'ARIA attributes must conform to valid values' + }, + 'aria-valid-attr': { + description: 'Ensure attributes that begin with aria- are valid ARIA attributes', + help: 'ARIA attributes must conform to valid names' + }, + 'audio-caption': { + description: 'Ensure