From 69ce50396c94ab636c480a18259e667584b0bf5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Tue, 31 May 2022 15:57:50 +0200 Subject: [PATCH 01/96] doc: use serial comma in console docs Refs: https://github.com/nodejs/node/pull/11321 Refs: https://github.com/nodejs/node/pull/17384 PR-URL: https://github.com/nodejs/node/pull/43257 Reviewed-By: Darshan Sen Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Luigi Pinca --- doc/api/console.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/console.md b/doc/api/console.md index 3c81a5784e2fbc..1818d6f776b9f5 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -11,7 +11,7 @@ the JavaScript console mechanism provided by web browsers. The module exports two specific components: -* A `Console` class with methods such as `console.log()`, `console.error()` and +* A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`][] and [`process.stderr`][]. The global `console` can be used without calling From b3d7dc1de88757b05e7de5428426177d5e885e0a Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Wed, 1 Jun 2022 15:53:55 +0530 Subject: [PATCH 02/96] tools: update clang-format 1.7.0 to 1.8.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v1.7.0 was shipping ARM64 binaries for macOS which doesn't run on Intel Macs. v1.8.0 moved back to x86_64 binaries which works on both Intel and M1 Macs. Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/43241 Reviewed-By: Tobias Nießen Reviewed-By: Rich Trott Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Luigi Pinca --- tools/clang-format/package-lock.json | 14 +++++++------- tools/clang-format/package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/clang-format/package-lock.json b/tools/clang-format/package-lock.json index 1a080a750eaf86..537314a7cb6727 100644 --- a/tools/clang-format/package-lock.json +++ b/tools/clang-format/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "MIT", "dependencies": { - "clang-format": "^1.7.0" + "clang-format": "^1.8.0" } }, "node_modules/async": { @@ -32,9 +32,9 @@ } }, "node_modules/clang-format": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.7.0.tgz", - "integrity": "sha512-BNuK+rXAK/Fk0rOQ1DW6bpSQUAZz6tpbZHTQn6m4PsgEkE1SNr6AQ/hhFK/b4KJrl4zjcl68molP+rEaKSZRAQ==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.8.0.tgz", + "integrity": "sha512-pK8gzfu55/lHzIpQ1givIbWfn3eXnU7SfxqIwVgnn5jEM6j4ZJYjpFqFs4iSBPNedzRMmfjYjuQhu657WAXHXw==", "dependencies": { "async": "^3.2.3", "glob": "^7.0.0", @@ -202,9 +202,9 @@ } }, "clang-format": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.7.0.tgz", - "integrity": "sha512-BNuK+rXAK/Fk0rOQ1DW6bpSQUAZz6tpbZHTQn6m4PsgEkE1SNr6AQ/hhFK/b4KJrl4zjcl68molP+rEaKSZRAQ==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/clang-format/-/clang-format-1.8.0.tgz", + "integrity": "sha512-pK8gzfu55/lHzIpQ1givIbWfn3eXnU7SfxqIwVgnn5jEM6j4ZJYjpFqFs4iSBPNedzRMmfjYjuQhu657WAXHXw==", "requires": { "async": "^3.2.3", "glob": "^7.0.0", diff --git a/tools/clang-format/package.json b/tools/clang-format/package.json index 50454249b52c10..4ae7d36a33c90e 100644 --- a/tools/clang-format/package.json +++ b/tools/clang-format/package.json @@ -4,6 +4,6 @@ "description": "Formatting C++ files for Node.js core", "license": "MIT", "dependencies": { - "clang-format": "^1.7.0" + "clang-format": "^1.8.0" } } From f93848fa501bbe2c0515f70fab434eb35780d934 Mon Sep 17 00:00:00 2001 From: "Node.js GitHub Bot" Date: Tue, 31 May 2022 09:11:30 +0000 Subject: [PATCH 03/96] tools: update lint-md-dependencies to rollup@2.75.3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43261 Reviewed-By: Rich Trott Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Darshan Sen Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca --- tools/lint-md/package-lock.json | 22 +++++++++++----------- tools/lint-md/package.json | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tools/lint-md/package-lock.json b/tools/lint-md/package-lock.json index d9ce2a13a5e2dc..d6ad8f4cd98175 100644 --- a/tools/lint-md/package-lock.json +++ b/tools/lint-md/package-lock.json @@ -18,7 +18,7 @@ "devDependencies": { "@rollup/plugin-commonjs": "^22.0.0", "@rollup/plugin-node-resolve": "^13.3.0", - "rollup": "^2.75.1", + "rollup": "^2.75.3", "rollup-plugin-cleanup": "^3.2.1" } }, @@ -387,7 +387,7 @@ "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "dev": true, "dependencies": { "once": "^1.3.0", @@ -449,7 +449,7 @@ "node_modules/is-module": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", - "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", "dev": true }, "node_modules/is-plain-obj": { @@ -2209,9 +2209,9 @@ } }, "node_modules/rollup": { - "version": "2.75.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.75.1.tgz", - "integrity": "sha512-zD73rq3Fanr/spmiybMqmGEvOpryj/heLqOb+lubxiXlo8azeJ/z306T2dJYuzfWZPQBS0OT++GXG6Lbd4ToKw==", + "version": "2.75.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.75.3.tgz", + "integrity": "sha512-YA29fLU6MAYSaDxIQYrGGOcbXlDmG96h0krGGYObroezcQ0KgEPM3+7MtKD/qeuUbFuAJXvKZee5dA1dpwq1PQ==", "dev": true, "bin": { "rollup": "dist/bin/rollup" @@ -2932,7 +2932,7 @@ "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "dev": true, "requires": { "once": "^1.3.0", @@ -2971,7 +2971,7 @@ "is-module": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", - "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", "dev": true }, "is-plain-obj": { @@ -4199,9 +4199,9 @@ } }, "rollup": { - "version": "2.75.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.75.1.tgz", - "integrity": "sha512-zD73rq3Fanr/spmiybMqmGEvOpryj/heLqOb+lubxiXlo8azeJ/z306T2dJYuzfWZPQBS0OT++GXG6Lbd4ToKw==", + "version": "2.75.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.75.3.tgz", + "integrity": "sha512-YA29fLU6MAYSaDxIQYrGGOcbXlDmG96h0krGGYObroezcQ0KgEPM3+7MtKD/qeuUbFuAJXvKZee5dA1dpwq1PQ==", "dev": true, "requires": { "fsevents": "~2.3.2" diff --git a/tools/lint-md/package.json b/tools/lint-md/package.json index d7e65b39f82e02..cb204d6c07f6df 100644 --- a/tools/lint-md/package.json +++ b/tools/lint-md/package.json @@ -16,7 +16,7 @@ "devDependencies": { "@rollup/plugin-commonjs": "^22.0.0", "@rollup/plugin-node-resolve": "^13.3.0", - "rollup": "^2.75.1", + "rollup": "^2.75.3", "rollup-plugin-cleanup": "^3.2.1" } } From 5a3a2a197fc77dd7a69670c97e6c1b1421ace13d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Wed, 1 Jun 2022 21:49:45 +0200 Subject: [PATCH 04/96] doc: add src/crypto to CC list for nodejs/crypto PR-URL: https://github.com/nodejs/node/pull/43286 Reviewed-By: Richard Lau Reviewed-By: Akhil Marsonya Reviewed-By: Luigi Pinca Reviewed-By: Antoine du Hamel --- doc/contributing/collaborator-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/contributing/collaborator-guide.md b/doc/contributing/collaborator-guide.md index 05b02f02192b03..5de13b79236b9e 100644 --- a/doc/contributing/collaborator-guide.md +++ b/doc/contributing/collaborator-guide.md @@ -815,7 +815,7 @@ might impact an LTS release. | `lib/zlib` | @nodejs/zlib | | `src/async_wrap.*` | @nodejs/async\_hooks | | `src/node_api.*` | @nodejs/node-api | -| `src/node_crypto.*` | @nodejs/crypto | +| `src/node_crypto.*`, `src/crypto` | @nodejs/crypto | | `test/*` | @nodejs/testing | | `tools/node_modules/eslint`, `.eslintrc` | @nodejs/linting | | build | @nodejs/build | From acd96d80eb0e8dbd04ff9faec02b42e2be97785e Mon Sep 17 00:00:00 2001 From: Livia Medeiros <74449973+LiviaMedeiros@users.noreply.github.com> Date: Thu, 2 Jun 2022 06:07:33 +0800 Subject: [PATCH 05/96] test: add `BigInt`s to `common.getArrayBufferViews()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43235 Reviewed-By: Michaël Zasso Reviewed-By: Luigi Pinca Reviewed-By: Darshan Sen Reviewed-By: Colin Ihrig Reviewed-By: Tobias Nießen --- test/common/index.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/common/index.js b/test/common/index.js index d2b23a6570f562..dbe40712862985 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -680,6 +680,8 @@ function getArrayBufferViews(buf) { Uint32Array, Float32Array, Float64Array, + BigInt64Array, + BigUint64Array, DataView, ]; From ee392c5c0b63a468a6d2796e02002d7b09d52c37 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Thu, 2 Jun 2022 14:42:30 +0200 Subject: [PATCH 06/96] doc: update CHANGELOG_V18.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43298 Reviewed-By: Antoine du Hamel Reviewed-By: Michaël Zasso Reviewed-By: Tobias Nießen --- doc/changelogs/CHANGELOG_V18.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/changelogs/CHANGELOG_V18.md b/doc/changelogs/CHANGELOG_V18.md index 96c6c43f1a6612..75c9cf9970192b 100644 --- a/doc/changelogs/CHANGELOG_V18.md +++ b/doc/changelogs/CHANGELOG_V18.md @@ -8,6 +8,7 @@ +18.3.0
18.2.0
18.1.0
18.0.0
From 10f79947d965f5a37b576dad193c05df94685521 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Thu, 2 Jun 2022 11:33:01 +0200 Subject: [PATCH 07/96] tools: update `codecov/codecov-action` version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: https://github.com/codecov/codecov-action/releases PR-URL: https://github.com/nodejs/node/pull/43297 Reviewed-By: Michaël Zasso Reviewed-By: Filip Skokan --- .github/workflows/coverage-linux.yml | 2 +- .github/workflows/coverage-windows.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coverage-linux.yml b/.github/workflows/coverage-linux.yml index ddc7be8b507557..77bad80cc269d5 100644 --- a/.github/workflows/coverage-linux.yml +++ b/.github/workflows/coverage-linux.yml @@ -60,6 +60,6 @@ jobs: - name: Clean tmp run: rm -rf coverage/tmp && rm -rf out - name: Upload - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 with: directory: ./coverage diff --git a/.github/workflows/coverage-windows.yml b/.github/workflows/coverage-windows.yml index dde4f30f8f2909..29e7ac689a2043 100644 --- a/.github/workflows/coverage-windows.yml +++ b/.github/workflows/coverage-windows.yml @@ -61,6 +61,6 @@ jobs: - name: Clean tmp run: npx rimraf ./coverage/tmp - name: Upload - uses: codecov/codecov-action@v1 + uses: codecov/codecov-action@v3 with: directory: ./coverage From 5e65c1f3da74a8c33ca009b5be1fd9baa2ade082 Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Thu, 2 Jun 2022 21:08:52 +0530 Subject: [PATCH 08/96] src: convey potential exceptions during StreamPipe construction This moves the V8 calls during the StreamPipe construction to an overload of StreamPipe::New(), so that it is possible to indicate if there is a pending exception/termination. Refs: https://github.com/nodejs/node/pull/40425#discussion_r726975901 Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/43240 Reviewed-By: Anna Henningsen Reviewed-By: Minwoo Jung --- src/stream_pipe.cc | 62 +++++++++++++++++++++++++++------------------- src/stream_pipe.h | 7 +++--- 2 files changed, 39 insertions(+), 30 deletions(-) diff --git a/src/stream_pipe.cc b/src/stream_pipe.cc index 94ba8604bd76c6..93b7ffeca9cd53 100644 --- a/src/stream_pipe.cc +++ b/src/stream_pipe.cc @@ -11,7 +11,10 @@ using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; +using v8::Just; using v8::Local; +using v8::Maybe; +using v8::Nothing; using v8::Object; using v8::Value; @@ -28,31 +31,6 @@ StreamPipe::StreamPipe(StreamBase* source, sink->PushStreamListener(&writable_listener_); uses_wants_write_ = sink->HasWantsWrite(); - - // Set up links between this object and the source/sink objects. - // In particular, this makes sure that they are garbage collected as a group, - // if that applies to the given streams (for example, Http2Streams use - // weak references). - if (obj->Set(env()->context(), - env()->source_string(), - source->GetObject()).IsNothing()) { - return; - } - if (source->GetObject()->Set(env()->context(), - env()->pipe_target_string(), - obj).IsNothing()) { - return; - } - if (obj->Set(env()->context(), - env()->sink_string(), - sink->GetObject()).IsNothing()) { - return; - } - if (sink->GetObject()->Set(env()->context(), - env()->pipe_source_string(), - obj).IsNothing()) { - return; - } } StreamPipe::~StreamPipe() { @@ -261,6 +239,38 @@ void StreamPipe::WritableListener::OnStreamRead(ssize_t nread, return previous_listener_->OnStreamRead(nread, buf); } +Maybe StreamPipe::New(StreamBase* source, + StreamBase* sink, + Local obj) { + std::unique_ptr stream_pipe(new StreamPipe(source, sink, obj)); + + // Set up links between this object and the source/sink objects. + // In particular, this makes sure that they are garbage collected as a group, + // if that applies to the given streams (for example, Http2Streams use + // weak references). + Environment* env = source->stream_env(); + if (obj->Set(env->context(), env->source_string(), source->GetObject()) + .IsNothing()) { + return Nothing(); + } + if (source->GetObject() + ->Set(env->context(), env->pipe_target_string(), obj) + .IsNothing()) { + return Nothing(); + } + if (obj->Set(env->context(), env->sink_string(), sink->GetObject()) + .IsNothing()) { + return Nothing(); + } + if (sink->GetObject() + ->Set(env->context(), env->pipe_source_string(), obj) + .IsNothing()) { + return Nothing(); + } + + return Just(stream_pipe.release()); +} + void StreamPipe::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); CHECK(args[0]->IsObject()); @@ -268,7 +278,7 @@ void StreamPipe::New(const FunctionCallbackInfo& args) { StreamBase* source = StreamBase::FromObject(args[0].As()); StreamBase* sink = StreamBase::FromObject(args[1].As()); - new StreamPipe(source, sink, args.This()); + if (StreamPipe::New(source, sink, args.This()).IsNothing()) return; } void StreamPipe::Start(const FunctionCallbackInfo& args) { diff --git a/src/stream_pipe.h b/src/stream_pipe.h index f411468294d3f0..54ca5bfdd04792 100644 --- a/src/stream_pipe.h +++ b/src/stream_pipe.h @@ -13,10 +13,9 @@ class StreamPipe : public AsyncWrap { void Unpipe(bool is_in_deletion = false); - // TODO(RaisinTen): Just like MessagePort, add the following overload: - // static StreamPipe* New(StreamBase* source, StreamBase* sink, - // v8::Local obj); - // so that we can indicate if there is a pending exception/termination. + static v8::Maybe New(StreamBase* source, + StreamBase* sink, + v8::Local obj); static void New(const v8::FunctionCallbackInfo& args); static void Start(const v8::FunctionCallbackInfo& args); static void Unpipe(const v8::FunctionCallbackInfo& args); From 8d892f52593b89e5f70d566c3fa063210860ed72 Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Thu, 2 Jun 2022 21:09:08 +0530 Subject: [PATCH 09/96] build: add nonpm and nocorepack to vcbuild.bat The `./configure` script allows you to produce a build without npm and corepack with the `--without-npm` and `--without-corepack` options respectively, so this change adds the same capability to the `vcbuild.bat` script. Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/43219 Reviewed-By: Luigi Pinca Reviewed-By: Antoine du Hamel --- vcbuild.bat | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/vcbuild.bat b/vcbuild.bat index 49fa899de7178e..1f200a6818eb6a 100644 --- a/vcbuild.bat +++ b/vcbuild.bat @@ -35,6 +35,8 @@ set projgen= set nobuild= set sign= set nosnapshot= +set nonpm= +set nocorepack= set cctest_args= set test_args= set stage_package= @@ -89,6 +91,8 @@ if /i "%1"=="nobuild" set nobuild=1&goto arg-ok if /i "%1"=="nosign" set "sign="&echo Note: vcbuild no longer signs by default. "nosign" is redundant.&goto arg-ok if /i "%1"=="sign" set sign=1&goto arg-ok if /i "%1"=="nosnapshot" set nosnapshot=1&goto arg-ok +if /i "%1"=="nonpm" set nonpm=1&goto arg-ok +if /i "%1"=="nocorepack" set nocorepack=1&goto arg-ok if /i "%1"=="noetw" set noetw=1&goto arg-ok if /i "%1"=="ltcg" set ltcg=1&goto arg-ok if /i "%1"=="licensertf" set licensertf=1&goto arg-ok @@ -184,6 +188,8 @@ if "%*"=="lint" if exist "%node_exe%" goto lint-cpp if "%config%"=="Debug" set configure_flags=%configure_flags% --debug if defined nosnapshot set configure_flags=%configure_flags% --without-snapshot +if defined nonpm set configure_flags=%configure_flags% --without-npm +if defined nocorepack set configure_flags=%configure_flags% --without-corepack if defined noetw set configure_flags=%configure_flags% --without-etw& set noetw_msi_arg=/p:NoETW=1 if defined ltcg set configure_flags=%configure_flags% --with-ltcg if defined release_urlbase set configure_flags=%configure_flags% --release-urlbase=%release_urlbase% @@ -444,22 +450,29 @@ copy /Y ..\README.md %TARGET_NAME%\ > nul if errorlevel 1 echo Cannot copy README.md && goto package_error copy /Y ..\CHANGELOG.md %TARGET_NAME%\ > nul if errorlevel 1 echo Cannot copy CHANGELOG.md && goto package_error -robocopy ..\deps\npm %TARGET_NAME%\node_modules\npm /e /xd test > nul -if errorlevel 8 echo Cannot copy npm package && goto package_error -robocopy ..\deps\corepack %TARGET_NAME%\node_modules\corepack /e /xd test > nul -if errorlevel 8 echo Cannot copy corepack package && goto package_error -copy /Y ..\deps\npm\bin\npm %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy npm && goto package_error -copy /Y ..\deps\npm\bin\npm.cmd %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy npm.cmd && goto package_error -copy /Y ..\deps\npm\bin\npx %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy npx && goto package_error -copy /Y ..\deps\npm\bin\npx.cmd %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy npx.cmd && goto package_error -copy /Y ..\deps\corepack\shims\nodewin\corepack %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy corepack && goto package_error -copy /Y ..\deps\corepack\shims\nodewin\corepack.cmd %TARGET_NAME%\ > nul -if errorlevel 1 echo Cannot copy corepack.cmd && goto package_error + +if not defined nonpm ( + robocopy ..\deps\npm %TARGET_NAME%\node_modules\npm /e /xd test > nul + if errorlevel 8 echo Cannot copy npm package && goto package_error + copy /Y ..\deps\npm\bin\npm %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy npm && goto package_error + copy /Y ..\deps\npm\bin\npm.cmd %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy npm.cmd && goto package_error + copy /Y ..\deps\npm\bin\npx %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy npx && goto package_error + copy /Y ..\deps\npm\bin\npx.cmd %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy npx.cmd && goto package_error +) + +if not defined nocorepack ( + robocopy ..\deps\corepack %TARGET_NAME%\node_modules\corepack /e /xd test > nul + if errorlevel 8 echo Cannot copy corepack package && goto package_error + copy /Y ..\deps\corepack\shims\nodewin\corepack %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy corepack && goto package_error + copy /Y ..\deps\corepack\shims\nodewin\corepack.cmd %TARGET_NAME%\ > nul + if errorlevel 1 echo Cannot copy corepack.cmd && goto package_error +) + copy /Y ..\tools\msvs\nodevars.bat %TARGET_NAME%\ > nul if errorlevel 1 echo Cannot copy nodevars.bat && goto package_error copy /Y ..\tools\msvs\install_tools\*.* %TARGET_NAME%\ > nul @@ -759,7 +772,7 @@ set exit_code=1 goto exit :help -echo vcbuild.bat [debug/release] [msi] [doc] [test/test-all/test-addons/test-doc/test-js-native-api/test-node-api/test-benchmark/test-internet/test-pummel/test-simple/test-message/test-tick-processor/test-known-issues/test-node-inspect/test-check-deopts/test-npm/test-async-hooks/test-v8/test-v8-intl/test-v8-benchmarks/test-v8-all] [ignore-flaky] [static/dll] [noprojgen] [projgen] [small-icu/full-icu/without-intl] [nobuild] [nosnapshot] [noetw] [ltcg] [licensetf] [sign] [ia32/x86/x64/arm64] [vs2019/vs2022] [download-all] [lint/lint-ci/lint-js/lint-md] [lint-md-build] [package] [build-release] [upload] [no-NODE-OPTIONS] [link-module path-to-module] [debug-http2] [debug-nghttp2] [clean] [cctest] [no-cctest] [openssl-no-asm] +echo vcbuild.bat [debug/release] [msi] [doc] [test/test-all/test-addons/test-doc/test-js-native-api/test-node-api/test-benchmark/test-internet/test-pummel/test-simple/test-message/test-tick-processor/test-known-issues/test-node-inspect/test-check-deopts/test-npm/test-async-hooks/test-v8/test-v8-intl/test-v8-benchmarks/test-v8-all] [ignore-flaky] [static/dll] [noprojgen] [projgen] [small-icu/full-icu/without-intl] [nobuild] [nosnapshot] [nonpm] [nocorepack] [noetw] [ltcg] [licensetf] [sign] [ia32/x86/x64/arm64] [vs2019/vs2022] [download-all] [lint/lint-ci/lint-js/lint-md] [lint-md-build] [package] [build-release] [upload] [no-NODE-OPTIONS] [link-module path-to-module] [debug-http2] [debug-nghttp2] [clean] [cctest] [no-cctest] [openssl-no-asm] echo Examples: echo vcbuild.bat : builds release build echo vcbuild.bat debug : builds debug build From 4674b0d2a5d9220d4b0903624f9102b5f52b8979 Mon Sep 17 00:00:00 2001 From: Feng Yu Date: Fri, 3 Jun 2022 00:34:01 +0800 Subject: [PATCH 10/96] doc: fix 404 link of BUILDING.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43234 Reviewed-By: Darshan Sen Reviewed-By: Tobias Nießen --- BUILDING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILDING.md b/BUILDING.md index 1e36403f53e454..22e50014380ff8 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -608,7 +608,7 @@ packages: * [NetWide Assembler](https://chocolatey.org/packages/nasm) To install Node.js prerequisites using -[Boxstarter WebLauncher](https://boxstarter.org/WebLauncher), open +[Boxstarter WebLauncher](https://boxstarter.org/weblauncher), open with Internet Explorer or Edge browser on the target machine. From 7d0f6da97fc166ee96c97c0a45c77117b08ac317 Mon Sep 17 00:00:00 2001 From: rikapo Date: Fri, 3 Jun 2022 08:27:08 +0900 Subject: [PATCH 11/96] doc: fix chromium document link in pull-requests.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43265 Reviewed-By: Tobias Nießen Reviewed-By: Michael Dawson Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Luigi Pinca Reviewed-By: Qingyu Deng Reviewed-By: Darshan Sen --- doc/contributing/pull-requests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/contributing/pull-requests.md b/doc/contributing/pull-requests.md index 7a9e1a051e7b50..2d4f6ace76933e 100644 --- a/doc/contributing/pull-requests.md +++ b/doc/contributing/pull-requests.md @@ -319,7 +319,7 @@ There are a number of more advanced mechanisms for managing commits using Feel free to post a comment in the pull request to ping reviewers if you are awaiting an answer on something. If you encounter words or acronyms that seem unfamiliar, refer to this -[glossary](https://sites.google.com/a/chromium.org/dev/glossary). +[glossary](https://chromium.googlesource.com/chromiumos/docs/+/HEAD/glossary.md). #### Approval and request changes workflow From b8644606eb2acf6d85cb290e8cab40b57b930ac9 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 3 Jun 2022 10:23:58 +0200 Subject: [PATCH 12/96] lib: use null-prototype objects for property descriptors Refs: https://github.com/nodejs/node/pull/42921 PR-URL: https://github.com/nodejs/node/pull/43270 Reviewed-By: Paolo Insogna Reviewed-By: Matteo Collina Reviewed-By: Chengzhong Wu Reviewed-By: Minwoo Jung --- lib/_http_incoming.js | 5 ++ lib/_http_outgoing.js | 11 +++ lib/_tls_wrap.js | 1 + lib/async_hooks.js | 2 + lib/buffer.js | 5 ++ lib/child_process.js | 2 + lib/crypto.js | 13 +++ lib/dgram.js | 6 ++ lib/dns.js | 7 +- lib/domain.js | 8 ++ lib/events.js | 7 ++ lib/fs.js | 18 +++-- lib/http.js | 2 + lib/internal/abort_controller.js | 2 + lib/internal/assert/assertion_error.js | 2 +- lib/internal/async_hooks.js | 1 + lib/internal/blob.js | 1 + lib/internal/bootstrap/browser.js | 3 + lib/internal/bootstrap/loaders.js | 1 + lib/internal/bootstrap/node.js | 11 +++ lib/internal/bootstrap/pre_execution.js | 10 ++- .../bootstrap/switches/is_main_thread.js | 1 + .../bootstrap/switches/is_not_main_thread.js | 1 + lib/internal/child_process.js | 1 + lib/internal/console/constructor.js | 30 +++++-- lib/internal/console/global.js | 2 +- lib/internal/crypto/diffiehellman.js | 2 + lib/internal/crypto/keygen.js | 1 + lib/internal/crypto/keys.js | 1 + lib/internal/crypto/webcrypto.js | 17 ++++ lib/internal/debugger/inspect_repl.js | 3 +- lib/internal/dns/promises.js | 2 +- lib/internal/encoding.js | 81 ++++++++++--------- lib/internal/error_serdes.js | 2 + lib/internal/errors.js | 13 ++- lib/internal/event_target.js | 4 + lib/internal/freeze_intrinsics.js | 3 + lib/internal/fs/dir.js | 1 + lib/internal/fs/streams.js | 4 + lib/internal/fs/watchers.js | 1 + lib/internal/http2/core.js | 1 + lib/internal/http2/util.js | 1 + lib/internal/main/worker_thread.js | 3 + lib/internal/modules/cjs/helpers.js | 2 + lib/internal/modules/cjs/loader.js | 3 + lib/internal/per_context/domexception.js | 10 ++- lib/internal/per_context/primordials.js | 5 ++ lib/internal/perf/nodetiming.js | 11 +++ lib/internal/perf/performance.js | 16 ++++ lib/internal/perf/timerify.js | 2 + lib/internal/policy/sri.js | 1 + lib/internal/process/promises.js | 1 + lib/internal/streams/duplex.js | 19 ++--- lib/internal/streams/lazy_transform.js | 3 + lib/internal/streams/readable.js | 15 ++++ lib/internal/streams/writable.js | 15 ++++ lib/internal/url.js | 10 ++- lib/internal/util.js | 8 +- lib/internal/util/debuglog.js | 1 + lib/internal/util/inspect.js | 2 + lib/internal/util/inspector.js | 1 + lib/internal/util/types.js | 2 + lib/internal/vm/module.js | 2 + lib/internal/webstreams/readablestream.js | 1 + lib/internal/webstreams/transfer.js | 3 + lib/internal/worker/io.js | 9 +++ lib/internal/worker/js_transferable.js | 10 ++- lib/net.js | 10 +++ lib/os.js | 3 + lib/perf_hooks.js | 1 + lib/readline.js | 30 +++++++ lib/repl.js | 15 +++- lib/stream.js | 13 ++- lib/string_decoder.js | 3 + lib/timers.js | 2 + lib/tls.js | 1 + lib/util.js | 1 + lib/zlib.js | 7 ++ 78 files changed, 446 insertions(+), 85 deletions(-) diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index f1e6b7f54ff7d7..950c8c6e08bbc9 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -98,6 +98,7 @@ ObjectSetPrototypeOf(IncomingMessage.prototype, Readable.prototype); ObjectSetPrototypeOf(IncomingMessage, Readable); ObjectDefineProperty(IncomingMessage.prototype, 'connection', { + __proto__: null, get: function() { return this.socket; }, @@ -107,6 +108,7 @@ ObjectDefineProperty(IncomingMessage.prototype, 'connection', { }); ObjectDefineProperty(IncomingMessage.prototype, 'headers', { + __proto__: null, get: function() { if (!this[kHeaders]) { this[kHeaders] = {}; @@ -126,6 +128,7 @@ ObjectDefineProperty(IncomingMessage.prototype, 'headers', { }); ObjectDefineProperty(IncomingMessage.prototype, 'headersDistinct', { + __proto__: null, get: function() { if (!this[kHeadersDistinct]) { this[kHeadersDistinct] = {}; @@ -145,6 +148,7 @@ ObjectDefineProperty(IncomingMessage.prototype, 'headersDistinct', { }); ObjectDefineProperty(IncomingMessage.prototype, 'trailers', { + __proto__: null, get: function() { if (!this[kTrailers]) { this[kTrailers] = {}; @@ -164,6 +168,7 @@ ObjectDefineProperty(IncomingMessage.prototype, 'trailers', { }); ObjectDefineProperty(IncomingMessage.prototype, 'trailersDistinct', { + __proto__: null, get: function() { if (!this[kTrailersDistinct]) { this[kTrailersDistinct] = {}; diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 8b2d24bbf694e6..e02b86e8a84929 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -145,6 +145,7 @@ ObjectSetPrototypeOf(OutgoingMessage.prototype, Stream.prototype); ObjectSetPrototypeOf(OutgoingMessage, Stream); ObjectDefineProperty(OutgoingMessage.prototype, 'writableFinished', { + __proto__: null, get() { return ( this.finished && @@ -155,24 +156,28 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'writableFinished', { }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableObjectMode', { + __proto__: null, get() { return false; } }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableLength', { + __proto__: null, get() { return this.outputSize + (this.socket ? this.socket.writableLength : 0); } }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableHighWaterMark', { + __proto__: null, get() { return this.socket ? this.socket.writableHighWaterMark : HIGH_WATER_MARK; } }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableCorked', { + __proto__: null, get() { const corked = this.socket ? this.socket.writableCorked : 0; return corked + this[kCorked]; @@ -180,6 +185,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'writableCorked', { }); ObjectDefineProperty(OutgoingMessage.prototype, '_headers', { + __proto__: null, get: internalUtil.deprecate(function() { return this.getHeaders(); }, 'OutgoingMessage.prototype._headers is deprecated', 'DEP0066'), @@ -200,6 +206,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, '_headers', { }); ObjectDefineProperty(OutgoingMessage.prototype, 'connection', { + __proto__: null, get: function() { return this.socket; }, @@ -209,6 +216,7 @@ ObjectDefineProperty(OutgoingMessage.prototype, 'connection', { }); ObjectDefineProperty(OutgoingMessage.prototype, '_headerNames', { + __proto__: null, get: internalUtil.deprecate(function() { const headers = this[kOutHeaders]; if (headers !== null) { @@ -731,16 +739,19 @@ OutgoingMessage.prototype._implicitHeader = function _implicitHeader() { }; ObjectDefineProperty(OutgoingMessage.prototype, 'headersSent', { + __proto__: null, configurable: true, enumerable: true, get: function() { return !!this._header; } }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableEnded', { + __proto__: null, get: function() { return this.finished; } }); ObjectDefineProperty(OutgoingMessage.prototype, 'writableNeedDrain', { + __proto__: null, get: function() { return !this.destroyed && !this.finished && this[kNeedDrain]; } diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 168df8e585423e..24e04010a28b9a 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -631,6 +631,7 @@ TLSSocket.prototype._wrapHandle = function(wrap) { // Ref: https://github.com/nodejs/node/commit/f7620fb96d339f704932f9bb9a0dceb9952df2d4 function defineHandleReading(socket, handle) { ObjectDefineProperty(handle, 'reading', { + __proto__: null, get: () => { return socket[kRes].reading; }, diff --git a/lib/async_hooks.js b/lib/async_hooks.js index 6cc2052474d9c2..fed0f07e647dcf 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -238,12 +238,14 @@ class AsyncResource { } ObjectDefineProperties(bound, { 'length': { + __proto__: null, configurable: true, enumerable: false, value: fn.length, writable: false, }, 'asyncResource': { + __proto__: null, configurable: true, enumerable: true, value: this, diff --git a/lib/buffer.js b/lib/buffer.js index bdf01156824180..109e5c45c724dc 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -282,6 +282,7 @@ function Buffer(arg, encodingOrOffset, length) { } ObjectDefineProperty(Buffer, SymbolSpecies, { + __proto__: null, enumerable: false, configurable: true, get() { return FastBuffer; } @@ -756,6 +757,7 @@ Buffer.byteLength = byteLength; // For backwards compatibility. ObjectDefineProperty(Buffer.prototype, 'parent', { + __proto__: null, enumerable: true, get() { if (!(this instanceof Buffer)) @@ -764,6 +766,7 @@ ObjectDefineProperty(Buffer.prototype, 'parent', { } }); ObjectDefineProperty(Buffer.prototype, 'offset', { + __proto__: null, enumerable: true, get() { if (!(this instanceof Buffer)) @@ -1302,11 +1305,13 @@ module.exports = { ObjectDefineProperties(module.exports, { constants: { + __proto__: null, configurable: false, enumerable: true, value: constants }, INSPECT_MAX_BYTES: { + __proto__: null, configurable: true, enumerable: true, get() { return INSPECT_MAX_BYTES; }, diff --git a/lib/child_process.js b/lib/child_process.js index 4b5da300b6295d..7c1b588995dbc5 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -243,6 +243,7 @@ const customPromiseExecFunction = (orig) => { }; ObjectDefineProperty(exec, promisify.custom, { + __proto__: null, enumerable: false, value: customPromiseExecFunction(exec) }); @@ -486,6 +487,7 @@ function execFile(file, args = [], options, callback) { } ObjectDefineProperty(execFile, promisify.custom, { + __proto__: null, enumerable: false, value: customPromiseExecFunction(execFile) }); diff --git a/lib/crypto.js b/lib/crypto.js index 77de7cda9d08a2..77debb9471f03c 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -259,9 +259,11 @@ function getRandomValues(array) { } ObjectDefineProperty(constants, 'defaultCipherList', { + __proto__: null, get() { const value = getOptionValue('--tls-cipher-list'); ObjectDefineProperty(this, 'defaultCipherList', { + __proto__: null, writable: true, configurable: true, enumerable: true, @@ -271,6 +273,7 @@ ObjectDefineProperty(constants, 'defaultCipherList', { }, set(val) { ObjectDefineProperty(this, 'defaultCipherList', { + __proto__: null, writable: true, configurable: true, enumerable: true, @@ -299,6 +302,7 @@ function getRandomBytesAlias(key) { this, key, { + __proto__: null, enumerable: false, configurable: true, writable: true, @@ -312,6 +316,7 @@ function getRandomBytesAlias(key) { this, key, { + __proto__: null, enumerable: true, configurable: true, writable: true, @@ -324,21 +329,25 @@ function getRandomBytesAlias(key) { ObjectDefineProperties(module.exports, { createCipher: { + __proto__: null, enumerable: false, value: deprecate(createCipher, 'crypto.createCipher is deprecated.', 'DEP0106') }, createDecipher: { + __proto__: null, enumerable: false, value: deprecate(createDecipher, 'crypto.createDecipher is deprecated.', 'DEP0106') }, // crypto.fips is deprecated. DEP0093. Use crypto.getFips()/crypto.setFips() fips: { + __proto__: null, get: getFips, set: setFips, }, DEFAULT_ENCODING: { + __proto__: null, enumerable: false, configurable: true, get: deprecate(getDefaultEncoding, @@ -347,12 +356,14 @@ ObjectDefineProperties(module.exports, { 'crypto.DEFAULT_ENCODING is deprecated.', 'DEP0091') }, constants: { + __proto__: null, configurable: false, enumerable: true, value: constants }, webcrypto: { + __proto__: null, configurable: false, enumerable: true, get() { return lazyWebCrypto().crypto; }, @@ -360,6 +371,7 @@ ObjectDefineProperties(module.exports, { }, subtle: { + __proto__: null, configurable: false, enumerable: true, get() { return lazyWebCrypto().crypto.subtle; }, @@ -367,6 +379,7 @@ ObjectDefineProperties(module.exports, { }, getRandomValues: { + __proto__: null, configurable: false, enumerable: true, get: () => getRandomValues, diff --git a/lib/dgram.js b/lib/dgram.js index 5dbc2f22dab658..5f644d2a6c30e3 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -971,6 +971,7 @@ Socket.prototype.getSendBufferSize = function() { // Deprecated private APIs. ObjectDefineProperty(Socket.prototype, '_handle', { + __proto__: null, get: deprecate(function() { return this[kStateSymbol].handle; }, 'Socket.prototype._handle is deprecated', 'DEP0112'), @@ -981,6 +982,7 @@ ObjectDefineProperty(Socket.prototype, '_handle', { ObjectDefineProperty(Socket.prototype, '_receiving', { + __proto__: null, get: deprecate(function() { return this[kStateSymbol].receiving; }, 'Socket.prototype._receiving is deprecated', 'DEP0112'), @@ -991,6 +993,7 @@ ObjectDefineProperty(Socket.prototype, '_receiving', { ObjectDefineProperty(Socket.prototype, '_bindState', { + __proto__: null, get: deprecate(function() { return this[kStateSymbol].bindState; }, 'Socket.prototype._bindState is deprecated', 'DEP0112'), @@ -1001,6 +1004,7 @@ ObjectDefineProperty(Socket.prototype, '_bindState', { ObjectDefineProperty(Socket.prototype, '_queue', { + __proto__: null, get: deprecate(function() { return this[kStateSymbol].queue; }, 'Socket.prototype._queue is deprecated', 'DEP0112'), @@ -1011,6 +1015,7 @@ ObjectDefineProperty(Socket.prototype, '_queue', { ObjectDefineProperty(Socket.prototype, '_reuseAddr', { + __proto__: null, get: deprecate(function() { return this[kStateSymbol].reuseAddr; }, 'Socket.prototype._reuseAddr is deprecated', 'DEP0112'), @@ -1033,6 +1038,7 @@ Socket.prototype._stopReceiving = deprecate(function() { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. ObjectDefineProperty(UDP.prototype, 'owner', { + __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); diff --git a/lib/dns.js b/lib/dns.js index af5416c62478cc..2e1a37b0818a14 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -198,7 +198,7 @@ function lookup(hostname, options, callback) { } ObjectDefineProperty(lookup, customPromisifyArgs, - { value: ['address', 'family'], enumerable: false }); + { __proto__: null, value: ['address', 'family'], enumerable: false }); function onlookupservice(err, hostname, service) { @@ -243,7 +243,7 @@ function lookupService(address, port, callback) { } ObjectDefineProperty(lookupService, customPromisifyArgs, - { value: ['hostname', 'service'], enumerable: false }); + { __proto__: null, value: ['hostname', 'service'], enumerable: false }); function onresolve(err, result, ttls) { @@ -288,7 +288,7 @@ function resolver(bindingName) { }); return req; } - ObjectDefineProperty(query, 'name', { value: bindingName }); + ObjectDefineProperty(query, 'name', { __proto__: null, value: bindingName }); return query; } @@ -381,6 +381,7 @@ bindDefaultResolver(module.exports, getDefaultResolver()); ObjectDefineProperties(module.exports, { promises: { + __proto__: null, configurable: true, enumerable: true, get() { diff --git a/lib/domain.js b/lib/domain.js index fbce94bad5fe28..20cdd4090d9c1f 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -59,6 +59,7 @@ const { WeakReference } = internalBinding('util'); // effective optimizations const _domain = [null]; ObjectDefineProperty(process, 'domain', { + __proto__: null, enumerable: true, get: function() { return _domain[0]; @@ -78,6 +79,7 @@ const asyncHook = createHook({ // have a domain property as it can be used to escape the sandbox. if (type !== 'PROMISE' || resource instanceof Promise) { ObjectDefineProperty(resource, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: process.domain, @@ -231,6 +233,7 @@ Domain.prototype._errorHandler = function(er) { if ((typeof er === 'object' && er !== null) || typeof er === 'function') { ObjectDefineProperty(er, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: this, @@ -356,6 +359,7 @@ Domain.prototype.add = function(ee) { } ObjectDefineProperty(ee, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: this, @@ -388,6 +392,7 @@ function intercepted(_this, self, cb, fnargs) { er.domainBound = cb; er.domainThrown = false; ObjectDefineProperty(er, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: self, @@ -433,6 +438,7 @@ Domain.prototype.bind = function(cb) { } ObjectDefineProperty(runBound, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: this, @@ -448,6 +454,7 @@ EventEmitter.usingDomains = true; const eventInit = EventEmitter.init; EventEmitter.init = function(opts) { ObjectDefineProperty(this, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: null, @@ -482,6 +489,7 @@ EventEmitter.prototype.emit = function emit(...args) { if (typeof er === 'object') { er.domainEmitter = this; ObjectDefineProperty(er, 'domain', { + __proto__: null, configurable: true, enumerable: false, value: domain, diff --git a/lib/events.js b/lib/events.js index 7b5de246b9cf99..ad5ded2d0e9fc0 100644 --- a/lib/events.js +++ b/lib/events.js @@ -219,6 +219,7 @@ EventEmitter.usingDomains = false; EventEmitter.captureRejectionSymbol = kRejection; ObjectDefineProperty(EventEmitter, 'captureRejections', { + __proto__: null, get() { return EventEmitter.prototype[kCapture]; }, @@ -231,6 +232,7 @@ ObjectDefineProperty(EventEmitter, 'captureRejections', { }); ObjectDefineProperty(EventEmitter, 'EventEmitterAsyncResource', { + __proto__: null, enumerable: true, get: lazyEventEmitterAsyncResource, set: undefined, @@ -241,6 +243,7 @@ EventEmitter.errorMonitor = kErrorMonitor; // The default for captureRejections is false ObjectDefineProperty(EventEmitter.prototype, kCapture, { + __proto__: null, value: false, writable: true, enumerable: false @@ -260,6 +263,7 @@ function checkListener(listener) { } ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', { + __proto__: null, enumerable: true, get: function() { return defaultMaxListeners; @@ -276,12 +280,14 @@ ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', { ObjectDefineProperties(EventEmitter, { kMaxEventTargetListeners: { + __proto__: null, value: kMaxEventTargetListeners, enumerable: false, configurable: false, writable: false, }, kMaxEventTargetListenersWarned: { + __proto__: null, value: kMaxEventTargetListenersWarned, enumerable: false, configurable: false, @@ -493,6 +499,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) { const capture = {}; ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit); ObjectDefineProperty(er, kEnhanceStackBeforeInspector, { + __proto__: null, value: FunctionPrototypeBind(enhanceStackTrace, this, er, capture), configurable: true }); diff --git a/lib/fs.js b/lib/fs.js index 912ca0503d5a25..b251761bd420a2 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -277,6 +277,7 @@ function exists(path, callback) { } ObjectDefineProperty(exists, internalUtil.promisify.custom, { + __proto__: null, value: (path) => { return new Promise((resolve) => fs.exists(path, resolve)); } @@ -679,7 +680,7 @@ function read(fd, buffer, offsetOrOptions, length, position, callback) { } ObjectDefineProperty(read, internalUtil.customPromisifyArgs, - { value: ['bytesRead', 'buffer'], enumerable: false }); + { __proto__: null, value: ['bytesRead', 'buffer'], enumerable: false }); /** * Synchronously reads the file from the @@ -772,7 +773,7 @@ function readv(fd, buffers, position, callback) { } ObjectDefineProperty(readv, internalUtil.customPromisifyArgs, - { value: ['bytesRead', 'buffers'], enumerable: false }); + { __proto__: null, value: ['bytesRead', 'buffers'], enumerable: false }); /** * Synchronously reads file from the @@ -872,7 +873,7 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { } ObjectDefineProperty(write, internalUtil.customPromisifyArgs, - { value: ['bytesWritten', 'buffer'], enumerable: false }); + { __proto__: null, value: ['bytesWritten', 'buffer'], enumerable: false }); /** * Synchronously writes `buffer` to the @@ -962,6 +963,7 @@ function writev(fd, buffers, position, callback) { } ObjectDefineProperty(writev, internalUtil.customPromisifyArgs, { + __proto__: null, value: ['bytesWritten', 'buffer'], enumerable: false }); @@ -3083,16 +3085,18 @@ module.exports = fs = { }; ObjectDefineProperties(fs, { - F_OK: { enumerable: true, value: F_OK || 0 }, - R_OK: { enumerable: true, value: R_OK || 0 }, - W_OK: { enumerable: true, value: W_OK || 0 }, - X_OK: { enumerable: true, value: X_OK || 0 }, + F_OK: { __proto__: null, enumerable: true, value: F_OK || 0 }, + R_OK: { __proto__: null, enumerable: true, value: R_OK || 0 }, + W_OK: { __proto__: null, enumerable: true, value: W_OK || 0 }, + X_OK: { __proto__: null, enumerable: true, value: X_OK || 0 }, constants: { + __proto__: null, configurable: false, enumerable: true, value: constants }, promises: { + __proto__: null, configurable: true, enumerable: true, get() { diff --git a/lib/http.js b/lib/http.js index 5120ec65e3f25b..1366656e42eb94 100644 --- a/lib/http.js +++ b/lib/http.js @@ -127,6 +127,7 @@ module.exports = { }; ObjectDefineProperty(module.exports, 'maxHeaderSize', { + __proto__: null, configurable: true, enumerable: true, get() { @@ -140,6 +141,7 @@ ObjectDefineProperty(module.exports, 'maxHeaderSize', { }); ObjectDefineProperty(module.exports, 'globalAgent', { + __proto__: null, configurable: true, enumerable: true, get() { diff --git a/lib/internal/abort_controller.js b/lib/internal/abort_controller.js index 7e89e43cc7cead..e4f5f14f1e4cbe 100644 --- a/lib/internal/abort_controller.js +++ b/lib/internal/abort_controller.js @@ -265,6 +265,7 @@ ObjectDefineProperties(AbortSignal.prototype, { }); ObjectDefineProperty(AbortSignal.prototype, SymbolToStringTag, { + __proto__: null, writable: false, enumerable: false, configurable: true, @@ -334,6 +335,7 @@ ObjectDefineProperties(AbortController.prototype, { }); ObjectDefineProperty(AbortController.prototype, SymbolToStringTag, { + __proto__: null, writable: false, enumerable: false, configurable: true, diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index e160d6d7e868eb..3deb8185229d7f 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -55,7 +55,7 @@ function copyError(source) { for (const key of keys) { target[key] = source[key]; } - ObjectDefineProperty(target, 'message', { value: source.message }); + ObjectDefineProperty(target, 'message', { __proto__: null, value: source.message }); return target; } diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 107aab227e4637..25f0075bf45a07 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -255,6 +255,7 @@ function emitHookFactory(symbol, name) { // Set the name property of the function as it looks good in the stack trace. ObjectDefineProperty(fn, 'name', { + __proto__: null, value: name }); return fn; diff --git a/lib/internal/blob.js b/lib/internal/blob.js index 8fee1d91f79448..723e0983435a75 100644 --- a/lib/internal/blob.js +++ b/lib/internal/blob.js @@ -356,6 +356,7 @@ function createBlob(handle, length, type = '') { } ObjectDefineProperty(Blob.prototype, SymbolToStringTag, { + __proto__: null, configurable: true, value: 'Blob', }); diff --git a/lib/internal/bootstrap/browser.js b/lib/internal/bootstrap/browser.js index 5704dedecb2ef8..92c98a7fa9cc55 100644 --- a/lib/internal/bootstrap/browser.js +++ b/lib/internal/bootstrap/browser.js @@ -87,6 +87,7 @@ function createGlobalConsole() { // https://heycam.github.io/webidl/#es-namespaces function exposeNamespace(target, name, namespaceObject) { ObjectDefineProperty(target, name, { + __proto__: null, writable: true, enumerable: false, configurable: true, @@ -96,6 +97,7 @@ function exposeNamespace(target, name, namespaceObject) { function exposeGetterAndSetter(target, name, getter, setter = undefined) { ObjectDefineProperty(target, name, { + __proto__: null, enumerable: false, configurable: true, get: getter, @@ -106,6 +108,7 @@ function exposeGetterAndSetter(target, name, getter, setter = undefined) { // https://heycam.github.io/webidl/#Replaceable function defineReplacableAttribute(target, name, value) { ObjectDefineProperty(target, name, { + __proto__: null, writable: true, enumerable: true, configurable: true, diff --git a/lib/internal/bootstrap/loaders.js b/lib/internal/bootstrap/loaders.js index bc2a83034256d6..41162fabcbc589 100644 --- a/lib/internal/bootstrap/loaders.js +++ b/lib/internal/bootstrap/loaders.js @@ -64,6 +64,7 @@ const { // Set up process.moduleLoadList. const moduleLoadList = []; ObjectDefineProperty(process, 'moduleLoadList', { + __proto__: null, value: moduleLoadList, configurable: true, enumerable: true, diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js index 0be64e136d19a6..e58538b34cb17e 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js @@ -134,6 +134,7 @@ let processConfig = new Proxy( deprecationHandler); ObjectDefineProperty(process, 'config', { + __proto__: null, enumerable: true, configurable: true, get() { return processConfig; }, @@ -233,6 +234,7 @@ setTraceCategoryStateUpdateHandler(perThreadSetup.toggleTraceCategoryState); // process.allowedNodeEnvironmentFlags ObjectDefineProperty(process, 'allowedNodeEnvironmentFlags', { + __proto__: null, get() { const flags = perThreadSetup.buildAllowedFlags(); process.allowedNodeEnvironmentFlags = flags; @@ -242,6 +244,7 @@ ObjectDefineProperty(process, 'allowedNodeEnvironmentFlags', { // this completely to that value. set(value) { ObjectDefineProperty(this, 'allowedNodeEnvironmentFlags', { + __proto__: null, value, configurable: true, enumerable: true, @@ -278,6 +281,7 @@ const features = { }; ObjectDefineProperty(process, 'features', { + __proto__: null, enumerable: true, writable: false, configurable: false, @@ -367,6 +371,7 @@ function setupProcessObject() { ObjectSetPrototypeOf(origProcProto, EventEmitter.prototype); FunctionPrototypeCall(EventEmitter, process); ObjectDefineProperty(process, SymbolToStringTag, { + __proto__: null, enumerable: false, writable: true, configurable: false, @@ -374,6 +379,7 @@ function setupProcessObject() { }); // Make process globally available to users by putting it on the global proxy ObjectDefineProperty(globalThis, 'process', { + __proto__: null, value: process, enumerable: false, writable: true, @@ -383,6 +389,7 @@ function setupProcessObject() { function setupGlobalProxy() { ObjectDefineProperty(globalThis, SymbolToStringTag, { + __proto__: null, value: 'global', writable: false, enumerable: false, @@ -406,24 +413,28 @@ function setupBuffer() { ObjectDefineProperties(globalThis, { 'Blob': { + __proto__: null, value: Blob, enumerable: false, writable: true, configurable: true, }, 'Buffer': { + __proto__: null, value: Buffer, enumerable: false, writable: true, configurable: true, }, 'atob': { + __proto__: null, value: atob, enumerable: false, writable: true, configurable: true, }, 'btoa': { + __proto__: null, value: btoa, enumerable: false, writable: true, diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index e2f3037ffd486c..dc8cb637870744 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -108,6 +108,7 @@ function patchProcessObject(expandArgv1) { require('internal/process/per_thread').refreshHrtimeBuffer(); ObjectDefineProperty(process, 'argv0', { + __proto__: null, enumerable: true, // Only set it to true during snapshot building. configurable: getOptionValue('--build-snapshot'), @@ -156,6 +157,7 @@ function addReadOnlyProcessAlias(name, option, enumerable = true) { const value = getOptionValue(option); if (value) { ObjectDefineProperty(process, name, { + __proto__: null, writable: false, configurable: true, enumerable, @@ -233,12 +235,12 @@ function setupWebCrypto() { let webcrypto; ObjectDefineProperty(globalThis, 'crypto', - ObjectGetOwnPropertyDescriptor({ + { __proto__: null, ...ObjectGetOwnPropertyDescriptor({ get crypto() { webcrypto ??= require('internal/crypto/webcrypto'); return webcrypto.crypto; } - }, 'crypto')); + }, 'crypto') }); if (internalBinding('config').hasOpenSSL) { webcrypto ??= require('internal/crypto/webcrypto'); exposeInterface(globalThis, 'Crypto', webcrypto.Crypto); @@ -281,6 +283,7 @@ function setupStacktracePrinterOnSigint() { function initializeReport() { const { report } = require('internal/process/report'); ObjectDefineProperty(process, 'report', { + __proto__: null, enumerable: true, configurable: true, get() { @@ -388,6 +391,7 @@ function initializeDeprecations() { const { noBrowserGlobals } = internalBinding('config'); if (noBrowserGlobals) { ObjectDefineProperty(process, '_noBrowserGlobals', { + __proto__: null, writable: false, enumerable: true, configurable: true, @@ -410,6 +414,7 @@ function initializeDeprecations() { // See https://github.com/nodejs/node/pull/26334. let _process = process; ObjectDefineProperty(globalThis, 'process', { + __proto__: null, get() { return _process; }, @@ -422,6 +427,7 @@ function initializeDeprecations() { let _Buffer = Buffer; ObjectDefineProperty(globalThis, 'Buffer', { + __proto__: null, get() { return _Buffer; }, diff --git a/lib/internal/bootstrap/switches/is_main_thread.js b/lib/internal/bootstrap/switches/is_main_thread.js index b7bd79e09c4acf..0b2ca03192dcb1 100644 --- a/lib/internal/bootstrap/switches/is_main_thread.js +++ b/lib/internal/bootstrap/switches/is_main_thread.js @@ -15,6 +15,7 @@ process._stopProfilerIdleNotifier = () => {}; function defineStream(name, getter) { ObjectDefineProperty(process, name, { + __proto__: null, configurable: true, enumerable: true, get: getter diff --git a/lib/internal/bootstrap/switches/is_not_main_thread.js b/lib/internal/bootstrap/switches/is_not_main_thread.js index 379ad0a587a22a..cb129189b200a3 100644 --- a/lib/internal/bootstrap/switches/is_not_main_thread.js +++ b/lib/internal/bootstrap/switches/is_not_main_thread.js @@ -7,6 +7,7 @@ delete process._debugEnd; function defineStream(name, getter) { ObjectDefineProperty(process, name, { + __proto__: null, configurable: true, enumerable: true, get: getter diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 0e4cfc2ead2bf4..9ad7bf8fd8593c 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -572,6 +572,7 @@ function setupChannel(target, channel, serializationMode) { target[kChannelHandle] = channel; ObjectDefineProperty(target, '_channel', { + __proto__: null, get: deprecate(() => { return target.channel; }, channelDeprecationMsg, 'DEP0129'), diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index 18e66a7afee0ee..bba2784bb92d44 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -154,6 +154,7 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) { // from the prototype chain of the subclass. this[key] = FunctionPrototypeBind(this[key], this); ObjectDefineProperty(this[key], 'name', { + __proto__: null, value: key }); }); @@ -170,6 +171,7 @@ const consolePropAttributes = { // Fixup global.console instanceof global.console.Console ObjectDefineProperty(Console, SymbolHasInstance, { + __proto__: null, value(instance) { return instance[kIsConsole]; } @@ -180,16 +182,18 @@ const kNoColorInspectOptions = {}; ObjectDefineProperties(Console.prototype, { [kBindStreamsEager]: { + __proto__: null, ...consolePropAttributes, // Eager version for the Console constructor value: function(stdout, stderr) { ObjectDefineProperties(this, { - '_stdout': { ...consolePropAttributes, value: stdout }, - '_stderr': { ...consolePropAttributes, value: stderr } + '_stdout': { __proto__: null, ...consolePropAttributes, value: stdout }, + '_stderr': { __proto__: null, ...consolePropAttributes, value: stderr }, }); } }, [kBindStreamsLazy]: { + __proto__: null, ...consolePropAttributes, // Lazily load the stdout and stderr from an object so we don't // create the stdio streams when they are not even accessed @@ -198,6 +202,7 @@ ObjectDefineProperties(Console.prototype, { let stderr; ObjectDefineProperties(this, { '_stdout': { + __proto__: null, enumerable: false, configurable: true, get() { @@ -207,6 +212,7 @@ ObjectDefineProperties(Console.prototype, { set(value) { stdout = value; } }, '_stderr': { + __proto__: null, enumerable: false, configurable: true, get() { @@ -219,32 +225,38 @@ ObjectDefineProperties(Console.prototype, { } }, [kBindProperties]: { + __proto__: null, ...consolePropAttributes, value: function(ignoreErrors, colorMode, groupIndentation = 2) { ObjectDefineProperties(this, { '_stdoutErrorHandler': { + __proto__: null, ...consolePropAttributes, value: createWriteErrorHandler(this, kUseStdout) }, '_stderrErrorHandler': { ...consolePropAttributes, + __proto__: null, value: createWriteErrorHandler(this, kUseStderr) }, '_ignoreErrors': { + __proto__: null, ...consolePropAttributes, value: Boolean(ignoreErrors) }, - '_times': { ...consolePropAttributes, value: new SafeMap() }, + '_times': { __proto__: null, ...consolePropAttributes, value: new SafeMap() }, // Corresponds to https://console.spec.whatwg.org/#count-map - [kCounts]: { ...consolePropAttributes, value: new SafeMap() }, - [kColorMode]: { ...consolePropAttributes, value: colorMode }, - [kIsConsole]: { ...consolePropAttributes, value: true }, - [kGroupIndent]: { ...consolePropAttributes, value: '' }, + [kCounts]: { __proto__: null, ...consolePropAttributes, value: new SafeMap() }, + [kColorMode]: { __proto__: null, ...consolePropAttributes, value: colorMode }, + [kIsConsole]: { __proto__: null, ...consolePropAttributes, value: true }, + [kGroupIndent]: { __proto__: null, ...consolePropAttributes, value: '' }, [kGroupIndentationWidth]: { + __proto__: null, ...consolePropAttributes, value: groupIndentation }, [SymbolToStringTag]: { + __proto__: null, writable: false, enumerable: false, configurable: true, @@ -254,6 +266,7 @@ ObjectDefineProperties(Console.prototype, { } }, [kWriteToConsole]: { + __proto__: null, ...consolePropAttributes, value: function(streamSymbol, string) { const ignoreErrors = this._ignoreErrors; @@ -296,6 +309,7 @@ ObjectDefineProperties(Console.prototype, { } }, [kGetInspectOptions]: { + __proto__: null, ...consolePropAttributes, value: function(stream) { let color = this[kColorMode]; @@ -317,6 +331,7 @@ ObjectDefineProperties(Console.prototype, { } }, [kFormatForStdout]: { + __proto__: null, ...consolePropAttributes, value: function(args) { const opts = this[kGetInspectOptions](this._stdout); @@ -325,6 +340,7 @@ ObjectDefineProperties(Console.prototype, { } }, [kFormatForStderr]: { + __proto__: null, ...consolePropAttributes, value: function(args) { const opts = this[kGetInspectOptions](this._stderr); diff --git a/lib/internal/console/global.js b/lib/internal/console/global.js index 782a585957f746..dd293b9f195fe9 100644 --- a/lib/internal/console/global.js +++ b/lib/internal/console/global.js @@ -37,7 +37,7 @@ for (const prop of ReflectOwnKeys(Console.prototype)) { if (typeof desc.value === 'function') { // fix the receiver const name = desc.value.name; desc.value = FunctionPrototypeBind(desc.value, globalConsole); - ReflectDefineProperty(desc.value, 'name', { value: name }); + ReflectDefineProperty(desc.value, 'name', { __proto__: null, value: name }); } ReflectDefineProperty(globalConsole, prop, desc); } diff --git a/lib/internal/crypto/diffiehellman.js b/lib/internal/crypto/diffiehellman.js index 598db4052b976c..7a735e17184413 100644 --- a/lib/internal/crypto/diffiehellman.js +++ b/lib/internal/crypto/diffiehellman.js @@ -138,6 +138,7 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { this[kHandle] = new _DiffieHellman(sizeOrKey, generator); ObjectDefineProperty(this, 'verifyError', { + __proto__: null, enumerable: true, value: this[kHandle].verifyError, writable: false @@ -150,6 +151,7 @@ function DiffieHellmanGroup(name) { return new DiffieHellmanGroup(name); this[kHandle] = new _DiffieHellmanGroup(name); ObjectDefineProperty(this, 'verifyError', { + __proto__: null, enumerable: true, value: this[kHandle].verifyError, writable: false diff --git a/lib/internal/crypto/keygen.js b/lib/internal/crypto/keygen.js index a2dad1154f0c41..b6c3d966712cda 100644 --- a/lib/internal/crypto/keygen.js +++ b/lib/internal/crypto/keygen.js @@ -93,6 +93,7 @@ function generateKeyPair(type, options, callback) { } ObjectDefineProperty(generateKeyPair, customPromisifyArgs, { + __proto__: null, value: ['publicKey', 'privateKey'], enumerable: false }); diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index 5c9f1fd0926506..143b602d2a7265 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -108,6 +108,7 @@ const { this[kKeyType] = type; ObjectDefineProperty(this, kHandle, { + __proto__: null, value: handle, enumerable: false, configurable: false, diff --git a/lib/internal/crypto/webcrypto.js b/lib/internal/crypto/webcrypto.js index 3b7e4d13d8b1c0..b31f1b1d7a054d 100644 --- a/lib/internal/crypto/webcrypto.js +++ b/lib/internal/crypto/webcrypto.js @@ -773,6 +773,7 @@ function getRandomValues(array) { ObjectDefineProperties( Crypto.prototype, { [SymbolToStringTag]: { + __proto__: null, enumerable: false, configurable: true, writable: false, @@ -780,18 +781,21 @@ ObjectDefineProperties( }, subtle: kEnumerableProperty, getRandomValues: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: getRandomValues, }, randomUUID: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: randomUUID, }, CryptoKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, @@ -802,78 +806,91 @@ ObjectDefineProperties( ObjectDefineProperties( SubtleCrypto.prototype, { [SymbolToStringTag]: { + __proto__: null, enumerable: false, configurable: true, writable: false, value: 'SubtleCrypto', }, encrypt: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: encrypt, }, decrypt: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: decrypt, }, sign: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: sign, }, verify: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: verify, }, digest: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: digest, }, generateKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: generateKey, }, deriveKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: deriveKey, }, deriveBits: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: deriveBits, }, importKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: importKey, }, exportKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: exportKey, }, wrapKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, value: wrapKey, }, unwrapKey: { + __proto__: null, enumerable: true, configurable: true, writable: true, diff --git a/lib/internal/debugger/inspect_repl.js b/lib/internal/debugger/inspect_repl.js index 742a7d64705043..49b41ef2af311f 100644 --- a/lib/internal/debugger/inspect_repl.js +++ b/lib/internal/debugger/inspect_repl.js @@ -179,7 +179,7 @@ function convertResultToError(result) { const { className, description } = result; const err = new ERR_DEBUGGER_ERROR(extractErrorMessage(description)); err.stack = description; - ObjectDefineProperty(err, 'name', { value: className }); + ObjectDefineProperty(err, 'name', { __proto__: null, value: className }); return err; } @@ -939,6 +939,7 @@ function createRepl(inspector) { function initializeContext(context) { ArrayPrototypeForEach(inspector.domainNames, (domain) => { ObjectDefineProperty(context, domain, { + __proto__: null, value: inspector[domain], enumerable: true, configurable: true, diff --git a/lib/internal/dns/promises.js b/lib/internal/dns/promises.js index 9625e9e7b9b6ea..9591c5826a5a96 100644 --- a/lib/internal/dns/promises.js +++ b/lib/internal/dns/promises.js @@ -262,7 +262,7 @@ function resolver(bindingName) { return createResolverPromise(this, bindingName, name, ttl); } - ObjectDefineProperty(query, 'name', { value: bindingName }); + ObjectDefineProperty(query, 'name', { __proto__: null, value: bindingName }); return query; } diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index def0e9223b84c7..1c0c17d534f036 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -7,6 +7,8 @@ const { ObjectCreate, ObjectDefineProperties, ObjectGetOwnPropertyDescriptors, + ObjectSetPrototypeOf, + ObjectValues, SafeMap, StringPrototypeSlice, Symbol, @@ -362,7 +364,7 @@ ObjectDefineProperties( 'encode': kEnumerableProperty, 'encodeInto': kEnumerableProperty, 'encoding': kEnumerableProperty, - [SymbolToStringTag]: { configurable: true, value: 'TextEncoder' }, + [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'TextEncoder' }, }); const TextDecoder = @@ -530,49 +532,54 @@ function makeTextDecoderJS() { } // Mix in some shared properties. -ObjectDefineProperties( - TextDecoder.prototype, - ObjectGetOwnPropertyDescriptors({ - get encoding() { - validateDecoder(this); - return this[kEncoding]; - }, - - get fatal() { - validateDecoder(this); - return (this[kFlags] & CONVERTER_FLAGS_FATAL) === CONVERTER_FLAGS_FATAL; - }, - - get ignoreBOM() { - validateDecoder(this); - return (this[kFlags] & CONVERTER_FLAGS_IGNORE_BOM) === +const sharedProperties = ObjectGetOwnPropertyDescriptors({ + get encoding() { + validateDecoder(this); + return this[kEncoding]; + }, + + get fatal() { + validateDecoder(this); + return (this[kFlags] & CONVERTER_FLAGS_FATAL) === CONVERTER_FLAGS_FATAL; + }, + + get ignoreBOM() { + validateDecoder(this); + return (this[kFlags] & CONVERTER_FLAGS_IGNORE_BOM) === CONVERTER_FLAGS_IGNORE_BOM; - }, + }, - [inspect](depth, opts) { - validateDecoder(this); - if (typeof depth === 'number' && depth < 0) - return this; - const constructor = getConstructorOf(this) || TextDecoder; - const obj = ObjectCreate({ constructor }); - obj.encoding = this.encoding; - obj.fatal = this.fatal; - obj.ignoreBOM = this.ignoreBOM; - if (opts.showHidden) { - obj[kFlags] = this[kFlags]; - obj[kHandle] = this[kHandle]; - } - // Lazy to avoid circular dependency - const { inspect } = require('internal/util/inspect'); - return `${constructor.name} ${inspect(obj)}`; + [inspect](depth, opts) { + validateDecoder(this); + if (typeof depth === 'number' && depth < 0) + return this; + const constructor = getConstructorOf(this) || TextDecoder; + const obj = ObjectCreate({ constructor }); + obj.encoding = this.encoding; + obj.fatal = this.fatal; + obj.ignoreBOM = this.ignoreBOM; + if (opts.showHidden) { + obj[kFlags] = this[kFlags]; + obj[kHandle] = this[kHandle]; } - }) -); + // Lazy to avoid circular dependency + const { inspect } = require('internal/util/inspect'); + return `${constructor.name} ${inspect(obj)}`; + } +}); +const propertiesValues = ObjectValues(sharedProperties); +for (let i = 0; i < propertiesValues.length; i++) { + // We want to use null-prototype objects to not rely on globally mutable + // %Object.prototype%. + ObjectSetPrototypeOf(propertiesValues[i], null); +} +sharedProperties[inspect].enumerable = false; ObjectDefineProperties(TextDecoder.prototype, { decode: kEnumerableProperty, - [inspect]: { enumerable: false }, + ...sharedProperties, [SymbolToStringTag]: { + __proto__: null, configurable: true, value: 'TextDecoder' } diff --git a/lib/internal/error_serdes.js b/lib/internal/error_serdes.js index c364820f60b1aa..68576c1c24d7a7 100644 --- a/lib/internal/error_serdes.js +++ b/lib/internal/error_serdes.js @@ -70,6 +70,7 @@ function GetConstructors(object) { const desc = ObjectGetOwnPropertyDescriptor(current, 'constructor'); if (desc && desc.value) { ObjectDefineProperty(constructors, constructors.length, { + __proto__: null, value: desc.value, enumerable: true }); } @@ -130,6 +131,7 @@ function deserializeError(error) { const { constructor, properties } = deserialize(error.subarray(1)); const ctor = errors[constructor]; ObjectDefineProperty(properties, SymbolToStringTag, { + __proto__: null, value: { value: 'Error', configurable: true }, enumerable: true }); diff --git a/lib/internal/errors.js b/lib/internal/errors.js index a72d73c5f2c282..388bf6dcfb0aed 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -242,30 +242,35 @@ class SystemError extends Error { ObjectDefineProperties(this, { [kIsNodeError]: { + __proto__: null, value: true, enumerable: false, writable: false, configurable: true, }, name: { + __proto__: null, value: 'SystemError', enumerable: false, writable: true, configurable: true, }, message: { + __proto__: null, value: message, enumerable: false, writable: true, configurable: true, }, info: { + __proto__: null, value: context, enumerable: true, configurable: true, writable: false, }, errno: { + __proto__: null, get() { return context.errno; }, @@ -276,6 +281,7 @@ class SystemError extends Error { configurable: true, }, syscall: { + __proto__: null, get() { return context.syscall; }, @@ -294,6 +300,7 @@ class SystemError extends Error { // `.toString()` and `Buffer.from()` operations and set the value on the // context as the user did. ObjectDefineProperty(this, 'path', { + __proto__: null, get() { return context.path != null ? context.path.toString() : context.path; @@ -309,6 +316,7 @@ class SystemError extends Error { if (context.dest !== undefined) { ObjectDefineProperty(this, 'dest', { + __proto__: null, get() { return context.dest != null ? context.dest.toString() : context.dest; @@ -354,18 +362,21 @@ function makeNodeErrorWithCode(Base, key) { const message = getMessage(key, args, error); ObjectDefineProperties(error, { [kIsNodeError]: { + __proto__: null, value: true, enumerable: false, writable: false, configurable: true, }, message: { + __proto__: null, value: message, enumerable: false, writable: true, configurable: true, }, toString: { + __proto__: null, value() { return `${this.name} [${key}]: ${this.message}`; }, @@ -389,7 +400,7 @@ function hideStackFrames(fn) { // We rename the functions that will be hidden to cut off the stacktrace // at the outermost one const hidden = nodeInternalPrefix + fn.name; - ObjectDefineProperty(fn, 'name', { value: hidden }); + ObjectDefineProperty(fn, 'name', { __proto__: null, value: hidden }); return fn; } diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index 0f9a896396f79c..d005e9edc08c13 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -110,6 +110,7 @@ class Event { // isTrusted is special (LegacyUnforgeable) ObjectDefineProperty(this, 'isTrusted', { + __proto__: null, get: isTrusted, enumerable: true, configurable: false @@ -296,6 +297,7 @@ class Event { ObjectDefineProperties( Event.prototype, { [SymbolToStringTag]: { + __proto__: null, writable: false, enumerable: false, configurable: true, @@ -677,6 +679,7 @@ ObjectDefineProperties(EventTarget.prototype, { removeEventListener: kEnumerableProperty, dispatchEvent: kEnumerableProperty, [SymbolToStringTag]: { + __proto__: null, writable: false, enumerable: false, configurable: true, @@ -924,6 +927,7 @@ function makeEventHandler(handler) { function defineEventHandler(emitter, name) { // 8.1.5.1 Event handlers - basically `on[eventName]` attributes ObjectDefineProperty(emitter, `on${name}`, { + __proto__: null, get() { return this[kHandlers]?.get(name)?.handler ?? null; }, diff --git a/lib/internal/freeze_intrinsics.js b/lib/internal/freeze_intrinsics.js index 0dcfea1ef2ec28..cb1d28f4b0feb4 100644 --- a/lib/internal/freeze_intrinsics.js +++ b/lib/internal/freeze_intrinsics.js @@ -372,6 +372,7 @@ module.exports = function() { // 19.1 Value Properties of the Global Object ObjectDefineProperty(globalThis, 'globalThis', { + __proto__: null, configurable: false, writable: false, value: globalThis, @@ -510,6 +511,7 @@ module.exports = function() { this[prop] = newValue; } else { ObjectDefineProperty(this, prop, { + __proto__: null, value: newValue, writable: true, enumerable: true, @@ -519,6 +521,7 @@ module.exports = function() { } ObjectDefineProperty(obj, prop, { + __proto__: null, get: getter, set: setter, enumerable: desc.enumerable, diff --git a/lib/internal/fs/dir.js b/lib/internal/fs/dir.js index 5fda9d8a7f3ef4..f2bf2485e11b1c 100644 --- a/lib/internal/fs/dir.js +++ b/lib/internal/fs/dir.js @@ -226,6 +226,7 @@ class Dir { } ObjectDefineProperty(Dir.prototype, SymbolAsyncIterator, { + __proto__: null, value: Dir.prototype.entries, enumerable: false, writable: true, diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index c7ecbff76cefd6..b59199e59e582e 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -212,6 +212,7 @@ ObjectSetPrototypeOf(ReadStream.prototype, Readable.prototype); ObjectSetPrototypeOf(ReadStream, Readable); ObjectDefineProperty(ReadStream.prototype, 'autoClose', { + __proto__: null, get() { return this._readableState.autoDestroy; }, @@ -295,6 +296,7 @@ ReadStream.prototype.close = function(cb) { }; ObjectDefineProperty(ReadStream.prototype, 'pending', { + __proto__: null, get() { return this.fd === null; }, configurable: true }); @@ -371,6 +373,7 @@ ObjectSetPrototypeOf(WriteStream.prototype, Writable.prototype); ObjectSetPrototypeOf(WriteStream, Writable); ObjectDefineProperty(WriteStream.prototype, 'autoClose', { + __proto__: null, get() { return this._writableState.autoDestroy; }, @@ -479,6 +482,7 @@ WriteStream.prototype.close = function(cb) { WriteStream.prototype.destroySoon = WriteStream.prototype.end; ObjectDefineProperty(WriteStream.prototype, 'pending', { + __proto__: null, get() { return this.fd === null; }, configurable: true }); diff --git a/lib/internal/fs/watchers.js b/lib/internal/fs/watchers.js index f86860f8fc0aed..7b820e70df1613 100644 --- a/lib/internal/fs/watchers.js +++ b/lib/internal/fs/watchers.js @@ -291,6 +291,7 @@ function emitCloseNT(self) { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. ObjectDefineProperty(FSEvent.prototype, 'owner', { + __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 7a7c9906c03a05..9268f5ea908527 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -3302,6 +3302,7 @@ function connect(authority, options, listener) { // Support util.promisify ObjectDefineProperty(connect, promisify.custom, { + __proto__: null, value: (authority, options) => { return new Promise((resolve) => { const server = connect(authority, options, () => resolve(server)); diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index 962bdd753c2717..ecb943c9b8e37d 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -555,6 +555,7 @@ class NghttpError extends Error { this.errno = integerCode; captureLargerStackTrace(this); ObjectDefineProperty(this, kIsNodeError, { + __proto__: null, value: true, enumerable: false, writable: false, diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js index a8167b86ca2e5a..91ca93e6e10062 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js @@ -90,11 +90,13 @@ const port = getEnvMessagePort(); if (process.env.NODE_CHANNEL_FD) { const workerThreadSetup = require('internal/process/worker_thread_only'); ObjectDefineProperty(process, 'channel', { + __proto__: null, enumerable: false, get: workerThreadSetup.unavailable('process.channel') }); ObjectDefineProperty(process, 'connected', { + __proto__: null, enumerable: false, get: workerThreadSetup.unavailable('process.connected') }); @@ -172,6 +174,7 @@ port.on('message', (message) => { // This is necessary for CJS module compilation. // TODO: pass this with something really internal. ObjectDefineProperty(process, '_eval', { + __proto__: null, configurable: true, enumerable: true, value: filename, diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js index 3ae63b46195f75..ef4544ca0aaa52 100644 --- a/lib/internal/modules/cjs/helpers.js +++ b/lib/internal/modules/cjs/helpers.js @@ -171,6 +171,7 @@ function addBuiltinLibsToObject(object, dummyModuleName) { }; ObjectDefineProperty(object, name, { + __proto__: null, get: () => { const lib = dummyModule.require(name); @@ -178,6 +179,7 @@ function addBuiltinLibsToObject(object, dummyModuleName) { // non-enumerable property. delete object[name]; ObjectDefineProperty(object, name, { + __proto__: null, get: () => lib, set: setReal, configurable: true, diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index de919e7406b4e7..9eaac14bcaa2a0 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -222,6 +222,7 @@ let wrapperProxy = new Proxy(wrapper, { }); ObjectDefineProperty(Module, 'wrap', { + __proto__: null, get() { return wrap; }, @@ -233,6 +234,7 @@ ObjectDefineProperty(Module, 'wrap', { }); ObjectDefineProperty(Module, 'wrapper', { + __proto__: null, get() { return wrapperProxy; }, @@ -256,6 +258,7 @@ function setModuleParent(value) { } ObjectDefineProperty(Module.prototype, 'parent', { + __proto__: null, get: pendingDeprecation ? deprecate( getModuleParent, 'module.parent is deprecated due to accuracy issues. Please use ' + diff --git a/lib/internal/per_context/domexception.js b/lib/internal/per_context/domexception.js index 1dd7a2a7f5a819..917e2c00bccda9 100644 --- a/lib/internal/per_context/domexception.js +++ b/lib/internal/per_context/domexception.js @@ -18,12 +18,14 @@ function throwInvalidThisError(Base, type) { const key = 'ERR_INVALID_THIS'; ObjectDefineProperties(err, { message: { + __proto__: null, value: `Value of "this" must be of ${type}`, enumerable: false, writable: true, configurable: true, }, toString: { + __proto__: null, value() { return `${this.name} [${key}]: ${this.message}`; }, @@ -88,10 +90,10 @@ class DOMException { ObjectSetPrototypeOf(DOMException.prototype, ErrorPrototype); ObjectDefineProperties(DOMException.prototype, { - [SymbolToStringTag]: { configurable: true, value: 'DOMException' }, - name: { enumerable: true, configurable: true }, - message: { enumerable: true, configurable: true }, - code: { enumerable: true, configurable: true } + [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'DOMException' }, + name: { __proto__: null, enumerable: true, configurable: true }, + message: { __proto__: null, enumerable: true, configurable: true }, + code: { __proto__: null, enumerable: true, configurable: true } }); for (const { 0: name, 1: codeName, 2: value } of [ diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 7d9368e678cc96..5c8df35522b847 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -57,11 +57,13 @@ function getNewKey(key) { function copyAccessor(dest, prefix, key, { enumerable, get, set }) { ReflectDefineProperty(dest, `${prefix}Get${key}`, { + __proto__: null, value: uncurryThis(get), enumerable }); if (set !== undefined) { ReflectDefineProperty(dest, `${prefix}Set${key}`, { + __proto__: null, value: uncurryThis(set), enumerable }); @@ -79,6 +81,7 @@ function copyPropsRenamed(src, dest, prefix) { ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { + __proto__: null, // `src` is bound as the `this` so that the static `this` points // to the object it was defined on, // e.g.: `ArrayOfApply` gets a `this` of `Array`: @@ -105,6 +108,7 @@ function copyPropsRenamedBound(src, dest, prefix) { ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { + __proto__: null, value: applyBind(value, src), }); } @@ -128,6 +132,7 @@ function copyPrototype(src, dest, prefix) { ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { + __proto__: null, value: applyBind(value), }); } diff --git a/lib/internal/perf/nodetiming.js b/lib/internal/perf/nodetiming.js index fcbd7efff49099..b0ab9df4473d63 100644 --- a/lib/internal/perf/nodetiming.js +++ b/lib/internal/perf/nodetiming.js @@ -34,30 +34,35 @@ class PerformanceNodeTiming { constructor() { ObjectDefineProperties(this, { name: { + __proto__: null, enumerable: true, configurable: true, value: 'node' }, entryType: { + __proto__: null, enumerable: true, configurable: true, value: 'node' }, startTime: { + __proto__: null, enumerable: true, configurable: true, value: 0 }, duration: { + __proto__: null, enumerable: true, configurable: true, get: now }, nodeStart: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -66,6 +71,7 @@ class PerformanceNodeTiming { }, v8Start: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -74,6 +80,7 @@ class PerformanceNodeTiming { }, environment: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -82,6 +89,7 @@ class PerformanceNodeTiming { }, loopStart: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -90,6 +98,7 @@ class PerformanceNodeTiming { }, loopExit: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -98,6 +107,7 @@ class PerformanceNodeTiming { }, bootstrapComplete: { + __proto__: null, enumerable: true, configurable: true, get() { @@ -107,6 +117,7 @@ class PerformanceNodeTiming { }, idleTime: { + __proto__: null, enumerable: true, configurable: true, get: loopIdleTime, diff --git a/lib/internal/perf/performance.js b/lib/internal/perf/performance.js index 5c7c008ee14a8e..26a80f51cf66c4 100644 --- a/lib/internal/perf/performance.js +++ b/lib/internal/perf/performance.js @@ -117,51 +117,61 @@ ObjectSetPrototypeOf(InternalPerformance.prototype, Performance.prototype); ObjectDefineProperties(Performance.prototype, { clearMarks: { + __proto__: null, configurable: true, enumerable: false, value: clearMarks, }, clearMeasures: { + __proto__: null, configurable: true, enumerable: false, value: clearMeasures, }, clearResourceTimings: { + __proto__: null, configurable: true, enumerable: false, value: clearResourceTimings, }, eventLoopUtilization: { + __proto__: null, configurable: true, enumerable: false, value: eventLoopUtilization, }, getEntries: { + __proto__: null, configurable: true, enumerable: false, value: getEntries, }, getEntriesByName: { + __proto__: null, configurable: true, enumerable: false, value: getEntriesByName, }, getEntriesByType: { + __proto__: null, configurable: true, enumerable: false, value: getEntriesByType, }, mark: { + __proto__: null, configurable: true, enumerable: false, value: mark, }, measure: { + __proto__: null, configurable: true, enumerable: false, value: measure, }, nodeTiming: { + __proto__: null, configurable: true, enumerable: false, value: nodeTiming, @@ -169,16 +179,19 @@ ObjectDefineProperties(Performance.prototype, { // In the browser, this function is not public. However, it must be used inside fetch // which is a Node.js dependency, not a internal module markResourceTiming: { + __proto__: null, configurable: true, enumerable: false, value: markResourceTiming, }, now: { + __proto__: null, configurable: true, enumerable: false, value: now, }, timerify: { + __proto__: null, configurable: true, enumerable: false, value: timerify, @@ -188,11 +201,13 @@ ObjectDefineProperties(Performance.prototype, { // TODO(joyeecheung): we may want to warn about access to // this during snapshot building. timeOrigin: { + __proto__: null, configurable: true, enumerable: true, value: getTimeOriginTimestamp(), }, toJSON: { + __proto__: null, configurable: true, enumerable: true, value: toJSON, @@ -201,6 +216,7 @@ ObjectDefineProperties(Performance.prototype, { function refreshTimeOrigin() { ObjectDefineProperty(Performance.prototype, 'timeOrigin', { + __proto__: null, configurable: true, enumerable: true, value: getTimeOriginTimestamp(), diff --git a/lib/internal/perf/timerify.js b/lib/internal/perf/timerify.js index 6bfede7aa1fa20..38f6b3d37acdd2 100644 --- a/lib/internal/perf/timerify.js +++ b/lib/internal/perf/timerify.js @@ -91,11 +91,13 @@ function timerify(fn, options = {}) { ObjectDefineProperties(timerified, { length: { + __proto__: null, configurable: false, enumerable: true, value: fn.length, }, name: { + __proto__: null, configurable: false, enumerable: true, value: `timerified ${fn.name}` diff --git a/lib/internal/policy/sri.js b/lib/internal/policy/sri.js index 22704704a310bc..0d8c24e89ae8aa 100644 --- a/lib/internal/policy/sri.js +++ b/lib/internal/policy/sri.js @@ -48,6 +48,7 @@ const parse = (str) => { // Avoid setters being fired ObjectDefineProperty(entries, entries.length, { + __proto__: null, enumerable: true, configurable: true, value: ObjectFreeze({ diff --git a/lib/internal/process/promises.js b/lib/internal/process/promises.js index 8f0899039b114e..421538373e0399 100644 --- a/lib/internal/process/promises.js +++ b/lib/internal/process/promises.js @@ -320,6 +320,7 @@ function getErrorWithoutStack(name, message) { const err = new Error(message); if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = tmp; ObjectDefineProperty(err, 'name', { + __proto__: null, value: name, enumerable: false, writable: true, diff --git a/lib/internal/streams/duplex.js b/lib/internal/streams/duplex.js index 79f91fa0866e25..4b9ca227ed5aa9 100644 --- a/lib/internal/streams/duplex.js +++ b/lib/internal/streams/duplex.js @@ -80,25 +80,26 @@ function Duplex(options) { ObjectDefineProperties(Duplex.prototype, { writable: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') }, writableHighWaterMark: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') }, writableObjectMode: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') }, writableBuffer: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') }, writableLength: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') }, writableFinished: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') }, writableCorked: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') }, writableEnded: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') }, writableNeedDrain: - ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain'), + { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') }, destroyed: { + __proto__: null, get() { if (this._readableState === undefined || this._writableState === undefined) { diff --git a/lib/internal/streams/lazy_transform.js b/lib/internal/streams/lazy_transform.js index 555e6430e33588..fc3e9815a37648 100644 --- a/lib/internal/streams/lazy_transform.js +++ b/lib/internal/streams/lazy_transform.js @@ -39,6 +39,7 @@ function makeGetter(name) { function makeSetter(name) { return function(val) { ObjectDefineProperty(this, name, { + __proto__: null, value: val, enumerable: true, configurable: true, @@ -49,12 +50,14 @@ function makeSetter(name) { ObjectDefineProperties(LazyTransform.prototype, { _readableState: { + __proto__: null, get: makeGetter('_readableState'), set: makeSetter('_readableState'), configurable: true, enumerable: true }, _writableState: { + __proto__: null, get: makeGetter('_writableState'), set: makeSetter('_writableState'), configurable: true, diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 8081e8fde13e0c..4164f7b27d56b2 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -1151,6 +1151,7 @@ async function* createAsyncIterator(stream, options) { // userland will fail. ObjectDefineProperties(Readable.prototype, { readable: { + __proto__: null, get() { const r = this._readableState; // r.readable === false means that this is part of a Duplex stream @@ -1169,6 +1170,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableDidRead: { + __proto__: null, enumerable: false, get: function() { return this._readableState.dataEmitted; @@ -1176,6 +1178,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableAborted: { + __proto__: null, enumerable: false, get: function() { return !!( @@ -1187,6 +1190,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableHighWaterMark: { + __proto__: null, enumerable: false, get: function() { return this._readableState.highWaterMark; @@ -1194,6 +1198,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableBuffer: { + __proto__: null, enumerable: false, get: function() { return this._readableState && this._readableState.buffer; @@ -1201,6 +1206,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableFlowing: { + __proto__: null, enumerable: false, get: function() { return this._readableState.flowing; @@ -1213,6 +1219,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableLength: { + __proto__: null, enumerable: false, get() { return this._readableState.length; @@ -1220,6 +1227,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableObjectMode: { + __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.objectMode : false; @@ -1227,6 +1235,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableEncoding: { + __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.encoding : null; @@ -1234,6 +1243,7 @@ ObjectDefineProperties(Readable.prototype, { }, errored: { + __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.errored : null; @@ -1241,12 +1251,14 @@ ObjectDefineProperties(Readable.prototype, { }, closed: { + __proto__: null, get() { return this._readableState ? this._readableState.closed : false; } }, destroyed: { + __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.destroyed : false; @@ -1265,6 +1277,7 @@ ObjectDefineProperties(Readable.prototype, { }, readableEnded: { + __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.endEmitted : false; @@ -1276,6 +1289,7 @@ ObjectDefineProperties(Readable.prototype, { ObjectDefineProperties(ReadableState.prototype, { // Legacy getter for `pipesCount`. pipesCount: { + __proto__: null, get() { return this.pipes.length; } @@ -1283,6 +1297,7 @@ ObjectDefineProperties(ReadableState.prototype, { // Legacy property for `paused`. paused: { + __proto__: null, get() { return this[kPaused] !== false; }, diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index 5ee0cbc969f2ad..1054631ddfee1a 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -211,6 +211,7 @@ WritableState.prototype.getBuffer = function getBuffer() { }; ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { + __proto__: null, get() { return this.buffered.length - this.bufferedIndex; } @@ -268,6 +269,7 @@ function Writable(options) { } ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, value: function(object) { if (FunctionPrototypeSymbolHasInstance(this, object)) return true; if (this !== Writable) return false; @@ -764,12 +766,14 @@ function finish(stream, state) { ObjectDefineProperties(Writable.prototype, { closed: { + __proto__: null, get() { return this._writableState ? this._writableState.closed : false; } }, destroyed: { + __proto__: null, get() { return this._writableState ? this._writableState.destroyed : false; }, @@ -782,6 +786,7 @@ ObjectDefineProperties(Writable.prototype, { }, writable: { + __proto__: null, get() { const w = this._writableState; // w.writable === false means that this is part of a Duplex stream @@ -800,30 +805,35 @@ ObjectDefineProperties(Writable.prototype, { }, writableFinished: { + __proto__: null, get() { return this._writableState ? this._writableState.finished : false; } }, writableObjectMode: { + __proto__: null, get() { return this._writableState ? this._writableState.objectMode : false; } }, writableBuffer: { + __proto__: null, get() { return this._writableState && this._writableState.getBuffer(); } }, writableEnded: { + __proto__: null, get() { return this._writableState ? this._writableState.ending : false; } }, writableNeedDrain: { + __proto__: null, get() { const wState = this._writableState; if (!wState) return false; @@ -832,24 +842,28 @@ ObjectDefineProperties(Writable.prototype, { }, writableHighWaterMark: { + __proto__: null, get() { return this._writableState && this._writableState.highWaterMark; } }, writableCorked: { + __proto__: null, get() { return this._writableState ? this._writableState.corked : 0; } }, writableLength: { + __proto__: null, get() { return this._writableState && this._writableState.length; } }, errored: { + __proto__: null, enumerable: false, get() { return this._writableState ? this._writableState.errored : null; @@ -857,6 +871,7 @@ ObjectDefineProperties(Writable.prototype, { }, writableAborted: { + __proto__: null, enumerable: false, get: function() { return !!( diff --git a/lib/internal/url.js b/lib/internal/url.js index 1b85660e07c73a..b483b4440ebf23 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -530,10 +530,11 @@ ObjectDefineProperties(URLSearchParams.prototype, { keys: kEnumerableProperty, values: kEnumerableProperty, toString: kEnumerableProperty, - [SymbolToStringTag]: { configurable: true, value: 'URLSearchParams' }, + [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URLSearchParams' }, // https://heycam.github.io/webidl/#es-iterable-entries [SymbolIterator]: { + __proto__: null, configurable: true, writable: true, value: URLSearchParams.prototype.entries, @@ -1045,8 +1046,8 @@ class URL { } ObjectDefineProperties(URL.prototype, { - [kFormat]: { configurable: false, writable: false }, - [SymbolToStringTag]: { configurable: true, value: 'URL' }, + [kFormat]: { __proto__: null, configurable: false, writable: false }, + [SymbolToStringTag]: { __proto__: null, configurable: true, value: 'URL' }, toString: kEnumerableProperty, href: kEnumerableProperty, origin: kEnumerableProperty, @@ -1229,6 +1230,7 @@ function serializeParams(array) { function defineIDLClass(proto, classStr, obj) { // https://heycam.github.io/webidl/#dfn-class-string ObjectDefineProperty(proto, SymbolToStringTag, { + __proto__: null, writable: false, enumerable: false, configurable: true, @@ -1238,6 +1240,7 @@ function defineIDLClass(proto, classStr, obj) { // https://heycam.github.io/webidl/#es-operations for (const key of ObjectKeys(obj)) { ObjectDefineProperty(proto, key, { + __proto__: null, writable: true, enumerable: true, configurable: true, @@ -1246,6 +1249,7 @@ function defineIDLClass(proto, classStr, obj) { } for (const key of ObjectGetOwnPropertySymbols(obj)) { ObjectDefineProperty(proto, key, { + __proto__: null, writable: true, enumerable: false, configurable: true, diff --git a/lib/internal/util.js b/lib/internal/util.js index 52039d0595c629..61e58a5d69d1cf 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -259,8 +259,8 @@ function createClassWrapper(type) { } // Mask the wrapper function name and length values ObjectDefineProperties(fn, { - name: { value: type.name }, - length: { value: type.length } + name: { __proto__: null, value: type.name }, + length: { __proto__: null, value: type.length }, }); ObjectSetPrototypeOf(fn, type); fn.prototype = type.prototype; @@ -334,6 +334,7 @@ function promisify(original) { validateFunction(fn, 'util.promisify.custom'); return ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { + __proto__: null, value: fn, enumerable: false, writable: false, configurable: true }); } @@ -364,6 +365,7 @@ function promisify(original) { ObjectSetPrototypeOf(fn, ObjectGetPrototypeOf(original)); ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { + __proto__: null, value: fn, enumerable: false, writable: false, configurable: true }); return ObjectDefineProperties( @@ -469,6 +471,7 @@ function createDeferredPromise() { // https://heycam.github.io/webidl/#define-the-operations function defineOperation(target, name, method) { ObjectDefineProperty(target, name, { + __proto__: null, writable: true, enumerable: true, configurable: true, @@ -479,6 +482,7 @@ function defineOperation(target, name, method) { // https://heycam.github.io/webidl/#es-interfaces function exposeInterface(target, name, interfaceObject) { ObjectDefineProperty(target, name, { + __proto__: null, writable: true, enumerable: false, configurable: true, diff --git a/lib/internal/util/debuglog.js b/lib/internal/util/debuglog.js index 4b5c7cab44ad77..de39457db2b47b 100644 --- a/lib/internal/util/debuglog.js +++ b/lib/internal/util/debuglog.js @@ -100,6 +100,7 @@ function debuglog(set, cb) { } }; ObjectDefineProperty(logger, 'enabled', { + __proto__: null, get() { return test(); }, diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 7285014e803cd7..6569822096a689 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -349,6 +349,7 @@ function inspect(value, opts) { inspect.custom = customInspectSymbol; ObjectDefineProperty(inspect, 'defaultOptions', { + __proto__: null, get() { return inspectDefaultOptions; }, @@ -413,6 +414,7 @@ inspect.colors = ObjectAssign(ObjectCreate(null), { function defineColorAlias(target, alias) { ObjectDefineProperty(inspect.colors, alias, { + __proto__: null, get() { return this[target]; }, diff --git a/lib/internal/util/inspector.js b/lib/internal/util/inspector.js index 5bc4fe5351ac86..d78467136c4918 100644 --- a/lib/internal/util/inspector.js +++ b/lib/internal/util/inspector.js @@ -52,6 +52,7 @@ function wrapConsole(consoleFromNode) { consoleFromNode[key] ); ObjectDefineProperty(consoleFromNode[key], 'name', { + __proto__: null, value: key }); } else { diff --git a/lib/internal/util/types.js b/lib/internal/util/types.js index aca7dbc4b2f2b6..0811a68f82a4dd 100644 --- a/lib/internal/util/types.js +++ b/lib/internal/util/types.js @@ -76,6 +76,7 @@ let isKeyObject; ObjectDefineProperties(module.exports, { isKeyObject: { + __proto__: null, configurable: false, enumerable: true, value(obj) { @@ -91,6 +92,7 @@ ObjectDefineProperties(module.exports, { } }, isCryptoKey: { + __proto__: null, configurable: false, enumerable: true, value(obj) { diff --git a/lib/internal/vm/module.js b/lib/internal/vm/module.js index eee629dda4fd05..a5024d97051b63 100644 --- a/lib/internal/vm/module.js +++ b/lib/internal/vm/module.js @@ -112,6 +112,7 @@ class Module { } else { identifier = `${defaultModuleName}(0)`; ObjectDefineProperty(context, kPerContextModuleId, { + __proto__: null, value: 1, writable: true, enumerable: false, @@ -239,6 +240,7 @@ class Module { ObjectSetPrototypeOf(o, ObjectGetPrototypeOf(this)); ObjectDefineProperty(o, SymbolToStringTag, { + __proto__: null, value: constructor.name, configurable: true }); diff --git a/lib/internal/webstreams/readablestream.js b/lib/internal/webstreams/readablestream.js index bea1084bdd72ad..33496587043523 100644 --- a/lib/internal/webstreams/readablestream.js +++ b/lib/internal/webstreams/readablestream.js @@ -585,6 +585,7 @@ class ReadableStream { ObjectDefineProperties(ReadableStream.prototype, { [SymbolAsyncIterator]: { + __proto__: null, configurable: true, enumerable: false, writable: true, diff --git a/lib/internal/webstreams/transfer.js b/lib/internal/webstreams/transfer.js index 985d7e86738f35..4467d90bb5a90f 100644 --- a/lib/internal/webstreams/transfer.js +++ b/lib/internal/webstreams/transfer.js @@ -73,16 +73,19 @@ class CloneableDOMException extends DOMException { [kDeserialize]({ message, name, code }) { ObjectDefineProperties(this, { message: { + __proto__: null, configurable: true, enumerable: true, get() { return message; }, }, name: { + __proto__: null, configurable: true, enumerable: true, get() { return name; }, }, code: { + __proto__: null, configurable: true, enumerable: true, get() { return code; }, diff --git a/lib/internal/worker/io.js b/lib/internal/worker/io.js index 996d98995108d0..97d7d1d408ee5d 100644 --- a/lib/internal/worker/io.js +++ b/lib/internal/worker/io.js @@ -140,6 +140,7 @@ class MessageEvent extends Event { ObjectDefineProperties(MessageEvent.prototype, { data: { + __proto__: null, get() { if (!isMessageEvent(this)) throw new ERR_INVALID_THIS('MessageEvent'); @@ -150,6 +151,7 @@ ObjectDefineProperties(MessageEvent.prototype, { set: undefined, }, origin: { + __proto__: null, get() { if (!isMessageEvent(this)) throw new ERR_INVALID_THIS('MessageEvent'); @@ -160,6 +162,7 @@ ObjectDefineProperties(MessageEvent.prototype, { set: undefined, }, lastEventId: { + __proto__: null, get() { if (!isMessageEvent(this)) throw new ERR_INVALID_THIS('MessageEvent'); @@ -170,6 +173,7 @@ ObjectDefineProperties(MessageEvent.prototype, { set: undefined, }, source: { + __proto__: null, get() { if (!isMessageEvent(this)) throw new ERR_INVALID_THIS('MessageEvent'); @@ -180,6 +184,7 @@ ObjectDefineProperties(MessageEvent.prototype, { set: undefined, }, ports: { + __proto__: null, get() { if (!isMessageEvent(this)) throw new ERR_INVALID_THIS('MessageEvent'); @@ -196,6 +201,7 @@ ObjectDefineProperty( MessagePort.prototype, kCreateEvent, { + __proto__: null, value: function(data, type) { if (type !== 'message' && type !== 'messageerror') { return ReflectApply(originalCreateEvent, this, arguments); @@ -220,6 +226,7 @@ defineEventHandler(MessagePort.prototype, 'message'); defineEventHandler(MessagePort.prototype, 'messageerror'); ObjectDefineProperty(MessagePort.prototype, onInitSymbol, { + __proto__: null, enumerable: true, writable: false, value: oninit @@ -237,6 +244,7 @@ function onclose() { } ObjectDefineProperty(MessagePort.prototype, handleOnCloseSymbol, { + __proto__: null, enumerable: false, writable: false, value: onclose @@ -249,6 +257,7 @@ MessagePort.prototype.close = function(cb) { }; ObjectDefineProperty(MessagePort.prototype, inspect.custom, { + __proto__: null, enumerable: false, writable: false, value: function inspect() { // eslint-disable-line func-name-matching diff --git a/lib/internal/worker/js_transferable.js b/lib/internal/worker/js_transferable.js index 7bd6c8cafc32e2..337413f0258a7e 100644 --- a/lib/internal/worker/js_transferable.js +++ b/lib/internal/worker/js_transferable.js @@ -5,6 +5,7 @@ const { ObjectGetOwnPropertyDescriptors, ObjectGetPrototypeOf, ObjectSetPrototypeOf, + ObjectValues, ReflectConstruct, StringPrototypeSplit, } = primordials; @@ -40,7 +41,14 @@ function setup() { function makeTransferable(obj) { const inst = ReflectConstruct(JSTransferable, [], obj.constructor); - ObjectDefineProperties(inst, ObjectGetOwnPropertyDescriptors(obj)); + const properties = ObjectGetOwnPropertyDescriptors(obj); + const propertiesValues = ObjectValues(properties); + for (let i = 0; i < propertiesValues.length; i++) { + // We want to use null-prototype objects to not rely on globally mutable + // %Object.prototype%. + ObjectSetPrototypeOf(propertiesValues[i], null); + } + ObjectDefineProperties(inst, properties); ObjectSetPrototypeOf(inst, ObjectGetPrototypeOf(obj)); return inst; } diff --git a/lib/net.js b/lib/net.js index 0110531619ab69..c8c5b5447be29d 100644 --- a/lib/net.js +++ b/lib/net.js @@ -380,6 +380,7 @@ function Socket(options) { // we need to let it do that by turning it into a writable, own // property. ObjectDefineProperty(this._handle, 'bytesWritten', { + __proto__: null, value: 0, writable: true }); } @@ -568,12 +569,14 @@ Socket.prototype.address = function() { ObjectDefineProperty(Socket.prototype, '_connecting', { + __proto__: null, get: function() { return this.connecting; } }); ObjectDefineProperty(Socket.prototype, 'pending', { + __proto__: null, get() { return !this._handle || this.connecting; }, @@ -582,6 +585,7 @@ ObjectDefineProperty(Socket.prototype, 'pending', { ObjectDefineProperty(Socket.prototype, 'readyState', { + __proto__: null, get: function() { if (this.connecting) { return 'opening'; @@ -598,6 +602,7 @@ ObjectDefineProperty(Socket.prototype, 'readyState', { ObjectDefineProperty(Socket.prototype, 'bufferSize', { + __proto__: null, get: function() { if (this._handle) { return this.writableLength; @@ -606,6 +611,7 @@ ObjectDefineProperty(Socket.prototype, 'bufferSize', { }); ObjectDefineProperty(Socket.prototype, kUpdateTimer, { + __proto__: null, get: function() { return this._unrefTimer; } @@ -777,6 +783,7 @@ Socket.prototype._getpeername = function() { function protoGetter(name, callback) { ObjectDefineProperty(Socket.prototype, name, { + __proto__: null, configurable: false, enumerable: true, get: callback @@ -1605,6 +1612,7 @@ function lookupAndListen(self, port, address, backlog, exclusive, flags) { } ObjectDefineProperty(Server.prototype, 'listening', { + __proto__: null, get: function() { return !!this._handle; }, @@ -1787,11 +1795,13 @@ Server.prototype[EventEmitter.captureRejectionSymbol] = function( // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. ObjectDefineProperty(TCP.prototype, 'owner', { + __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); ObjectDefineProperty(Socket.prototype, '_handle', { + __proto__: null, get() { return this[kHandle]; }, set(v) { return this[kHandle] = v; } }); diff --git a/lib/os.js b/lib/os.js index e8a6e252198aa5..90920b67b37aa7 100644 --- a/lib/os.js +++ b/lib/os.js @@ -372,12 +372,14 @@ module.exports = { ObjectDefineProperties(module.exports, { constants: { + __proto__: null, configurable: false, enumerable: true, value: constants }, EOL: { + __proto__: null, configurable: true, enumerable: true, writable: false, @@ -385,6 +387,7 @@ ObjectDefineProperties(module.exports, { }, devNull: { + __proto__: null, configurable: true, enumerable: true, writable: false, diff --git a/lib/perf_hooks.js b/lib/perf_hooks.js index 2456bcb7e7e029..e84c8948f3c609 100644 --- a/lib/perf_hooks.js +++ b/lib/perf_hooks.js @@ -39,6 +39,7 @@ module.exports = { }; ObjectDefineProperty(module.exports, 'constants', { + __proto__: null, configurable: false, enumerable: true, value: constants diff --git a/lib/readline.js b/lib/readline.js index 11514614c33ab9..0957de58506a66 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -208,111 +208,133 @@ ObjectDefineProperties(Interface.prototype, { // Redirect internal prototype methods to the underscore notation for backward // compatibility. [kSetRawMode]: { + __proto__: null, get() { return this._setRawMode; } }, [kOnLine]: { + __proto__: null, get() { return this._onLine; } }, [kWriteToOutput]: { + __proto__: null, get() { return this._writeToOutput; } }, [kAddHistory]: { + __proto__: null, get() { return this._addHistory; } }, [kRefreshLine]: { + __proto__: null, get() { return this._refreshLine; } }, [kNormalWrite]: { + __proto__: null, get() { return this._normalWrite; } }, [kInsertString]: { + __proto__: null, get() { return this._insertString; } }, [kTabComplete]: { + __proto__: null, get() { return this._tabComplete; } }, [kWordLeft]: { + __proto__: null, get() { return this._wordLeft; } }, [kWordRight]: { + __proto__: null, get() { return this._wordRight; } }, [kDeleteLeft]: { + __proto__: null, get() { return this._deleteLeft; } }, [kDeleteRight]: { + __proto__: null, get() { return this._deleteRight; } }, [kDeleteWordLeft]: { + __proto__: null, get() { return this._deleteWordLeft; } }, [kDeleteWordRight]: { + __proto__: null, get() { return this._deleteWordRight; } }, [kDeleteLineLeft]: { + __proto__: null, get() { return this._deleteLineLeft; } }, [kDeleteLineRight]: { + __proto__: null, get() { return this._deleteLineRight; } }, [kLine]: { + __proto__: null, get() { return this._line; } }, [kHistoryNext]: { + __proto__: null, get() { return this._historyNext; } }, [kHistoryPrev]: { + __proto__: null, get() { return this._historyPrev; } }, [kGetDisplayPos]: { + __proto__: null, get() { return this._getDisplayPos; } }, [kMoveCursor]: { + __proto__: null, get() { return this._moveCursor; } }, [kTtyWrite]: { + __proto__: null, get() { return this._ttyWrite; } @@ -321,6 +343,7 @@ ObjectDefineProperties(Interface.prototype, { // Defining proxies for the internal instance properties for backward // compatibility. _decoder: { + __proto__: null, get() { return this[kDecoder]; }, @@ -329,6 +352,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _line_buffer: { + __proto__: null, get() { return this[kLine_buffer]; }, @@ -337,6 +361,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _oldPrompt: { + __proto__: null, get() { return this[kOldPrompt]; }, @@ -345,6 +370,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _previousKey: { + __proto__: null, get() { return this[kPreviousKey]; }, @@ -353,6 +379,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _prompt: { + __proto__: null, get() { return this[kPrompt]; }, @@ -361,6 +388,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _questionCallback: { + __proto__: null, get() { return this[kQuestionCallback]; }, @@ -369,6 +397,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _sawKeyPress: { + __proto__: null, get() { return this[kSawKeyPress]; }, @@ -377,6 +406,7 @@ ObjectDefineProperties(Interface.prototype, { }, }, _sawReturnAt: { + __proto__: null, get() { return this[kSawReturnAt]; }, diff --git a/lib/repl.js b/lib/repl.js index af9b607b022372..7c17272f6e63ee 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -285,6 +285,7 @@ function REPLServer(prompt, (options.preview !== undefined ? !!options.preview : !eval_); ObjectDefineProperty(this, 'inputStream', { + __proto__: null, get: pendingDeprecation ? deprecate(() => this.input, 'repl.inputStream and repl.outputStream are deprecated. ' + @@ -301,6 +302,7 @@ function REPLServer(prompt, configurable: true }); ObjectDefineProperty(this, 'outputStream', { + __proto__: null, get: pendingDeprecation ? deprecate(() => this.output, 'repl.inputStream and repl.outputStream are deprecated. ' + @@ -783,6 +785,7 @@ function REPLServer(prompt, if (options[kStandaloneREPL]) { ObjectDefineProperty(inspect, 'replDefaults', { + __proto__: null, get() { return writer.options; }, @@ -1083,12 +1086,16 @@ REPLServer.prototype.createContext = function() { // Only set properties that do not already exist as a global builtin. if (!globalBuiltins.has(name)) { ObjectDefineProperty(context, name, - ObjectGetOwnPropertyDescriptor(globalThis, name)); + { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(globalThis, name), + }); } }); context.global = context; const _console = new Console(this.output); ObjectDefineProperty(context, 'console', { + __proto__: null, configurable: true, writable: true, value: _console @@ -1099,11 +1106,13 @@ REPLServer.prototype.createContext = function() { replModule.paths = CJSModule._resolveLookupPaths('', parentModule); ObjectDefineProperty(context, 'module', { + __proto__: null, configurable: true, writable: true, value: replModule }); ObjectDefineProperty(context, 'require', { + __proto__: null, configurable: true, writable: true, value: makeRequireFunction(replModule) @@ -1123,6 +1132,7 @@ REPLServer.prototype.resetContext = function() { this.lines.level = []; ObjectDefineProperty(this.context, '_', { + __proto__: null, configurable: true, get: () => this.last, set: (value) => { @@ -1135,6 +1145,7 @@ REPLServer.prototype.resetContext = function() { }); ObjectDefineProperty(this.context, '_error', { + __proto__: null, configurable: true, get: () => this.lastError, set: (value) => { @@ -1805,6 +1816,7 @@ module.exports = { }; ObjectDefineProperty(module.exports, 'builtinModules', { + __proto__: null, get: () => _builtinLibs, set: (val) => _builtinLibs = val, enumerable: true, @@ -1812,6 +1824,7 @@ ObjectDefineProperty(module.exports, 'builtinModules', { }); ObjectDefineProperty(module.exports, '_builtinLibs', { + __proto__: null, get: pendingDeprecation ? deprecate( () => _builtinLibs, 'repl._builtinLibs is deprecated. Check module.builtinModules instead', diff --git a/lib/stream.js b/lib/stream.js index 55f903f295fecf..e8a38120cb2ceb 100644 --- a/lib/stream.js +++ b/lib/stream.js @@ -63,9 +63,10 @@ for (const key of ObjectKeys(streamReturningOperators)) { } return Stream.Readable.from(ReflectApply(op, this, args)); } - ObjectDefineProperty(fn, 'name', { value: op.name }); - ObjectDefineProperty(fn, 'length', { value: op.length }); + ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }); + ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }); ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, value: fn, enumerable: false, configurable: true, @@ -80,9 +81,10 @@ for (const key of ObjectKeys(promiseReturningOperators)) { } return ReflectApply(op, this, args); } - ObjectDefineProperty(fn, 'name', { value: op.name }); - ObjectDefineProperty(fn, 'length', { value: op.length }); + ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }); + ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }); ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, value: fn, enumerable: false, configurable: true, @@ -101,6 +103,7 @@ Stream.destroy = destroyer; Stream.compose = compose; ObjectDefineProperty(Stream, 'promises', { + __proto__: null, configurable: true, enumerable: true, get() { @@ -109,6 +112,7 @@ ObjectDefineProperty(Stream, 'promises', { }); ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, enumerable: true, get() { return promises.pipeline; @@ -116,6 +120,7 @@ ObjectDefineProperty(pipeline, customPromisify, { }); ObjectDefineProperty(eos, customPromisify, { + __proto__: null, enumerable: true, get() { return promises.finished; diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 9eae594aaa27ea..a22da17f505efb 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -140,6 +140,7 @@ StringDecoder.prototype.text = function text(buf, offset) { ObjectDefineProperties(StringDecoder.prototype, { lastChar: { + __proto__: null, configurable: true, enumerable: true, get() { @@ -149,6 +150,7 @@ ObjectDefineProperties(StringDecoder.prototype, { } }, lastNeed: { + __proto__: null, configurable: true, enumerable: true, get() { @@ -156,6 +158,7 @@ ObjectDefineProperties(StringDecoder.prototype, { } }, lastTotal: { + __proto__: null, configurable: true, enumerable: true, get() { diff --git a/lib/timers.js b/lib/timers.js index cd721ad4550164..b2126d9711fc8e 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -168,6 +168,7 @@ function setTimeout(callback, after, arg1, arg2, arg3) { } ObjectDefineProperty(setTimeout, customPromisify, { + __proto__: null, enumerable: true, get() { if (!timersPromises) @@ -302,6 +303,7 @@ function setImmediate(callback, arg1, arg2, arg3) { } ObjectDefineProperty(setImmediate, customPromisify, { + __proto__: null, enumerable: true, get() { if (!timersPromises) diff --git a/lib/tls.js b/lib/tls.js index 17ad9fb24a0898..136fe50c78eed2 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -110,6 +110,7 @@ function cacheRootCertificates() { } ObjectDefineProperty(exports, 'rootCertificates', { + __proto__: null, configurable: false, enumerable: true, get: () => { diff --git a/lib/util.js b/lib/util.js index 05c4d4f98da9ec..78e6b807ee5ef6 100644 --- a/lib/util.js +++ b/lib/util.js @@ -244,6 +244,7 @@ function inherits(ctor, superCtor) { 'Object', superCtor.prototype); } ObjectDefineProperty(ctor, 'super_', { + __proto__: null, value: superCtor, writable: true, configurable: true diff --git a/lib/zlib.js b/lib/zlib.js index 718f72af67650e..9bde1997d95720 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -308,6 +308,7 @@ ObjectSetPrototypeOf(ZlibBase.prototype, Transform.prototype); ObjectSetPrototypeOf(ZlibBase, Transform); ObjectDefineProperty(ZlibBase.prototype, '_closed', { + __proto__: null, configurable: true, enumerable: true, get() { @@ -320,6 +321,7 @@ ObjectDefineProperty(ZlibBase.prototype, '_closed', { // that have this concept, where it stands for the number of bytes read // *from* the stream (that is, net.Socket/tls.Socket & file system streams). ObjectDefineProperty(ZlibBase.prototype, 'bytesRead', { + __proto__: null, configurable: true, enumerable: true, get: deprecate(function() { @@ -871,6 +873,7 @@ ObjectSetPrototypeOf(BrotliDecompress, Brotli); function createProperty(ctor) { return { + __proto__: null, configurable: true, enumerable: true, value: function(options) { @@ -882,6 +885,7 @@ function createProperty(ctor) { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. ObjectDefineProperty(binding.Zlib.prototype, 'jsref', { + __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; } }); @@ -930,11 +934,13 @@ ObjectDefineProperties(module.exports, { createBrotliCompress: createProperty(BrotliCompress), createBrotliDecompress: createProperty(BrotliDecompress), constants: { + __proto__: null, configurable: false, enumerable: true, value: constants }, codes: { + __proto__: null, enumerable: true, writable: false, value: ObjectFreeze(codes) @@ -946,6 +952,7 @@ ObjectDefineProperties(module.exports, { for (const bkey of ObjectKeys(constants)) { if (StringPrototypeStartsWith(bkey, 'BROTLI')) continue; ObjectDefineProperty(module.exports, bkey, { + __proto__: null, enumerable: false, value: constants[bkey], writable: false }); } From 9b764531b95de54b302f8fac0e82e951d6d0d4ae Mon Sep 17 00:00:00 2001 From: Feng Yu Date: Fri, 3 Jun 2022 16:24:08 +0800 Subject: [PATCH 13/96] fs: export constants from `fs/promises` PR-URL: https://github.com/nodejs/node/pull/43177 Reviewed-By: LiviaMedeiros Reviewed-By: Luigi Pinca Reviewed-By: Antoine du Hamel --- doc/api/fs.md | 17 ++++++++++++----- lib/internal/fs/promises.js | 5 ++++- test/parallel/test-fs-promises-exists.js | 5 ++++- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 21a454136af8ec..e957e655ba9ae0 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -789,8 +789,7 @@ with an {Error} object. The following example checks if the file `/etc/passwd` can be read and written by the current process. ```mjs -import { access } from 'node:fs/promises'; -import { constants } from 'node:fs'; +import { access, constants } from 'node:fs/promises'; try { await access('/etc/passwd', constants.R_OK | constants.W_OK); @@ -892,8 +891,7 @@ error occurs after the destination file has been opened for writing, an attempt will be made to remove the destination. ```mjs -import { constants } from 'node:fs'; -import { copyFile } from 'node:fs/promises'; +import { copyFile, constants } from 'node:fs/promises'; try { await copyFile('source.txt', 'destination.txt'); @@ -1622,6 +1620,14 @@ try { Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering `fs.writeFile` performs. +### `fsPromises.constants` + +* {Object} + +Returns an object containing commonly used constants for file system +operations. The object is the same as `fs.constants`. See [FS constants][] +for more details. + ## Callback API The callback APIs perform all operations asynchronously, without blocking the @@ -6879,7 +6885,7 @@ operations. #### FS constants -The following constants are exported by `fs.constants`. +The following constants are exported by `fs.constants` and `fsPromises.constants`. Not every constant will be available on every operating system; this is especially important for Windows, where many of the POSIX specific @@ -7584,6 +7590,7 @@ the file contents. [#25741]: https://github.com/nodejs/node/issues/25741 [Common System Errors]: errors.md#common-system-errors +[FS constants]: #fs-constants [File access constants]: #file-access-constants [MDN-Date]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date [MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index c3c5874453a8b6..5f29a1df98bf61 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -17,13 +17,15 @@ const { Uint8Array, } = primordials; +const { fs: constants } = internalBinding('constants'); const { F_OK, O_SYMLINK, O_WRONLY, S_IFMT, S_IFREG -} = internalBinding('constants').fs; +} = constants; + const binding = internalBinding('fs'); const { Buffer } = require('buffer'); @@ -899,6 +901,7 @@ module.exports = { appendFile, readFile, watch, + constants, }, FileHandle, diff --git a/test/parallel/test-fs-promises-exists.js b/test/parallel/test-fs-promises-exists.js index d56308257e6b17..b9bbeee1de97fd 100644 --- a/test/parallel/test-fs-promises-exists.js +++ b/test/parallel/test-fs-promises-exists.js @@ -2,5 +2,8 @@ require('../common'); const assert = require('assert'); +const fs = require('fs'); +const fsPromises = require('fs/promises'); -assert.strictEqual(require('fs/promises'), require('fs').promises); +assert.strictEqual(fsPromises, fs.promises); +assert.strictEqual(fsPromises.constants, fs.constants); From fff0560a6643ccf0bfecc3c69097f324550d7b9b Mon Sep 17 00:00:00 2001 From: Tony Gorez Date: Fri, 3 Jun 2022 15:59:35 +0200 Subject: [PATCH 14/96] doc: promote cdt to tier 3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43290 Reviewed-By: Rafael Gonzaga Reviewed-By: Chengzhong Wu Reviewed-By: Gireesh Punathil Reviewed-By: Darshan Sen Reviewed-By: Luigi Pinca Reviewed-By: Gerhard Stöbich Reviewed-By: Matteo Collina Reviewed-By: Akhil Marsonya --- doc/contributing/diagnostic-tooling-support-tiers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/contributing/diagnostic-tooling-support-tiers.md b/doc/contributing/diagnostic-tooling-support-tiers.md index be8b79bdfc9282..69e8b161507186 100644 --- a/doc/contributing/diagnostic-tooling-support-tiers.md +++ b/doc/contributing/diagnostic-tooling-support-tiers.md @@ -114,6 +114,7 @@ The tools are currently assigned to Tiers as follows: | Profiling | V8 --interpreted-frames-native-stack | Yes | Yes | 2 | | Profiling | Linux perf | Yes | Partial | 2 | | Profiling | node-clinic | No | No | 3 | +| Debugger | Chrome Dev tools | No | No | 3 | ## Tier 4 @@ -132,7 +133,6 @@ The tools are currently assigned to Tiers as follows: | Debugger | V8 Debug protocol (API) | No | Yes | 1 | | Debugger | Command line Debug Client | ? | Yes | 1 | | Debugger | llnode | ? | No | 2 | -| Debugger | Chrome Dev tools | ? | No | 3 | | Tracing | trace\_events (API) | No | Yes | 1 | | Tracing | trace\_gc | No | Yes | 1 | | Tracing | DTrace | No | Partial | 3 | From 7f8f61a7498b87710f66db8aed6ce3e8ee48821f Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Mon, 30 May 2022 19:41:57 +0800 Subject: [PATCH 15/96] tls: fix performance regression in `convertALPNProtocols()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `isUint8Array()` covers instances of `Buffer` `isArrayBufferView()` path is cold and not worth additional check PR-URL: https://github.com/nodejs/node/pull/43250 Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Tobias Nießen Reviewed-By: Luigi Pinca Reviewed-By: Minwoo Jung Reviewed-By: Darshan Sen --- lib/tls.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/tls.js b/lib/tls.js index 136fe50c78eed2..5a248c7d60ccf1 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -56,7 +56,6 @@ const internalUtil = require('internal/util'); internalUtil.assertCrypto(); const { isArrayBufferView, - isDataView, isUint8Array, } = require('internal/util/types'); @@ -148,16 +147,14 @@ exports.convertALPNProtocols = function convertALPNProtocols(protocols, out) { // If protocols is Array - translate it into buffer if (ArrayIsArray(protocols)) { out.ALPNProtocols = convertProtocols(protocols); - } else if (Buffer.isBuffer(protocols) || isUint8Array(protocols)) { + } else if (isUint8Array(protocols)) { // Copy new buffer not to be modified by user. out.ALPNProtocols = Buffer.from(protocols); - } else if (isDataView(protocols)) { + } else if (isArrayBufferView(protocols)) { out.ALPNProtocols = Buffer.from(protocols.buffer.slice( protocols.byteOffset, protocols.byteOffset + protocols.byteLength )); - } else if (isArrayBufferView(protocols)) { - out.ALPNProtocols = Buffer.from(protocols.slice().buffer); } }; From 28c034d6b546d16273c24ed1f536f66ef41795ce Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Sat, 4 Jun 2022 08:20:27 +0200 Subject: [PATCH 16/96] crypto: add CFRG curves to Web Crypto API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/42507 Reviewed-By: Tobias Nießen --- doc/api/webcrypto.md | 341 +++++-------- lib/internal/crypto/cfrg.js | 369 ++++++++++++++ lib/internal/crypto/diffiehellman.js | 16 +- lib/internal/crypto/ec.js | 302 ++--------- lib/internal/crypto/keys.js | 2 +- lib/internal/crypto/util.js | 10 +- lib/internal/crypto/webcrypto.js | 103 +++- src/crypto/crypto_ec.cc | 8 +- test/fixtures/crypto/eddsa.js | 51 ++ test/parallel/test-crypto-keygen.js | 16 - .../test-webcrypto-derivebits-cfrg.js | 213 ++++++++ .../test-webcrypto-derivebits-ecdh.js | 2 +- test/parallel/test-webcrypto-derivebits.js | 26 + .../parallel/test-webcrypto-derivekey-cfrg.js | 188 +++++++ .../parallel/test-webcrypto-derivekey-ecdh.js | 2 +- test/parallel/test-webcrypto-derivekey.js | 43 +- test/parallel/test-webcrypto-ed25519-ed448.js | 481 ------------------ .../test-webcrypto-export-import-cfrg.js | 308 +++++++++++ test/parallel/test-webcrypto-keygen.js | 94 ++++ .../test-webcrypto-sign-verify-ecdsa.js | 24 + .../test-webcrypto-sign-verify-eddsa.js | 263 ++++++++++ test/parallel/test-webcrypto-sign-verify.js | 40 ++ test/parallel/test-webcrypto-x25519-x448.js | 315 ------------ tools/doc/type-parser.mjs | 15 +- 24 files changed, 1898 insertions(+), 1334 deletions(-) create mode 100644 lib/internal/crypto/cfrg.js create mode 100644 test/fixtures/crypto/eddsa.js create mode 100644 test/parallel/test-webcrypto-derivebits-cfrg.js create mode 100644 test/parallel/test-webcrypto-derivekey-cfrg.js delete mode 100644 test/parallel/test-webcrypto-ed25519-ed448.js create mode 100644 test/parallel/test-webcrypto-export-import-cfrg.js create mode 100644 test/parallel/test-webcrypto-sign-verify-eddsa.js delete mode 100644 test/parallel/test-webcrypto-x25519-x448.js diff --git a/doc/api/webcrypto.md b/doc/api/webcrypto.md index 9454fead349b69..8973ce9d820545 100644 --- a/doc/api/webcrypto.md +++ b/doc/api/webcrypto.md @@ -1,5 +1,21 @@ # Web Crypto API + + > Stability: 1 - Experimental @@ -69,22 +85,22 @@ async function generateEcKey(namedCurve = 'P-521') { } ``` -#### ED25519/ED448/X25519/X448 key pairs +#### Ed25519/Ed448/X25519/X448 key pairs + +> Stability: 1 - Experimental ```js const { subtle } = require('node:crypto').webcrypto; async function generateEd25519Key() { return subtle.generateKey({ - name: 'NODE-ED25519', - namedCurve: 'NODE-ED25519', + name: 'Ed25519', }, true, ['sign', 'verify']); } async function generateX25519Key() { return subtle.generateKey({ - name: 'ECDH', - namedCurve: 'NODE-X25519', + name: 'X25519', }, true, ['deriveKey']); } ``` @@ -315,7 +331,11 @@ implementation and the APIs supported for each: | `'RSA-PSS'` | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | | `'RSA-OAEP'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | | | `'ECDSA'` | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | +| `'Ed25519'`[^2] | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | +| `'Ed448'`[^2] | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | | `'ECDH'` | ✔ | ✔ | ✔ | | | | | ✔ | ✔ | | | | +| `'X25519'`[^2] | ✔ | ✔ | ✔ | | | | | ✔ | ✔ | | | | +| `'X448'`[^2] | ✔ | ✔ | ✔ | | | | | ✔ | ✔ | | | | | `'AES-CTR'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | | | `'AES-CBC'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | | | `'AES-GCM'` | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | | | | | | @@ -329,8 +349,6 @@ implementation and the APIs supported for each: | `'SHA-512'` | | | | | | | | | | | | ✔ | | `'NODE-DSA'`[^1] | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | | `'NODE-DH'`[^1] | ✔ | ✔ | ✔ | | | | | ✔ | ✔ | | | | -| `'NODE-ED25519'`[^1] | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | -| `'NODE-ED448'`[^1] | ✔ | ✔ | ✔ | | | | | | | ✔ | ✔ | | ## Class: `Crypto` @@ -394,7 +412,7 @@ added: v15.0.0 -* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams|NodeEdKeyGenParams} +* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} @@ -459,7 +477,11 @@ Valid key usages depend on the key algorithm (identified by | `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | | `'AES-KW'` | | | | | | | ✔ | ✔ | | `'ECDH'` | | | | | ✔ | ✔ | | | +| `'X25519'`[^2] | | | | | ✔ | ✔ | | | +| `'X448'`[^2] | | | | | ✔ | ✔ | | | | `'ECDSA'` | | | ✔ | ✔ | | | | | +| `'Ed25519'`[^2] | | | ✔ | ✔ | | | | | +| `'Ed448'`[^2] | | | ✔ | ✔ | | | | | | `'HDKF'` | | | | | ✔ | ✔ | | | | `'HMAC'` | | | ✔ | ✔ | | | | | | `'PBKDF2'` | | | | | ✔ | ✔ | | | @@ -469,8 +491,6 @@ Valid key usages depend on the key algorithm (identified by | `'NODE-DSA'`[^1] | | | ✔ | ✔ | | | | | | `'NODE-DH'`[^1] | | | | | ✔ | ✔ | | | | `'NODE-SCRYPT'`[^1] | | | | | ✔ | ✔ | | | -| `'NODE-ED25519'`[^1] | | | ✔ | ✔ | | | | | -| `'NODE-ED448'`[^1] | | | ✔ | ✔ | | | | | ## Class: `CryptoKeyPair` @@ -530,11 +550,15 @@ The algorithms currently supported include: -* `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} +* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `length`: {number} * Returns: {Promise} containing {ArrayBuffer} @@ -559,11 +583,15 @@ The algorithms currently supported include: -* `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} +* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `derivedKeyAlgorithm`: {HmacKeyGenParams|AesKeyGenParams} * `extractable`: {boolean} @@ -640,6 +668,10 @@ The algorithms currently supported include: -* `algorithm`: {RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams|NodeEdKeyGenParams} +* `algorithm`: {AlgorithmIdentifier|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} @@ -713,11 +745,13 @@ include: * `'RSA-PSS'` * `'RSA-OAEP'` * `'ECDSA'` +* `'Ed25519'`[^2] +* `'Ed448'`[^2] * `'ECDH'` +* `'X25519'`[^2] +* `'X448'`[^2] * `'NODE-DSA'`[^1] * `'NODE-DH'`[^1] -* `'NODE-ED25519'`[^1] -* `'NODE-ED448'`[^1] The {CryptoKey} (secret key) generating algorithms supported include: @@ -732,6 +766,10 @@ The {CryptoKey} (secret key) generating algorithms supported include: -* `algorithm`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams|Pbkdf2ImportParams|NodeDsaImportParams|NodeDhImportParams|NodeScryptImportParams|NodeEdKeyImportParams} +* `algorithm`: {AlgorithmIdentifier|RsaHashedImportParams|EcKeyImportParams|HmacImportParams|NodeDsaImportParams} @@ -770,7 +808,11 @@ The algorithms currently supported include: | `'AES-GCM'` | | | ✔ | ✔ | | `'AES-KW'` | | | ✔ | ✔ | | `'ECDH'` | ✔ | ✔ | ✔ | ✔ | +| `'X25519'`[^2] | ✔ | ✔ | ✔ | ✔ | +| `'X448'`[^2] | ✔ | ✔ | ✔ | ✔ | | `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | +| `'Ed25519'`[^2] | ✔ | ✔ | ✔ | ✔ | +| `'Ed448'`[^2] | ✔ | ✔ | ✔ | ✔ | | `'HDKF'` | | | | ✔ | | `'HMAC'` | | | ✔ | ✔ | | `'PBKDF2'` | | | | ✔ | @@ -780,18 +822,20 @@ The algorithms currently supported include: | `'NODE-DSA'`[^1] | ✔ | ✔ | | | | `'NODE-DH'`[^1] | ✔ | ✔ | | | | `'NODE-SCRYPT'`[^1] | | | | ✔ | -| `'NODE-ED25519'`[^1] | ✔ | ✔ | ✔ | ✔ | -| `'NODE-ED448'`[^1] | ✔ | ✔ | ✔ | ✔ | ### `subtle.sign(algorithm, key, data)` -* `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} +* `algorithm`: {AlgorithmIdentifier|RsaPssParams|EcdsaParams|Ed448Params} * `key`: {CryptoKey} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} * Returns: {Promise} containing {ArrayBuffer} @@ -808,10 +852,10 @@ The algorithms currently supported include: * `'RSASSA-PKCS1-v1_5'` * `'RSA-PSS'` * `'ECDSA'` +* `'Ed25519'`[^2] +* `'Ed448'`[^2] * `'HMAC'` * `'NODE-DSA'`[^1] -* `'NODE-ED25519'`[^1] -* `'NODE-ED448'`[^1] ### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` @@ -825,8 +869,8 @@ added: v15.0.0 -* `unwrapAlgo`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams} -* `unwrappedKeyAlgo`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams} +* `unwrapAlgo`: {AlgorithmIdentifier|RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams} +* `unwrappedKeyAlgo`: {AlgorithmIdentifier|RsaHashedImportParams|EcKeyImportParams|HmacImportParams} @@ -870,11 +914,15 @@ The unwrapped key algorithms supported include: -* `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} +* `algorithm`: {AlgorithmIdentifier|RsaPssParams|EcdsaParams|Ed448Params} * `key`: {CryptoKey} * `signature`: {ArrayBuffer|TypedArray|DataView|Buffer} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} @@ -892,10 +940,10 @@ The algorithms currently supported include: * `'RSASSA-PKCS1-v1_5'` * `'RSA-PSS'` * `'ECDSA'` +* `'Ed25519'`[^2] +* `'Ed448'`[^2] * `'HMAC'` * `'NODE-DSA'`[^1] -* `'NODE-ED25519'`[^1] -* `'NODE-ED448'`[^1] ### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` @@ -903,12 +951,16 @@ The algorithms currently supported include: added: v15.0.0 --> + + * `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `key`: {CryptoKey} * `wrappingKey`: {CryptoKey} -* `wrapAlgo`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams} +* `wrapAlgo`: {AlgorithmIdentifier|RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams} * Returns: {Promise} containing {ArrayBuffer} + + In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, then encrypts it using the method and @@ -933,6 +985,20 @@ The algorithm parameter objects define the methods and parameters used by the various {SubtleCrypto} methods. While described here as "classes", they are simple JavaScript dictionary objects. +### Class: `AlgorithmIdentifier` + + + +#### `algorithmIdentifier.name` + + + +* Type: {string} + ### Class: `AesCbcParams` - -#### `aesImportParams.name` - - - -* Type: {string} Must be one of `'AES-CTR'`, `'AES-CBC'`, `'AES-GCM'`, or - `'AES-KW'`. - ### Class: `AesKeyGenParams` - -#### `aesKwParams.name` - - - -* Type: {string} Must be `'AES-KW'`. - ### Class: `EcdhKeyDeriveParams` -* Type: {string} Must be `'ECDH'`. +* Type: {string} Must be `'ECDH'`, `'X25519'`, or `'X448'`. #### `ecdhKeyDeriveParams.public` @@ -1181,8 +1218,7 @@ added: v15.0.0 added: v15.0.0 --> -* Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`, - `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. +* Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`. ### Class: `EcKeyImportParams` @@ -1204,8 +1240,34 @@ added: v15.0.0 added: v15.0.0 --> -* Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`, - `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. +* Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`. + +### Class: `Ed448Params` + + + +#### `ed448Params.name` + + + +* Type: {string} Must be `'Ed448'`. + +#### `ed448Params.context` + + + +* Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} + +The `context` member represents the optional context data to associate with +the message. +The Node.js Web Crypto API implementation only supports zero-length context +which is equivalent to not providing context at all. ### Class: `HkdfParams` @@ -1350,34 +1412,6 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. -### Class: `HmacParams` - - - -#### `hmacParams.name` - - - -* Type: {string} Must be `'HMAC'`. - -### Class: `Pbkdf2ImportParams` - - - -#### `pbkdf2ImportParams.name` - - - -* Type: {string} Must be `'PBKDF2'` - ### Class: `Pbkdf2Params` - -#### `rsaSignParams.name` - - - -* Type: {string} Must be `'RSASSA-PKCS1-v1_5'` - ## Node.js-specific extensions The Node.js Web Crypto API extends various aspects of the Web Crypto API. @@ -1607,20 +1627,6 @@ added: v15.0.0 The `NODE-DH` algorithm is the common implementation of Diffie-Hellman key agreement. -#### Class: `NodeDhImportParams` - - - -##### `nodeDhImportParams.name` - - - -* Type: {string} Must be `'NODE-DH'`. - #### Class: `NodeDhKeyGenParams` - -##### `nodeDsaSignParams.name` - - - -* Type: {string} Must be `'NODE-DSA'` - -### `NODE-ED25519` and `NODE-ED448` Algorithms - - - -#### Class: `NodeEdKeyGenParams` - - - -##### `nodeEdKeyGenParams.name` - - - -* Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'` or `'ECDH'`. - -##### `nodeEdKeyGenParams.namedCurve` - - - -* Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, - `'NODE-X25519'`, or `'NODE-X448'`. - -#### Class: `NodeEdKeyImportParams` - - - -##### `nodeEdKeyImportParams.name` - - - -* Type: {string} Must be one of `'NODE-ED25519'` or `'NODE-ED448'` - if importing an `Ed25519` or `Ed448` key, or `'ECDH'` if importing - an `X25519` or `X448` key. - -##### `nodeEdKeyImportParams.namedCurve` - - - -* Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, - `'NODE-X25519'`, or `'NODE-X448'`. - -##### `nodeEdKeyImportParams.public` - - - -* Type: {boolean} - -The `public` parameter is used to specify that the `'raw'` format key is to be -interpreted as a public key. **Default:** `false`. - ### `NODE-SCRYPT` Algorithm - -##### `nodeScryptImportParams.name` - - - -* Type: {string} Must be `'NODE-SCRYPT'`. - #### Class: `NodeScryptParams` -* `reason` {any} An optional reason, retrievable on the `AbortSignal`s +* `reason` {any} An optional reason, retrievable on the `AbortSignal`'s `reason` property. Triggers the abort signal, causing the `abortController.signal` to emit From 6d0053345e56015a043a45022703e7f6406417ff Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Sat, 11 Jun 2022 09:04:20 +0200 Subject: [PATCH 38/96] crypto: remove Node.js-specific webcrypto extensions PR-URL: https://github.com/nodejs/node/pull/43310 Reviewed-By: James M Snell --- doc/api/webcrypto.md | 333 ++---------------- lib/internal/crypto/aes.js | 20 -- lib/internal/crypto/cfrg.js | 16 - lib/internal/crypto/diffiehellman.js | 221 ------------ lib/internal/crypto/dsa.js | 225 ------------ lib/internal/crypto/ec.js | 11 - lib/internal/crypto/hashnames.js | 6 - lib/internal/crypto/mac.js | 14 - lib/internal/crypto/rsa.js | 10 - lib/internal/crypto/scrypt.js | 44 --- lib/internal/crypto/util.js | 8 +- lib/internal/crypto/webcrypto.js | 73 +--- test/fixtures/crypto/dsa.js | 93 ----- test/parallel/test-crypto-key-objects.js | 23 -- .../test-webcrypto-derivebits-node-dh.js | 219 ------------ test/parallel/test-webcrypto-derivebits.js | 32 -- test/parallel/test-webcrypto-derivekey.js | 34 -- .../test-webcrypto-export-import-cfrg.js | 10 - .../test-webcrypto-export-import-dsa.js | 164 --------- .../test-webcrypto-export-import-ec.js | 10 - .../test-webcrypto-export-import-rsa.js | 10 - test/parallel/test-webcrypto-export-import.js | 7 - test/parallel/test-webcrypto-keygen.js | 132 ------- .../test-webcrypto-sign-verify-node-dsa.js | 220 ------------ tools/doc/type-parser.mjs | 6 - 25 files changed, 40 insertions(+), 1901 deletions(-) delete mode 100644 lib/internal/crypto/dsa.js delete mode 100644 test/fixtures/crypto/dsa.js delete mode 100644 test/parallel/test-webcrypto-derivebits-node-dh.js delete mode 100644 test/parallel/test-webcrypto-export-import-dsa.js delete mode 100644 test/parallel/test-webcrypto-sign-verify-node-dsa.js diff --git a/doc/api/webcrypto.md b/doc/api/webcrypto.md index 8973ce9d820545..6377bb32bfa27c 100644 --- a/doc/api/webcrypto.md +++ b/doc/api/webcrypto.md @@ -2,6 +2,13 @@ -* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} +* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams} @@ -477,20 +482,17 @@ Valid key usages depend on the key algorithm (identified by | `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | | `'AES-KW'` | | | | | | | ✔ | ✔ | | `'ECDH'` | | | | | ✔ | ✔ | | | -| `'X25519'`[^2] | | | | | ✔ | ✔ | | | -| `'X448'`[^2] | | | | | ✔ | ✔ | | | +| `'X25519'`[^1] | | | | | ✔ | ✔ | | | +| `'X448'`[^1] | | | | | ✔ | ✔ | | | | `'ECDSA'` | | | ✔ | ✔ | | | | | -| `'Ed25519'`[^2] | | | ✔ | ✔ | | | | | -| `'Ed448'`[^2] | | | ✔ | ✔ | | | | | +| `'Ed25519'`[^1] | | | ✔ | ✔ | | | | | +| `'Ed448'`[^1] | | | ✔ | ✔ | | | | | | `'HDKF'` | | | | | ✔ | ✔ | | | | `'HMAC'` | | | ✔ | ✔ | | | | | | `'PBKDF2'` | | | | | ✔ | ✔ | | | | `'RSA-OAEP'` | ✔ | ✔ | | | | | ✔ | ✔ | | `'RSA-PSS'` | | | ✔ | ✔ | | | | | | `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | -| `'NODE-DSA'`[^1] | | | ✔ | ✔ | | | | | -| `'NODE-DH'`[^1] | | | | | ✔ | ✔ | | | -| `'NODE-SCRYPT'`[^1] | | | | | ✔ | ✔ | | | ## Class: `CryptoKeyPair` @@ -558,7 +560,7 @@ changes: -* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} +* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params} * `baseKey`: {CryptoKey} * `length`: {number} * Returns: {Promise} containing {ArrayBuffer} @@ -576,8 +578,6 @@ The algorithms currently supported include: * `'ECDH'` * `'HKDF'` * `'PBKDF2'` -* `'NODE-DH'`[^1] -* `'NODE-SCRYPT'`[^1] ### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)` @@ -591,7 +591,7 @@ changes: -* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} +* `algorithm`: {AlgorithmIdentifier|EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params} * `baseKey`: {CryptoKey} * `derivedKeyAlgorithm`: {HmacKeyGenParams|AesKeyGenParams} * `extractable`: {boolean} @@ -614,8 +614,6 @@ The algorithms currently supported include: * `'ECDH'` * `'HKDF'` * `'PBKDF2'` -* `'NODE-DH'`[^1] -* '`NODE-SCRYPT'`[^1] ### `subtle.digest(algorithm, data)` @@ -677,11 +675,9 @@ changes: description: Removed `'NODE-DSA'` JWK export. --> -* `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or - `'node.keyObject'`. +* `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `key`: {CryptoKey} -* Returns: {Promise} containing {ArrayBuffer}, or, if `format` is - `'node.keyObject'`, a {KeyObject}. +* Returns: {Promise} containing {ArrayBuffer}. Exports the given key into the specified format, if supported. @@ -695,9 +691,6 @@ When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a JavaScript object conforming to the [JSON Web Key][] specification. -The special `'node.keyObject'` value for `format` is a Node.js-specific -extension that allows converting a {CryptoKey} into a Node.js {KeyObject}. - | Key Type | `'spki'` | `'pkcs8'` | `'jwk'` | `'raw'` | | --------------------- | -------- | --------- | ------- | ------- | | `'AES-CBC'` | | | ✔ | ✔ | @@ -706,17 +699,14 @@ extension that allows converting a {CryptoKey} into a Node.js {KeyObject}. | `'AES-KW'` | | | ✔ | ✔ | | `'ECDH'` | ✔ | ✔ | ✔ | ✔ | | `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | -| `'Ed25519'`[^2] | ✔ | ✔ | ✔ | ✔ | -| `'Ed448'`[^2] | ✔ | ✔ | ✔ | ✔ | +| `'Ed25519'`[^1] | ✔ | ✔ | ✔ | ✔ | +| `'Ed448'`[^1] | ✔ | ✔ | ✔ | ✔ | | `'HDKF'` | | | | | | `'HMAC'` | | | ✔ | ✔ | | `'PBKDF2'` | | | | | | `'RSA-OAEP'` | ✔ | ✔ | ✔ | | | `'RSA-PSS'` | ✔ | ✔ | ✔ | | | `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -| `'NODE-DSA'`[^1] | ✔ | ✔ | | | -| `'NODE-DH'`[^1] | ✔ | ✔ | | | -| `'NODE-SCRYPT'`[^1] | | | | | ### `subtle.generateKey(algorithm, extractable, keyUsages)` @@ -726,7 +716,7 @@ added: v15.0.0 -* `algorithm`: {AlgorithmIdentifier|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} +* `algorithm`: {AlgorithmIdentifier|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams} @@ -745,13 +735,11 @@ include: * `'RSA-PSS'` * `'RSA-OAEP'` * `'ECDSA'` -* `'Ed25519'`[^2] -* `'Ed448'`[^2] +* `'Ed25519'`[^1] +* `'Ed448'`[^1] * `'ECDH'` -* `'X25519'`[^2] -* `'X448'`[^2] -* `'NODE-DSA'`[^1] -* `'NODE-DH'`[^1] +* `'X25519'`[^1] +* `'X448'`[^1] The {CryptoKey} (secret key) generating algorithms supported include: @@ -775,13 +763,12 @@ changes: description: Removed `'NODE-DSA'` JWK import. --> -* `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or - `'node.keyObject'`. +* `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `keyData`: {ArrayBuffer|TypedArray|DataView|Buffer|KeyObject} -* `algorithm`: {AlgorithmIdentifier|RsaHashedImportParams|EcKeyImportParams|HmacImportParams|NodeDsaImportParams} +* `algorithm`: {AlgorithmIdentifier|RsaHashedImportParams|EcKeyImportParams|HmacImportParams} @@ -794,9 +781,6 @@ as the given `format` to create a {CryptoKey} instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. If the import is successful, the returned promise will be resolved with the created {CryptoKey}. -The special `'node.keyObject'` value for `format` is a Node.js-specific -extension that allows converting a Node.js {KeyObject} into a {CryptoKey}. - If importing a `'PBKDF2'` key, `extractable` must be `false`. The algorithms currently supported include: @@ -808,20 +792,17 @@ The algorithms currently supported include: | `'AES-GCM'` | | | ✔ | ✔ | | `'AES-KW'` | | | ✔ | ✔ | | `'ECDH'` | ✔ | ✔ | ✔ | ✔ | -| `'X25519'`[^2] | ✔ | ✔ | ✔ | ✔ | -| `'X448'`[^2] | ✔ | ✔ | ✔ | ✔ | +| `'X25519'`[^1] | ✔ | ✔ | ✔ | ✔ | +| `'X448'`[^1] | ✔ | ✔ | ✔ | ✔ | | `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | -| `'Ed25519'`[^2] | ✔ | ✔ | ✔ | ✔ | -| `'Ed448'`[^2] | ✔ | ✔ | ✔ | ✔ | +| `'Ed25519'`[^1] | ✔ | ✔ | ✔ | ✔ | +| `'Ed448'`[^1] | ✔ | ✔ | ✔ | ✔ | | `'HDKF'` | | | | ✔ | | `'HMAC'` | | | ✔ | ✔ | | `'PBKDF2'` | | | | ✔ | | `'RSA-OAEP'` | ✔ | ✔ | ✔ | | | `'RSA-PSS'` | ✔ | ✔ | ✔ | | | `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -| `'NODE-DSA'`[^1] | ✔ | ✔ | | | -| `'NODE-DH'`[^1] | ✔ | ✔ | | | -| `'NODE-SCRYPT'`[^1] | | | | ✔ | ### `subtle.sign(algorithm, key, data)` @@ -852,10 +833,9 @@ The algorithms currently supported include: * `'RSASSA-PKCS1-v1_5'` * `'RSA-PSS'` * `'ECDSA'` -* `'Ed25519'`[^2] -* `'Ed448'`[^2] +* `'Ed25519'`[^1] +* `'Ed448'`[^1] * `'HMAC'` -* `'NODE-DSA'`[^1] ### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` @@ -907,8 +887,6 @@ The unwrapped key algorithms supported include: * `'AES-CBC'` * `'AES-GCM'` * `'AES-KW'` -* `'NODE-DSA'`[^1] -* `'NODE-DH'`[^1] ### `subtle.verify(algorithm, key, signature, data)` @@ -940,10 +918,9 @@ The algorithms currently supported include: * `'RSASSA-PKCS1-v1_5'` * `'RSA-PSS'` * `'ECDSA'` -* `'Ed25519'`[^2] -* `'Ed448'`[^2] +* `'Ed25519'`[^1] +* `'Ed448'`[^1] * `'HMAC'` -* `'NODE-DSA'`[^1] ### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` @@ -1606,241 +1583,7 @@ added: v15.0.0 The length (in bytes) of the random salt to use. -## Node.js-specific extensions - -The Node.js Web Crypto API extends various aspects of the Web Crypto API. -These extensions are consistently identified by prepending names with the -`node.` prefix. For instance, the `'node.keyObject'` key format can be -used with the `subtle.exportKey()` and `subtle.importKey()` methods to -convert between a WebCrypto {CryptoKey} object and a Node.js {KeyObject}. - -Care should be taken when using Node.js-specific extensions as they are -not supported by other WebCrypto implementations and reduce the portability -of code to other environments. - -### `NODE-DH` Algorithm - - - -The `NODE-DH` algorithm is the common implementation of Diffie-Hellman -key agreement. - -#### Class: `NodeDhKeyGenParams` - - - -##### `nodeDhKeyGenParams.generator` - - - -* Type: {number} A custom generator. - -##### `nodeDhKeyGenParams.group` - - - -* Type: {string} The Diffie-Hellman group name. - -##### `nodeDhKeyGenParams.prime` - - - -* Type: {Buffer} The prime parameter. - -##### `nodeDhKeyGenParams.primeLength` - - - -* Type: {number} The length in bits of the prime. - -#### Class: NodeDhDeriveBitsParams - - - -##### `nodeDhDeriveBitsParams.public` - - - -* Type: {CryptoKey} The other parties public key. - -### `NODE-DSA` Algorithm - - - -The `NODE-DSA` algorithm is the common implementation of the DSA digital -signature algorithm. - -#### Class: `NodeDsaImportParams` - - - -##### `nodeDsaImportParams.hash` - - - -* Type: {string|Object} - -If represented as a {string}, the value must be one of: - -* `'SHA-1'` -* `'SHA-256'` -* `'SHA-384'` -* `'SHA-512'` - -If represented as an {Object}, the object must have a `name` property -whose value is one of the above listed values. - -##### `nodeDsaImportParams.name` - - - -* Type: {string} Must be `'NODE-DSA'`. - -#### Class: `NodeDsaKeyGenParams` - - - -##### `nodeDsaKeyGenParams.divisorLength` - - - -* Type: {number} - -The optional length in bits of the DSA divisor. - -##### `nodeDsaKeyGenParams.hash` - - - -* Type: {string|Object} - -If represented as a {string}, the value must be one of: - -* `'SHA-1'` -* `'SHA-256'` -* `'SHA-384'` -* `'SHA-512'` - -If represented as an {Object}, the object must have a `name` property -whose value is one of the above listed values. - -##### `nodeDsaKeyGenParams.modulusLength` - - - -* Type: {number} - -The length in bits of the DSA modulus. As a best practice, this should be -at least `2048`. - -##### `nodeDsaKeyGenParams.name` - - - -* Type: {string} Must be `'NODE-DSA'`. - -### `NODE-SCRYPT` Algorithm - - - -The `NODE-SCRYPT` algorithm is the common implementation of the scrypt key -derivation algorithm. - -#### Class: `NodeScryptParams` - - - -##### `nodeScryptParams.encoding` - - - -* Type: {string} The string encoding when `salt` is a string. - -##### `nodeScryptParams.maxmem` - - - -* Type: {number} Memory upper bound. It is an error when (approximately) - `127 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`. - -##### `nodeScryptParams.N` - - - -* Type: {number} The CPU/memory cost parameter. Must e a power of two - greater than 1. **Default:** `16384`. - -##### `nodeScryptParams.p` - - - -* Type: {number} Parallelization parameter. **Default:** `1`. - -##### `nodeScryptParams.r` - - - -* Type: {number} Block size parameter. **Default:** `8`. - -##### `nodeScryptParams.salt` - - - -* Type: {string|ArrayBuffer|Buffer|TypedArray|DataView} - -[^1]: Non-standard Node.js-specific extension - -[^2]: An experimental implementation of +[^1]: An experimental implementation of [Secure Curves in the Web Cryptography API][] as of 05 May 2022 [JSON Web Key]: https://tools.ietf.org/html/rfc7517 diff --git a/lib/internal/crypto/aes.js b/lib/internal/crypto/aes.js index 9136913b7b9d14..2c74a49139a70a 100644 --- a/lib/internal/crypto/aes.js +++ b/lib/internal/crypto/aes.js @@ -50,17 +50,10 @@ const { const { PromiseReject } = primordials; -const { - codes: { - ERR_INVALID_ARG_TYPE, - } -} = require('internal/errors'); - const { InternalCryptoKey, SecretKeyObject, createSecretKey, - isKeyObject, } = require('internal/crypto/keys'); const { @@ -283,19 +276,6 @@ async function aesImportKey( let keyObject; let length; switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - - if (keyData.type !== 'secret') { - throw lazyDOMException( - `Unable to import AES key with format ${format}`, - 'NotSupportedError'); - } - - keyObject = keyData; - break; - } case 'raw': { validateKeyLength(keyData.byteLength * 8); keyObject = createSecretKey(keyData); diff --git a/lib/internal/crypto/cfrg.js b/lib/internal/crypto/cfrg.js index 041f2d824a79bf..826610a5fd6b8e 100644 --- a/lib/internal/crypto/cfrg.js +++ b/lib/internal/crypto/cfrg.js @@ -18,12 +18,6 @@ const { kSignJobModeVerify, } = internalBinding('crypto'); -const { - codes: { - ERR_INVALID_ARG_TYPE, - }, -} = require('internal/errors'); - const { getArrayBufferOrView, getUsagesUnion, @@ -49,7 +43,6 @@ const { PublicKeyObject, createPrivateKey, createPublicKey, - isKeyObject, } = require('internal/crypto/keys'); function verifyAcceptableCfrgKeyUse(name, type, usages) { @@ -226,15 +219,6 @@ async function cfrgImportKey( let keyObject; const usagesSet = new SafeSet(keyUsages); switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - if (keyData.type === 'secret') - throw lazyDOMException('Invalid key type', 'InvalidAccessException'); - verifyAcceptableCfrgKeyUse(name, keyData.type, usagesSet); - keyObject = keyData; - break; - } case 'spki': { verifyAcceptableCfrgKeyUse(name, 'public', usagesSet); keyObject = createPublicKey({ diff --git a/lib/internal/crypto/diffiehellman.js b/lib/internal/crypto/diffiehellman.js index b0dad2db233f52..85f2be16007c74 100644 --- a/lib/internal/crypto/diffiehellman.js +++ b/lib/internal/crypto/diffiehellman.js @@ -12,8 +12,6 @@ const { const { Buffer } = require('buffer'); const { - DHBitsJob, - DHKeyExportJob, DiffieHellman: _DiffieHellman, DiffieHellmanGroup: _DiffieHellmanGroup, ECDH: _ECDH, @@ -53,23 +51,12 @@ const { const { KeyObject, - InternalCryptoKey, - createPrivateKey, - createPublicKey, isCryptoKey, - isKeyObject, } = require('internal/crypto/keys'); -const { - generateKeyPair, -} = require('internal/crypto/keygen'); - const { getArrayBufferOrView, getDefaultEncoding, - getUsagesUnion, - hasAnyNotIn, - jobPromise, toBuf, kHandle, kKeyObject, @@ -345,89 +332,6 @@ function deriveBitsECDH(name, publicKey, privateKey, callback) { job.run(); } -// The deriveBitsDH function is part of the Web Crypto API and serves both -// deriveKeys and deriveBits functions. -function deriveBitsDH(publicKey, privateKey, callback) { - validateObject(publicKey, 'publicKey'); - validateObject(privateKey, 'privateKey'); - validateFunction(callback, 'callback'); - const job = new DHBitsJob(kCryptoJobAsync, publicKey, privateKey); - job.ondone = (error, bits) => { - if (error) return FunctionPrototypeCall(callback, job, error); - FunctionPrototypeCall(callback, job, null, bits); - }; - job.run(); -} - -function verifyAcceptableDhKeyUse(name, type, usages) { - let checkSet; - switch (type) { - case 'private': - checkSet = ['deriveBits', 'deriveKey']; - break; - case 'public': - checkSet = []; - break; - } - if (hasAnyNotIn(usages, checkSet)) { - throw lazyDOMException( - `Unsupported key usage for an ${name} key`, - 'SyntaxError'); - } -} - -async function dhGenerateKey( - algorithm, - extractable, - keyUsages) { - const usageSet = new SafeSet(keyUsages); - - if (hasAnyNotIn(usageSet, ['deriveKey', 'deriveBits'])) { - throw lazyDOMException( - 'Unsupported key usage for a DH key', - 'SyntaxError'); - } - - const { - name, - primeLength, - generator, - group - } = algorithm; - let { prime } = algorithm; - - if (prime !== undefined) - prime = getArrayBufferOrView(prime); - - return new Promise((resolve, reject) => { - generateKeyPair('dh', { - prime, - primeLength, - generator, - group, - }, (err, pubKey, privKey) => { - if (err) { - return reject(lazyDOMException( - 'The operation failed for an operation-specific reason', - 'OperationError')); - } - - const algorithm = { name, prime, primeLength, generator, group }; - - const publicKey = new InternalCryptoKey(pubKey, algorithm, [], true); - - const privateKey = - new InternalCryptoKey( - privKey, - algorithm, - getUsagesUnion(usageSet, 'deriveBits', 'deriveKey'), - extractable); - - resolve({ publicKey, privateKey }); - }); - }); -} - async function asyncDeriveBitsECDH(algorithm, baseKey, length) { const { 'public': key } = algorithm; @@ -498,136 +402,11 @@ async function asyncDeriveBitsECDH(algorithm, baseKey, length) { ArrayBufferPrototypeSlice(bits, 0, length); } -async function asyncDeriveBitsDH(algorithm, baseKey, length) { - const { 'public': key } = algorithm; - // Null has a specific meaning for DH - if (length !== null) - validateUint32(length, 'length'); - if (!isCryptoKey(key)) - throw new ERR_INVALID_ARG_TYPE('algorithm.public', 'CryptoKey', key); - - if (key.type !== 'public') { - throw lazyDOMException( - 'algorithm.public must be a public key', 'InvalidAccessError'); - } - if (baseKey.type !== 'private') { - throw lazyDOMException( - 'baseKey must be a private key', 'InvalidAccessError'); - } - - if (key.algorithm.name !== 'NODE-DH') - throw lazyDOMException('Keys must be DH keys', 'InvalidAccessError'); - - if (key.algorithm.name !== baseKey.algorithm.name) { - throw lazyDOMException( - 'The public and private keys must be of the same type', - 'InvalidAccessError'); - } - - const bits = await new Promise((resolve, reject) => { - deriveBitsDH( - key[kKeyObject][kHandle], - baseKey[kKeyObject][kHandle], (err, bits) => { - if (err) return reject(err); - resolve(bits); - }); - }); - - // If a length is not specified, return the full derived secret - if (length === null) - return bits; - - // If the length is not a multiple of 8, it will be truncated - // down to the nearest multiple of 8. - length = MathFloor(length / 8); - const { byteLength } = bits; - - // If the length is larger than the derived secret, throw. - // Otherwise, we either return the secret or a truncated - // slice. - if (byteLength < length) - throw lazyDOMException('derived bit length is too small', 'OperationError'); - - return length === byteLength ? - bits : - ArrayBufferPrototypeSlice(bits, 0, length); -} - -function dhExportKey(key, format) { - return jobPromise(new DHKeyExportJob( - kCryptoJobAsync, - format, - key[kKeyObject][kHandle])); -} - -async function dhImportKey( - format, - keyData, - algorithm, - extractable, - keyUsages) { - const usagesSet = new SafeSet(keyUsages); - let keyObject; - switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - if (keyData.type === 'secret') - throw lazyDOMException('Invalid key type', 'InvalidAccessException'); - verifyAcceptableDhKeyUse(algorithm.name, keyData.type, usagesSet); - keyObject = keyData; - break; - } - case 'spki': { - verifyAcceptableDhKeyUse(algorithm.name, 'public', usagesSet); - keyObject = createPublicKey({ - key: keyData, - format: 'der', - type: 'spki' - }); - break; - } - case 'pkcs8': { - verifyAcceptableDhKeyUse(algorithm.name, 'private', usagesSet); - keyObject = createPrivateKey({ - key: keyData, - format: 'der', - type: 'pkcs8' - }); - break; - } - default: - throw lazyDOMException( - `Unable to import DH key with format ${format}`, - 'NotSupportedError'); - } - - const { - prime, - primeLength, - generator, - group, - } = keyObject[kHandle].keyDetail({}); - - return new InternalCryptoKey(keyObject, { - name: algorithm.name, - prime, - primeLength, - generator, - group, - }, keyUsages, extractable); -} - module.exports = { DiffieHellman, DiffieHellmanGroup, ECDH, diffieHellman, deriveBitsECDH, - deriveBitsDH, - dhGenerateKey, asyncDeriveBitsECDH, - asyncDeriveBitsDH, - dhExportKey, - dhImportKey, }; diff --git a/lib/internal/crypto/dsa.js b/lib/internal/crypto/dsa.js deleted file mode 100644 index faaf7d6b889c07..00000000000000 --- a/lib/internal/crypto/dsa.js +++ /dev/null @@ -1,225 +0,0 @@ -'use strict'; - -const { - Promise, - SafeSet, -} = primordials; - -const { - DSAKeyExportJob, - SignJob, - kCryptoJobAsync, - kSigEncDER, - kSignJobModeSign, - kSignJobModeVerify, -} = internalBinding('crypto'); - -const { - codes: { - ERR_INVALID_ARG_TYPE, - ERR_MISSING_OPTION, - } -} = require('internal/errors'); - -const { - validateUint32, -} = require('internal/validators'); - -const { - InternalCryptoKey, - createPrivateKey, - createPublicKey, - isKeyObject, -} = require('internal/crypto/keys'); - -const { - generateKeyPair, -} = require('internal/crypto/keygen'); - -const { - getUsagesUnion, - hasAnyNotIn, - jobPromise, - normalizeHashName, - kKeyObject, - kHandle, -} = require('internal/crypto/util'); - -const { - lazyDOMException, -} = require('internal/util'); - -function verifyAcceptableDsaKeyUse(name, type, usages) { - let checkSet; - switch (type) { - case 'private': - checkSet = ['sign']; - break; - case 'public': - checkSet = ['verify']; - break; - } - if (hasAnyNotIn(usages, checkSet)) { - throw lazyDOMException( - `Unsupported key usage for an ${name} key`, - 'SyntaxError'); - } -} - -async function dsaGenerateKey( - algorithm, - extractable, - keyUsages) { - const { - name, - modulusLength, - divisorLength, - hash - } = algorithm; - - if (hash === undefined) - throw new ERR_MISSING_OPTION('algorithm.hash'); - validateUint32(modulusLength, 'algorithm.modulusLength'); - - const usageSet = new SafeSet(keyUsages); - - if (hasAnyNotIn(usageSet, ['sign', 'verify'])) { - throw lazyDOMException( - 'Unsupported key usage for a DSA key', - 'SyntaxError'); - } - - return new Promise((resolve, reject) => { - generateKeyPair('dsa', { - modulusLength, - divisorLength, - }, (err, pubKey, privKey) => { - if (err) { - return reject(lazyDOMException( - 'The operation failed for an operation-specific reason', - 'OperationError')); - } - - const algorithm = { - name, - modulusLength, - divisorLength, - hash: { name: hash.name } - }; - - const publicKey = - new InternalCryptoKey( - pubKey, - algorithm, - getUsagesUnion(usageSet, 'verify'), - true); - - const privateKey = - new InternalCryptoKey( - privKey, - algorithm, - getUsagesUnion(usageSet, 'sign'), - extractable); - - resolve({ publicKey, privateKey }); - }); - }); -} - -function dsaExportKey(key, format) { - return jobPromise(new DSAKeyExportJob( - kCryptoJobAsync, - format, - key[kKeyObject][kHandle])); -} - -async function dsaImportKey( - format, - keyData, - algorithm, - extractable, - keyUsages) { - const { hash } = algorithm; - if (hash === undefined) - throw new ERR_MISSING_OPTION('algorithm.hash'); - - const usagesSet = new SafeSet(keyUsages); - let keyObject; - switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - if (keyData.type === 'secret') - throw lazyDOMException('Invalid key type', 'InvalidAccessException'); - verifyAcceptableDsaKeyUse(algorithm.name, keyData.type, usagesSet); - keyObject = keyData; - break; - } - case 'spki': { - verifyAcceptableDsaKeyUse(algorithm.name, 'public', usagesSet); - keyObject = createPublicKey({ - key: keyData, - format: 'der', - type: 'spki' - }); - break; - } - case 'pkcs8': { - verifyAcceptableDsaKeyUse(algorithm.name, 'private', usagesSet); - keyObject = createPrivateKey({ - key: keyData, - format: 'der', - type: 'pkcs8' - }); - break; - } - default: - throw lazyDOMException( - `Unable to import DSA key with format ${format}`, - 'NotSupportedError'); - } - - if (keyObject.asymmetricKeyType !== 'dsa') - throw lazyDOMException('Invalid key type', 'DataError'); - - const { - modulusLength, - divisorLength, - } = keyObject[kHandle].keyDetail({}); - - return new InternalCryptoKey(keyObject, { - name: algorithm.name, - modulusLength, - divisorLength, - hash: algorithm.hash - }, keyUsages, extractable); -} - -function dsaSignVerify(key, data, algorithm, signature) { - const mode = signature === undefined ? kSignJobModeSign : kSignJobModeVerify; - const type = mode === kSignJobModeSign ? 'private' : 'public'; - - if (key.type !== type) - throw lazyDOMException(`Key must be a ${type} key`, 'InvalidAccessError'); - - return jobPromise(new SignJob( - kCryptoJobAsync, - signature === undefined ? kSignJobModeSign : kSignJobModeVerify, - key[kKeyObject][kHandle], - undefined, - undefined, - undefined, - data, - normalizeHashName(key.algorithm.hash.name), - undefined, // Salt-length is not used in DSA - undefined, // Padding is not used in DSA - kSigEncDER, - signature)); -} - -module.exports = { - dsaExportKey, - dsaGenerateKey, - dsaImportKey, - dsaSignVerify, -}; diff --git a/lib/internal/crypto/ec.js b/lib/internal/crypto/ec.js index f7614b8f5d78d4..980c0f57cb046e 100644 --- a/lib/internal/crypto/ec.js +++ b/lib/internal/crypto/ec.js @@ -24,7 +24,6 @@ const { const { codes: { - ERR_INVALID_ARG_TYPE, ERR_MISSING_OPTION, } } = require('internal/errors'); @@ -55,7 +54,6 @@ const { PublicKeyObject, createPrivateKey, createPublicKey, - isKeyObject, } = require('internal/crypto/keys'); function verifyAcceptableEcKeyUse(name, type, usages) { @@ -178,15 +176,6 @@ async function ecImportKey( let keyObject; const usagesSet = new SafeSet(keyUsages); switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - if (keyData.type === 'secret') - throw lazyDOMException('Invalid key type', 'InvalidAccessException'); - verifyAcceptableEcKeyUse(name, keyData.type, usagesSet); - keyObject = keyData; - break; - } case 'spki': { verifyAcceptableEcKeyUse(name, 'public', usagesSet); keyObject = createPublicKey({ diff --git a/lib/internal/crypto/hashnames.js b/lib/internal/crypto/hashnames.js index be5064532c86c9..5c0051e0a8f563 100644 --- a/lib/internal/crypto/hashnames.js +++ b/lib/internal/crypto/hashnames.js @@ -11,7 +11,6 @@ const kHashContextJwkRsa = 3; const kHashContextJwkRsaPss = 4; const kHashContextJwkRsaOaep = 5; const kHashContextJwkHmac = 6; -const kHashContextJwkDsa = 7; // WebCrypto and JWK use a bunch of different names for the // standard set of SHA-* digest algorithms... which is ... fun. @@ -26,7 +25,6 @@ const kHashNames = { [kHashContextJwkRsaPss]: 'PS1', [kHashContextJwkRsaOaep]: 'RSA-OAEP', [kHashContextJwkHmac]: 'HS1', - [kHashContextJwkDsa]: 'NODE-DSA-SHA-1', }, sha256: { [kHashContextNode]: 'sha256', @@ -35,7 +33,6 @@ const kHashNames = { [kHashContextJwkRsaPss]: 'PS256', [kHashContextJwkRsaOaep]: 'RSA-OAEP-256', [kHashContextJwkHmac]: 'HS256', - [kHashContextJwkDsa]: 'NODE-DSA-SHA-256', }, sha384: { [kHashContextNode]: 'sha384', @@ -44,7 +41,6 @@ const kHashNames = { [kHashContextJwkRsaPss]: 'PS384', [kHashContextJwkRsaOaep]: 'RSA-OAEP-384', [kHashContextJwkHmac]: 'HS384', - [kHashContextJwkDsa]: 'NODE-DSA-SHA-384', }, sha512: { [kHashContextNode]: 'sha512', @@ -53,7 +49,6 @@ const kHashNames = { [kHashContextJwkRsaPss]: 'PS512', [kHashContextJwkRsaOaep]: 'RSA-OAEP-512', [kHashContextJwkHmac]: 'HS512', - [kHashContextJwkDsa]: 'NODE-DSA-SHA-512', } }; @@ -85,6 +80,5 @@ normalizeHashName.kContextJwkRsa = kHashContextJwkRsa; normalizeHashName.kContextJwkRsaPss = kHashContextJwkRsaPss; normalizeHashName.kContextJwkRsaOaep = kHashContextJwkRsaOaep; normalizeHashName.kContextJwkHmac = kHashContextJwkHmac; -normalizeHashName.kContextJwkDsa = kHashContextJwkDsa; module.exports = normalizeHashName; diff --git a/lib/internal/crypto/mac.js b/lib/internal/crypto/mac.js index 61fcc88a923dad..3054f66b27d4f2 100644 --- a/lib/internal/crypto/mac.js +++ b/lib/internal/crypto/mac.js @@ -32,7 +32,6 @@ const { const { codes: { ERR_MISSING_OPTION, - ERR_INVALID_ARG_TYPE, } } = require('internal/errors'); @@ -44,7 +43,6 @@ const { InternalCryptoKey, SecretKeyObject, createSecretKey, - isKeyObject, } = require('internal/crypto/keys'); async function hmacGenerateKey(algorithm, extractable, keyUsages) { @@ -99,18 +97,6 @@ async function hmacImportKey( } let keyObject; switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - - if (keyData.type !== 'secret') { - throw lazyDOMException( - `Unable to import HMAC key with format ${format}`); - } - - keyObject = keyData; - break; - } case 'raw': { const checkLength = keyData.byteLength * 8; diff --git a/lib/internal/crypto/rsa.js b/lib/internal/crypto/rsa.js index 524227fef69659..27b5803db4f77d 100644 --- a/lib/internal/crypto/rsa.js +++ b/lib/internal/crypto/rsa.js @@ -61,7 +61,6 @@ const { PublicKeyObject, createPublicKey, createPrivateKey, - isKeyObject, } = require('internal/crypto/keys'); const { @@ -247,15 +246,6 @@ async function rsaImportKey( const usagesSet = new SafeSet(keyUsages); let keyObject; switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - if (keyData.type === 'secret') - throw lazyDOMException('Invalid key type', 'InvalidAccessException'); - verifyAcceptableRsaKeyUse(algorithm.name, keyData.type, usagesSet); - keyObject = keyData; - break; - } case 'spki': { verifyAcceptableRsaKeyUse(algorithm.name, 'public', usagesSet); keyObject = createPublicKey({ diff --git a/lib/internal/crypto/scrypt.js b/lib/internal/crypto/scrypt.js index a36fb6dfba5260..3e6565b85d36f0 100644 --- a/lib/internal/crypto/scrypt.js +++ b/lib/internal/crypto/scrypt.js @@ -2,7 +2,6 @@ const { FunctionPrototypeCall, - Promise, } = primordials; const { Buffer } = require('buffer'); @@ -30,13 +29,8 @@ const { const { getArrayBufferOrView, getDefaultEncoding, - kKeyObject, } = require('internal/crypto/util'); -const { - lazyDOMException, -} = require('internal/util'); - const defaults = { N: 16384, r: 8, @@ -141,45 +135,7 @@ function check(password, salt, keylen, options) { return { password, salt, keylen, N, r, p, maxmem }; } -async function scryptDeriveBits(algorithm, baseKey, length) { - validateUint32(length, 'length'); - const { - N = 16384, - r = 8, - p = 1, - maxmem = 32 * 1024 * 1024, - encoding, - } = algorithm; - validateUint32(N, 'algorithm.N'); - validateUint32(r, 'algorithm.r'); - validateUint32(p, 'algorithm.p'); - validateUint32(maxmem, 'algorithm.maxmem'); - const salt = getArrayBufferOrView(algorithm.salt, 'algorithm.salt', encoding); - - const raw = baseKey[kKeyObject].export(); - - let byteLength = 64; // the default - if (length !== undefined) { - if (length === 0) - throw lazyDOMException('length cannot be zero', 'OperationError'); - if (length % 8) { - throw lazyDOMException( - 'length must be a multiple of 8', - 'OperationError'); - } - byteLength = length / 8; - } - - return new Promise((resolve, reject) => { - scrypt(raw, salt, byteLength, { N, r, p, maxmem }, (err, result) => { - if (err) return reject(err); - resolve(result.buffer); - }); - }); -} - module.exports = { scrypt, scryptSync, - scryptDeriveBits, }; diff --git a/lib/internal/crypto/util.js b/lib/internal/crypto/util.js index 83926451edd490..40a677606bf3f0 100644 --- a/lib/internal/crypto/util.js +++ b/lib/internal/crypto/util.js @@ -170,11 +170,6 @@ const kAlgorithms = { 'ed448': 'Ed448', 'x25519': 'X25519', 'x448': 'X448', - // Following here are Node.js specific extensions. All - // should be prefixed with 'node-' - 'node-dsa': 'NODE-DSA', - 'node-dh': 'NODE-DH', - 'node-scrypt': 'NODE-SCRYPT', }; const kAlgorithmsKeys = ObjectKeys(kAlgorithms); @@ -184,8 +179,7 @@ const kExportFormats = [ 'raw', 'pkcs8', 'spki', - 'jwk', - 'node.keyObject']; + 'jwk']; // These are the only hash algorithms we currently support via // the Web Crypto API. diff --git a/lib/internal/crypto/webcrypto.js b/lib/internal/crypto/webcrypto.js index 503603a9f0aa63..a5f442b0e57cfb 100644 --- a/lib/internal/crypto/webcrypto.js +++ b/lib/internal/crypto/webcrypto.js @@ -43,7 +43,6 @@ const { InternalCryptoKey, createSecretKey, isCryptoKey, - isKeyObject, } = require('internal/crypto/keys'); const { @@ -124,15 +123,6 @@ async function generateKey( case 'AES-KW': return lazyRequire('internal/crypto/aes') .aesGenerateKey(algorithm, extractable, keyUsages); - - // Following are Node.js specific extensions. Names must be prefixed - // with the `NODE-` - case 'NODE-DSA': - return lazyRequire('internal/crypto/dsa') - .dsaGenerateKey(algorithm, extractable, keyUsages); - case 'NODE-DH': - return lazyRequire('internal/crypto/diffiehellman') - .dhGenerateKey(algorithm, extractable, keyUsages); default: throw lazyDOMException('Unrecognized name.'); } @@ -164,12 +154,6 @@ async function deriveBits(algorithm, baseKey, length) { case 'PBKDF2': return lazyRequire('internal/crypto/pbkdf2') .pbkdf2DeriveBits(algorithm, baseKey, length); - case 'NODE-SCRYPT': - return lazyRequire('internal/crypto/scrypt') - .scryptDeriveBits(algorithm, baseKey, length); - case 'NODE-DH': - return lazyRequire('internal/crypto/diffiehellman') - .asyncDeriveBitsDH(algorithm, baseKey, length); } throw lazyDOMException('Unrecognized name.'); } @@ -252,14 +236,6 @@ async function deriveKey( bits = await lazyRequire('internal/crypto/pbkdf2') .pbkdf2DeriveBits(algorithm, baseKey, length); break; - case 'NODE-SCRYPT': - bits = await lazyRequire('internal/crypto/scrypt') - .scryptDeriveBits(algorithm, baseKey, length); - break; - case 'NODE-DH': - bits = await lazyRequire('internal/crypto/diffiehellman') - .asyncDeriveBitsDH(algorithm, baseKey, length); - break; default: throw lazyDOMException('Unrecognized name.'); } @@ -303,18 +279,6 @@ async function exportKeySpki(key) { .cfrgExportKey(key, kWebCryptoKeyFormatSPKI); } break; - case 'NODE-DSA': - if (key.type === 'public') { - return lazyRequire('internal/crypto/dsa') - .dsaExportKey(key, kWebCryptoKeyFormatSPKI); - } - break; - case 'NODE-DH': - if (key.type === 'public') { - return lazyRequire('internal/crypto/diffiehellman') - .dhExportKey(key, kWebCryptoKeyFormatSPKI); - } - break; } throw lazyDOMException( @@ -354,18 +318,6 @@ async function exportKeyPkcs8(key) { .cfrgExportKey(key, kWebCryptoKeyFormatPKCS8); } break; - case 'NODE-DSA': - if (key.type === 'private') { - return lazyRequire('internal/crypto/dsa') - .dsaExportKey(key, kWebCryptoKeyFormatPKCS8); - } - break; - case 'NODE-DH': - if (key.type === 'private') { - return lazyRequire('internal/crypto/diffiehellman') - .dhExportKey(key, kWebCryptoKeyFormatPKCS8); - } - break; } throw lazyDOMException( @@ -482,7 +434,6 @@ async function exportKey(format, key) { throw lazyDOMException('key is not extractable', 'InvalidAccessException'); switch (format) { - case 'node.keyObject': return key[kKeyObject]; case 'spki': return exportKeySpki(key); case 'pkcs8': return exportKeyPkcs8(key); case 'jwk': return exportKeyJWK(key); @@ -509,15 +460,6 @@ async function importGenericSecretKey( } switch (format) { - case 'node.keyObject': { - if (!isKeyObject(keyData)) - throw new ERR_INVALID_ARG_TYPE('keyData', 'KeyObject', keyData); - - if (keyData.type === 'secret') - return new InternalCryptoKey(keyData, { name }, keyUsages, extractable); - - break; - } case 'raw': { if (hasAnyNotIn(usagesSet, ['deriveKey', 'deriveBits'])) { throw lazyDOMException( @@ -557,7 +499,7 @@ async function importKey( if (this !== subtle) throw new ERR_INVALID_THIS('SubtleCrypto'); validateString(format, 'format'); validateOneOf(format, 'format', kExportFormats); - if (format !== 'node.keyObject' && format !== 'jwk') + if (format !== 'jwk') keyData = getArrayBufferOrView(keyData, 'keyData'); algorithm = normalizeAlgorithm(algorithm); validateBoolean(extractable, 'extractable'); @@ -598,8 +540,6 @@ async function importKey( .aesImportKey(algorithm, format, keyData, extractable, keyUsages); case 'HKDF': // Fall through - case 'NODE-SCRYPT': - // Fall through case 'PBKDF2': return importGenericSecretKey( algorithm, @@ -607,12 +547,6 @@ async function importKey( keyData, extractable, keyUsages); - case 'NODE-DSA': - return lazyRequire('internal/crypto/dsa') - .dsaImportKey(format, keyData, algorithm, extractable, keyUsages); - case 'NODE-DH': - return lazyRequire('internal/crypto/diffiehellman') - .dhImportKey(format, keyData, algorithm, extractable, keyUsages); } throw lazyDOMException('Unrecognized name.', 'NotSupportedError'); @@ -716,11 +650,6 @@ function signVerify(algorithm, key, data, signature) { case 'HMAC': return lazyRequire('internal/crypto/mac') .hmacSignVerify(key, data, algorithm, signature); - // The following are Node.js specific extensions. They must begin with - // the `NODE-` prefix - case 'NODE-DSA': - return lazyRequire('internal/crypto/dsa') - .dsaSignVerify(key, data, algorithm, signature); } throw lazyDOMException('Unrecognized named.', 'NotSupportedError'); } diff --git a/test/fixtures/crypto/dsa.js b/test/fixtures/crypto/dsa.js deleted file mode 100644 index c88720220c5e03..00000000000000 --- a/test/fixtures/crypto/dsa.js +++ /dev/null @@ -1,93 +0,0 @@ -'use strict'; - -module.exports = function() { - const pkcs8 = Buffer.from( - '3082015b0201003082013406072a8648ce3804013082012702818100d5f35aa5730e2' + - '6166fd3ea81f8f0eeb05bd1250e164b7c76b180b6dae95096d13dee6956e15a9aea7c' + - 'f18a0df7c5dc326ccef1cbf97636d22f870b76f2607f9a867db2756aecf65505aa48f' + - 'dea5f5ee54f508a05d9dae76bf262b4ca3662cc176b7c628c7bee2076df07f9a64e04' + - '02630dfee63eaf0ed64d48b469fe1c9ac4a1021d00b14213226cfcfb59e3a0379e559' + - 'c74ff8a7383eb4c41cecb6f3732b702818100a0865b7f8954e7ae587c8e6a89e391e8' + - '2657c58f05ccd94de61748e89e217efab3d9b5fa842ebc62525966916ad2b7af422a9' + - 'b2407817a5b382b6581434fd1a169c75ad4d0e3862a3f484e9f9f2a816f943a8e6060' + - 'f26fe27c533587b765e57948439084e76fd6a4fd004f5c78d972cf7f100ec9494a902' + - '645baca4b4c6f3993041e021c600daa0a9c4cc674c98bb07956374c84ac1c33af8816' + - '3ea7e2587876', 'hex'); - - const spki = Buffer.from( - '308201c03082013406072a8648ce3804013082012702818100d5f35aa5730e26166fd' + - '3ea81f8f0eeb05bd1250e164b7c76b180b6dae95096d13dee6956e15a9aea7cf18a0d' + - 'f7c5dc326ccef1cbf97636d22f870b76f2607f9a867db2756aecf65505aa48fdea5f5' + - 'ee54f508a05d9dae76bf262b4ca3662cc176b7c628c7bee2076df07f9a64e0402630d' + - 'fee63eaf0ed64d48b469fe1c9ac4a1021d00b14213226cfcfb59e3a0379e559c74ff8' + - 'a7383eb4c41cecb6f3732b702818100a0865b7f8954e7ae587c8e6a89e391e82657c5' + - '8f05ccd94de61748e89e217efab3d9b5fa842ebc62525966916ad2b7af422a9b24078' + - '17a5b382b6581434fd1a169c75ad4d0e3862a3f484e9f9f2a816f943a8e6060f26fe2' + - '7c533587b765e57948439084e76fd6a4fd004f5c78d972cf7f100ec9494a902645bac' + - 'a4b4c6f399303818500028181009a8df69f2fe321869e2094e387bc1dc2b5f3bff2a2' + - 'e23cfba51d3c119fba6b4c15a49485fa811b6955d91d28c9e2e0445a79ddc5426b2fe' + - '44e00a6c9254c776f13fd10dbc934262077b1df72c16bc848817c61fb6a607abe60c7' + - 'd11528ab9bdf55de45495733a047bd75a48b8166f1aa3deab681a2574a4f35106f0d7' + - '8b641d7', 'hex'); - - const plaintext = Buffer.from( - '5f4dba4f320c0ce876725afce5fbd25bf83e5a7125a08cafe73c3ebac421779df9d55' + - 'd180c3ae9942645e1d82fee8c9d294b3cb1a08a9931201b3c0e81fc47cacf8315a2af' + - '66324113c3b66230c34608c4f4593634ce02b267362277f0a840ca74bc3d1a6236952' + - 'c5ed7aaf8a8fecbddfa7584e6978cea5d2a5b9fb7f1b48c8b0be58a305202754d8376' + - '107374793cf026aaee5300727d836cd71e71b345ddb2e44446ffc5b901635413890d9' + - '10ea380984a90191031323f16dbcc9d6be168b84885384ca03e12600ac1c248028af3' + - '726cc93463882ea8c02aab', 'hex'); - - const signatures = { - 'sha-1': Buffer.from( - '303d021c685192dc48fbd8c6dd80536eaf92050ca07aa85af5a25a41a93bc8ea021' + - 'd009a032a19182ceca7b202d7e0ce327fe5830a9937a37714d4c6801ae9', 'hex'), - 'sha-256': Buffer.from( - '303d021c7b660d1b2b40237d0f615877efbf2a3f51577bc42a3cb4e280c0a6a9021' + - 'd008393a01a9bcabce267dfcc6bc867d348911f6eda3db96d3078a380c1', 'hex'), - 'sha-384': Buffer.from( - '303e021d00ab84d3c306aea1c5e69e126d21dafc03ee9c7aa8fa38884de5015d510' + - '21d0099030adacdc6787dcb1dc3b05fa122ad72d4ddc281cc619565dba947', 'hex'), - 'sha-512': Buffer.from( - '303c021c069c40654607388a56d3cb827c11121d07850b3b62ed203c1d92ce7f021' + - 'c0e69f41933d0ee3b1c1b184d742f3813ee3b32d053f13fbb93ab8229', 'hex'), - } - - const vectors = [ - { - publicKeyBuffer: spki, - privateKeyBuffer: pkcs8, - algorithm: { name: 'NODE-DSA' }, - hash: 'SHA-1', - plaintext, - signature: signatures['sha-1'] - }, - { - publicKeyBuffer: spki, - privateKeyBuffer: pkcs8, - algorithm: { name: 'NODE-DSA' }, - hash: 'SHA-256', - plaintext, - signature: signatures['sha-256'] - }, - { - publicKeyBuffer: spki, - privateKeyBuffer: pkcs8, - algorithm: { name: 'NODE-DSA'}, - hash: 'SHA-384', - plaintext, - signature: signatures['sha-384'] - }, - { - publicKeyBuffer: spki, - privateKeyBuffer: pkcs8, - algorithm: { name: 'NODE-DSA' }, - hash: 'SHA-512', - plaintext, - signature: signatures['sha-512'] - } - ]; - - return vectors; -}; diff --git a/test/parallel/test-crypto-key-objects.js b/test/parallel/test-crypto-key-objects.js index 40a982ea7b6cd6..ce8de4d0cdba2d 100644 --- a/test/parallel/test-crypto-key-objects.js +++ b/test/parallel/test-crypto-key-objects.js @@ -5,7 +5,6 @@ if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); -const { types: { isKeyObject } } = require('util'); const { createCipheriv, createDecipheriv, @@ -23,7 +22,6 @@ const { getCurves, generateKeySync, generateKeyPairSync, - webcrypto, } = require('crypto'); const fixtures = require('../common/fixtures'); @@ -825,27 +823,6 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', }); } -{ - const buffer = Buffer.from('Hello World'); - const keyObject = createSecretKey(buffer); - const keyPair = generateKeyPairSync('ec', { namedCurve: 'P-256' }); - assert(isKeyObject(keyPair.publicKey)); - assert(isKeyObject(keyPair.privateKey)); - assert(isKeyObject(keyObject)); - - assert(!isKeyObject(buffer)); - - webcrypto.subtle.importKey( - 'node.keyObject', - keyPair.publicKey, - { name: 'ECDH', namedCurve: 'P-256' }, - false, - [], - ).then((cryptoKey) => { - assert(!isKeyObject(cryptoKey)); - }); -} - { const first = Buffer.from('Hello'); const second = Buffer.from('World'); diff --git a/test/parallel/test-webcrypto-derivebits-node-dh.js b/test/parallel/test-webcrypto-derivebits-node-dh.js deleted file mode 100644 index 2503bc17032e0d..00000000000000 --- a/test/parallel/test-webcrypto-derivebits-node-dh.js +++ /dev/null @@ -1,219 +0,0 @@ -'use strict'; - -const common = require('../common'); - -if (!common.hasCrypto) - common.skip('missing crypto'); - -const assert = require('assert'); -const { subtle } = require('crypto').webcrypto; - -const kTestData = { - pkcs8: '308203260201003082019706092a864886f70d010301308201880282018100ff' + - 'ffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc7402' + - '0bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374f' + - 'e1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee' + - '386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598' + - 'da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9e' + - 'd529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be3' + - '9e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf69558171839' + - '95497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a8' + - '5521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7ab' + - 'f5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d8' + - '7602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208' + - 'e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff02' + - '010204820184028201806ba21bec44fe29bee2d1f6f5d717b9af1c62973b342c' + - '28b850d2e39b31abf3ce7f58a26da0cdf538b3328648ee8738e49434bdf697ff' + - '2ac5da64d308fa0abbd75f0554bcef58fd1a688bf93af00ffbdb9ba05558a8e6' + - '16db9818769e2c7e37ba0c07bca10fffd19cb7aa44876170f0a8fe0c1bdba2f9' + - 'b0606d479796e1b6bdab153188b03f684584fd909814c5055fc184eaf05577f7' + - 'f447fcc2dd90889ab853830993d8fbf087f942d8e7a9f331570e7eee5954fb7a' + - 'a6920f4df2f8a33d5cb59961162b1216a4382f984cce02512f0100e20f15e480' + - 'a9d19bb01414a75c74d0854595e58ed060f7bb0f4b451f82b476dc039cc1bb8c' + - '1a05999e6abb20915a3cfca40f314538c00f42d0c4f2070cb163788d6dea0adb' + - '03c75d8001c7057ef61e60b407272adffc2669b82e634ebebda45826229bb2f8' + - 'ed742ee97429e34de06c41c25563025285d5f8a43acdc57cf12779222ae125d5' + - '438857d6bf6341815b9aebf6878fd23944cfd240e74caea13419163fde5ec1ec' + - 'fe2fb2e740b9301a9c04', - spki: '308203253082019706092a864886f70d010301308201880282018100fffffffff' + - 'fffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b' + - '139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d5' + - '1c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a89' + - '9fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d' + - '39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed52907709696' + - '6d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e860' + - '39b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae5' + - '15d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64e' + - 'cfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e' + - '8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521' + - 'f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db' + - '5bfce0fd108e4b82d120a93ad2caffffffffffffffff020102038201860002820' + - '1810098b01807f77a722cd30fe0390f8cdd0b3f7e0fb33fd3e0ca3d573a7b481e' + - 'dc0fc9f7bc58bfc4509f34efe118ba48bcefbbd57c4878e87b4d0fbb4b661d771' + - '19055cf190b5e8ad05c4821ff0445f4e12049e708ee83e2272c2c269b8b3bfa1b' + - '37df8dc4ec77a430ed6b89beb69093ceeca48497d8ab3ceac25429df58e96d2df' + - 'd01a94b1d164697b93475ed3d5962fd7c300de959474568aecc15c880c36b14a7' + - '9c2144ad4207c9760c11fbcc9ccbb29727a7f5a7789d47f1fa7a154289f83c528' + - '1fb97e01c37f937a25b4057017961ebd52b936f6b8f6d9ad35e3e094c3850cde2' + - '9e98895eaa9b56bff17dc6d8c03edce51c0aa009864da9cbe49a2063bddc64f11' + - '67beb0ab1c5d9bccf9a10078d0236237986f53c4074f30399deb829c544026fe0' + - '532e54e1bc9d933bd4db8dbfd43cf7839a9f64c135d2188896294d54cb7812e6e' + - '9586a03e91893edf7240011e8cda8f59a4dde0ce6d3c40d85847a3985fa25967f' + - 'a2c9598b269ac28da067704f15eb5bb4d8afdea8c67f56f9b604e172bc', - result: '42e77c77568f4387858771b006bebf213a2894efed8efdcfe23640bbd6df765' + - '1b2afa9f5acfba5b1d3db5401fd3427cd9226f6c2fdbd2b8fd7948e12cc7e016' + - 'eb2ed0e0fb02ce434c68c5d511ded05c1150718cf4c8b9db0adcc639a8b52b74' + - 'c2c90e2df5f6f55462d38e2d2769b4bd23bf0db8b4a82253addc1d5d6d19289d' + - '9e60ddabe1203aa3f45956f4dd32683f55fc2f7400e92712e5bb4dea737e03ad' + - '4b94640ccd63a0b8485dfa63f3b98232a34354aa91aebb3e86bb67a48b50ac21' + - 'e62dbce80c0913a9dba92c1c2333f4a43efe9c6c24ce23c252c7ff37e9e74a78' + - '6a8c5b82453fda8b6b40463461d22765e26d4f444272254ee6a492d3e6737e52' + - 'a94440aeddde3c0b449c52ca64bdc698f683ba6cb27794b84edcab7694cadfe8' + - 'f76ce94bf127ca42323b1995a863bcecab455f5d6283eb0eed44942aad3d1a46' + - '79713ed4757917f95d1a61ecae45b9978a863b16e199418bfe6e98435ad146a4' + - '7bd9c8cad9f787a29888954ae58fa683ea163921eb9d3e7a5aa2f52f74ec15333', -}; - -async function prepareKeys() { - const [ - privateKey, - publicKey, - ] = await Promise.all([ - subtle.importKey( - 'pkcs8', - Buffer.from(kTestData.pkcs8, 'hex'), - { name: 'NODE-DH' }, - true, - ['deriveKey', 'deriveBits']), - subtle.importKey( - 'spki', - Buffer.from(kTestData.spki, 'hex'), - { name: 'NODE-DH' }, - true, []), - ]); - return { - privateKey, - publicKey, - result: kTestData.result, - }; -} - -(async function() { - const { - publicKey, - privateKey, - result - } = await prepareKeys(); - - { - // Good parameters - const bits = await subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey - }, privateKey, null); - - assert(bits instanceof ArrayBuffer); - assert.strictEqual(Buffer.from(bits).toString('hex'), result); - } - - { - // Case insensitivity - const bits = await subtle.deriveBits({ - name: 'node-dH', - public: publicKey - }, privateKey, null); - - assert.strictEqual(Buffer.from(bits).toString('hex'), result); - } - - { - // Short Result - const bits = await subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey - }, privateKey, 16); - - assert.strictEqual( - Buffer.from(bits).toString('hex'), - result.slice(0, 4)); - } - - { - // Too long result - await assert.rejects(subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey - }, privateKey, result.length * 16), { - message: /derived bit length is too small/ - }); - } - - { - // Non-multiple of 8 - const bits = await subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey - }, privateKey, 15); - - assert.strictEqual( - Buffer.from(bits).toString('hex'), - result.slice(0, 2)); - } - - // Error tests - { - // Missing public property - await assert.rejects( - subtle.deriveBits( - { name: 'NODE-DH' }, - privateKey, - null), - { code: 'ERR_INVALID_ARG_TYPE' }); - } - - { - // The public property is not a CryptoKey - await assert.rejects( - subtle.deriveBits( - { - name: 'NODE-DH', - public: { message: 'Not a CryptoKey' } - }, - privateKey, - null), - { code: 'ERR_INVALID_ARG_TYPE' }); - } - - { - // Incorrect public key algorithm - const { publicKey } = await subtle.generateKey( - { - name: 'ECDSA', - namedCurve: 'P-521' - }, false, ['verify']); - - await assert.rejects(subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey - }, privateKey, null), { - message: /Keys must be DH keys/ - }); - } - - { - // Private key does not have correct usages - const privateKey = await subtle.importKey( - 'pkcs8', - Buffer.from(kTestData.pkcs8, 'hex'), - { - name: 'NODE-DH', - }, false, ['deriveKey']); - - await assert.rejects(subtle.deriveBits({ - name: 'NODE-DH', - public: publicKey, - }, privateKey, null), { - message: /baseKey does not have deriveBits usage/ - }); - } -})().then(common.mustCall()); diff --git a/test/parallel/test-webcrypto-derivebits.js b/test/parallel/test-webcrypto-derivebits.js index d4c0f8cbe239b0..442423954b10b2 100644 --- a/test/parallel/test-webcrypto-derivebits.js +++ b/test/parallel/test-webcrypto-derivebits.js @@ -9,8 +9,6 @@ if (!common.hasCrypto) const assert = require('assert'); const { subtle } = require('crypto').webcrypto; -const { internalBinding } = require('internal/test/binding'); - // This is only a partial test. The WebCrypto Web Platform Tests // will provide much greater coverage. @@ -103,36 +101,6 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } -// Test Scrypt bit derivation -if (typeof internalBinding('crypto').ScryptJob === 'function') { - async function test(pass, salt, length, expected) { - const ec = new TextEncoder(); - const key = await subtle.importKey( - 'raw', - ec.encode(pass), - { name: 'NODE-SCRYPT' }, - false, ['deriveBits']); - const secret = await subtle.deriveBits({ - name: 'NODE-SCRYPT', - salt: ec.encode(salt), - }, key, length); - assert(secret instanceof ArrayBuffer); - assert.strictEqual(Buffer.from(secret).toString('hex'), expected); - } - - const kTests = [ - ['hello', 'there', 512, - '30ddda6feabaac788eb81cc38f496cd5d9a165d320c537ea05331fe720db1061b3a27' + - 'b91a8428e49d44078c1fa395cb1c6db336ba44ccb80faa6d74918769374'], - ['hello', 'there', 128, - '30ddda6feabaac788eb81cc38f496cd5'], - ]; - - const tests = Promise.all(kTests.map((args) => test(...args))); - - tests.then(common.mustCall()); -} - // Test X25519 and X448 bit derivation { async function test(name) { diff --git a/test/parallel/test-webcrypto-derivekey.js b/test/parallel/test-webcrypto-derivekey.js index 67513252545368..f8eb996000ec89 100644 --- a/test/parallel/test-webcrypto-derivekey.js +++ b/test/parallel/test-webcrypto-derivekey.js @@ -9,8 +9,6 @@ if (!common.hasCrypto) const assert = require('assert'); const { webcrypto: { subtle }, KeyObject } = require('crypto'); -const { internalBinding } = require('internal/test/binding'); - // This is only a partial test. The WebCrypto Web Platform Tests // will provide much greater coverage. @@ -121,38 +119,6 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } -// Test Scrypt key derivation -if (typeof internalBinding('crypto').ScryptJob === 'function') { - async function test(pass, salt, expected) { - const ec = new TextEncoder(); - const key = await subtle.importKey( - 'raw', - ec.encode(pass), - { name: 'NODE-SCRYPT' }, - false, ['deriveKey']); - const secret = await subtle.deriveKey({ - name: 'NODE-SCRYPT', - salt: ec.encode(salt), - }, key, { - name: 'AES-CTR', - length: 256 - }, true, ['encrypt']); - - const raw = await subtle.exportKey('raw', secret); - - assert.strictEqual(Buffer.from(raw).toString('hex'), expected); - } - - const kTests = [ - ['hello', 'there', - '30ddda6feabaac788eb81cc38f496cd5d9a165d320c537ea05331fe720db1061'], - ]; - - const tests = Promise.all(kTests.map((args) => test(...args))); - - tests.then(common.mustCall()); -} - // Test default key lengths { const vectors = [ diff --git a/test/parallel/test-webcrypto-export-import-cfrg.js b/test/parallel/test-webcrypto-export-import-cfrg.js index 9f73701ad246e8..c37c1535747917 100644 --- a/test/parallel/test-webcrypto-export-import-cfrg.js +++ b/test/parallel/test-webcrypto-export-import-cfrg.js @@ -284,16 +284,6 @@ async function testImportJwk({ name, publicUsages, privateUsages }, extractable) 'Ed25519': ['verify', 'sign'], 'X448': ['deriveBits', 'deriveBits'], })) { - assert.rejects(subtle.importKey( - 'node.keyObject', - rsaPublic, - { name }, - true, [publicUsage]), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'node.keyObject', - rsaPrivate, - { name }, - true, [privateUsage]), { message: /Invalid key type/ }); assert.rejects(subtle.importKey( 'spki', rsaPublic.export({ format: 'der', type: 'spki' }), diff --git a/test/parallel/test-webcrypto-export-import-dsa.js b/test/parallel/test-webcrypto-export-import-dsa.js deleted file mode 100644 index 01e31d747942ae..00000000000000 --- a/test/parallel/test-webcrypto-export-import-dsa.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; - -const common = require('../common'); -const fixtures = require('../common/fixtures'); - -if (!common.hasCrypto) - common.skip('missing crypto'); - -const assert = require('assert'); -const crypto = require('crypto'); -const { subtle } = crypto.webcrypto; - -const sizes = [1024]; - -const hashes = [ - 'SHA-1', - 'SHA-256', - 'SHA-384', - 'SHA-512', -]; - -const keyData = { - 1024: { - spki: Buffer.from( - '308201c03082013406072a8648ce3804013082012702818100d5f35aa5730e26166fd' + - '3ea81f8f0eeb05bd1250e164b7c76b180b6dae95096d13dee6956e15a9aea7cf18a0d' + - 'f7c5dc326ccef1cbf97636d22f870b76f2607f9a867db2756aecf65505aa48fdea5f5' + - 'ee54f508a05d9dae76bf262b4ca3662cc176b7c628c7bee2076df07f9a64e0402630d' + - 'fee63eaf0ed64d48b469fe1c9ac4a1021d00b14213226cfcfb59e3a0379e559c74ff8' + - 'a7383eb4c41cecb6f3732b702818100a0865b7f8954e7ae587c8e6a89e391e82657c5' + - '8f05ccd94de61748e89e217efab3d9b5fa842ebc62525966916ad2b7af422a9b24078' + - '17a5b382b6581434fd1a169c75ad4d0e3862a3f484e9f9f2a816f943a8e6060f26fe2' + - '7c533587b765e57948439084e76fd6a4fd004f5c78d972cf7f100ec9494a902645bac' + - 'a4b4c6f399303818500028181009a8df69f2fe321869e2094e387bc1dc2b5f3bff2a2' + - 'e23cfba51d3c119fba6b4c15a49485fa811b6955d91d28c9e2e0445a79ddc5426b2fe' + - '44e00a6c9254c776f13fd10dbc934262077b1df72c16bc848817c61fb6a607abe60c7' + - 'd11528ab9bdf55de45495733a047bd75a48b8166f1aa3deab681a2574a4f35106f0d7' + - '8b641d7', 'hex'), - pkcs8: Buffer.from( - '3082015b0201003082013406072a8648ce3804013082012702818100d5f35aa5730e2' + - '6166fd3ea81f8f0eeb05bd1250e164b7c76b180b6dae95096d13dee6956e15a9aea7c' + - 'f18a0df7c5dc326ccef1cbf97636d22f870b76f2607f9a867db2756aecf65505aa48f' + - 'dea5f5ee54f508a05d9dae76bf262b4ca3662cc176b7c628c7bee2076df07f9a64e04' + - '02630dfee63eaf0ed64d48b469fe1c9ac4a1021d00b14213226cfcfb59e3a0379e559' + - 'c74ff8a7383eb4c41cecb6f3732b702818100a0865b7f8954e7ae587c8e6a89e391e8' + - '2657c58f05ccd94de61748e89e217efab3d9b5fa842ebc62525966916ad2b7af422a9' + - 'b2407817a5b382b6581434fd1a169c75ad4d0e3862a3f484e9f9f2a816f943a8e6060' + - 'f26fe27c533587b765e57948439084e76fd6a4fd004f5c78d972cf7f100ec9494a902' + - '645baca4b4c6f3993041e021c600daa0a9c4cc674c98bb07956374c84ac1c33af8816' + - '3ea7e2587876', 'hex'), - }, -}; - -async function testImportSpki({ name, publicUsages }, size, hash, extractable) { - const key = await subtle.importKey( - 'spki', - keyData[size].spki, - { name, hash }, - extractable, - publicUsages); - - assert.strictEqual(key.type, 'public'); - assert.strictEqual(key.extractable, extractable); - assert.deepStrictEqual(key.usages, publicUsages); - assert.strictEqual(key.algorithm.name, name); - assert.strictEqual(key.algorithm.modulusLength, size); - assert.strictEqual(key.algorithm.hash.name, hash); - - if (extractable) { - const spki = await subtle.exportKey('spki', key); - assert.strictEqual( - Buffer.from(spki).toString('hex'), - keyData[size].spki.toString('hex')); - } else { - await assert.rejects( - subtle.exportKey('spki', key), { - message: /key is not extractable/ - }); - } -} - -async function testImportPkcs8( - { name, privateUsages }, - size, - hash, - extractable) { - const key = await subtle.importKey( - 'pkcs8', - keyData[size].pkcs8, - { name, hash }, - extractable, - privateUsages); - - assert.strictEqual(key.type, 'private'); - assert.strictEqual(key.extractable, extractable); - assert.deepStrictEqual(key.usages, privateUsages); - assert.strictEqual(key.algorithm.name, name); - assert.strictEqual(key.algorithm.modulusLength, size); - assert.strictEqual(key.algorithm.hash.name, hash); - - if (extractable) { - const pkcs8 = await subtle.exportKey('pkcs8', key); - assert.strictEqual( - Buffer.from(pkcs8).toString('hex'), - keyData[size].pkcs8.toString('hex')); - } else { - await assert.rejects( - subtle.exportKey('pkcs8', key), { - message: /key is not extractable/ - }); - } -} - -// combinations to test -const testVectors = [ - { - name: 'NODE-DSA', - privateUsages: ['sign'], - publicUsages: ['verify'] - }, -]; - -(async function() { - const variations = []; - sizes.forEach((size) => { - hashes.forEach((hash) => { - [true, false].forEach((extractable) => { - testVectors.forEach((vector) => { - variations.push(testImportSpki(vector, size, hash, extractable)); - variations.push(testImportPkcs8(vector, size, hash, extractable)); - }); - }); - }); - }); - await Promise.all(variations); -})().then(common.mustCall()); - -{ - const ecPublic = crypto.createPublicKey( - fixtures.readKey('ec_p256_public.pem')); - const ecPrivate = crypto.createPrivateKey( - fixtures.readKey('ec_p256_private.pem')); - - assert.rejects(subtle.importKey( - 'node.keyObject', - ecPublic, - { name: 'NODE-DSA', hash: 'SHA-256' }, - true, ['verify']), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'node.keyObject', - ecPrivate, - { name: 'NODE-DSA', hash: 'SHA-256' }, - true, ['sign']), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'spki', - ecPublic.export({ format: 'der', type: 'spki' }), - { name: 'NODE-DSA', hash: 'SHA-256' }, - true, ['verify']), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'pkcs8', - ecPrivate.export({ format: 'der', type: 'pkcs8' }), - { name: 'NODE-DSA', hash: 'SHA-256' }, - true, ['sign']), { message: /Invalid key type/ }); -} diff --git a/test/parallel/test-webcrypto-export-import-ec.js b/test/parallel/test-webcrypto-export-import-ec.js index 682d5f54be5563..931323620c932c 100644 --- a/test/parallel/test-webcrypto-export-import-ec.js +++ b/test/parallel/test-webcrypto-export-import-ec.js @@ -287,16 +287,6 @@ async function testImportJwk( 'ECDSA': ['verify', 'sign'], 'ECDH': ['deriveBits', 'deriveBits'], })) { - assert.rejects(subtle.importKey( - 'node.keyObject', - rsaPublic, - { name, hash: 'SHA-256', namedCurve: 'P-256' }, - true, [publicUsage]), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'node.keyObject', - rsaPrivate, - { name, hash: 'SHA-256', namedCurve: 'P-256' }, - true, [privateUsage]), { message: /Invalid key type/ }); assert.rejects(subtle.importKey( 'spki', rsaPublic.export({ format: 'der', type: 'spki' }), diff --git a/test/parallel/test-webcrypto-export-import-rsa.js b/test/parallel/test-webcrypto-export-import-rsa.js index 3a2ea7b279852d..1efc69b70aa971 100644 --- a/test/parallel/test-webcrypto-export-import-rsa.js +++ b/test/parallel/test-webcrypto-export-import-rsa.js @@ -492,16 +492,6 @@ const testVectors = [ 'RSASSA-PKCS1-v1_5': ['verify', 'sign'], 'RSA-OAEP': ['encrypt', 'decrypt'], })) { - assert.rejects(subtle.importKey( - 'node.keyObject', - ecPublic, - { name, hash: 'SHA-256' }, - true, [publicUsage]), { message: /Invalid key type/ }); - assert.rejects(subtle.importKey( - 'node.keyObject', - ecPrivate, - { name, hash: 'SHA-256' }, - true, [privateUsage]), { message: /Invalid key type/ }); assert.rejects(subtle.importKey( 'spki', ecPublic.export({ format: 'der', type: 'spki' }), diff --git a/test/parallel/test-webcrypto-export-import.js b/test/parallel/test-webcrypto-export-import.js index b4fd26b0cda6ae..02e178f72628d5 100644 --- a/test/parallel/test-webcrypto-export-import.js +++ b/test/parallel/test-webcrypto-export-import.js @@ -42,13 +42,6 @@ const { subtle } = webcrypto; name: 'SyntaxError', message: 'Unsupported key usage for an HMAC key' }); - await assert.rejects( - subtle.importKey('node.keyObject', '', { - name: 'HMAC', - hash: 'SHA-256' - }, false, ['sign', 'verify']), { - code: 'ERR_INVALID_ARG_TYPE' - }); await assert.rejects( subtle.importKey('raw', keyData, { name: 'HMAC', diff --git a/test/parallel/test-webcrypto-keygen.js b/test/parallel/test-webcrypto-keygen.js index 17f6924caec286..948c755a9114bc 100644 --- a/test/parallel/test-webcrypto-keygen.js +++ b/test/parallel/test-webcrypto-keygen.js @@ -163,17 +163,6 @@ const vectors = { 'deriveBits', ] }, - 'NODE-DSA': { - algorithm: { modulusLength: 1024, hash: 'SHA-256' }, - usages: [ - 'sign', - 'verify', - ], - mandatoryUsages: [ - 'sign', - 'verify', - ] - } }; // Test invalid algorithms @@ -569,127 +558,6 @@ const vectors = { tests.then(common.mustCall()); } -// Test NODE-DSA key generation -{ - async function test( - name, - modulusLength, - hash, - privateUsages, - publicUsages = privateUsages) { - let usages = privateUsages; - if (publicUsages !== privateUsages) - usages = usages.concat(publicUsages); - const { publicKey, privateKey } = await subtle.generateKey({ - name, - modulusLength, - hash - }, true, usages); - - assert(publicKey); - assert(privateKey); - assert(isCryptoKey(publicKey)); - assert(isCryptoKey(privateKey)); - - assert.strictEqual(publicKey.type, 'public'); - assert.strictEqual(privateKey.type, 'private'); - assert.strictEqual(publicKey.extractable, true); - assert.strictEqual(privateKey.extractable, true); - assert.deepStrictEqual(publicKey.usages, publicUsages); - assert.deepStrictEqual(privateKey.usages, privateUsages); - assert.strictEqual(publicKey.algorithm.name, name); - assert.strictEqual(publicKey.algorithm.modulusLength, modulusLength); - assert.strictEqual(publicKey.algorithm.hash.name, hash); - assert.strictEqual(privateKey.algorithm.name, name); - assert.strictEqual(privateKey.algorithm.modulusLength, modulusLength); - assert.strictEqual(privateKey.algorithm.hash.name, hash); - - // Missing parameters - await assert.rejects( - subtle.generateKey({ name, hash }, true, usages), { - code: 'ERR_INVALID_ARG_TYPE' - }); - - await assert.rejects( - subtle.generateKey({ name, modulusLength }, true, usages), { - code: 'ERR_MISSING_OPTION' - }); - - await Promise.all(['', true, {}].map((modulusLength) => { - return assert.rejects(subtle.generateKey({ - name, - modulusLength, - hash - }, true, usages), { - code: 'ERR_INVALID_ARG_TYPE' - }); - })); - - await Promise.all([true, {}, 1, []].map((hash) => { - return assert.rejects(subtle.generateKey({ - name, - modulusLength, - hash - }, true, usages), { - message: /Unrecognized name/ - }); - })); - - await Promise.all(['', {}, 1, []].map((extractable) => { - return assert.rejects(subtle.generateKey({ - name, - modulusLength, - hash - }, extractable, usages), { - code: 'ERR_INVALID_ARG_TYPE' - }); - })); - - await Promise.all(['', {}, 1, false].map((usages) => { - return assert.rejects(subtle.generateKey({ - name, - modulusLength, - hash - }, true, usages), { - code: 'ERR_INVALID_ARG_TYPE' - }); - })); - } - - const kTests = [ - [ - 'NODE-DSA', - 1024, - 'SHA-256', - ['sign'], - ['verify'], - ], - ]; - - const tests = kTests.map((args) => test(...args)); - - Promise.all(tests).then(common.mustCall()); -} - -// Test NODE-DH key generation -(async function() { - const { publicKey, privateKey } = - await subtle.generateKey({ - name: 'NODE-DH', - group: 'modp15' - }, true, ['deriveKey']); - assert(publicKey); - assert(privateKey); - assert(isCryptoKey(publicKey)); - assert(isCryptoKey(privateKey)); - assert.strictEqual(publicKey.type, 'public'); - assert.strictEqual(privateKey.type, 'private'); - assert.strictEqual(publicKey.algorithm.name, 'NODE-DH'); - assert.strictEqual(privateKey.algorithm.name, 'NODE-DH'); - assert.strictEqual(publicKey.algorithm.group, 'modp15'); - assert.strictEqual(privateKey.algorithm.group, 'modp15'); -})().then(common.mustCall()); - // End user code cannot create CryptoKey directly assert.throws(() => new CryptoKey(), { code: 'ERR_ILLEGAL_CONSTRUCTOR' }); diff --git a/test/parallel/test-webcrypto-sign-verify-node-dsa.js b/test/parallel/test-webcrypto-sign-verify-node-dsa.js deleted file mode 100644 index 73b006b9236249..00000000000000 --- a/test/parallel/test-webcrypto-sign-verify-node-dsa.js +++ /dev/null @@ -1,220 +0,0 @@ -'use strict'; - -const common = require('../common'); - -if (!common.hasCrypto) - common.skip('missing crypto'); - -const assert = require('assert'); -const { subtle } = require('crypto').webcrypto; - -const dsa = require('../fixtures/crypto/dsa'); - -async function testVerify({ algorithm, - hash, - publicKeyBuffer, - privateKeyBuffer, - signature, - plaintext }) { - const [ - publicKey, - noVerifyPublicKey, - privateKey, - hmacKey, - wrongKeys, - ] = await Promise.all([ - subtle.importKey( - 'spki', - publicKeyBuffer, - { name: algorithm.name, hash }, - false, - ['verify']), - subtle.importKey( - 'spki', - publicKeyBuffer, - { name: algorithm.name, hash }, - false, - [ /* No usages */ ]), - subtle.importKey( - 'pkcs8', - privateKeyBuffer, - { name: algorithm.name, hash }, - false, - ['sign']), - subtle.generateKey( - { name: 'HMAC', hash: 'SHA-256' }, - false, - ['sign']), - subtle.generateKey( - { - name: 'ECDSA', - namedCurve: 'P-521', - hash: 'SHA-256', - }, - false, - ['sign']), - ]); - - assert(await subtle.verify(algorithm, publicKey, signature, plaintext)); - - // Test verification with altered buffers - const copy = Buffer.from(plaintext); - const sigcopy = Buffer.from(signature); - const p = subtle.verify(algorithm, publicKey, sigcopy, copy); - copy[0] = 255 - copy[0]; - sigcopy[0] = 255 - sigcopy[0]; - assert(await p); - - // Test failure when using wrong key - await assert.rejects( - subtle.verify(algorithm, privateKey, signature, plaintext), { - message: /Unable to use this key to verify/ - }); - - await assert.rejects( - subtle.verify(algorithm, noVerifyPublicKey, signature, plaintext), { - message: /Unable to use this key to verify/ - }); - - // Test failure when using the wrong algorithms - await assert.rejects( - subtle.verify(algorithm, hmacKey, signature, plaintext), { - message: /Unable to use this key to verify/ - }); - - await assert.rejects( - subtle.verify(algorithm, wrongKeys.publicKey, signature, plaintext), { - message: /Unable to use this key to verify/ - }); - - // Test failure when signature is altered - { - const copy = Buffer.from(signature); - copy[0] = 255 - copy[0]; - assert(!(await subtle.verify(algorithm, publicKey, copy, plaintext))); - assert(!(await subtle.verify( - algorithm, - publicKey, - copy.slice(1), - plaintext))); - } - - // Test failure when data is altered - { - const copy = Buffer.from(plaintext); - copy[0] = 255 - copy[0]; - assert(!(await subtle.verify(algorithm, publicKey, signature, copy))); - } - - // Test failure when wrong hash is used - { - const otherhash = hash === 'SHA-1' ? 'SHA-256' : 'SHA-1'; - assert(!(await subtle.verify({ - ...algorithm, - hash: otherhash - }, publicKey, signature, copy))); - } - - await assert.rejects( - subtle.verify( - { ...algorithm, hash: 'sha256' }, - publicKey, - signature, - copy), - { message: /Unrecognized name/ }); -} - -async function testSign({ - algorithm, - hash, - publicKeyBuffer, - privateKeyBuffer, - signature, - plaintext, -}) { - const [ - publicKey, - noSignPrivateKey, - privateKey, - hmacKey, - wrongKeys, - ] = await Promise.all([ - subtle.importKey( - 'spki', - publicKeyBuffer, - { name: algorithm.name, hash }, - false, - ['verify']), - subtle.importKey( - 'pkcs8', - privateKeyBuffer, - { name: algorithm.name, hash }, - false, - [ /* No usages */ ]), - subtle.importKey( - 'pkcs8', - privateKeyBuffer, - { name: algorithm.name, hash }, - false, - ['sign']), - subtle.generateKey( - { name: 'HMAC', hash: 'SHA-256' }, - false, - ['sign']), - subtle.generateKey( - { - name: 'ECDSA', - namedCurve: 'P-521', - hash: 'SHA-256', - }, - false, - ['sign']), - ]); - - { - const sig = await subtle.sign(algorithm, privateKey, plaintext); - assert(await subtle.verify(algorithm, publicKey, sig, plaintext)); - } - - { - const copy = Buffer.from(plaintext); - const p = subtle.sign(algorithm, privateKey, copy); - copy[0] = 255 - copy[0]; - const sig = await p; - assert(await subtle.verify(algorithm, publicKey, sig, plaintext)); - } - - // Test failure when using wrong key - await assert.rejects( - subtle.sign(algorithm, publicKey, plaintext), { - message: /Unable to use this key to sign/ - }); - - // Test failure when no sign usage - await assert.rejects( - subtle.sign(algorithm, noSignPrivateKey, plaintext), { - message: /Unable to use this key to sign/ - }); - - // Test failure when using the wrong algorithms - await assert.rejects( - subtle.sign(algorithm, hmacKey, plaintext), { - message: /Unable to use this key to sign/ - }); - - await assert.rejects( - subtle.sign(algorithm, wrongKeys.privateKey, plaintext), { - message: /Unable to use this key to sign/ - }); -} - -(async function() { - const variations = []; - - dsa().forEach((vector) => { - variations.push(testVerify(vector)); - variations.push(testSign(vector)); - }); - - await Promise.all(variations); -})().then(common.mustCall()); diff --git a/tools/doc/type-parser.mjs b/tools/doc/type-parser.mjs index be55cadc287001..09a3cabc57afa0 100644 --- a/tools/doc/type-parser.mjs +++ b/tools/doc/type-parser.mjs @@ -103,12 +103,6 @@ const customTypesMap = { 'EcdsaParams': 'webcrypto.html#class-ecdsaparams', 'RsaPssParams': 'webcrypto.html#class-rsapssparams', 'Ed448Params': 'webcrypto.html#class-ed448params', - 'NodeDhKeyGenParams': 'webcrypto.html#class-nodedhkeygenparams', - 'NodeDhDeriveBitsParams': - 'webcrypto.html#class-nodedhderivebitsparams', - 'NodeDsaImportParams': 'webcrypto.html#class-nodedsaimportparams', - 'NodeDsaKeyGenParams': 'webcrypto.html#class-nodedsakeygenparams', - 'NodeScryptParams': 'webcrypto.html#class-nodescryptparams', 'dgram.Socket': 'dgram.html#class-dgramsocket', From a8ecec57e32ba8237def075415f7d02aa96bea70 Mon Sep 17 00:00:00 2001 From: "Node.js GitHub Bot" Date: Sat, 11 Jun 2022 09:09:24 +0200 Subject: [PATCH 39/96] meta: move one or more collaborators to emeritus (#43183) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43183 Reviewed-By: Darshan Sen Reviewed-By: Tobias Nießen Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f01bf3b675075e..866314c21a3e26 100644 --- a/README.md +++ b/README.md @@ -286,8 +286,6 @@ For information about the governance of the Node.js project, see **Ben Noordhuis** <> * [BridgeAR](https://github.com/BridgeAR) - **Ruben Bridgewater** <> (he/him) -* [bzoz](https://github.com/bzoz) - - **Bartosz Sosnowski** <> * [cclauss](https://github.com/cclauss) - **Christian Clauss** <> (he/him) * [ChALkeR](https://github.com/ChALkeR) - @@ -364,8 +362,6 @@ For information about the governance of the Node.js project, see **LiviaMedeiros** <> * [lpinca](https://github.com/lpinca) - **Luigi Pinca** <> (he/him) -* [lundibundi](https://github.com/lundibundi) - - **Denys Otrishko** <> (he/him) * [Lxxyx](https://github.com/Lxxyx) - **Zijian Liu** <> (he/him) * [marsonya](https://github.com/marsonya) - @@ -474,6 +470,8 @@ For information about the governance of the Node.js project, see **Christopher Hiller** <> (he/him) * [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <> +* [bzoz](https://github.com/bzoz) - + **Bartosz Sosnowski** <> * [calvinmetcalf](https://github.com/calvinmetcalf) - **Calvin Metcalf** <> * [chrisdickinson](https://github.com/chrisdickinson) - @@ -538,6 +536,8 @@ For information about the governance of the Node.js project, see **Lance Ball** <> (he/him) * [lucamaraschi](https://github.com/lucamaraschi) - **Luca Maraschi** <> (he/him) +* [lundibundi](https://github.com/lundibundi) - + **Denys Otrishko** <> (he/him) * [lxe](https://github.com/lxe) - **Aleksey Smolenchuk** <> * [maclover7](https://github.com/maclover7) - From 8c0fe1e184cdb8cce3c75ed046058beb613b4253 Mon Sep 17 00:00:00 2001 From: Livia Medeiros <74449973+LiviaMedeiros@users.noreply.github.com> Date: Sat, 11 Jun 2022 17:27:04 +0800 Subject: [PATCH 40/96] tools: fix find-inactive actions PR-URL: https://github.com/nodejs/node/pull/43377 Reviewed-By: Rich Trott Reviewed-By: Antoine du Hamel --- .github/workflows/find-inactive-collaborators.yml | 2 +- .github/workflows/find-inactive-tsc.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/find-inactive-collaborators.yml b/.github/workflows/find-inactive-collaborators.yml index 157c8dafdd0e05..7445dd8ca843fb 100644 --- a/.github/workflows/find-inactive-collaborators.yml +++ b/.github/workflows/find-inactive-collaborators.yml @@ -30,7 +30,7 @@ jobs: run: tools/find-inactive-collaborators.mjs - name: Open pull request - - uses: gr2m/create-or-update-pull-request-action@466b1b84c3291c6c69bc56377a6de54a1f4a297c + uses: gr2m/create-or-update-pull-request-action@6720400cad8e74d7adc64640e4e6ea6748b83d8f # Creates a PR or update the Action's existing PR, or # no-op if the base branch is already up-to-date. env: diff --git a/.github/workflows/find-inactive-tsc.yml b/.github/workflows/find-inactive-tsc.yml index 24dea2a0108265..389a6d1e0f56c7 100644 --- a/.github/workflows/find-inactive-tsc.yml +++ b/.github/workflows/find-inactive-tsc.yml @@ -39,7 +39,7 @@ jobs: run: tools/find-inactive-tsc.mjs >> $GITHUB_ENV - name: Open pull request - - uses: gr2m/create-or-update-pull-request-action@466b1b84c3291c6c69bc56377a6de54a1f4a297c + uses: gr2m/create-or-update-pull-request-action@6720400cad8e74d7adc64640e4e6ea6748b83d8f # Creates a PR or update the Action's existing PR, or # no-op if the base branch is already up-to-date. env: From b187d55b6dbffac67e44cb5a019fbf68f89bd4b5 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:48:37 +0800 Subject: [PATCH 41/96] util: add `kEmptyObject` to internal/util PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/util.js | 4 + test/parallel/test-internal-util-objects.js | 90 +++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 test/parallel/test-internal-util-objects.js diff --git a/lib/internal/util.js b/lib/internal/util.js index 61e58a5d69d1cf..030af62be8761e 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -13,6 +13,7 @@ const { ObjectGetOwnPropertyDescriptor, ObjectGetOwnPropertyDescriptors, ObjectGetPrototypeOf, + ObjectFreeze, ObjectSetPrototypeOf, Promise, ReflectApply, @@ -504,6 +505,8 @@ const lazyDOMException = hideStackFrames((message, name) => { const kEnumerableProperty = ObjectCreate(null); kEnumerableProperty.enumerable = true; +const kEmptyObject = ObjectFreeze(ObjectCreate(null)); + module.exports = { assertCrypto, cachedResult, @@ -544,5 +547,6 @@ module.exports = { kIsEncodingSymbol: Symbol('kIsEncodingSymbol'), kVmBreakFirstLineSymbol: Symbol('kVmBreakFirstLineSymbol'), + kEmptyObject, kEnumerableProperty, }; diff --git a/test/parallel/test-internal-util-objects.js b/test/parallel/test-internal-util-objects.js new file mode 100644 index 00000000000000..092deb9e09464b --- /dev/null +++ b/test/parallel/test-internal-util-objects.js @@ -0,0 +1,90 @@ +// Flags: --expose-internals +'use strict'; +require('../common'); + +// Test helper objects from internal/util + +const assert = require('assert'); +const { + kEnumerableProperty, + kEmptyObject, +} = require('internal/util'); + +Object.prototype.blep = 'blop'; + +{ + assert.strictEqual( + kEnumerableProperty.blep, + undefined + ); + assert.strictEqual( + kEnumerableProperty.enumerable, + true + ); + assert.strictEqual( + Object.getPrototypeOf(kEnumerableProperty), + null + ); + assert.deepStrictEqual( + Object.getOwnPropertyNames(kEnumerableProperty), + [ 'enumerable' ] + ); +} + +{ + assert.strictEqual( + kEmptyObject.blep, + undefined + ); + assert.strictEqual( + kEmptyObject.prototype, + undefined + ); + assert.strictEqual( + Object.getPrototypeOf(kEmptyObject), + null + ); + assert.strictEqual( + kEmptyObject instanceof Object, + false + ); + assert.deepStrictEqual( + Object.getOwnPropertyDescriptors(kEmptyObject), + {} + ); + assert.deepStrictEqual( + Object.getOwnPropertyNames(kEmptyObject), + [] + ); + assert.deepStrictEqual( + Object.getOwnPropertySymbols(kEmptyObject), + [] + ); + assert.strictEqual( + Object.isExtensible(kEmptyObject), + false + ); + assert.strictEqual( + Object.isSealed(kEmptyObject), + true + ); + assert.strictEqual( + Object.isFrozen(kEmptyObject), + true + ); + + assert.throws( + () => kEmptyObject.foo = 'bar', + TypeError + ); + assert.throws( + () => Object.assign(kEmptyObject, { foo: 'bar' }), + TypeError + ); + assert.throws( + () => Object.defineProperty(kEmptyObject, 'foo', {}), + TypeError + ); +} + +delete Object.prototype.blep; From 702bfa0b7c9cb2344522990d9654b8c821456fe0 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:49:57 +0800 Subject: [PATCH 42/96] async_hooks: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/async_hooks.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/async_hooks.js b/lib/async_hooks.js index fed0f07e647dcf..8638bb4d7b3497 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -20,6 +20,7 @@ const { ERR_ASYNC_TYPE, ERR_INVALID_ASYNC_ID } = require('internal/errors').codes; +const { kEmptyObject } = require('internal/util'); const { validateFunction, validateString, @@ -156,7 +157,7 @@ function createHook(fns) { const destroyedSymbol = Symbol('destroyed'); class AsyncResource { - constructor(type, opts = {}) { + constructor(type, opts = kEmptyObject) { validateString(type, 'type'); let triggerAsyncId = opts; From 4109ddc0056df8c117116b0cb0720eec55c4b043 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:50:33 +0800 Subject: [PATCH 43/96] child_process: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/child_process.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/child_process.js b/lib/child_process.js index 7c1b588995dbc5..d89e2f66fa0a7b 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -43,10 +43,11 @@ const { } = primordials; const { - promisify, convertToValidSignal, createDeferredPromise, - getSystemErrorName + getSystemErrorName, + kEmptyObject, + promisify, } = require('internal/util'); const { isArrayBufferView } = require('internal/util/types'); let debug = require('internal/util/debuglog').debuglog( @@ -510,7 +511,7 @@ function normalizeSpawnArguments(file, args, options) { } if (options === undefined) - options = {}; + options = kEmptyObject; else validateObject(options, 'options'); From 7b5cb14f0cc8b5d01b85db479da73a1c96ef5a51 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:51:01 +0800 Subject: [PATCH 44/96] cluster: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/cluster/worker.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/internal/cluster/worker.js b/lib/internal/cluster/worker.js index 53285413530230..d5dfef4387175f 100644 --- a/lib/internal/cluster/worker.js +++ b/lib/internal/cluster/worker.js @@ -7,6 +7,8 @@ const { const EventEmitter = require('events'); +const { kEmptyObject } = require('internal/util'); + module.exports = Worker; // Common Worker implementation shared between the cluster primary and workers. @@ -17,7 +19,7 @@ function Worker(options) { ReflectApply(EventEmitter, this, []); if (options === null || typeof options !== 'object') - options = {}; + options = kEmptyObject; this.exitedAfterDisconnect = undefined; From df0903c8e8dedfb98778ef0239440a8d8e135252 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:51:28 +0800 Subject: [PATCH 45/96] crypto: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/crypto/keygen.js | 7 +++++-- lib/internal/crypto/random.js | 13 +++++++------ lib/internal/crypto/x509.js | 3 ++- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/internal/crypto/keygen.js b/lib/internal/crypto/keygen.js index b6c3d966712cda..8f8fbfb1c0893d 100644 --- a/lib/internal/crypto/keygen.js +++ b/lib/internal/crypto/keygen.js @@ -38,7 +38,10 @@ const { kAesKeyLengths, } = require('internal/crypto/util'); -const { customPromisifyArgs } = require('internal/util'); +const { + customPromisifyArgs, + kEmptyObject, +} = require('internal/util'); const { validateFunction, @@ -119,7 +122,7 @@ function handleError(ret) { }; } -function parseKeyEncoding(keyType, options = {}) { +function parseKeyEncoding(keyType, options = kEmptyObject) { const { publicKeyEncoding, privateKeyEncoding } = options; let publicFormat, publicType; diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index 0a889cbebf6a7d..6705bcd2e7d592 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -26,6 +26,7 @@ const { } = internalBinding('crypto'); const { + kEmptyObject, lazyDOMException, } = require('internal/util'); @@ -399,7 +400,7 @@ function randomUUID(options) { validateObject(options, 'options'); const { disableEntropyCache = false, - } = options || {}; + } = options || kEmptyObject; validateBoolean(disableEntropyCache, 'options.disableEntropyCache'); @@ -464,7 +465,7 @@ function generatePrime(size, options, callback) { validateInt32(size, 'size', 1); if (typeof options === 'function') { callback = options; - options = {}; + options = kEmptyObject; } validateFunction(callback, 'callback'); @@ -482,7 +483,7 @@ function generatePrime(size, options, callback) { job.run(); } -function generatePrimeSync(size, options = {}) { +function generatePrimeSync(size, options = kEmptyObject) { validateInt32(size, 'size', 1); const job = createRandomPrimeJob(kCryptoJobSync, size, options); @@ -506,7 +507,7 @@ function unsignedBigIntToBuffer(bigint, name) { return Buffer.from(padded, 'hex'); } -function checkPrime(candidate, options = {}, callback) { +function checkPrime(candidate, options = kEmptyObject, callback) { if (typeof candidate === 'bigint') candidate = unsignedBigIntToBuffer(candidate, 'candidate'); if (!isAnyArrayBuffer(candidate) && !isArrayBufferView(candidate)) { @@ -524,7 +525,7 @@ function checkPrime(candidate, options = {}, callback) { } if (typeof options === 'function') { callback = options; - options = {}; + options = kEmptyObject; } validateFunction(callback, 'callback'); validateObject(options, 'options'); @@ -539,7 +540,7 @@ function checkPrime(candidate, options = {}, callback) { job.run(); } -function checkPrimeSync(candidate, options = {}) { +function checkPrimeSync(candidate, options = kEmptyObject) { if (typeof candidate === 'bigint') candidate = unsignedBigIntToBuffer(candidate, 'candidate'); if (!isAnyArrayBuffer(candidate) && !isArrayBufferView(candidate)) { diff --git a/lib/internal/crypto/x509.js b/lib/internal/crypto/x509.js index 386b41f3e4a42f..d08893d959f73a 100644 --- a/lib/internal/crypto/x509.js +++ b/lib/internal/crypto/x509.js @@ -23,6 +23,7 @@ const { const { customInspectSymbol: kInspect, + kEmptyObject, } = require('internal/util'); const { @@ -64,7 +65,7 @@ function isX509Certificate(value) { return value[kInternalState] !== undefined; } -function getFlags(options = {}) { +function getFlags(options = kEmptyObject) { validateObject(options, 'options'); const { subject = 'default', // Can be 'default', 'always', or 'never' From fda2105481209f3825c552501d677c99ac7c01da Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:51:52 +0800 Subject: [PATCH 46/96] events: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/events.js | 5 ++++- lib/internal/event_target.js | 12 ++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/lib/events.js b/lib/events.js index ad5ded2d0e9fc0..603f3083ed2ce0 100644 --- a/lib/events.js +++ b/lib/events.js @@ -52,6 +52,9 @@ const { SymbolAsyncIterator, } = primordials; const kRejection = SymbolFor('nodejs.rejection'); + +const { kEmptyObject } = require('internal/util'); + const { inspect } = require('internal/util/inspect'); let spliceOne; @@ -945,7 +948,7 @@ function getEventListeners(emitterOrTarget, type) { * @param {{ signal: AbortSignal; }} [options] * @returns {Promise} */ -async function once(emitter, name, options = {}) { +async function once(emitter, name, options = kEmptyObject) { const signal = options?.signal; validateAbortSignal(signal, 'options.signal'); if (signal?.aborted) diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index d005e9edc08c13..651cf55d5f3f8e 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -35,7 +35,11 @@ const { } = require('internal/errors'); const { validateObject, validateString } = require('internal/validators'); -const { customInspectSymbol, kEnumerableProperty } = require('internal/util'); +const { + customInspectSymbol, + kEmptyObject, + kEnumerableProperty, +} = require('internal/util'); const { inspect } = require('util'); const kIsEventTarget = SymbolFor('nodejs.event_target'); @@ -453,7 +457,7 @@ class EventTarget { * signal?: AbortSignal * }} [options] */ - addEventListener(type, listener, options = {}) { + addEventListener(type, listener, options = kEmptyObject) { if (!isEventTarget(this)) throw new ERR_INVALID_THIS('EventTarget'); if (arguments.length < 2) @@ -540,7 +544,7 @@ class EventTarget { * capture?: boolean, * }} [options] */ - removeEventListener(type, listener, options = {}) { + removeEventListener(type, listener, options = kEmptyObject) { if (!isEventTarget(this)) throw new ERR_INVALID_THIS('EventTarget'); if (!shouldAddListener(listener)) @@ -869,7 +873,7 @@ function validateEventListenerOptions(options) { return { capture: options }; if (options === null) - return {}; + return kEmptyObject; validateObject(options, 'options', { allowArray: true, allowFunction: true, }); From 63bf49b1437a806b1066073bd0669dbd5dff6efe Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:52:23 +0800 Subject: [PATCH 47/96] fs: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/fs.js | 61 +++++++++++++++------------- lib/internal/fs/promises.js | 21 ++++++---- lib/internal/fs/streams.js | 9 ++-- lib/internal/fs/sync_write_stream.js | 3 +- lib/internal/fs/utils.js | 10 +++-- 5 files changed, 59 insertions(+), 45 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index a3f72535d77554..ba1b3597bda479 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -83,7 +83,14 @@ const { const { FSReqCallback } = binding; const { toPathIfFileURL } = require('internal/url'); -const internalUtil = require('internal/util'); +const { + customPromisifyArgs: kCustomPromisifyArgsSymbol, + deprecate, + kEmptyObject, + promisify: { + custom: kCustomPromisifiedSymbol, + }, +} = require('internal/util'); const { constants: { kIoMaxLength, @@ -164,7 +171,7 @@ const isWindows = process.platform === 'win32'; const isOSX = process.platform === 'darwin'; -const showStringCoercionDeprecation = internalUtil.deprecate( +const showStringCoercionDeprecation = deprecate( () => {}, 'Implicit coercion of objects with own toString property is deprecated.', 'DEP0162' @@ -276,7 +283,7 @@ function exists(path, callback) { } } -ObjectDefineProperty(exists, internalUtil.promisify.custom, { +ObjectDefineProperty(exists, kCustomPromisifiedSymbol, { __proto__: null, value: function exists(path) { // eslint-disable-line func-name-matching return new Promise((resolve) => fs.exists(path, resolve)); @@ -623,7 +630,7 @@ function read(fd, buffer, offsetOrOptions, length, position, callback) { if (!isArrayBufferView(buffer)) { // This is fs.read(fd, params, callback) params = buffer; - ({ buffer = Buffer.alloc(16384) } = params ?? ObjectCreate(null)); + ({ buffer = Buffer.alloc(16384) } = params ?? kEmptyObject); } callback = offsetOrOptions; } else { @@ -636,7 +643,7 @@ function read(fd, buffer, offsetOrOptions, length, position, callback) { offset = 0, length = buffer.byteLength - offset, position = null, - } = params ?? ObjectCreate(null)); + } = params ?? kEmptyObject); } validateBuffer(buffer); @@ -679,7 +686,7 @@ function read(fd, buffer, offsetOrOptions, length, position, callback) { binding.read(fd, buffer, offset, length, position, req); } -ObjectDefineProperty(read, internalUtil.customPromisifyArgs, +ObjectDefineProperty(read, kCustomPromisifyArgsSymbol, { __proto__: null, value: ['bytesRead', 'buffer'], enumerable: false }); /** @@ -701,7 +708,7 @@ function readSync(fd, buffer, offset, length, position) { if (arguments.length <= 3) { // Assume fs.readSync(fd, buffer, options) - const options = offset || ObjectCreate(null); + const options = offset || kEmptyObject; ({ offset = 0, @@ -772,7 +779,7 @@ function readv(fd, buffers, position, callback) { return binding.readBuffers(fd, buffers, position, req); } -ObjectDefineProperty(readv, internalUtil.customPromisifyArgs, +ObjectDefineProperty(readv, kCustomPromisifyArgsSymbol, { __proto__: null, value: ['bytesRead', 'buffers'], enumerable: false }); /** @@ -829,7 +836,7 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { offset = 0, length = buffer.byteLength - offset, position = null, - } = offsetOrOptions ?? ObjectCreate(null)); + } = offsetOrOptions ?? kEmptyObject); } if (offset == null || typeof offset === 'function') { @@ -872,7 +879,7 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { return binding.writeString(fd, str, offset, length, req); } -ObjectDefineProperty(write, internalUtil.customPromisifyArgs, +ObjectDefineProperty(write, kCustomPromisifyArgsSymbol, { __proto__: null, value: ['bytesWritten', 'buffer'], enumerable: false }); /** @@ -899,7 +906,7 @@ function writeSync(fd, buffer, offsetOrOptions, length, position) { offset = 0, length = buffer.byteLength - offset, position = null, - } = offsetOrOptions ?? ObjectCreate(null)); + } = offsetOrOptions ?? kEmptyObject); } if (position === undefined) position = null; @@ -962,7 +969,7 @@ function writev(fd, buffers, position, callback) { return binding.writeBuffers(fd, buffers, position, req); } -ObjectDefineProperty(writev, internalUtil.customPromisifyArgs, { +ObjectDefineProperty(writev, kCustomPromisifyArgsSymbol, { __proto__: null, value: ['bytesWritten', 'buffer'], enumerable: false @@ -1405,7 +1412,7 @@ function mkdirSync(path, options) { */ function readdir(path, options, callback) { callback = makeCallback(typeof options === 'function' ? options : callback); - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); const req = new FSReqCallback(); @@ -1434,7 +1441,7 @@ function readdir(path, options, callback) { * @returns {string | Buffer[] | Dirent[]} */ function readdirSync(path, options) { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); const ctx = { path }; const result = binding.readdir(pathModule.toNamespacedPath(path), @@ -1458,7 +1465,7 @@ function readdirSync(path, options) { function fstat(fd, options = { bigint: false }, callback) { if (typeof options === 'function') { callback = options; - options = {}; + options = kEmptyObject; } fd = getValidatedFd(fd); callback = makeStatsCallback(callback); @@ -1482,7 +1489,7 @@ function fstat(fd, options = { bigint: false }, callback) { function lstat(path, options = { bigint: false }, callback) { if (typeof options === 'function') { callback = options; - options = {}; + options = kEmptyObject; } callback = makeStatsCallback(callback); path = getValidatedPath(path); @@ -1505,7 +1512,7 @@ function lstat(path, options = { bigint: false }, callback) { function stat(path, options = { bigint: false }, callback) { if (typeof options === 'function') { callback = options; - options = {}; + options = kEmptyObject; } callback = makeStatsCallback(callback); path = getValidatedPath(path); @@ -1603,7 +1610,7 @@ function statSync(path, options = { bigint: false, throwIfNoEntry: true }) { */ function readlink(path, options, callback) { callback = makeCallback(typeof options === 'function' ? options : callback); - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path, 'oldPath'); const req = new FSReqCallback(); req.oncomplete = callback; @@ -1618,7 +1625,7 @@ function readlink(path, options, callback) { * @returns {string | Buffer} */ function readlinkSync(path, options) { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path, 'oldPath'); const ctx = { path }; const result = binding.readlink(pathModule.toNamespacedPath(path), @@ -2295,7 +2302,7 @@ function watch(filename, options, listener) { if (typeof options === 'function') { listener = options; } - options = getOptions(options, {}); + options = getOptions(options); // Don't make changes directly on options object options = copyObject(options); @@ -2458,8 +2465,6 @@ if (isWindows) { }; } -const emptyObj = ObjectCreate(null); - /** * Returns the resolved pathname. * @param {string | Buffer | URL} p @@ -2467,7 +2472,7 @@ const emptyObj = ObjectCreate(null); * @returns {string | Buffer} */ function realpathSync(p, options) { - options = getOptions(options, emptyObj); + options = getOptions(options); p = toPathIfFileURL(p); if (typeof p !== 'string') { p += ''; @@ -2604,7 +2609,7 @@ function realpathSync(p, options) { * @returns {string | Buffer} */ realpathSync.native = (path, options) => { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); const ctx = { path }; const result = binding.realpath(path, options.encoding, undefined, ctx); @@ -2625,7 +2630,7 @@ realpathSync.native = (path, options) => { */ function realpath(p, options, callback) { callback = typeof options === 'function' ? options : maybeCallback(callback); - options = getOptions(options, {}); + options = getOptions(options); p = toPathIfFileURL(p); if (typeof p !== 'string') { @@ -2763,7 +2768,7 @@ function realpath(p, options, callback) { */ realpath.native = (path, options, callback) => { callback = makeCallback(callback || options); - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); const req = new FSReqCallback(); req.oncomplete = callback; @@ -2782,7 +2787,7 @@ realpath.native = (path, options, callback) => { */ function mkdtemp(prefix, options, callback) { callback = makeCallback(typeof options === 'function' ? options : callback); - options = getOptions(options, {}); + options = getOptions(options); validateString(prefix, 'prefix'); nullCheck(prefix, 'prefix'); @@ -2799,7 +2804,7 @@ function mkdtemp(prefix, options, callback) { * @returns {string} */ function mkdtempSync(prefix, options) { - options = getOptions(options, {}); + options = getOptions(options); validateString(prefix, 'prefix'); nullCheck(prefix, 'prefix'); diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 5f29a1df98bf61..34fd0f586766dd 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -5,7 +5,6 @@ const { Error, MathMax, MathMin, - ObjectCreate, NumberIsSafeInteger, Promise, PromisePrototypeThen, @@ -81,7 +80,11 @@ const { validateString, } = require('internal/validators'); const pathModule = require('path'); -const { lazyDOMException, promisify } = require('internal/util'); +const { + kEmptyObject, + lazyDOMException, + promisify, +} = require('internal/util'); const { EventEmitterMixin } = require('internal/event_target'); const { watch } = require('internal/fs/watchers'); const { isIterable } = require('internal/streams/utils'); @@ -519,7 +522,7 @@ async function read(handle, bufferOrParams, offset, length, position) { offset = 0, length = buffer.byteLength - offset, position = null, - } = bufferOrParams ?? ObjectCreate(null)); + } = bufferOrParams ?? kEmptyObject); validateBuffer(buffer); } @@ -582,7 +585,7 @@ async function write(handle, buffer, offsetOrOptions, length, position) { offset = 0, length = buffer.byteLength - offset, position = null, - } = offsetOrOptions ?? ObjectCreate(null)); + } = offsetOrOptions ?? kEmptyObject); } if (offset == null) { @@ -678,7 +681,7 @@ async function mkdir(path, options) { const { recursive = false, mode = 0o777 - } = options || {}; + } = options || kEmptyObject; path = getValidatedPath(path); validateBoolean(recursive, 'options.recursive'); @@ -688,7 +691,7 @@ async function mkdir(path, options) { } async function readdir(path, options) { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); const result = await binding.readdir(pathModule.toNamespacedPath(path), options.encoding, @@ -700,7 +703,7 @@ async function readdir(path, options) { } async function readlink(path, options) { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path, 'oldPath'); return binding.readlink(pathModule.toNamespacedPath(path), options.encoding, kUsePromises); @@ -812,13 +815,13 @@ async function lutimes(path, atime, mtime) { } async function realpath(path, options) { - options = getOptions(options, {}); + options = getOptions(options); path = getValidatedPath(path); return binding.realpath(path, options.encoding, kUsePromises); } async function mkdtemp(prefix, options) { - options = getOptions(options, {}); + options = getOptions(options); validateString(prefix, 'prefix'); nullCheck(prefix); diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index b59199e59e582e..c5bc567a8409bf 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -16,7 +16,10 @@ const { ERR_OUT_OF_RANGE, ERR_METHOD_NOT_IMPLEMENTED, } = require('internal/errors').codes; -const { deprecate } = require('internal/util'); +const { + deprecate, + kEmptyObject, +} = require('internal/util'); const { validateFunction, validateInteger, @@ -147,7 +150,7 @@ function ReadStream(path, options) { return new ReadStream(path, options); // A little bit bigger buffer and water marks by default - options = copyObject(getOptions(options, {})); + options = copyObject(getOptions(options, kEmptyObject)); if (options.highWaterMark === undefined) options.highWaterMark = 64 * 1024; @@ -305,7 +308,7 @@ function WriteStream(path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); - options = copyObject(getOptions(options, {})); + options = copyObject(getOptions(options, kEmptyObject)); // Only buffers are supported. options.decodeStrings = true; diff --git a/lib/internal/fs/sync_write_stream.js b/lib/internal/fs/sync_write_stream.js index df366edce4716b..8fa5c56aaffc62 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -4,6 +4,7 @@ const { ObjectSetPrototypeOf, ReflectApply, } = primordials; +const { kEmptyObject } = require('internal/util'); const { Writable } = require('stream'); const { closeSync, writeSync } = require('fs'); @@ -11,7 +12,7 @@ const { closeSync, writeSync } = require('fs'); function SyncWriteStream(fd, options) { ReflectApply(Writable, this, [{ autoDestroy: true }]); - options = options || {}; + options = options || kEmptyObject; this.fd = fd; this.readable = false; diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index e570b42da88204..9280fcfef7018e 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -43,7 +43,10 @@ const { isDate, isBigUint64Array } = require('internal/util/types'); -const { once } = require('internal/util'); +const { + kEmptyObject, + once, +} = require('internal/util'); const { toPathIfFileURL } = require('internal/url'); const { validateAbortSignal, @@ -312,9 +315,8 @@ function getDirent(path, name, type, callback) { } } -function getOptions(options, defaultOptions) { - if (options === null || options === undefined || - typeof options === 'function') { +function getOptions(options, defaultOptions = kEmptyObject) { + if (options == null || typeof options === 'function') { return defaultOptions; } From a4409f85f8f4e05534092fadfcc217aad967b815 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:52:47 +0800 Subject: [PATCH 48/96] http: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/_http_agent.js | 7 +++++-- lib/_http_client.js | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/_http_agent.js b/lib/_http_agent.js index ff2047d4ea81bb..6784e884859986 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -54,7 +54,10 @@ const { ERR_OUT_OF_RANGE, }, } = require('internal/errors'); -const { once } = require('internal/util'); +const { + kEmptyObject, + once, +} = require('internal/util'); const { validateNumber, validateOneOf, @@ -220,7 +223,7 @@ Agent.defaultMaxSockets = Infinity; Agent.prototype.createConnection = net.createConnection; // Get the key for a given set of request options -Agent.prototype.getName = function getName(options = {}) { +Agent.prototype.getName = function getName(options = kEmptyObject) { let name = options.host || 'localhost'; name += ':'; diff --git a/lib/_http_client.js b/lib/_http_client.js index 59329ff243643d..91906b85a38910 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -43,7 +43,10 @@ const { const net = require('net'); const assert = require('internal/assert'); -const { once } = require('internal/util'); +const { + kEmptyObject, + once, +} = require('internal/util'); const { _checkIsHttpToken: checkIsHttpToken, freeParser, @@ -133,7 +136,7 @@ function ClientRequest(input, options, cb) { if (typeof options === 'function') { cb = options; - options = input || {}; + options = input || kEmptyObject; } else { options = ObjectAssign(input || {}, options); } From 2ffd54105ae1e04228b2bac7245622fe1caf9d8e Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:53:04 +0800 Subject: [PATCH 49/96] http2: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/http2/core.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 9268f5ea908527..d6319286fa7f64 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -37,7 +37,8 @@ const { const { assertCrypto, customInspectSymbol: kInspect, - promisify + kEmptyObject, + promisify, } = require('internal/util'); assertCrypto(); @@ -3332,7 +3333,7 @@ function getPackedSettings(settings) { return binding.packSettings(); } -function getUnpackedSettings(buf, options = {}) { +function getUnpackedSettings(buf, options = kEmptyObject) { if (!isArrayBufferView(buf) || buf.length === undefined) { throw new ERR_INVALID_ARG_TYPE('buf', ['Buffer', 'TypedArray'], buf); From b468b8fe5164e1841056a3fba2a2f21d8cb8c441 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:53:17 +0800 Subject: [PATCH 50/96] https: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/https.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/https.js b/lib/https.js index 6ca3f335d0f885..7ae8ab2987538b 100644 --- a/lib/https.js +++ b/lib/https.js @@ -34,7 +34,11 @@ const { ReflectConstruct, } = primordials; -require('internal/util').assertCrypto(); +const { + assertCrypto, + kEmptyObject, +} = require('internal/util'); +assertCrypto(); const tls = require('tls'); const { Agent: HttpAgent } = require('_http_agent'); @@ -206,7 +210,7 @@ Agent.prototype.createConnection = createConnection; * }} [options] * @returns {string} */ -Agent.prototype.getName = function getName(options = {}) { +Agent.prototype.getName = function getName(options = kEmptyObject) { let name = FunctionPrototypeCall(HttpAgent.prototype.getName, this, options); name += ':'; From a3310d13bf37a2d3af08353bec3bbd07595ee55a Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:53:52 +0800 Subject: [PATCH 51/96] perf_hooks: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/perf/event_loop_delay.js | 6 +++++- lib/internal/perf/observe.js | 3 ++- lib/internal/perf/timerify.js | 6 +++++- lib/internal/perf/usertiming.js | 9 ++++++--- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/internal/perf/event_loop_delay.js b/lib/internal/perf/event_loop_delay.js index efd45f4ed77349..18d7967477e0e4 100644 --- a/lib/internal/perf/event_loop_delay.js +++ b/lib/internal/perf/event_loop_delay.js @@ -27,6 +27,10 @@ const { kMap, } = require('internal/histogram'); +const { + kEmptyObject, +} = require('internal/util'); + const { makeTransferable, } = require('internal/worker/js_transferable'); @@ -69,7 +73,7 @@ class ELDHistogram extends Histogram { * }} [options] * @returns {ELDHistogram} */ -function monitorEventLoopDelay(options = {}) { +function monitorEventLoopDelay(options = kEmptyObject) { validateObject(options, 'options'); const { resolution = 10 } = options; diff --git a/lib/internal/perf/observe.js b/lib/internal/perf/observe.js index c58aec7040fc9c..656015f8410888 100644 --- a/lib/internal/perf/observe.js +++ b/lib/internal/perf/observe.js @@ -55,6 +55,7 @@ const { customInspectSymbol: kInspect, deprecate, lazyDOMException, + kEmptyObject, } = require('internal/util'); const { @@ -212,7 +213,7 @@ class PerformanceObserver { this.#callback = callback; } - observe(options = {}) { + observe(options = kEmptyObject) { validateObject(options, 'options'); const { entryTypes, diff --git a/lib/internal/perf/timerify.js b/lib/internal/perf/timerify.js index 38f6b3d37acdd2..926b6537adeba8 100644 --- a/lib/internal/perf/timerify.js +++ b/lib/internal/perf/timerify.js @@ -34,6 +34,10 @@ const { enqueue, } = require('internal/perf/observe'); +const { + kEmptyObject, +} = require('internal/util'); + function processComplete(name, start, args, histogram) { const duration = now() - start; if (histogram !== undefined) @@ -52,7 +56,7 @@ function processComplete(name, start, args, histogram) { enqueue(entry); } -function timerify(fn, options = {}) { +function timerify(fn, options = kEmptyObject) { validateFunction(fn, 'fn'); validateObject(options, 'options'); diff --git a/lib/internal/perf/usertiming.js b/lib/internal/perf/usertiming.js index 7266b14ef40b2e..51625ee08d5467 100644 --- a/lib/internal/perf/usertiming.js +++ b/lib/internal/perf/usertiming.js @@ -27,7 +27,10 @@ const { } = require('internal/errors'); const { structuredClone } = require('internal/structured_clone'); -const { lazyDOMException } = require('internal/util'); +const { + kEmptyObject, + lazyDOMException, +} = require('internal/util'); const markTimings = new SafeMap(); @@ -61,7 +64,7 @@ class PerformanceMark extends InternalPerformanceEntry { name = `${name}`; if (nodeTimingReadOnlyAttributes.has(name)) throw new ERR_INVALID_ARG_VALUE('name', name); - options ??= {}; + options ??= kEmptyObject; validateObject(options, 'options'); const startTime = options.startTime ?? now(); validateNumber(startTime, 'startTime'); @@ -91,7 +94,7 @@ class PerformanceMeasure extends InternalPerformanceEntry { } } -function mark(name, options = {}) { +function mark(name, options = kEmptyObject) { const mark = new PerformanceMark(name, options); enqueue(mark); return mark; From 5e98cacf77b19a9034730f288737606d0ab03ac0 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:54:41 +0800 Subject: [PATCH 52/96] readline: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/readline/interface.js | 3 ++- lib/readline.js | 15 +++++++++++---- lib/readline/promises.js | 6 +++++- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/internal/readline/interface.js b/lib/internal/readline/interface.js index 47e5ca580ab317..457b67716c460f 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -48,6 +48,7 @@ const { validateString, validateUint32, } = require('internal/validators'); +const { kEmptyObject } = require('internal/util'); const { inspect, getStringWidth, @@ -1053,7 +1054,7 @@ class Interface extends InterfaceConstructor { // Handle a write from the tty [kTtyWrite](s, key) { const previousKey = this[kPreviousKey]; - key = key || {}; + key = key || kEmptyObject; this[kPreviousKey] = key; if (!key.meta || key.name !== 'y') { diff --git a/lib/readline.js b/lib/readline.js index 82afaa285d67ad..26e277c7abfd15 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -47,7 +47,10 @@ const { const { inspect, } = require('internal/util/inspect'); -const { promisify } = require('internal/util'); +const { + kEmptyObject, + promisify, +} = require('internal/util'); const { validateAbortSignal } = require('internal/validators'); /** @@ -128,7 +131,9 @@ const superQuestion = _Interface.prototype.question; */ Interface.prototype.question = function(query, options, cb) { cb = typeof options === 'function' ? options : cb; - options = typeof options === 'object' && options !== null ? options : {}; + if (options === null || typeof options !== 'object') { + options = kEmptyObject; + } if (options.signal) { validateAbortSignal(options.signal, 'options.signal'); @@ -154,7 +159,9 @@ Interface.prototype.question = function(query, options, cb) { } }; Interface.prototype.question[promisify.custom] = function question(query, options) { - options = typeof options === 'object' && options !== null ? options : {}; + if (options === null || typeof options !== 'object') { + options = kEmptyObject; + } if (options.signal && options.signal.aborted) { return PromiseReject( @@ -457,7 +464,7 @@ Interface.prototype._moveCursor = _Interface.prototype[kMoveCursor]; Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite]; function _ttyWriteDumb(s, key) { - key = key || {}; + key = key || kEmptyObject; if (key.name === 'escape') return; diff --git a/lib/readline/promises.js b/lib/readline/promises.js index 534558ec31ffdc..728a6253fd5e67 100644 --- a/lib/readline/promises.js +++ b/lib/readline/promises.js @@ -18,12 +18,16 @@ const { } = require('internal/errors'); const { validateAbortSignal } = require('internal/validators'); +const { + kEmptyObject, +} = require('internal/util'); + class Interface extends _Interface { // eslint-disable-next-line no-useless-constructor constructor(input, output, completer, terminal) { super(input, output, completer, terminal); } - question(query, options = {}) { + question(query, options = kEmptyObject) { return new Promise((resolve, reject) => { let cb = resolve; From b200a5ff67b7e91c1579221f113abce815241cb8 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:55:42 +0800 Subject: [PATCH 53/96] stream: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/streams/end-of-stream.js | 9 ++++++--- lib/internal/webstreams/adapters.js | 9 +++++---- lib/internal/webstreams/encoding.js | 3 ++- lib/internal/webstreams/readablestream.js | 11 ++++++----- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index 0b2044d53e735b..806280ebc1f1d2 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -11,7 +11,10 @@ const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes; -const { once } = require('internal/util'); +const { + kEmptyObject, + once, +} = require('internal/util'); const { validateAbortSignal, validateFunction, @@ -43,9 +46,9 @@ const nop = () => {}; function eos(stream, options, callback) { if (arguments.length === 2) { callback = options; - options = {}; + options = kEmptyObject; } else if (options == null) { - options = {}; + options = kEmptyObject; } else { validateObject(options, 'options'); } diff --git a/lib/internal/webstreams/adapters.js b/lib/internal/webstreams/adapters.js index 1058c1c0356ead..0fd571bfe11d19 100644 --- a/lib/internal/webstreams/adapters.js +++ b/lib/internal/webstreams/adapters.js @@ -55,6 +55,7 @@ const { const { createDeferredPromise, + kEmptyObject, } = require('internal/util'); const { @@ -198,7 +199,7 @@ function newWritableStreamFromStreamWritable(streamWritable) { * }} [options] * @returns {Writable} */ -function newStreamWritableFromWritableStream(writableStream, options = {}) { +function newStreamWritableFromWritableStream(writableStream, options = kEmptyObject) { if (!isWritableStream(writableStream)) { throw new ERR_INVALID_ARG_TYPE( 'writableStream', @@ -441,7 +442,7 @@ function newReadableStreamFromStreamReadable(streamReadable) { * }} [options] * @returns {Readable} */ -function newStreamReadableFromReadableStream(readableStream, options = {}) { +function newStreamReadableFromReadableStream(readableStream, options = kEmptyObject) { if (!isReadableStream(readableStream)) { throw new ERR_INVALID_ARG_TYPE( 'readableStream', @@ -585,7 +586,7 @@ function newReadableWritablePairFromDuplex(duplex) { * }} [options] * @returns {Duplex} */ -function newStreamDuplexFromReadableWritablePair(pair = {}, options = {}) { +function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = kEmptyObject) { validateObject(pair, 'pair'); const { readable: readableStream, @@ -876,7 +877,7 @@ function newWritableStreamFromStreamBase(streamBase, strategy) { * @param {QueuingStrategy} strategy * @returns {ReadableStream} */ -function newReadableStreamFromStreamBase(streamBase, strategy, options = {}) { +function newReadableStreamFromStreamBase(streamBase, strategy, options = kEmptyObject) { validateObject(streamBase, 'streamBase'); validateObject(options, 'options'); diff --git a/lib/internal/webstreams/encoding.js b/lib/internal/webstreams/encoding.js index 9cc76fae2ce10d..233a09a216d72d 100644 --- a/lib/internal/webstreams/encoding.js +++ b/lib/internal/webstreams/encoding.js @@ -24,6 +24,7 @@ const { const { customInspectSymbol: kInspect, + kEmptyObject, kEnumerableProperty, } = require('internal/util'); @@ -114,7 +115,7 @@ class TextDecoderStream { * ignoreBOM? : boolean, * }} [options] */ - constructor(encoding = 'utf-8', options = {}) { + constructor(encoding = 'utf-8', options = kEmptyObject) { this[kType] = 'TextDecoderStream'; this[kHandle] = new TextDecoder(encoding, options); this[kTransform] = new TransformStream({ diff --git a/lib/internal/webstreams/readablestream.js b/lib/internal/webstreams/readablestream.js index 33496587043523..b44df2ff77896d 100644 --- a/lib/internal/webstreams/readablestream.js +++ b/lib/internal/webstreams/readablestream.js @@ -50,6 +50,7 @@ const { const { createDeferredPromise, customInspectSymbol: kInspect, + kEmptyObject, kEnumerableProperty, } = require('internal/util'); @@ -206,7 +207,7 @@ class ReadableStream { * @param {UnderlyingSource} [source] * @param {QueuingStrategy} [strategy] */ - constructor(source = {}, strategy = {}) { + constructor(source = {}, strategy = kEmptyObject) { if (source === null) throw new ERR_INVALID_ARG_VALUE('source', 'Object', source); this[kState] = { @@ -296,7 +297,7 @@ class ReadableStream { * }} [options] * @returns {ReadableStreamReader} */ - getReader(options = {}) { + getReader(options = kEmptyObject) { if (!isReadableStream(this)) throw new ERR_INVALID_THIS('ReadableStream'); validateObject(options, 'options', { nullable: true, allowFunction: true }); @@ -315,7 +316,7 @@ class ReadableStream { * @param {StreamPipeOptions} [options] * @returns {ReadableStream} */ - pipeThrough(transform, options = {}) { + pipeThrough(transform, options = kEmptyObject) { if (!isReadableStream(this)) throw new ERR_INVALID_THIS('ReadableStream'); const readable = transform?.readable; @@ -365,7 +366,7 @@ class ReadableStream { * @param {StreamPipeOptions} [options] * @returns {Promise} */ - pipeTo(destination, options = {}) { + pipeTo(destination, options = kEmptyObject) { try { if (!isReadableStream(this)) throw new ERR_INVALID_THIS('ReadableStream'); @@ -416,7 +417,7 @@ class ReadableStream { * }} [options] * @returns {AsyncIterable} */ - values(options = {}) { + values(options = kEmptyObject) { if (!isReadableStream(this)) throw new ERR_INVALID_THIS('ReadableStream'); validateObject(options, 'options'); From e576a7fa50bb625d962e51c4b4f011bd0bee1097 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:56:01 +0800 Subject: [PATCH 54/96] test_runner: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/test_runner/test.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index d35bf6307bfb15..cac379b32582a4 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -4,7 +4,6 @@ const { ArrayPrototypeShift, FunctionPrototype, Number, - ObjectCreate, SafeMap, } = primordials; const { AsyncResource } = require('async_hooks'); @@ -16,7 +15,10 @@ const { } = require('internal/errors'); const { getOptionValue } = require('internal/options'); const { TapStream } = require('internal/test_runner/tap_stream'); -const { createDeferredPromise } = require('internal/util'); +const { + createDeferredPromise, + kEmptyObject, +} = require('internal/util'); const { isPromise } = require('internal/util/types'); const { isUint32 } = require('internal/validators'); const { cpus } = require('os'); @@ -198,7 +200,7 @@ class Test extends AsyncResource { } if (options === null || typeof options !== 'object') { - options = ObjectCreate(null); + options = kEmptyObject; } let parent = this; From fecad7a3a529d7b3af4d617806a3b4558424d8ac Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:56:32 +0800 Subject: [PATCH 55/96] timers: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/timers/promises.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/timers/promises.js b/lib/timers/promises.js index 47a78de32efa3b..7c8d364b1dde4f 100644 --- a/lib/timers/promises.js +++ b/lib/timers/promises.js @@ -35,6 +35,10 @@ const { validateObject, } = require('internal/validators'); +const { + kEmptyObject, +} = require('internal/util'); + const kScheduler = Symbol('kScheduler'); function cancelListenerHandler(clear, reject, signal) { @@ -44,7 +48,7 @@ function cancelListenerHandler(clear, reject, signal) { } } -function setTimeout(after, value, options = {}) { +function setTimeout(after, value, options = kEmptyObject) { const args = value !== undefined ? [value] : value; if (options == null || typeof options !== 'object') { return PromiseReject( @@ -88,7 +92,7 @@ function setTimeout(after, value, options = {}) { () => signal.removeEventListener('abort', oncancel)) : ret; } -function setImmediate(value, options = {}) { +function setImmediate(value, options = kEmptyObject) { if (options == null || typeof options !== 'object') { return PromiseReject( new ERR_INVALID_ARG_TYPE( @@ -132,7 +136,7 @@ function setImmediate(value, options = {}) { () => signal.removeEventListener('abort', oncancel)) : ret; } -async function* setInterval(after, value, options = {}) { +async function* setInterval(after, value, options = kEmptyObject) { validateObject(options, 'options'); const { signal, ref = true } = options; validateAbortSignal(signal, 'options.signal'); From e31baca76a1c36aef834908028c4f05931181006 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:57:01 +0800 Subject: [PATCH 56/96] tls: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/_tls_common.js | 6 +++++- lib/_tls_wrap.js | 7 ++++--- lib/internal/tls/secure-context.js | 6 +++++- lib/internal/tls/secure-pair.js | 3 ++- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 79d3ac1136ec99..b6e1774f38f5d9 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -47,6 +47,10 @@ const { }, } = internalBinding('constants'); +const { + kEmptyObject, +} = require('internal/util'); + const { validateInteger, } = require('internal/validators'); @@ -93,7 +97,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) { } function createSecureContext(options) { - if (!options) options = {}; + if (!options) options = kEmptyObject; const { honorCipherOrder, diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 24e04010a28b9a..55c60c34e0a702 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -40,7 +40,8 @@ const { const { assertCrypto, - deprecate + deprecate, + kEmptyObject, } = require('internal/util'); assertCrypto(); @@ -1182,9 +1183,9 @@ function Server(options, listener) { if (typeof options === 'function') { listener = options; - options = {}; + options = kEmptyObject; } else if (options == null || typeof options === 'object') { - options = options || {}; + options = options ?? kEmptyObject; } else { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } diff --git a/lib/internal/tls/secure-context.js b/lib/internal/tls/secure-context.js index 8cb3ae06d2e2e1..152627b420a612 100644 --- a/lib/internal/tls/secure-context.js +++ b/lib/internal/tls/secure-context.js @@ -17,6 +17,10 @@ const { }, } = require('internal/errors'); +const { + kEmptyObject, +} = require('internal/util'); + const { isArrayBufferView, } = require('internal/util/types'); @@ -117,7 +121,7 @@ function processCiphers(ciphers, name) { return { cipherList, cipherSuites }; } -function configSecureContext(context, options = {}, name = 'options') { +function configSecureContext(context, options = kEmptyObject, name = 'options') { validateObject(options, name); const { diff --git a/lib/internal/tls/secure-pair.js b/lib/internal/tls/secure-pair.js index b3f0930a3c7118..db999d90ccffd9 100644 --- a/lib/internal/tls/secure-pair.js +++ b/lib/internal/tls/secure-pair.js @@ -1,6 +1,7 @@ 'use strict'; const EventEmitter = require('events'); +const { kEmptyObject } = require('internal/util'); const { Duplex } = require('stream'); const _tls_wrap = require('_tls_wrap'); const _tls_common = require('_tls_common'); @@ -57,7 +58,7 @@ class SecurePair extends EventEmitter { isServer = false, requestCert = !isServer, rejectUnauthorized = false, - options = {}) { + options = kEmptyObject) { super(); const { socket1, socket2 } = new DuplexPair(); From 024b39627505f9c7b653903ead966f305b6469a5 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:57:12 +0800 Subject: [PATCH 57/96] vm: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/vm/module.js | 9 +++++---- lib/vm.js | 13 +++++++------ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/internal/vm/module.js b/lib/internal/vm/module.js index a5024d97051b63..d3818e6fd6c27c 100644 --- a/lib/internal/vm/module.js +++ b/lib/internal/vm/module.js @@ -24,9 +24,10 @@ const { isArrayBufferView, } = require('internal/util/types'); const { - getConstructorOf, customInspectSymbol, emitExperimentalWarning, + getConstructorOf, + kEmptyObject, } = require('internal/util'); const { ERR_INVALID_ARG_TYPE, @@ -199,7 +200,7 @@ class Module { this[kWrap].instantiate(); } - async evaluate(options = {}) { + async evaluate(options = kEmptyObject) { if (this[kWrap] === undefined) { throw new ERR_VM_MODULE_NOT_MODULE(); } @@ -258,7 +259,7 @@ class SourceTextModule extends Module { #error = kNoError; #statusOverride; - constructor(sourceText, options = {}) { + constructor(sourceText, options = kEmptyObject) { validateString(sourceText, 'sourceText'); validateObject(options, 'options'); @@ -387,7 +388,7 @@ class SourceTextModule extends Module { } class SyntheticModule extends Module { - constructor(exportNames, evaluateCallback, options = {}) { + constructor(exportNames, evaluateCallback, options = kEmptyObject) { if (!ArrayIsArray(exportNames) || ArrayPrototypeSome(exportNames, (e) => typeof e !== 'string')) { throw new ERR_INVALID_ARG_TYPE('exportNames', diff --git a/lib/vm.js b/lib/vm.js index 92afa9f6964acf..7bcef6e5f4ff9a 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -57,13 +57,14 @@ const { validateUint32, } = require('internal/validators'); const { - kVmBreakFirstLineSymbol, emitExperimentalWarning, + kEmptyObject, + kVmBreakFirstLineSymbol, } = require('internal/util'); const kParsingContext = Symbol('script parsing context'); class Script extends ContextifyScript { - constructor(code, options = {}) { + constructor(code, options = kEmptyObject) { code = `${code}`; if (typeof options === 'string') { options = { filename: options }; @@ -152,7 +153,7 @@ function validateContext(contextifiedObject) { } } -function getRunInContextArgs(options = {}) { +function getRunInContextArgs(options = kEmptyObject) { validateObject(options, 'options'); let timeout = options.timeout; @@ -212,7 +213,7 @@ function isContext(object) { } let defaultContextNameIndex = 1; -function createContext(contextObject = {}, options = {}) { +function createContext(contextObject = {}, options = kEmptyObject) { if (isContext(contextObject)) { return contextObject; } @@ -305,7 +306,7 @@ function runInThisContext(code, options) { return createScript(code, options).runInThisContext(options); } -function compileFunction(code, params, options = {}) { +function compileFunction(code, params, options = kEmptyObject) { validateString(code, 'code'); if (params !== undefined) { validateArray(params, 'params'); @@ -395,7 +396,7 @@ const measureMemoryExecutions = { eager: constants.measureMemory.execution.EAGER, }; -function measureMemory(options = {}) { +function measureMemory(options = kEmptyObject) { emitExperimentalWarning('vm.measureMemory'); validateObject(options, 'options'); const { mode = 'summary', execution = 'default' } = options; From 7fc432fa357979e8ea7a2f4566afff7e318a2cd5 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:57:20 +0800 Subject: [PATCH 58/96] wasi: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/wasi.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/wasi.js b/lib/wasi.js index 43ecf94b4cb050..7093953a00739a 100644 --- a/lib/wasi.js +++ b/lib/wasi.js @@ -13,7 +13,10 @@ const { ERR_INVALID_ARG_TYPE, ERR_WASI_ALREADY_STARTED } = require('internal/errors').codes; -const { emitExperimentalWarning } = require('internal/util'); +const { + emitExperimentalWarning, + kEmptyObject, +} = require('internal/util'); const { isArrayBuffer } = require('internal/util/types'); const { validateArray, @@ -55,7 +58,7 @@ function setupInstance(self, instance) { } class WASI { - constructor(options = {}) { + constructor(options = kEmptyObject) { validateObject(options, 'options'); if (options.args !== undefined) From 44b65d0ca7a6c8a6f30ebc6affe4c94280b32c35 Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:57:56 +0800 Subject: [PATCH 59/96] worker: use `kEmptyObject` PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/worker.js | 3 ++- lib/internal/worker/io.js | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 1d2cd8cefd2996..0cede10ca4bf9b 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -55,6 +55,7 @@ const { } = workerIo; const { deserializeError } = require('internal/error_serdes'); const { fileURLToPath, isURLInstance, pathToFileURL } = require('internal/url'); +const { kEmptyObject } = require('internal/util'); const { validateArray } = require('internal/validators'); const { @@ -118,7 +119,7 @@ function assignEnvironmentData(data) { } class Worker extends EventEmitter { - constructor(filename, options = {}) { + constructor(filename, options = kEmptyObject) { super(); debug(`[${threadId}] create new worker`, filename, options); if (options.execArgv) diff --git a/lib/internal/worker/io.js b/lib/internal/worker/io.js index 97d7d1d408ee5d..9e2bbbdb33fd3e 100644 --- a/lib/internal/worker/io.js +++ b/lib/internal/worker/io.js @@ -18,7 +18,10 @@ const { SymbolFor, } = primordials; -const { kEnumerableProperty } = require('internal/util'); +const { + kEmptyObject, + kEnumerableProperty, +} = require('internal/util'); const { handle_onclose: handleOnCloseSymbol, @@ -123,7 +126,7 @@ class MessageEvent extends Event { lastEventId = '', source = null, ports = [], - } = {}) { + } = kEmptyObject) { super(type); this[kData] = data; this[kOrigin] = `${origin}`; From 3b2f7eed391b9beaeb619626e13953811b778b5a Mon Sep 17 00:00:00 2001 From: LiviaMedeiros Date: Sat, 21 May 2022 17:59:38 +0800 Subject: [PATCH 60/96] lib: use `kEmptyObject` in various places PR-URL: https://github.com/nodejs/node/pull/43159 Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- lib/internal/blob.js | 3 ++- lib/internal/encoding.js | 9 +++++---- lib/internal/histogram.js | 3 ++- lib/internal/promise_hooks.js | 3 ++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/internal/blob.js b/lib/internal/blob.js index 723e0983435a75..836baac7ed2452 100644 --- a/lib/internal/blob.js +++ b/lib/internal/blob.js @@ -44,6 +44,7 @@ const { const { createDeferredPromise, customInspectSymbol: kInspect, + kEmptyObject, } = require('internal/util'); const { inspect } = require('internal/util/inspect'); @@ -134,7 +135,7 @@ class Blob { * }} [options] * @constructs {Blob} */ - constructor(sources = [], options = {}) { + constructor(sources = [], options = kEmptyObject) { if (sources === null || typeof sources[SymbolIterator] !== 'function' || typeof sources === 'string') { diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index 1c0c17d534f036..f9fa43228d5f57 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -33,6 +33,7 @@ const kEncoder = Symbol('encoder'); const { getConstructorOf, customInspectSymbol: inspect, + kEmptyObject, kEnumerableProperty, } = require('internal/util'); @@ -379,7 +380,7 @@ function makeTextDecoderICU() { } = internalBinding('icu'); class TextDecoder { - constructor(encoding = 'utf-8', options = {}) { + constructor(encoding = 'utf-8', options = kEmptyObject) { encoding = `${encoding}`; validateObject(options, 'options', { nullable: true, @@ -408,7 +409,7 @@ function makeTextDecoderICU() { } - decode(input = empty, options = {}) { + decode(input = empty, options = kEmptyObject) { validateDecoder(this); if (isAnyArrayBuffer(input)) { input = lazyBuffer().from(input); @@ -453,7 +454,7 @@ function makeTextDecoderJS() { } class TextDecoder { - constructor(encoding = 'utf-8', options = {}) { + constructor(encoding = 'utf-8', options = kEmptyObject) { encoding = `${encoding}`; validateObject(options, 'options', { nullable: true, @@ -481,7 +482,7 @@ function makeTextDecoderJS() { this[kBOMSeen] = false; } - decode(input = empty, options = {}) { + decode(input = empty, options = kEmptyObject) { validateDecoder(this); if (isAnyArrayBuffer(input)) { input = lazyBuffer().from(input); diff --git a/lib/internal/histogram.js b/lib/internal/histogram.js index 4237e716dc07e4..ca540e555e0160 100644 --- a/lib/internal/histogram.js +++ b/lib/internal/histogram.js @@ -17,6 +17,7 @@ const { const { customInspectSymbol: kInspect, + kEmptyObject, } = require('internal/util'); const { inspect } = require('util'); @@ -352,7 +353,7 @@ internalRecordableHistogram.prototype[kDeserialize] = () => {}; * }} [options] * @returns {RecordableHistogram} */ -function createHistogram(options = {}) { +function createHistogram(options = kEmptyObject) { validateObject(options, 'options'); const { lowest = 1, diff --git a/lib/internal/promise_hooks.js b/lib/internal/promise_hooks.js index be70879cbcbb93..0938a86d06407b 100644 --- a/lib/internal/promise_hooks.js +++ b/lib/internal/promise_hooks.js @@ -11,6 +11,7 @@ const { const { setPromiseHooks } = internalBinding('async_wrap'); const { triggerUncaughtException } = internalBinding('errors'); +const { kEmptyObject } = require('internal/util'); const { validatePlainFunction } = require('internal/validators'); const hooks = { @@ -101,7 +102,7 @@ const onBefore = makeUseHook('before'); const onAfter = makeUseHook('after'); const onSettled = makeUseHook('settled'); -function createHook({ init, before, after, settled } = {}) { +function createHook({ init, before, after, settled } = kEmptyObject) { const hooks = []; if (init) ArrayPrototypePush(hooks, onInit(init)); From cf8a115983add8c5b34d7c6def68583e40903b78 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Sat, 11 Jun 2022 14:45:31 +0100 Subject: [PATCH 61/96] tools: add `avoid-prototype-pollution` lint rule PR-URL: https://github.com/nodejs/node/pull/43308 Reviewed-By: Rich Trott --- lib/.eslintrc.yaml | 1 + lib/internal/per_context/primordials.js | 10 +- .../test-eslint-avoid-prototype-pollution.js | 147 ++++++++++++++++++ .../eslint-rules/avoid-prototype-pollution.js | 92 +++++++++++ 4 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-eslint-avoid-prototype-pollution.js create mode 100644 tools/eslint-rules/avoid-prototype-pollution.js diff --git a/lib/.eslintrc.yaml b/lib/.eslintrc.yaml index c1635e4cf080af..3fe62b4fe542dc 100644 --- a/lib/.eslintrc.yaml +++ b/lib/.eslintrc.yaml @@ -156,6 +156,7 @@ rules: - name: SubtleCrypto message: Use `const { SubtleCrypto } = require('internal/crypto/webcrypto');` instead of the global. # Custom rules in tools/eslint-rules + node-core/avoid-prototype-pollution: error node-core/lowercase-name-for-primitive: error node-core/non-ascii-character: error node-core/no-array-destructuring: error diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 5c8df35522b847..bbaad4ea760767 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -78,7 +78,7 @@ function copyPropsRenamed(src, dest, prefix) { copyAccessor(dest, prefix, newKey, desc); } else { const name = `${prefix}${newKey}`; - ReflectDefineProperty(dest, name, desc); + ReflectDefineProperty(dest, name, { __proto__: null, ...desc }); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { __proto__: null, @@ -105,7 +105,7 @@ function copyPropsRenamedBound(src, dest, prefix) { } const name = `${prefix}${newKey}`; - ReflectDefineProperty(dest, name, desc); + ReflectDefineProperty(dest, name, { __proto__: null, ...desc }); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { __proto__: null, @@ -129,7 +129,7 @@ function copyPrototype(src, dest, prefix) { } const name = `${prefix}${newKey}`; - ReflectDefineProperty(dest, name, desc); + ReflectDefineProperty(dest, name, { __proto__: null, ...desc }); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { __proto__: null, @@ -312,7 +312,7 @@ const copyProps = (src, dest) => { ReflectDefineProperty( dest, key, - ReflectGetOwnPropertyDescriptor(src, key)); + { __proto__: null, ...ReflectGetOwnPropertyDescriptor(src, key) }); } }); }; @@ -340,7 +340,7 @@ const makeSafe = (unsafe, safe) => { return new SafeIterator(this); }; } - ReflectDefineProperty(safe.prototype, key, desc); + ReflectDefineProperty(safe.prototype, key, { __proto__: null, ...desc }); } }); } else { diff --git a/test/parallel/test-eslint-avoid-prototype-pollution.js b/test/parallel/test-eslint-avoid-prototype-pollution.js new file mode 100644 index 00000000000000..047def545e9a90 --- /dev/null +++ b/test/parallel/test-eslint-avoid-prototype-pollution.js @@ -0,0 +1,147 @@ +'use strict'; + +const common = require('../common'); +if ((!common.hasCrypto) || (!common.hasIntl)) { + common.skip('ESLint tests require crypto and Intl'); +} + +common.skipIfEslintMissing(); + +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; +const rule = require('../../tools/eslint-rules/avoid-prototype-pollution'); + +new RuleTester({ + parserOptions: { ecmaVersion: 2022 }, +}) + .run('property-descriptor-no-prototype-pollution', rule, { + valid: [ + 'ObjectDefineProperties({}, {})', + 'ObjectCreate(null, {})', + 'ObjectDefineProperties({}, { key })', + 'ObjectCreate(null, { key })', + 'ObjectDefineProperties({}, { ...spread })', + 'ObjectCreate(null, { ...spread })', + 'ObjectDefineProperties({}, { key: valueDescriptor })', + 'ObjectCreate(null, { key: valueDescriptor })', + 'ObjectDefineProperties({}, { key: { ...{}, __proto__: null } })', + 'ObjectCreate(null, { key: { ...{}, __proto__: null } })', + 'ObjectDefineProperties({}, { key: { __proto__: null } })', + 'ObjectCreate(null, { key: { __proto__: null } })', + 'ObjectDefineProperties({}, { key: { __proto__: null, enumerable: true } })', + 'ObjectCreate(null, { key: { __proto__: null, enumerable: true } })', + 'ObjectDefineProperties({}, { key: { "__proto__": null } })', + 'ObjectCreate(null, { key: { "__proto__": null } })', + 'ObjectDefineProperties({}, { key: { \'__proto__\': null } })', + 'ObjectCreate(null, { key: { \'__proto__\': null } })', + 'ObjectDefineProperty({}, "key", ObjectCreate(null))', + 'ReflectDefineProperty({}, "key", ObjectCreate(null))', + 'ObjectDefineProperty({}, "key", valueDescriptor)', + 'ReflectDefineProperty({}, "key", valueDescriptor)', + 'ObjectDefineProperty({}, "key", { __proto__: null })', + 'ReflectDefineProperty({}, "key", { __proto__: null })', + 'ObjectDefineProperty({}, "key", { __proto__: null, enumerable: true })', + 'ReflectDefineProperty({}, "key", { __proto__: null, enumerable: true })', + 'ObjectDefineProperty({}, "key", { "__proto__": null })', + 'ReflectDefineProperty({}, "key", { "__proto__": null })', + 'ObjectDefineProperty({}, "key", { \'__proto__\': null })', + 'ReflectDefineProperty({}, "key", { \'__proto__\': null })', + ], + invalid: [ + { + code: 'ObjectDefineProperties({}, ObjectGetOwnPropertyDescriptors({}))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ObjectCreate(null, ObjectGetOwnPropertyDescriptors({}))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ObjectDefineProperties({}, { key: {} })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectCreate(null, { key: {} })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperties({}, { key: { [void 0]: { ...{ __proto__: null } } } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectCreate(null, { key: { [void 0]: { ...{ __proto__: null } } } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperties({}, { key: { __proto__: Object.prototype } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectCreate(null, { key: { __proto__: Object.prototype } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperties({}, { key: { [`__proto__`]: null } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectCreate(null, { key: { [`__proto__`]: null } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperties({}, { key: { enumerable: true } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectCreate(null, { key: { enumerable: true } })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", {})', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", {})', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", ObjectGetOwnPropertyDescriptor({}, "key"))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", ObjectGetOwnPropertyDescriptor({}, "key"))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", ReflectGetOwnPropertyDescriptor({}, "key"))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", ReflectGetOwnPropertyDescriptor({}, "key"))', + errors: [{ message: /prototype pollution/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", { __proto__: Object.prototype })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", { __proto__: Object.prototype })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", { [`__proto__`]: null })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", { [`__proto__`]: null })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ObjectDefineProperty({}, "key", { enumerable: true })', + errors: [{ message: /null-prototype/ }], + }, + { + code: 'ReflectDefineProperty({}, "key", { enumerable: true })', + errors: [{ message: /null-prototype/ }], + }, + ] + }); diff --git a/tools/eslint-rules/avoid-prototype-pollution.js b/tools/eslint-rules/avoid-prototype-pollution.js new file mode 100644 index 00000000000000..bf6bd1e0a81825 --- /dev/null +++ b/tools/eslint-rules/avoid-prototype-pollution.js @@ -0,0 +1,92 @@ +'use strict'; + +function checkProperties(context, node) { + if ( + node.type === 'CallExpression' && + node.callee.name === 'ObjectGetOwnPropertyDescriptors' + ) { + context.report({ + node, + message: + 'Property descriptors inherits from the Object prototype, therefore are subject to prototype pollution', + }); + } + if (node.type !== 'ObjectExpression') return; + for (const { key, value } of node.properties) { + if ( + key != null && value != null && + !(key.type === 'Identifier' && key.name === '__proto__') && + !(key.type === 'Literal' && key.value === '__proto__') + ) { + checkPropertyDescriptor(context, value); + } + } +} + +function checkPropertyDescriptor(context, node) { + if ( + node.type === 'CallExpression' && + (node.callee.name === 'ObjectGetOwnPropertyDescriptor' || + node.callee.name === 'ReflectGetOwnPropertyDescriptor') + ) { + context.report({ + node, + message: + 'Property descriptors inherits from the Object prototype, therefore are subject to prototype pollution', + suggest: [{ + desc: 'Wrap the property descriptor in a null-prototype object', + fix(fixer) { + return [ + fixer.insertTextBefore(node, '{ __proto__: null,...'), + fixer.insertTextAfter(node, ' }'), + ]; + }, + }], + }); + } + if (node.type !== 'ObjectExpression') return; + + for (const { key, value } of node.properties) { + if ( + key != null && value != null && + ((key.type === 'Identifier' && key.name === '__proto__') || + (key.type === 'Literal' && key.value === '__proto__')) && + value.type === 'Literal' && value.value === null + ) { + return true; + } + } + + context.report({ + node, + message: 'Must use null-prototype object for property descriptors', + }); +} + +const CallExpression = 'ExpressionStatement[expression.type="CallExpression"]'; +module.exports = { + meta: { hasSuggestions: true }, + create(context) { + return { + [`${CallExpression}[expression.callee.name=${/^(Object|Reflect)DefinePropert(ies|y)$/}]`]( + node + ) { + switch (node.expression.callee.name) { + case 'ObjectDefineProperties': + checkProperties(context, node.expression.arguments[1]); + break; + case 'ReflectDefineProperty': + case 'ObjectDefineProperty': + checkPropertyDescriptor(context, node.expression.arguments[2]); + break; + default: + throw new Error('Unreachable'); + } + }, + + [`${CallExpression}[expression.callee.name="ObjectCreate"][expression.arguments.length=2]`](node) { + checkProperties(context, node.expression.arguments[1]); + }, + }; + }, +}; From b69d874592741ab7e126d466d594bcc64484169a Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Sat, 11 Jun 2022 14:59:37 +0100 Subject: [PATCH 62/96] tools: fix `create-or-update-pull-request-action` hash on GHA PR-URL: https://github.com/nodejs/node/pull/43378 Reviewed-By: LiviaMedeiros Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Tierney Cyren --- .github/workflows/authors.yml | 2 +- .github/workflows/license-builder.yml | 2 +- .github/workflows/tools.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/authors.yml b/.github/workflows/authors.yml index 1fe2ea16663403..80d6b0ab22fb62 100644 --- a/.github/workflows/authors.yml +++ b/.github/workflows/authors.yml @@ -16,7 +16,7 @@ jobs: fetch-depth: '0' # This is required to actually get all the authors persist-credentials: false - run: tools/update-authors.mjs # Run the AUTHORS tool - - uses: gr2m/create-or-update-pull-request-action@466b1b84c3291c6c69bc56377a6de54a1f4a297c + - uses: gr2m/create-or-update-pull-request-action@6720400cad8e74d7adc64640e4e6ea6748b83d8f # Creates a PR or update the Action's existing PR, or # no-op if the base branch is already up-to-date. env: diff --git a/.github/workflows/license-builder.yml b/.github/workflows/license-builder.yml index 44864cfdb2c750..790bab9e3973f1 100644 --- a/.github/workflows/license-builder.yml +++ b/.github/workflows/license-builder.yml @@ -15,7 +15,7 @@ jobs: with: persist-credentials: false - run: ./tools/license-builder.sh # Run the license builder tool - - uses: gr2m/create-or-update-pull-request-action@466b1b84c3291c6c69bc56377a6de54a1f4a297c + - uses: gr2m/create-or-update-pull-request-action@6720400cad8e74d7adc64640e4e6ea6748b83d8f # Creates a PR or update the Action's existing PR, or # no-op if the base branch is already up-to-date. env: diff --git a/.github/workflows/tools.yml b/.github/workflows/tools.yml index b29dfd205684f1..3d58558ce69a4d 100644 --- a/.github/workflows/tools.yml +++ b/.github/workflows/tools.yml @@ -80,7 +80,7 @@ jobs: with: persist-credentials: false - run: ${{ matrix.run }} - - uses: gr2m/create-or-update-pull-request-action@466b1b84c3291c6c69bc56377a6de54a1f4a297c + - uses: gr2m/create-or-update-pull-request-action@6720400cad8e74d7adc64640e4e6ea6748b83d8f # Creates a PR or update the Action's existing PR, or # no-op if the base branch is already up-to-date. env: From adec5fa9294c73d22d4a025973b5486a6f144193 Mon Sep 17 00:00:00 2001 From: Feng Yu Date: Sat, 11 Jun 2022 22:56:42 +0800 Subject: [PATCH 63/96] doc: add F3n67u to triagers PR-URL: https://github.com/nodejs/node/pull/43350 Reviewed-By: Qingyu Deng Reviewed-By: Rich Trott Reviewed-By: Gireesh Punathil Reviewed-By: Akhil Marsonya Reviewed-By: LiviaMedeiros Reviewed-By: Darshan Sen Reviewed-By: Xuguang Mei Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Antoine du Hamel --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 866314c21a3e26..b487ae5cfd3e7b 100644 --- a/README.md +++ b/README.md @@ -646,6 +646,8 @@ maintaining the Node.js project. * [Ayase-252](https://github.com/Ayase-252) - **Qingyu Deng** <> +* [F3n67u](https://github.com/F3n67u) - + **Feng Yu** <> (he/him) * [himadriganguly](https://github.com/himadriganguly) - **Himadri Ganguly** <> (he/him) * [iam-frankqiu](https://github.com/iam-frankqiu) - From b05cea57babcacb03411ebf51f0f872c721cd8e6 Mon Sep 17 00:00:00 2001 From: "Node.js GitHub Bot" Date: Sun, 12 Jun 2022 07:54:33 +0200 Subject: [PATCH 64/96] meta: update AUTHORS PR-URL: https://github.com/nodejs/node/pull/43387 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca --- AUTHORS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AUTHORS b/AUTHORS index 4c8c6f5c90575e..f20f9bc3313a08 100644 --- a/AUTHORS +++ b/AUTHORS @@ -3462,5 +3462,7 @@ Feng Yu pupilTong rikapo Meek Simbule <55823259+meekdenzo@users.noreply.github.com> +Michael Ficarra +hiroki osame # Generated by tools/update-authors.mjs From e30d4c1cb0b18382c02c944e14a366ecfb61dc76 Mon Sep 17 00:00:00 2001 From: Tierney Cyren Date: Sun, 12 Jun 2022 04:33:29 -0500 Subject: [PATCH 65/96] doc: add fspromises mkdir example Signed-off-by: Tierney Cyren PR-URL: https://github.com/nodejs/node/pull/40843 Reviewed-By: Adrian Estrada Reviewed-By: Antoine du Hamel Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: James M Snell --- doc/api/fs.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/doc/api/fs.md b/doc/api/fs.md index e957e655ba9ae0..f34314518f01ee 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1053,6 +1053,34 @@ property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory that exists results in a rejection only when `recursive` is false. +```mjs +import { mkdir } from 'node:fs/promises'; + +try { + const projectFolder = new URL('./test/project/', import.meta.url); + const createDir = await mkdir(path, { recursive: true }); + + console.log(`created ${createDir}`); +} catch (err) { + console.error(err.message); +} +``` + +```cjs +const { mkdir } = require('node:fs/promises'); +const { resolve, join } = require('node:path'); + +async function makeDirectory() { + const projectFolder = join(__dirname, 'test', 'project'); + const dirCreation = await mkdir(projectFolder, { recursive: true }); + + console.log(dirCreation); + return dirCreation; +} + +makeDirectory().catch(console.error); +``` + ### `fsPromises.mkdtemp(prefix[, options])` + + +#### `auth-type` + +* Default: "legacy" +* Type: "legacy", "webauthn", "sso", "saml", or "oauth" +* DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in + a future version of npm in favor of web-based login. + +What authentication strategy to use with `adduser`/`login`. + +Pass `webauthn` to use a web-based login. + diff --git a/deps/npm/docs/content/commands/npm-bin.md b/deps/npm/docs/content/commands/npm-bin.md index b344ea2fc94159..94b72cfd5c81ce 100644 --- a/deps/npm/docs/content/commands/npm-bin.md +++ b/deps/npm/docs/content/commands/npm-bin.md @@ -34,8 +34,6 @@ Print the folder where npm will install executables. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-config.md b/deps/npm/docs/content/commands/npm-config.md index 809e42a1be1cdb..28c6003571de5f 100644 --- a/deps/npm/docs/content/commands/npm-config.md +++ b/deps/npm/docs/content/commands/npm-config.md @@ -124,8 +124,6 @@ Not supported by all npm commands. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-diff.md b/deps/npm/docs/content/commands/npm-diff.md index 7183e4a2b752e3..7dcc8af7c3b4c7 100644 --- a/deps/npm/docs/content/commands/npm-diff.md +++ b/deps/npm/docs/content/commands/npm-diff.md @@ -248,8 +248,6 @@ Treat all files as text in `npm diff`. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-init.md b/deps/npm/docs/content/commands/npm-init.md index 5a7dd4c97ac60e..35343cceb4aa13 100644 --- a/deps/npm/docs/content/commands/npm-init.md +++ b/deps/npm/docs/content/commands/npm-init.md @@ -253,6 +253,17 @@ This value is not exported to the environment for child processes. +#### `workspaces-update` + +* Default: true +* Type: Boolean + +If set to true, the npm cli will run an update after operations that may +possibly change the workspaces installed to the `node_modules` folder. + + + + #### `include-workspace-root` * Default: false diff --git a/deps/npm/docs/content/commands/npm-install-test.md b/deps/npm/docs/content/commands/npm-install-test.md index 18e374869d5a60..3dd860ea5c6f68 100644 --- a/deps/npm/docs/content/commands/npm-install-test.md +++ b/deps/npm/docs/content/commands/npm-install-test.md @@ -70,8 +70,6 @@ rather than using npm's default semver range operator. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-install.md b/deps/npm/docs/content/commands/npm-install.md index 318df5780e8dba..d6668a2c2bd0fb 100644 --- a/deps/npm/docs/content/commands/npm-install.md +++ b/deps/npm/docs/content/commands/npm-install.md @@ -460,8 +460,6 @@ rather than using npm's default semver range operator. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-link.md b/deps/npm/docs/content/commands/npm-link.md index 34c67aa3def81d..975c807c38b348 100644 --- a/deps/npm/docs/content/commands/npm-link.md +++ b/deps/npm/docs/content/commands/npm-link.md @@ -153,8 +153,6 @@ rather than using npm's default semver range operator. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-ls.md b/deps/npm/docs/content/commands/npm-ls.md index 5ad4593bfa2f6a..ded8c0c0d26ef1 100644 --- a/deps/npm/docs/content/commands/npm-ls.md +++ b/deps/npm/docs/content/commands/npm-ls.md @@ -137,8 +137,6 @@ Output parseable results from commands that write to standard output. For * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-outdated.md b/deps/npm/docs/content/commands/npm-outdated.md index 1bf2de039c3159..6fa026550e7477 100644 --- a/deps/npm/docs/content/commands/npm-outdated.md +++ b/deps/npm/docs/content/commands/npm-outdated.md @@ -150,8 +150,6 @@ Output parseable results from commands that write to standard output. For * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-prefix.md b/deps/npm/docs/content/commands/npm-prefix.md index 6f08e43fa8c0c4..39328bcc88a143 100644 --- a/deps/npm/docs/content/commands/npm-prefix.md +++ b/deps/npm/docs/content/commands/npm-prefix.md @@ -51,8 +51,6 @@ npm prefix -g * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-rebuild.md b/deps/npm/docs/content/commands/npm-rebuild.md index fa5b0cfa97d7c1..52c368c8c513b9 100644 --- a/deps/npm/docs/content/commands/npm-rebuild.md +++ b/deps/npm/docs/content/commands/npm-rebuild.md @@ -42,8 +42,6 @@ will be rebuilt. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-root.md b/deps/npm/docs/content/commands/npm-root.md index 80545235fc9693..40b58e4b33d0b2 100644 --- a/deps/npm/docs/content/commands/npm-root.md +++ b/deps/npm/docs/content/commands/npm-root.md @@ -41,8 +41,6 @@ echo "Global packages installed in: ${global_node_modules}" * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/commands/npm-update.md b/deps/npm/docs/content/commands/npm-update.md index 55aad182fcafe8..421d04ca3dc583 100644 --- a/deps/npm/docs/content/commands/npm-update.md +++ b/deps/npm/docs/content/commands/npm-update.md @@ -188,8 +188,6 @@ Will also prevent writing to `package-lock.json` if set to `false`. * Default: false * Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. Operates in "global" mode, so that packages are installed into the `prefix` folder instead of the current working directory. See diff --git a/deps/npm/docs/content/configuring-npm/package-json.md b/deps/npm/docs/content/configuring-npm/package-json.md index 0c2047ad9abe08..8b188cfb0b9380 100644 --- a/deps/npm/docs/content/configuring-npm/package-json.md +++ b/deps/npm/docs/content/configuring-npm/package-json.md @@ -643,6 +643,26 @@ git+https://isaacs@github.com/npm/cli.git git://github.com/npm/cli.git#v1.0.27 ``` +When installing from a `git` repository, the presence of certain fields in the +`package.json` will cause npm to believe it needs to perform a build. To do so +your repository will be cloned into a temporary directory, all of its deps +installed, relevant scripts run, and the resulting directory packed and +installed. + +This flow will occur if your git dependency uses `workspaces`, or if any of the +following scripts are present: + +* `build` +* `prepare` +* `prepack` +* `preinstall` +* `install` +* `postinstall` + +If your git repository includes pre-built artifacts, you will likely want to +make sure that none of the above scripts are defined, or your dependency +will be rebuilt for every installation. + #### GitHub URLs As of version 1.1.65, you can refer to GitHub urls as just "foo": diff --git a/deps/npm/docs/content/using-npm/config.md b/deps/npm/docs/content/using-npm/config.md index 12b508582af1c3..6ef854eb6e0ff4 100644 --- a/deps/npm/docs/content/using-npm/config.md +++ b/deps/npm/docs/content/using-npm/config.md @@ -687,6 +687,23 @@ results in no commit being made at all. +#### `global` + +* Default: false +* Type: Boolean + +Operates in "global" mode, so that packages are installed into the `prefix` +folder instead of the current working directory. See +[folders](/configuring-npm/folders) for more on the differences in behavior. + +* packages are installed into the `{prefix}/lib/node_modules` folder, instead + of the current working directory. +* bin files are linked to `{prefix}/bin` +* man pages are linked to `{prefix}/share/man` + + + + #### `global-style` * Default: false @@ -1891,12 +1908,14 @@ When set to `dev` or `development`, this is an alias for `--include=dev`. #### `auth-type` * Default: "legacy" -* Type: "legacy", "sso", "saml", or "oauth" -* DEPRECATED: This method of SSO/SAML/OAuth is deprecated and will be removed - in a future version of npm in favor of web-based login. +* Type: "legacy", "webauthn", "sso", "saml", or "oauth" +* DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in + a future version of npm in favor of web-based login. What authentication strategy to use with `adduser`/`login`. +Pass `webauthn` to use a web-based login. + @@ -1933,25 +1952,6 @@ Alias for `--include=dev`. -#### `global` - -* Default: false -* Type: Boolean -* DEPRECATED: `--global`, `--local` are deprecated. Use `--location=global` - instead. - -Operates in "global" mode, so that packages are installed into the `prefix` -folder instead of the current working directory. See -[folders](/configuring-npm/folders) for more on the differences in behavior. - -* packages are installed into the `{prefix}/lib/node_modules` folder, instead - of the current working directory. -* bin files are linked to `{prefix}/bin` -* man pages are linked to `{prefix}/share/man` - - - - #### `init.author.email` * Default: "" diff --git a/deps/npm/docs/content/using-npm/scripts.md b/deps/npm/docs/content/using-npm/scripts.md index b37ca593e4ce63..381c0a71812f09 100644 --- a/deps/npm/docs/content/using-npm/scripts.md +++ b/deps/npm/docs/content/using-npm/scripts.md @@ -203,6 +203,12 @@ will default the `start` command to `node server.js`. `prestart` and * `test` * `posttest` +#### [`npm version`](/commands/npm-version) + +* `preversion` +* `version` +* `postversion` + #### A Note on a lack of [`npm uninstall`](/commands/npm-uninstall) scripts While npm v6 had `uninstall` lifecycle scripts, npm v7 does not. Removal of a package can happen for a wide variety of reasons, and there's no clear way to currently give the script enough context to be useful. diff --git a/deps/npm/docs/output/commands/npm-adduser.html b/deps/npm/docs/output/commands/npm-adduser.html index c0b870e534631e..3b8eaa3159dda3 100644 --- a/deps/npm/docs/output/commands/npm-adduser.html +++ b/deps/npm/docs/output/commands/npm-adduser.html @@ -142,7 +142,7 @@

npm-adduser

Table of contents

- +

Synopsis

@@ -204,6 +204,17 @@

scope

+

auth-type

+
    +
  • Default: "legacy"
  • +
  • Type: "legacy", "webauthn", "sso", "saml", or "oauth"
  • +
  • DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in +a future version of npm in favor of web-based login.
  • +
+

What authentication strategy to use with adduser/login.

+

Pass webauthn to use a web-based login.

+ +

See Also

    diff --git a/deps/npm/docs/output/commands/npm-bin.html b/deps/npm/docs/output/commands/npm-bin.html index 7b957b6014dc44..5961ea7e50fb74 100644 --- a/deps/npm/docs/output/commands/npm-bin.html +++ b/deps/npm/docs/output/commands/npm-bin.html @@ -165,8 +165,6 @@

    global

    • Default: false
    • Type: Boolean
    • -
    • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

    Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-config.html b/deps/npm/docs/output/commands/npm-config.html index e267531fc0462f..184895e036fc0a 100644 --- a/deps/npm/docs/output/commands/npm-config.html +++ b/deps/npm/docs/output/commands/npm-config.html @@ -223,8 +223,6 @@

    global

    • Default: false
    • Type: Boolean
    • -
    • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

    Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-diff.html b/deps/npm/docs/output/commands/npm-diff.html index 7ee9d76d227f8b..13ed989c461801 100644 --- a/deps/npm/docs/output/commands/npm-diff.html +++ b/deps/npm/docs/output/commands/npm-diff.html @@ -334,8 +334,6 @@

    global

    • Default: false
    • Type: Boolean
    • -
    • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

    Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-init.html b/deps/npm/docs/output/commands/npm-init.html index e2e9b01a04ea5d..b25bfec2d4ffe4 100644 --- a/deps/npm/docs/output/commands/npm-init.html +++ b/deps/npm/docs/output/commands/npm-init.html @@ -142,7 +142,7 @@

    npm-init

    Table of contents

    - +

    Synopsis

    @@ -339,6 +339,15 @@

    workspaces

    This value is not exported to the environment for child processes.

    +

    workspaces-update

    +
      +
    • Default: true
    • +
    • Type: Boolean
    • +
    +

    If set to true, the npm cli will run an update after operations that may +possibly change the workspaces installed to the node_modules folder.

    + +

    include-workspace-root

    • Default: false
    • diff --git a/deps/npm/docs/output/commands/npm-install-test.html b/deps/npm/docs/output/commands/npm-install-test.html index fce049dc2c09e5..6306ceb5938558 100644 --- a/deps/npm/docs/output/commands/npm-install-test.html +++ b/deps/npm/docs/output/commands/npm-install-test.html @@ -196,8 +196,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-install.html b/deps/npm/docs/output/commands/npm-install.html index ca6ca1ee260f33..509702b5bd4ead 100644 --- a/deps/npm/docs/output/commands/npm-install.html +++ b/deps/npm/docs/output/commands/npm-install.html @@ -522,8 +522,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-link.html b/deps/npm/docs/output/commands/npm-link.html index cb43c0478d7015..f7d5f66a9e2bd2 100644 --- a/deps/npm/docs/output/commands/npm-link.html +++ b/deps/npm/docs/output/commands/npm-link.html @@ -251,8 +251,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-ls.html b/deps/npm/docs/output/commands/npm-ls.html index 10caff53c3a090..7b1c29f9a80639 100644 --- a/deps/npm/docs/output/commands/npm-ls.html +++ b/deps/npm/docs/output/commands/npm-ls.html @@ -166,7 +166,7 @@

      Description

      the results to only the paths to the packages named. Note that nested packages will also show the paths to the specified packages. For example, running npm ls promzard in npm's source tree will show:

      -
      npm@8.11.0 /path/to/npm
      +
      npm@8.12.1 /path/to/npm
       └─┬ init-package-json@0.0.4
         └── promzard@0.1.5
       
      @@ -246,8 +246,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-outdated.html b/deps/npm/docs/output/commands/npm-outdated.html index 15030d60080819..0bdb9f9a66a14a 100644 --- a/deps/npm/docs/output/commands/npm-outdated.html +++ b/deps/npm/docs/output/commands/npm-outdated.html @@ -268,8 +268,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-prefix.html b/deps/npm/docs/output/commands/npm-prefix.html index df6960ef97bbcd..2f302144269200 100644 --- a/deps/npm/docs/output/commands/npm-prefix.html +++ b/deps/npm/docs/output/commands/npm-prefix.html @@ -176,8 +176,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-rebuild.html b/deps/npm/docs/output/commands/npm-rebuild.html index 84837a3be5d394..f4524f1a4f0baa 100644 --- a/deps/npm/docs/output/commands/npm-rebuild.html +++ b/deps/npm/docs/output/commands/npm-rebuild.html @@ -173,8 +173,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-root.html b/deps/npm/docs/output/commands/npm-root.html index c9cc1d4b67843b..e0595fd8e76256 100644 --- a/deps/npm/docs/output/commands/npm-root.html +++ b/deps/npm/docs/output/commands/npm-root.html @@ -170,8 +170,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm-update.html b/deps/npm/docs/output/commands/npm-update.html index d0cb6d5f75501b..d88ea8578bacef 100644 --- a/deps/npm/docs/output/commands/npm-update.html +++ b/deps/npm/docs/output/commands/npm-update.html @@ -275,8 +275,6 @@

      global

      • Default: false
      • Type: Boolean
      • -
      • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.

      Operates in "global" mode, so that packages are installed into the prefix folder instead of the current working directory. See diff --git a/deps/npm/docs/output/commands/npm.html b/deps/npm/docs/output/commands/npm.html index 99c109c4e25cfa..040166af65cabb 100644 --- a/deps/npm/docs/output/commands/npm.html +++ b/deps/npm/docs/output/commands/npm.html @@ -149,7 +149,7 @@

      Table of contents

      Version

      -

      8.11.0

      +

      8.12.1

      Description

      npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency diff --git a/deps/npm/docs/output/configuring-npm/package-json.html b/deps/npm/docs/output/configuring-npm/package-json.html index b318eee5795193..d5860ee6e299a1 100644 --- a/deps/npm/docs/output/configuring-npm/package-json.html +++ b/deps/npm/docs/output/configuring-npm/package-json.html @@ -629,6 +629,24 @@

      Git URLs as Dependencies

      git+https://isaacs@github.com/npm/cli.git git://github.com/npm/cli.git#v1.0.27
      +

      When installing from a git repository, the presence of certain fields in the +package.json will cause npm to believe it needs to perform a build. To do so +your repository will be cloned into a temporary directory, all of its deps +installed, relevant scripts run, and the resulting directory packed and +installed.

      +

      This flow will occur if your git dependency uses workspaces, or if any of the +following scripts are present:

      +
        +
      • build
      • +
      • prepare
      • +
      • prepack
      • +
      • preinstall
      • +
      • install
      • +
      • postinstall
      • +
      +

      If your git repository includes pre-built artifacts, you will likely want to +make sure that none of the above scripts are defined, or your dependency +will be rebuilt for every installation.

      GitHub URLs

      As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be diff --git a/deps/npm/docs/output/using-npm/config.html b/deps/npm/docs/output/using-npm/config.html index ef033b8693e4fd..4ec52124ffe563 100644 --- a/deps/npm/docs/output/using-npm/config.html +++ b/deps/npm/docs/output/using-npm/config.html @@ -142,7 +142,7 @@

      config

      Table of contents

      -
      +

      Description

      @@ -696,6 +696,22 @@

      git-tag-version

      results in no commit being made at all.

      +

      global

      +
        +
      • Default: false
      • +
      • Type: Boolean
      • +
      +

      Operates in "global" mode, so that packages are installed into the prefix +folder instead of the current working directory. See +folders for more on the differences in behavior.

      +
        +
      • packages are installed into the {prefix}/lib/node_modules folder, instead +of the current working directory.
      • +
      • bin files are linked to {prefix}/bin
      • +
      • man pages are linked to {prefix}/share/man
      • +
      + +

      global-style

      • Default: false
      • @@ -1660,11 +1676,12 @@

        also

        auth-type

        • Default: "legacy"
        • -
        • Type: "legacy", "sso", "saml", or "oauth"
        • -
        • DEPRECATED: This method of SSO/SAML/OAuth is deprecated and will be removed -in a future version of npm in favor of web-based login.
        • +
        • Type: "legacy", "webauthn", "sso", "saml", or "oauth"
        • +
        • DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in +a future version of npm in favor of web-based login.

        What authentication strategy to use with adduser/login.

        +

        Pass webauthn to use a web-based login.

        cache-max

        @@ -1694,24 +1711,6 @@

        dev

        Alias for --include=dev.

        -

        global

        -
          -
        • Default: false
        • -
        • Type: Boolean
        • -
        • DEPRECATED: --global, --local are deprecated. Use --location=global -instead.
        • -
        -

        Operates in "global" mode, so that packages are installed into the prefix -folder instead of the current working directory. See -folders for more on the differences in behavior.

        -
          -
        • packages are installed into the {prefix}/lib/node_modules folder, instead -of the current working directory.
        • -
        • bin files are linked to {prefix}/bin
        • -
        • man pages are linked to {prefix}/share/man
        • -
        - -

        init.author.email

        +

        npm version

        +
          +
        • preversion
        • +
        • version
        • +
        • postversion
        • +

        A Note on a lack of npm uninstall scripts

        While npm v6 had uninstall lifecycle scripts, npm v7 does not. Removal of a package can happen for a wide variety of reasons, and there's no clear way to currently give the script enough context to be useful.

        Reasons for a package removal include:

        diff --git a/deps/npm/lib/commands/adduser.js b/deps/npm/lib/commands/adduser.js index 755abea8eb9ebe..cf467b7a73a5e8 100644 --- a/deps/npm/lib/commands/adduser.js +++ b/deps/npm/lib/commands/adduser.js @@ -3,6 +3,7 @@ const replaceInfo = require('../utils/replace-info.js') const BaseCommand = require('../base-command.js') const authTypes = { legacy: require('../auth/legacy.js'), + webauthn: require('../auth/legacy.js'), oauth: require('../auth/oauth.js'), saml: require('../auth/saml.js'), sso: require('../auth/sso.js'), @@ -14,6 +15,7 @@ class AddUser extends BaseCommand { static params = [ 'registry', 'scope', + 'auth-type', ] static ignoreImplicitWorkspace = true diff --git a/deps/npm/lib/commands/init.js b/deps/npm/lib/commands/init.js index 2a6b6aaddc7e65..4c299e65137bed 100644 --- a/deps/npm/lib/commands/init.js +++ b/deps/npm/lib/commands/init.js @@ -8,13 +8,22 @@ const libexec = require('libnpmexec') const mapWorkspaces = require('@npmcli/map-workspaces') const PackageJson = require('@npmcli/package-json') const log = require('../utils/log-shim.js') +const updateWorkspaces = require('../workspaces/update-workspaces.js') const getLocationMsg = require('../exec/get-workspace-location-msg.js') const BaseCommand = require('../base-command.js') class Init extends BaseCommand { static description = 'Create a package.json file' - static params = ['yes', 'force', 'workspace', 'workspaces', 'include-workspace-root'] + static params = [ + 'yes', + 'force', + 'workspace', + 'workspaces', + 'workspaces-update', + 'include-workspace-root', + ] + static name = 'init' static usage = [ '[--force|-f|--yes|-y|--scope]', @@ -46,11 +55,13 @@ class Init extends BaseCommand { const pkg = await rpj(resolve(this.npm.localPrefix, 'package.json')) const wPath = filterArg => resolve(this.npm.localPrefix, filterArg) + const workspacesPaths = [] // npm-exec style, runs in the context of each workspace filter if (args.length) { for (const filterArg of filters) { const path = wPath(filterArg) await mkdirp(path) + workspacesPaths.push(path) await this.execCreate({ args, path }) await this.setWorkspace({ pkg, workspacePath: path }) } @@ -61,9 +72,13 @@ class Init extends BaseCommand { for (const filterArg of filters) { const path = wPath(filterArg) await mkdirp(path) + workspacesPaths.push(path) await this.template(path) await this.setWorkspace({ pkg, workspacePath: path }) } + + // reify packages once all workspaces have been initialized + await this.update(workspacesPaths) } async execCreate ({ args, path }) { @@ -196,6 +211,34 @@ class Init extends BaseCommand { await pkgJson.save() } + + async update (workspacesPaths) { + // translate workspaces paths into an array containing workspaces names + const workspaces = [] + for (const path of workspacesPaths) { + const pkgPath = resolve(path, 'package.json') + const { name } = await rpj(pkgPath) + .catch(() => ({})) + + if (name) { + workspaces.push(name) + } + } + + const { + config, + flatOptions, + localPrefix, + } = this.npm + + await updateWorkspaces({ + config, + flatOptions, + localPrefix, + npm: this.npm, + workspaces, + }) + } } module.exports = Init diff --git a/deps/npm/lib/commands/version.js b/deps/npm/lib/commands/version.js index ed506f663e89fd..ab59fff5a308cc 100644 --- a/deps/npm/lib/commands/version.js +++ b/deps/npm/lib/commands/version.js @@ -3,9 +3,7 @@ const { resolve } = require('path') const { promisify } = require('util') const readFile = promisify(require('fs').readFile) -const Arborist = require('@npmcli/arborist') -const reifyFinish = require('../utils/reify-finish.js') - +const updateWorkspaces = require('../workspaces/update-workspaces.js') const BaseCommand = require('../base-command.js') class Version extends BaseCommand { @@ -137,32 +135,20 @@ class Version extends BaseCommand { return this.list(results) } - async update (args) { - if (!this.npm.flatOptions.workspacesUpdate || !args.length) { - return - } - - // default behavior is to not save by default in order to avoid - // race condition problems when publishing multiple workspaces - // that have dependencies on one another, it might still be useful - // in some cases, which then need to set --save - const save = this.npm.config.isDefault('save') - ? false - : this.npm.config.get('save') - - // runs a minimalistic reify update, targetting only the workspaces - // that had version updates and skipping fund/audit/save - const opts = { - ...this.npm.flatOptions, - audit: false, - fund: false, - path: this.npm.localPrefix, - save, - } - const arb = new Arborist(opts) - - await arb.reify({ ...opts, update: args }) - await reifyFinish(this.npm, arb) + async update (workspaces) { + const { + config, + flatOptions, + localPrefix, + } = this.npm + + await updateWorkspaces({ + config, + flatOptions, + localPrefix, + npm: this.npm, + workspaces, + }) } } diff --git a/deps/npm/lib/utils/config/definitions.js b/deps/npm/lib/utils/config/definitions.js index 92fbbd1e6dc20e..4c77e375c5ccf3 100644 --- a/deps/npm/lib/utils/config/definitions.js +++ b/deps/npm/lib/utils/config/definitions.js @@ -238,13 +238,15 @@ define('audit-level', { define('auth-type', { default: 'legacy', - type: ['legacy', 'sso', 'saml', 'oauth'], + type: ['legacy', 'webauthn', 'sso', 'saml', 'oauth'], deprecated: ` - This method of SSO/SAML/OAuth is deprecated and will be removed in + The SSO/SAML/OAuth methods are deprecated and will be removed in a future version of npm in favor of web-based login. `, description: ` What authentication strategy to use with \`adduser\`/\`login\`. + + Pass \`webauthn\` to use a web-based login. `, flatten, }) @@ -811,9 +813,6 @@ define('global', { default: false, type: Boolean, short: 'g', - deprecated: ` - \`--global\`, \`--local\` are deprecated. Use \`--location=global\` instead. - `, description: ` Operates in "global" mode, so that packages are installed into the \`prefix\` folder instead of the current working directory. See diff --git a/deps/npm/lib/workspaces/update-workspaces.js b/deps/npm/lib/workspaces/update-workspaces.js new file mode 100644 index 00000000000000..4cba1245ac2e57 --- /dev/null +++ b/deps/npm/lib/workspaces/update-workspaces.js @@ -0,0 +1,40 @@ +'use strict' + +const Arborist = require('@npmcli/arborist') +const reifyFinish = require('../utils/reify-finish.js') + +async function updateWorkspaces ({ + config, + flatOptions, + localPrefix, + npm, + workspaces, +}) { + if (!flatOptions.workspacesUpdate || !workspaces.length) { + return + } + + // default behavior is to not save by default in order to avoid + // race condition problems when publishing multiple workspaces + // that have dependencies on one another, it might still be useful + // in some cases, which then need to set --save + const save = config.isDefault('save') + ? false + : config.get('save') + + // runs a minimalistic reify update, targetting only the workspaces + // that had version updates and skipping fund/audit/save + const opts = { + ...flatOptions, + audit: false, + fund: false, + path: localPrefix, + save, + } + const arb = new Arborist(opts) + + await arb.reify({ ...opts, update: workspaces }) + await reifyFinish(npm, arb) +} + +module.exports = updateWorkspaces diff --git a/deps/npm/man/man1/npm-access.1 b/deps/npm/man/man1/npm-access.1 index 66e859f6a2a6d8..0529f88ac9e172 100644 --- a/deps/npm/man/man1/npm-access.1 +++ b/deps/npm/man/man1/npm-access.1 @@ -1,4 +1,4 @@ -.TH "NPM\-ACCESS" "1" "May 2022" "" "" +.TH "NPM\-ACCESS" "1" "June 2022" "" "" .SH "NAME" \fBnpm-access\fR \- Set access level on published packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-adduser.1 b/deps/npm/man/man1/npm-adduser.1 index 08a78c48e85522..de87ef4df4a199 100644 --- a/deps/npm/man/man1/npm-adduser.1 +++ b/deps/npm/man/man1/npm-adduser.1 @@ -1,4 +1,4 @@ -.TH "NPM\-ADDUSER" "1" "May 2022" "" "" +.TH "NPM\-ADDUSER" "1" "June 2022" "" "" .SH "NAME" \fBnpm-adduser\fR \- Add a registry user account .SS Synopsis @@ -77,6 +77,21 @@ This will also cause \fBnpm init\fP to create a scoped package\. npm init \-\-scope=@foo \-\-yes .fi .RE +.SS \fBauth\-type\fP +.RS 0 +.IP \(bu 2 +Default: "legacy" +.IP \(bu 2 +Type: "legacy", "webauthn", "sso", "saml", or "oauth" +.IP \(bu 2 +DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in +a future version of npm in favor of web\-based login\. + +.RE +.P +What authentication strategy to use with \fBadduser\fP/\fBlogin\fP\|\. +.P +Pass \fBwebauthn\fP to use a web\-based login\. .SS See Also .RS 0 .IP \(bu 2 diff --git a/deps/npm/man/man1/npm-audit.1 b/deps/npm/man/man1/npm-audit.1 index d84fdd59e583c3..2f2d0b394b6e71 100644 --- a/deps/npm/man/man1/npm-audit.1 +++ b/deps/npm/man/man1/npm-audit.1 @@ -1,4 +1,4 @@ -.TH "NPM\-AUDIT" "1" "May 2022" "" "" +.TH "NPM\-AUDIT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-audit\fR \- Run a security audit .SS Synopsis diff --git a/deps/npm/man/man1/npm-bin.1 b/deps/npm/man/man1/npm-bin.1 index 9c6d2ccf4c7723..a053d7bc882e8e 100644 --- a/deps/npm/man/man1/npm-bin.1 +++ b/deps/npm/man/man1/npm-bin.1 @@ -1,4 +1,4 @@ -.TH "NPM\-BIN" "1" "May 2022" "" "" +.TH "NPM\-BIN" "1" "June 2022" "" "" .SH "NAME" \fBnpm-bin\fR \- Display npm bin folder .SS Synopsis @@ -20,9 +20,6 @@ Print the folder where npm will install executables\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-bugs.1 b/deps/npm/man/man1/npm-bugs.1 index 1c1ec8a08e28c1..bee4cd4d01e139 100644 --- a/deps/npm/man/man1/npm-bugs.1 +++ b/deps/npm/man/man1/npm-bugs.1 @@ -1,4 +1,4 @@ -.TH "NPM\-BUGS" "1" "May 2022" "" "" +.TH "NPM\-BUGS" "1" "June 2022" "" "" .SH "NAME" \fBnpm-bugs\fR \- Report bugs for a package in a web browser .SS Synopsis diff --git a/deps/npm/man/man1/npm-cache.1 b/deps/npm/man/man1/npm-cache.1 index 1b5e5a843725b3..42e1998371c0e4 100644 --- a/deps/npm/man/man1/npm-cache.1 +++ b/deps/npm/man/man1/npm-cache.1 @@ -1,4 +1,4 @@ -.TH "NPM\-CACHE" "1" "May 2022" "" "" +.TH "NPM\-CACHE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-cache\fR \- Manipulates packages cache .SS Synopsis diff --git a/deps/npm/man/man1/npm-ci.1 b/deps/npm/man/man1/npm-ci.1 index 70182bf407ae5b..533ec91005862d 100644 --- a/deps/npm/man/man1/npm-ci.1 +++ b/deps/npm/man/man1/npm-ci.1 @@ -1,4 +1,4 @@ -.TH "NPM\-CI" "1" "May 2022" "" "" +.TH "NPM\-CI" "1" "June 2022" "" "" .SH "NAME" \fBnpm-ci\fR \- Clean install a project .SS Synopsis diff --git a/deps/npm/man/man1/npm-completion.1 b/deps/npm/man/man1/npm-completion.1 index 87eb098ce92098..7b6be088ca14cd 100644 --- a/deps/npm/man/man1/npm-completion.1 +++ b/deps/npm/man/man1/npm-completion.1 @@ -1,4 +1,4 @@ -.TH "NPM\-COMPLETION" "1" "May 2022" "" "" +.TH "NPM\-COMPLETION" "1" "June 2022" "" "" .SH "NAME" \fBnpm-completion\fR \- Tab Completion for npm .SS Synopsis diff --git a/deps/npm/man/man1/npm-config.1 b/deps/npm/man/man1/npm-config.1 index 88ffa9aa054c67..2cd7faf69bb333 100644 --- a/deps/npm/man/man1/npm-config.1 +++ b/deps/npm/man/man1/npm-config.1 @@ -1,4 +1,4 @@ -.TH "NPM\-CONFIG" "1" "May 2022" "" "" +.TH "NPM\-CONFIG" "1" "June 2022" "" "" .SH "NAME" \fBnpm-config\fR \- Manage the npm configuration files .SS Synopsis @@ -117,9 +117,6 @@ Not supported by all npm commands\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-dedupe.1 b/deps/npm/man/man1/npm-dedupe.1 index c337c715017a57..3f235b273eb79e 100644 --- a/deps/npm/man/man1/npm-dedupe.1 +++ b/deps/npm/man/man1/npm-dedupe.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DEDUPE" "1" "May 2022" "" "" +.TH "NPM\-DEDUPE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-dedupe\fR \- Reduce duplication in the package tree .SS Synopsis diff --git a/deps/npm/man/man1/npm-deprecate.1 b/deps/npm/man/man1/npm-deprecate.1 index 594b1689b73f62..e9ab9bae71a6fb 100644 --- a/deps/npm/man/man1/npm-deprecate.1 +++ b/deps/npm/man/man1/npm-deprecate.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DEPRECATE" "1" "May 2022" "" "" +.TH "NPM\-DEPRECATE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-deprecate\fR \- Deprecate a version of a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-diff.1 b/deps/npm/man/man1/npm-diff.1 index d32c343f064372..753d2863e87106 100644 --- a/deps/npm/man/man1/npm-diff.1 +++ b/deps/npm/man/man1/npm-diff.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DIFF" "1" "May 2022" "" "" +.TH "NPM\-DIFF" "1" "June 2022" "" "" .SH "NAME" \fBnpm-diff\fR \- The registry diff command .SS Synopsis @@ -232,9 +232,6 @@ Treat all files as text in \fBnpm diff\fP\|\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-dist-tag.1 b/deps/npm/man/man1/npm-dist-tag.1 index 33166e1c45a244..7e1c14539540d7 100644 --- a/deps/npm/man/man1/npm-dist-tag.1 +++ b/deps/npm/man/man1/npm-dist-tag.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DIST\-TAG" "1" "May 2022" "" "" +.TH "NPM\-DIST\-TAG" "1" "June 2022" "" "" .SH "NAME" \fBnpm-dist-tag\fR \- Modify package distribution tags .SS Synopsis diff --git a/deps/npm/man/man1/npm-docs.1 b/deps/npm/man/man1/npm-docs.1 index e7dc87e834e440..55ad03256ba8aa 100644 --- a/deps/npm/man/man1/npm-docs.1 +++ b/deps/npm/man/man1/npm-docs.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DOCS" "1" "May 2022" "" "" +.TH "NPM\-DOCS" "1" "June 2022" "" "" .SH "NAME" \fBnpm-docs\fR \- Open documentation for a package in a web browser .SS Synopsis diff --git a/deps/npm/man/man1/npm-doctor.1 b/deps/npm/man/man1/npm-doctor.1 index 4c7dd20a9df826..a21a8eef1bee7e 100644 --- a/deps/npm/man/man1/npm-doctor.1 +++ b/deps/npm/man/man1/npm-doctor.1 @@ -1,4 +1,4 @@ -.TH "NPM\-DOCTOR" "1" "May 2022" "" "" +.TH "NPM\-DOCTOR" "1" "June 2022" "" "" .SH "NAME" \fBnpm-doctor\fR \- Check your npm environment .SS Synopsis diff --git a/deps/npm/man/man1/npm-edit.1 b/deps/npm/man/man1/npm-edit.1 index d5e4fd9398fa6d..5c95bb10538b65 100644 --- a/deps/npm/man/man1/npm-edit.1 +++ b/deps/npm/man/man1/npm-edit.1 @@ -1,4 +1,4 @@ -.TH "NPM\-EDIT" "1" "May 2022" "" "" +.TH "NPM\-EDIT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-edit\fR \- Edit an installed package .SS Synopsis diff --git a/deps/npm/man/man1/npm-exec.1 b/deps/npm/man/man1/npm-exec.1 index 1203e1427e0b90..6403191e1c6741 100644 --- a/deps/npm/man/man1/npm-exec.1 +++ b/deps/npm/man/man1/npm-exec.1 @@ -1,4 +1,4 @@ -.TH "NPM\-EXEC" "1" "May 2022" "" "" +.TH "NPM\-EXEC" "1" "June 2022" "" "" .SH "NAME" \fBnpm-exec\fR \- Run a command from a local or remote npm package .SS Synopsis diff --git a/deps/npm/man/man1/npm-explain.1 b/deps/npm/man/man1/npm-explain.1 index 29866d5c36b214..9a3eec6756ddd8 100644 --- a/deps/npm/man/man1/npm-explain.1 +++ b/deps/npm/man/man1/npm-explain.1 @@ -1,4 +1,4 @@ -.TH "NPM\-EXPLAIN" "1" "May 2022" "" "" +.TH "NPM\-EXPLAIN" "1" "June 2022" "" "" .SH "NAME" \fBnpm-explain\fR \- Explain installed packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-explore.1 b/deps/npm/man/man1/npm-explore.1 index 266248676dfacb..f57776e2df6c5a 100644 --- a/deps/npm/man/man1/npm-explore.1 +++ b/deps/npm/man/man1/npm-explore.1 @@ -1,4 +1,4 @@ -.TH "NPM\-EXPLORE" "1" "May 2022" "" "" +.TH "NPM\-EXPLORE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-explore\fR \- Browse an installed package .SS Synopsis diff --git a/deps/npm/man/man1/npm-find-dupes.1 b/deps/npm/man/man1/npm-find-dupes.1 index 4f1652d54bb5bc..32e036cd73ad95 100644 --- a/deps/npm/man/man1/npm-find-dupes.1 +++ b/deps/npm/man/man1/npm-find-dupes.1 @@ -1,4 +1,4 @@ -.TH "NPM\-FIND\-DUPES" "1" "May 2022" "" "" +.TH "NPM\-FIND\-DUPES" "1" "June 2022" "" "" .SH "NAME" \fBnpm-find-dupes\fR \- Find duplication in the package tree .SS Synopsis diff --git a/deps/npm/man/man1/npm-fund.1 b/deps/npm/man/man1/npm-fund.1 index 44d848357d5281..ef77df60ce83d5 100644 --- a/deps/npm/man/man1/npm-fund.1 +++ b/deps/npm/man/man1/npm-fund.1 @@ -1,4 +1,4 @@ -.TH "NPM\-FUND" "1" "May 2022" "" "" +.TH "NPM\-FUND" "1" "June 2022" "" "" .SH "NAME" \fBnpm-fund\fR \- Retrieve funding information .SS Synopsis diff --git a/deps/npm/man/man1/npm-help-search.1 b/deps/npm/man/man1/npm-help-search.1 index f4e9ec4c91e4d5..e9b7f3e34eecab 100644 --- a/deps/npm/man/man1/npm-help-search.1 +++ b/deps/npm/man/man1/npm-help-search.1 @@ -1,4 +1,4 @@ -.TH "NPM\-HELP\-SEARCH" "1" "May 2022" "" "" +.TH "NPM\-HELP\-SEARCH" "1" "June 2022" "" "" .SH "NAME" \fBnpm-help-search\fR \- Search npm help documentation .SS Synopsis diff --git a/deps/npm/man/man1/npm-help.1 b/deps/npm/man/man1/npm-help.1 index 83cb8f92d04db8..1c22611f8e8059 100644 --- a/deps/npm/man/man1/npm-help.1 +++ b/deps/npm/man/man1/npm-help.1 @@ -1,4 +1,4 @@ -.TH "NPM\-HELP" "1" "May 2022" "" "" +.TH "NPM\-HELP" "1" "June 2022" "" "" .SH "NAME" \fBnpm-help\fR \- Get help on npm .SS Synopsis diff --git a/deps/npm/man/man1/npm-hook.1 b/deps/npm/man/man1/npm-hook.1 index 27b8888c8cda20..b90d873b0944d5 100644 --- a/deps/npm/man/man1/npm-hook.1 +++ b/deps/npm/man/man1/npm-hook.1 @@ -1,4 +1,4 @@ -.TH "NPM\-HOOK" "1" "May 2022" "" "" +.TH "NPM\-HOOK" "1" "June 2022" "" "" .SH "NAME" \fBnpm-hook\fR \- Manage registry hooks .SS Synopsis diff --git a/deps/npm/man/man1/npm-init.1 b/deps/npm/man/man1/npm-init.1 index 829b1b4752bdb5..51e9f42f824c75 100644 --- a/deps/npm/man/man1/npm-init.1 +++ b/deps/npm/man/man1/npm-init.1 @@ -1,4 +1,4 @@ -.TH "NPM\-INIT" "1" "May 2022" "" "" +.TH "NPM\-INIT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-init\fR \- Create a package\.json file .SS Synopsis @@ -286,6 +286,17 @@ other things (test, exec, publish, etc\.) will operate on the root project, .RE .P This value is not exported to the environment for child processes\. +.SS \fBworkspaces\-update\fP +.RS 0 +.IP \(bu 2 +Default: true +.IP \(bu 2 +Type: Boolean + +.RE +.P +If set to true, the npm cli will run an update after operations that may +possibly change the workspaces installed to the \fBnode_modules\fP folder\. .SS \fBinclude\-workspace\-root\fP .RS 0 .IP \(bu 2 diff --git a/deps/npm/man/man1/npm-install-ci-test.1 b/deps/npm/man/man1/npm-install-ci-test.1 index aeddd06d146dda..e50f7e90aec027 100644 --- a/deps/npm/man/man1/npm-install-ci-test.1 +++ b/deps/npm/man/man1/npm-install-ci-test.1 @@ -1,4 +1,4 @@ -.TH "NPM\-INSTALL\-CI\-TEST" "1" "May 2022" "" "" +.TH "NPM\-INSTALL\-CI\-TEST" "1" "June 2022" "" "" .SH "NAME" \fBnpm-install-ci-test\fR \- Install a project with a clean slate and run tests .SS Synopsis diff --git a/deps/npm/man/man1/npm-install-test.1 b/deps/npm/man/man1/npm-install-test.1 index e29397bf940453..1e6ece0f47b616 100644 --- a/deps/npm/man/man1/npm-install-test.1 +++ b/deps/npm/man/man1/npm-install-test.1 @@ -1,4 +1,4 @@ -.TH "NPM\-INSTALL\-TEST" "1" "May 2022" "" "" +.TH "NPM\-INSTALL\-TEST" "1" "June 2022" "" "" .SH "NAME" \fBnpm-install-test\fR \- Install package(s) and run tests .SS Synopsis @@ -56,9 +56,6 @@ rather than using npm's default semver range operator\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-install.1 b/deps/npm/man/man1/npm-install.1 index 4bb41f2d7b4670..9d720117819769 100644 --- a/deps/npm/man/man1/npm-install.1 +++ b/deps/npm/man/man1/npm-install.1 @@ -1,4 +1,4 @@ -.TH "NPM\-INSTALL" "1" "May 2022" "" "" +.TH "NPM\-INSTALL" "1" "June 2022" "" "" .SH "NAME" \fBnpm-install\fR \- Install a package .SS Synopsis @@ -467,9 +467,6 @@ rather than using npm's default semver range operator\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-link.1 b/deps/npm/man/man1/npm-link.1 index 1b982044e48d69..d748d168451826 100644 --- a/deps/npm/man/man1/npm-link.1 +++ b/deps/npm/man/man1/npm-link.1 @@ -1,4 +1,4 @@ -.TH "NPM\-LINK" "1" "May 2022" "" "" +.TH "NPM\-LINK" "1" "June 2022" "" "" .SH "NAME" \fBnpm-link\fR \- Symlink a package folder .SS Synopsis @@ -145,9 +145,6 @@ rather than using npm's default semver range operator\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-logout.1 b/deps/npm/man/man1/npm-logout.1 index 8307918100789e..4f37c3f7b0faac 100644 --- a/deps/npm/man/man1/npm-logout.1 +++ b/deps/npm/man/man1/npm-logout.1 @@ -1,4 +1,4 @@ -.TH "NPM\-LOGOUT" "1" "May 2022" "" "" +.TH "NPM\-LOGOUT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-logout\fR \- Log out of the registry .SS Synopsis diff --git a/deps/npm/man/man1/npm-ls.1 b/deps/npm/man/man1/npm-ls.1 index 1efd612984c8dd..2308cc16016a62 100644 --- a/deps/npm/man/man1/npm-ls.1 +++ b/deps/npm/man/man1/npm-ls.1 @@ -1,4 +1,4 @@ -.TH "NPM\-LS" "1" "May 2022" "" "" +.TH "NPM\-LS" "1" "June 2022" "" "" .SH "NAME" \fBnpm-ls\fR \- List installed packages .SS Synopsis @@ -26,7 +26,7 @@ example, running \fBnpm ls promzard\fP in npm's source tree will show: .P .RS 2 .nf -npm@8\.11\.0 /path/to/npm +npm@8\.12\.1 /path/to/npm └─┬ init\-package\-json@0\.0\.4 └── promzard@0\.1\.5 .fi @@ -127,9 +127,6 @@ Output parseable results from commands that write to standard output\. For Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-org.1 b/deps/npm/man/man1/npm-org.1 index 28d623b204b760..b8b606c61d8145 100644 --- a/deps/npm/man/man1/npm-org.1 +++ b/deps/npm/man/man1/npm-org.1 @@ -1,4 +1,4 @@ -.TH "NPM\-ORG" "1" "May 2022" "" "" +.TH "NPM\-ORG" "1" "June 2022" "" "" .SH "NAME" \fBnpm-org\fR \- Manage orgs .SS Synopsis diff --git a/deps/npm/man/man1/npm-outdated.1 b/deps/npm/man/man1/npm-outdated.1 index 03bcf925884496..3d5025e0e04335 100644 --- a/deps/npm/man/man1/npm-outdated.1 +++ b/deps/npm/man/man1/npm-outdated.1 @@ -1,4 +1,4 @@ -.TH "NPM\-OUTDATED" "1" "May 2022" "" "" +.TH "NPM\-OUTDATED" "1" "June 2022" "" "" .SH "NAME" \fBnpm-outdated\fR \- Check for outdated packages .SS Synopsis @@ -159,9 +159,6 @@ Output parseable results from commands that write to standard output\. For Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-owner.1 b/deps/npm/man/man1/npm-owner.1 index 09f488ed8ea57f..312bf22942d6c6 100644 --- a/deps/npm/man/man1/npm-owner.1 +++ b/deps/npm/man/man1/npm-owner.1 @@ -1,4 +1,4 @@ -.TH "NPM\-OWNER" "1" "May 2022" "" "" +.TH "NPM\-OWNER" "1" "June 2022" "" "" .SH "NAME" \fBnpm-owner\fR \- Manage package owners .SS Synopsis diff --git a/deps/npm/man/man1/npm-pack.1 b/deps/npm/man/man1/npm-pack.1 index 94a0df9efc3bb5..028fab69b1af14 100644 --- a/deps/npm/man/man1/npm-pack.1 +++ b/deps/npm/man/man1/npm-pack.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PACK" "1" "May 2022" "" "" +.TH "NPM\-PACK" "1" "June 2022" "" "" .SH "NAME" \fBnpm-pack\fR \- Create a tarball from a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-ping.1 b/deps/npm/man/man1/npm-ping.1 index bf065b16f1573d..643504f3d9a638 100644 --- a/deps/npm/man/man1/npm-ping.1 +++ b/deps/npm/man/man1/npm-ping.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PING" "1" "May 2022" "" "" +.TH "NPM\-PING" "1" "June 2022" "" "" .SH "NAME" \fBnpm-ping\fR \- Ping npm registry .SS Synopsis diff --git a/deps/npm/man/man1/npm-pkg.1 b/deps/npm/man/man1/npm-pkg.1 index 1307a6664b1e64..7ffaf09ccac98c 100644 --- a/deps/npm/man/man1/npm-pkg.1 +++ b/deps/npm/man/man1/npm-pkg.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PKG" "1" "May 2022" "" "" +.TH "NPM\-PKG" "1" "June 2022" "" "" .SH "NAME" \fBnpm-pkg\fR \- Manages your package\.json .SS Synopsis diff --git a/deps/npm/man/man1/npm-prefix.1 b/deps/npm/man/man1/npm-prefix.1 index e053f315ff3d08..b209abac6c74a1 100644 --- a/deps/npm/man/man1/npm-prefix.1 +++ b/deps/npm/man/man1/npm-prefix.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PREFIX" "1" "May 2022" "" "" +.TH "NPM\-PREFIX" "1" "June 2022" "" "" .SH "NAME" \fBnpm-prefix\fR \- Display prefix .SS Synopsis @@ -40,9 +40,6 @@ npm prefix \-g Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-profile.1 b/deps/npm/man/man1/npm-profile.1 index a7a1733b63d179..ffdfbb5af52aab 100644 --- a/deps/npm/man/man1/npm-profile.1 +++ b/deps/npm/man/man1/npm-profile.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PROFILE" "1" "May 2022" "" "" +.TH "NPM\-PROFILE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-profile\fR \- Change settings on your registry profile .SS Synopsis diff --git a/deps/npm/man/man1/npm-prune.1 b/deps/npm/man/man1/npm-prune.1 index a0d23793206b3b..1f91bd1f2352ae 100644 --- a/deps/npm/man/man1/npm-prune.1 +++ b/deps/npm/man/man1/npm-prune.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PRUNE" "1" "May 2022" "" "" +.TH "NPM\-PRUNE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-prune\fR \- Remove extraneous packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-publish.1 b/deps/npm/man/man1/npm-publish.1 index 241f7cffd2045f..dc914cf75cc4c2 100644 --- a/deps/npm/man/man1/npm-publish.1 +++ b/deps/npm/man/man1/npm-publish.1 @@ -1,4 +1,4 @@ -.TH "NPM\-PUBLISH" "1" "May 2022" "" "" +.TH "NPM\-PUBLISH" "1" "June 2022" "" "" .SH "NAME" \fBnpm-publish\fR \- Publish a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-rebuild.1 b/deps/npm/man/man1/npm-rebuild.1 index f3c51a34e49030..8d6d90b10f0871 100644 --- a/deps/npm/man/man1/npm-rebuild.1 +++ b/deps/npm/man/man1/npm-rebuild.1 @@ -1,4 +1,4 @@ -.TH "NPM\-REBUILD" "1" "May 2022" "" "" +.TH "NPM\-REBUILD" "1" "June 2022" "" "" .SH "NAME" \fBnpm-rebuild\fR \- Rebuild a package .SS Synopsis @@ -28,9 +28,6 @@ will be rebuilt\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-repo.1 b/deps/npm/man/man1/npm-repo.1 index 7b9993a2fd7b60..453434dbb85818 100644 --- a/deps/npm/man/man1/npm-repo.1 +++ b/deps/npm/man/man1/npm-repo.1 @@ -1,4 +1,4 @@ -.TH "NPM\-REPO" "1" "May 2022" "" "" +.TH "NPM\-REPO" "1" "June 2022" "" "" .SH "NAME" \fBnpm-repo\fR \- Open package repository page in the browser .SS Synopsis diff --git a/deps/npm/man/man1/npm-restart.1 b/deps/npm/man/man1/npm-restart.1 index 9866fa5792cd6d..2f99ee51ed4fc1 100644 --- a/deps/npm/man/man1/npm-restart.1 +++ b/deps/npm/man/man1/npm-restart.1 @@ -1,4 +1,4 @@ -.TH "NPM\-RESTART" "1" "May 2022" "" "" +.TH "NPM\-RESTART" "1" "June 2022" "" "" .SH "NAME" \fBnpm-restart\fR \- Restart a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-root.1 b/deps/npm/man/man1/npm-root.1 index a9143ebe882e2d..3cda79f406879d 100644 --- a/deps/npm/man/man1/npm-root.1 +++ b/deps/npm/man/man1/npm-root.1 @@ -1,4 +1,4 @@ -.TH "NPM\-ROOT" "1" "May 2022" "" "" +.TH "NPM\-ROOT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-root\fR \- Display npm root .SS Synopsis @@ -29,9 +29,6 @@ echo "Global packages installed in: ${global_node_modules}" Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-run-script.1 b/deps/npm/man/man1/npm-run-script.1 index b9e2afb2696852..fc26c71e0310f9 100644 --- a/deps/npm/man/man1/npm-run-script.1 +++ b/deps/npm/man/man1/npm-run-script.1 @@ -1,4 +1,4 @@ -.TH "NPM\-RUN\-SCRIPT" "1" "May 2022" "" "" +.TH "NPM\-RUN\-SCRIPT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-run-script\fR \- Run arbitrary package scripts .SS Synopsis diff --git a/deps/npm/man/man1/npm-search.1 b/deps/npm/man/man1/npm-search.1 index 51fa43b80e73c8..19bebf6c25d2d4 100644 --- a/deps/npm/man/man1/npm-search.1 +++ b/deps/npm/man/man1/npm-search.1 @@ -1,4 +1,4 @@ -.TH "NPM\-SEARCH" "1" "May 2022" "" "" +.TH "NPM\-SEARCH" "1" "June 2022" "" "" .SH "NAME" \fBnpm-search\fR \- Search for packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-set-script.1 b/deps/npm/man/man1/npm-set-script.1 index 85106d95fbc443..d6c6c36f2141bf 100644 --- a/deps/npm/man/man1/npm-set-script.1 +++ b/deps/npm/man/man1/npm-set-script.1 @@ -1,4 +1,4 @@ -.TH "NPM\-SET\-SCRIPT" "1" "May 2022" "" "" +.TH "NPM\-SET\-SCRIPT" "1" "June 2022" "" "" .SH "NAME" \fBnpm-set-script\fR \- Set tasks in the scripts section of package\.json .SS Synopsis diff --git a/deps/npm/man/man1/npm-shrinkwrap.1 b/deps/npm/man/man1/npm-shrinkwrap.1 index fa87fb7e72b2d4..bcfcae2fcc878c 100644 --- a/deps/npm/man/man1/npm-shrinkwrap.1 +++ b/deps/npm/man/man1/npm-shrinkwrap.1 @@ -1,4 +1,4 @@ -.TH "NPM\-SHRINKWRAP" "1" "May 2022" "" "" +.TH "NPM\-SHRINKWRAP" "1" "June 2022" "" "" .SH "NAME" \fBnpm-shrinkwrap\fR \- Lock down dependency versions for publication .SS Synopsis diff --git a/deps/npm/man/man1/npm-star.1 b/deps/npm/man/man1/npm-star.1 index 57f9c5d361f8ec..2ccd4046e42d7e 100644 --- a/deps/npm/man/man1/npm-star.1 +++ b/deps/npm/man/man1/npm-star.1 @@ -1,4 +1,4 @@ -.TH "NPM\-STAR" "1" "May 2022" "" "" +.TH "NPM\-STAR" "1" "June 2022" "" "" .SH "NAME" \fBnpm-star\fR \- Mark your favorite packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-stars.1 b/deps/npm/man/man1/npm-stars.1 index aa290760aad377..91fcb6560b064c 100644 --- a/deps/npm/man/man1/npm-stars.1 +++ b/deps/npm/man/man1/npm-stars.1 @@ -1,4 +1,4 @@ -.TH "NPM\-STARS" "1" "May 2022" "" "" +.TH "NPM\-STARS" "1" "June 2022" "" "" .SH "NAME" \fBnpm-stars\fR \- View packages marked as favorites .SS Synopsis diff --git a/deps/npm/man/man1/npm-start.1 b/deps/npm/man/man1/npm-start.1 index f45e4a2a24c3e7..589ecea4a240a7 100644 --- a/deps/npm/man/man1/npm-start.1 +++ b/deps/npm/man/man1/npm-start.1 @@ -1,4 +1,4 @@ -.TH "NPM\-START" "1" "May 2022" "" "" +.TH "NPM\-START" "1" "June 2022" "" "" .SH "NAME" \fBnpm-start\fR \- Start a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-stop.1 b/deps/npm/man/man1/npm-stop.1 index a7bb25b3a44dd1..19695cc0e04174 100644 --- a/deps/npm/man/man1/npm-stop.1 +++ b/deps/npm/man/man1/npm-stop.1 @@ -1,4 +1,4 @@ -.TH "NPM\-STOP" "1" "May 2022" "" "" +.TH "NPM\-STOP" "1" "June 2022" "" "" .SH "NAME" \fBnpm-stop\fR \- Stop a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-team.1 b/deps/npm/man/man1/npm-team.1 index 05f508427a4a08..b56e3fc7862911 100644 --- a/deps/npm/man/man1/npm-team.1 +++ b/deps/npm/man/man1/npm-team.1 @@ -1,4 +1,4 @@ -.TH "NPM\-TEAM" "1" "May 2022" "" "" +.TH "NPM\-TEAM" "1" "June 2022" "" "" .SH "NAME" \fBnpm-team\fR \- Manage organization teams and team memberships .SS Synopsis diff --git a/deps/npm/man/man1/npm-test.1 b/deps/npm/man/man1/npm-test.1 index 590d9519df51f6..fbbe80d2638e40 100644 --- a/deps/npm/man/man1/npm-test.1 +++ b/deps/npm/man/man1/npm-test.1 @@ -1,4 +1,4 @@ -.TH "NPM\-TEST" "1" "May 2022" "" "" +.TH "NPM\-TEST" "1" "June 2022" "" "" .SH "NAME" \fBnpm-test\fR \- Test a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-token.1 b/deps/npm/man/man1/npm-token.1 index f2e32ea27fdbec..0292cf80135184 100644 --- a/deps/npm/man/man1/npm-token.1 +++ b/deps/npm/man/man1/npm-token.1 @@ -1,4 +1,4 @@ -.TH "NPM\-TOKEN" "1" "May 2022" "" "" +.TH "NPM\-TOKEN" "1" "June 2022" "" "" .SH "NAME" \fBnpm-token\fR \- Manage your authentication tokens .SS Synopsis diff --git a/deps/npm/man/man1/npm-uninstall.1 b/deps/npm/man/man1/npm-uninstall.1 index d918034ba19490..7ffd372951c792 100644 --- a/deps/npm/man/man1/npm-uninstall.1 +++ b/deps/npm/man/man1/npm-uninstall.1 @@ -1,4 +1,4 @@ -.TH "NPM\-UNINSTALL" "1" "May 2022" "" "" +.TH "NPM\-UNINSTALL" "1" "June 2022" "" "" .SH "NAME" \fBnpm-uninstall\fR \- Remove a package .SS Synopsis diff --git a/deps/npm/man/man1/npm-unpublish.1 b/deps/npm/man/man1/npm-unpublish.1 index 20198422799984..ff538299e7c355 100644 --- a/deps/npm/man/man1/npm-unpublish.1 +++ b/deps/npm/man/man1/npm-unpublish.1 @@ -1,4 +1,4 @@ -.TH "NPM\-UNPUBLISH" "1" "May 2022" "" "" +.TH "NPM\-UNPUBLISH" "1" "June 2022" "" "" .SH "NAME" \fBnpm-unpublish\fR \- Remove a package from the registry .SS Synopsis diff --git a/deps/npm/man/man1/npm-unstar.1 b/deps/npm/man/man1/npm-unstar.1 index 1fa7b88c64a5d4..d71bfff266b312 100644 --- a/deps/npm/man/man1/npm-unstar.1 +++ b/deps/npm/man/man1/npm-unstar.1 @@ -1,4 +1,4 @@ -.TH "NPM\-UNSTAR" "1" "May 2022" "" "" +.TH "NPM\-UNSTAR" "1" "June 2022" "" "" .SH "NAME" \fBnpm-unstar\fR \- Remove an item from your favorite packages .SS Synopsis diff --git a/deps/npm/man/man1/npm-update.1 b/deps/npm/man/man1/npm-update.1 index aebe0c88953b90..df54155942bbf6 100644 --- a/deps/npm/man/man1/npm-update.1 +++ b/deps/npm/man/man1/npm-update.1 @@ -1,4 +1,4 @@ -.TH "NPM\-UPDATE" "1" "May 2022" "" "" +.TH "NPM\-UPDATE" "1" "June 2022" "" "" .SH "NAME" \fBnpm-update\fR \- Update packages .SS Synopsis @@ -180,9 +180,6 @@ Will also prevent writing to \fBpackage\-lock\.json\fP if set to \fBfalse\fP\|\. Default: false .IP \(bu 2 Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. .RE .P diff --git a/deps/npm/man/man1/npm-version.1 b/deps/npm/man/man1/npm-version.1 index 444c0709759de0..49717643237826 100644 --- a/deps/npm/man/man1/npm-version.1 +++ b/deps/npm/man/man1/npm-version.1 @@ -1,4 +1,4 @@ -.TH "NPM\-VERSION" "1" "May 2022" "" "" +.TH "NPM\-VERSION" "1" "June 2022" "" "" .SH "NAME" \fBnpm-version\fR \- Bump a package version .SS Synopsis diff --git a/deps/npm/man/man1/npm-view.1 b/deps/npm/man/man1/npm-view.1 index b77c7705667115..efba9ebd6bd696 100644 --- a/deps/npm/man/man1/npm-view.1 +++ b/deps/npm/man/man1/npm-view.1 @@ -1,4 +1,4 @@ -.TH "NPM\-VIEW" "1" "May 2022" "" "" +.TH "NPM\-VIEW" "1" "June 2022" "" "" .SH "NAME" \fBnpm-view\fR \- View registry info .SS Synopsis diff --git a/deps/npm/man/man1/npm-whoami.1 b/deps/npm/man/man1/npm-whoami.1 index d79c448a7a1141..726153e012e6d6 100644 --- a/deps/npm/man/man1/npm-whoami.1 +++ b/deps/npm/man/man1/npm-whoami.1 @@ -1,4 +1,4 @@ -.TH "NPM\-WHOAMI" "1" "May 2022" "" "" +.TH "NPM\-WHOAMI" "1" "June 2022" "" "" .SH "NAME" \fBnpm-whoami\fR \- Display npm username .SS Synopsis diff --git a/deps/npm/man/man1/npm.1 b/deps/npm/man/man1/npm.1 index 6ac72ad35cba3d..45db3c9e53776e 100644 --- a/deps/npm/man/man1/npm.1 +++ b/deps/npm/man/man1/npm.1 @@ -1,10 +1,10 @@ -.TH "NPM" "1" "May 2022" "" "" +.TH "NPM" "1" "June 2022" "" "" .SH "NAME" \fBnpm\fR \- javascript package manager .SS Synopsis .SS Version .P -8\.11\.0 +8\.12\.1 .SS Description .P npm is the package manager for the Node JavaScript platform\. It puts diff --git a/deps/npm/man/man1/npx.1 b/deps/npm/man/man1/npx.1 index 51634bc8e8f9f3..1f8c292bc545d8 100644 --- a/deps/npm/man/man1/npx.1 +++ b/deps/npm/man/man1/npx.1 @@ -1,4 +1,4 @@ -.TH "NPX" "1" "May 2022" "" "" +.TH "NPX" "1" "June 2022" "" "" .SH "NAME" \fBnpx\fR \- Run a command from a local or remote npm package .SS Synopsis diff --git a/deps/npm/man/man5/folders.5 b/deps/npm/man/man5/folders.5 index 74403f97bfccae..925373df6d425e 100644 --- a/deps/npm/man/man5/folders.5 +++ b/deps/npm/man/man5/folders.5 @@ -1,4 +1,4 @@ -.TH "FOLDERS" "5" "May 2022" "" "" +.TH "FOLDERS" "5" "June 2022" "" "" .SH "NAME" \fBfolders\fR \- Folder Structures Used by npm .SS Description diff --git a/deps/npm/man/man5/install.5 b/deps/npm/man/man5/install.5 index 40d8a825c9ef54..e587d17aafef20 100644 --- a/deps/npm/man/man5/install.5 +++ b/deps/npm/man/man5/install.5 @@ -1,4 +1,4 @@ -.TH "INSTALL" "5" "May 2022" "" "" +.TH "INSTALL" "5" "June 2022" "" "" .SH "NAME" \fBinstall\fR \- Download and install node and npm .SS Description diff --git a/deps/npm/man/man5/npm-shrinkwrap-json.5 b/deps/npm/man/man5/npm-shrinkwrap-json.5 index 2928a9bae6cfdb..783976fb6c52b0 100644 --- a/deps/npm/man/man5/npm-shrinkwrap-json.5 +++ b/deps/npm/man/man5/npm-shrinkwrap-json.5 @@ -1,4 +1,4 @@ -.TH "NPM\-SHRINKWRAP\.JSON" "5" "May 2022" "" "" +.TH "NPM\-SHRINKWRAP\.JSON" "5" "June 2022" "" "" .SH "NAME" \fBnpm-shrinkwrap.json\fR \- A publishable lockfile .SS Description diff --git a/deps/npm/man/man5/npmrc.5 b/deps/npm/man/man5/npmrc.5 index 429bcc3875dd50..cce0b9201c7d8e 100644 --- a/deps/npm/man/man5/npmrc.5 +++ b/deps/npm/man/man5/npmrc.5 @@ -1,4 +1,4 @@ -.TH "NPMRC" "5" "May 2022" "" "" +.TH "NPMRC" "5" "June 2022" "" "" .SH "NAME" \fBnpmrc\fR \- The npm config files .SS Description diff --git a/deps/npm/man/man5/package-json.5 b/deps/npm/man/man5/package-json.5 index 47156509747685..17c4c1e322c6b1 100644 --- a/deps/npm/man/man5/package-json.5 +++ b/deps/npm/man/man5/package-json.5 @@ -1,4 +1,4 @@ -.TH "PACKAGE\.JSON" "5" "May 2022" "" "" +.TH "PACKAGE\.JSON" "5" "June 2022" "" "" .SH "NAME" \fBpackage.json\fR \- Specifics of npm's package\.json handling .SS Description @@ -721,6 +721,34 @@ git+https://isaacs@github\.com/npm/cli\.git git://github\.com/npm/cli\.git#v1\.0\.27 .fi .RE +.P +When installing from a \fBgit\fP repository, the presence of certain fields in the +\fBpackage\.json\fP will cause npm to believe it needs to perform a build\. To do so +your repository will be cloned into a temporary directory, all of its deps +installed, relevant scripts run, and the resulting directory packed and +installed\. +.P +This flow will occur if your git dependency uses \fBworkspaces\fP, or if any of the +following scripts are present: +.RS 0 +.IP \(bu 2 +\fBbuild\fP +.IP \(bu 2 +\fBprepare\fP +.IP \(bu 2 +\fBprepack\fP +.IP \(bu 2 +\fBpreinstall\fP +.IP \(bu 2 +\fBinstall\fP +.IP \(bu 2 +\fBpostinstall\fP + +.RE +.P +If your git repository includes pre\-built artifacts, you will likely want to +make sure that none of the above scripts are defined, or your dependency +will be rebuilt for every installation\. .SS GitHub URLs .P As of version 1\.1\.65, you can refer to GitHub urls as just "foo": diff --git a/deps/npm/man/man5/package-lock-json.5 b/deps/npm/man/man5/package-lock-json.5 index 569d9c5ae679d9..9e17a85f750876 100644 --- a/deps/npm/man/man5/package-lock-json.5 +++ b/deps/npm/man/man5/package-lock-json.5 @@ -1,4 +1,4 @@ -.TH "PACKAGE\-LOCK\.JSON" "5" "May 2022" "" "" +.TH "PACKAGE\-LOCK\.JSON" "5" "June 2022" "" "" .SH "NAME" \fBpackage-lock.json\fR \- A manifestation of the manifest .SS Description diff --git a/deps/npm/man/man7/config.7 b/deps/npm/man/man7/config.7 index e3dc9a995216a5..70f6742b10ada1 100644 --- a/deps/npm/man/man7/config.7 +++ b/deps/npm/man/man7/config.7 @@ -1,4 +1,4 @@ -.TH "CONFIG" "7" "May 2022" "" "" +.TH "CONFIG" "7" "June 2022" "" "" .SH "NAME" \fBconfig\fR \- More than you probably want to know about npm configuration .SS Description @@ -739,6 +739,28 @@ Type: Boolean .P Tag the commit when using the \fBnpm version\fP command\. Setting this to false results in no commit being made at all\. +.SS \fBglobal\fP +.RS 0 +.IP \(bu 2 +Default: false +.IP \(bu 2 +Type: Boolean + +.RE +.P +Operates in "global" mode, so that packages are installed into the \fBprefix\fP +folder instead of the current working directory\. See +npm help folders for more on the differences in behavior\. +.RS 0 +.IP \(bu 2 +packages are installed into the \fB{prefix}/lib/node_modules\fP folder, instead +of the current working directory\. +.IP \(bu 2 +bin files are linked to \fB{prefix}/bin\fP +.IP \(bu 2 +man pages are linked to \fB{prefix}/share/man\fP + +.RE .SS \fBglobal\-style\fP .RS 0 .IP \(bu 2 @@ -1975,14 +1997,16 @@ When set to \fBdev\fP or \fBdevelopment\fP, this is an alias for \fB\-\-include= .IP \(bu 2 Default: "legacy" .IP \(bu 2 -Type: "legacy", "sso", "saml", or "oauth" +Type: "legacy", "webauthn", "sso", "saml", or "oauth" .IP \(bu 2 -DEPRECATED: This method of SSO/SAML/OAuth is deprecated and will be removed -in a future version of npm in favor of web\-based login\. +DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in +a future version of npm in favor of web\-based login\. .RE .P What authentication strategy to use with \fBadduser\fP/\fBlogin\fP\|\. +.P +Pass \fBwebauthn\fP to use a web\-based login\. .SS \fBcache\-max\fP .RS 0 .IP \(bu 2 @@ -2019,31 +2043,6 @@ DEPRECATED: Please use \-\-include=dev instead\. .RE .P Alias for \fB\-\-include=dev\fP\|\. -.SS \fBglobal\fP -.RS 0 -.IP \(bu 2 -Default: false -.IP \(bu 2 -Type: Boolean -.IP \(bu 2 -DEPRECATED: \fB\-\-global\fP, \fB\-\-local\fP are deprecated\. Use \fB\-\-location=global\fP -instead\. - -.RE -.P -Operates in "global" mode, so that packages are installed into the \fBprefix\fP -folder instead of the current working directory\. See -npm help folders for more on the differences in behavior\. -.RS 0 -.IP \(bu 2 -packages are installed into the \fB{prefix}/lib/node_modules\fP folder, instead -of the current working directory\. -.IP \(bu 2 -bin files are linked to \fB{prefix}/bin\fP -.IP \(bu 2 -man pages are linked to \fB{prefix}/share/man\fP - -.RE .SS \fBinit\.author\.email\fP .RS 0 .IP \(bu 2 diff --git a/deps/npm/man/man7/developers.7 b/deps/npm/man/man7/developers.7 index 12e9b535fce56a..e5c163c68062e8 100644 --- a/deps/npm/man/man7/developers.7 +++ b/deps/npm/man/man7/developers.7 @@ -1,4 +1,4 @@ -.TH "DEVELOPERS" "7" "May 2022" "" "" +.TH "DEVELOPERS" "7" "June 2022" "" "" .SH "NAME" \fBdevelopers\fR \- Developer Guide .SS Description diff --git a/deps/npm/man/man7/logging.7 b/deps/npm/man/man7/logging.7 index ea0a7a8f1873b0..821edc2b03add2 100644 --- a/deps/npm/man/man7/logging.7 +++ b/deps/npm/man/man7/logging.7 @@ -1,4 +1,4 @@ -.TH "LOGGING" "7" "May 2022" "" "" +.TH "LOGGING" "7" "June 2022" "" "" .SH "NAME" \fBLogging\fR \- Why, What & How We Log .SS Description diff --git a/deps/npm/man/man7/orgs.7 b/deps/npm/man/man7/orgs.7 index 84c949949dc60c..c713fb501c7c3d 100644 --- a/deps/npm/man/man7/orgs.7 +++ b/deps/npm/man/man7/orgs.7 @@ -1,4 +1,4 @@ -.TH "ORGS" "7" "May 2022" "" "" +.TH "ORGS" "7" "June 2022" "" "" .SH "NAME" \fBorgs\fR \- Working with Teams & Orgs .SS Description diff --git a/deps/npm/man/man7/registry.7 b/deps/npm/man/man7/registry.7 index eff3f31ab64127..2452816cff3ae6 100644 --- a/deps/npm/man/man7/registry.7 +++ b/deps/npm/man/man7/registry.7 @@ -1,4 +1,4 @@ -.TH "REGISTRY" "7" "May 2022" "" "" +.TH "REGISTRY" "7" "June 2022" "" "" .SH "NAME" \fBregistry\fR \- The JavaScript Package Registry .SS Description diff --git a/deps/npm/man/man7/removal.7 b/deps/npm/man/man7/removal.7 index 27bb1de4c99af1..5896b1f07a4c01 100644 --- a/deps/npm/man/man7/removal.7 +++ b/deps/npm/man/man7/removal.7 @@ -1,4 +1,4 @@ -.TH "REMOVAL" "7" "May 2022" "" "" +.TH "REMOVAL" "7" "June 2022" "" "" .SH "NAME" \fBremoval\fR \- Cleaning the Slate .SS Synopsis diff --git a/deps/npm/man/man7/scope.7 b/deps/npm/man/man7/scope.7 index 5d4f0e7270a02b..e519a2b4323913 100644 --- a/deps/npm/man/man7/scope.7 +++ b/deps/npm/man/man7/scope.7 @@ -1,4 +1,4 @@ -.TH "SCOPE" "7" "May 2022" "" "" +.TH "SCOPE" "7" "June 2022" "" "" .SH "NAME" \fBscope\fR \- Scoped packages .SS Description diff --git a/deps/npm/man/man7/scripts.7 b/deps/npm/man/man7/scripts.7 index 2ced12c63d9006..945cb86e9052e8 100644 --- a/deps/npm/man/man7/scripts.7 +++ b/deps/npm/man/man7/scripts.7 @@ -1,4 +1,4 @@ -.TH "SCRIPTS" "7" "May 2022" "" "" +.TH "SCRIPTS" "7" "June 2022" "" "" .SH "NAME" \fBscripts\fR \- How npm handles the "scripts" field .SS Description @@ -289,6 +289,16 @@ will default the \fBstart\fP command to \fBnode server\.js\fP\|\. \fBprestart\f .IP \(bu 2 \fBposttest\fP +.RE +.SS npm help \fBversion\fP +.RS 0 +.IP \(bu 2 +\fBpreversion\fP +.IP \(bu 2 +\fBversion\fP +.IP \(bu 2 +\fBpostversion\fP + .RE .SS A Note on a lack of npm help \fBuninstall\fP scripts .P diff --git a/deps/npm/man/man7/workspaces.7 b/deps/npm/man/man7/workspaces.7 index 494b4068621421..16460caa951cb6 100644 --- a/deps/npm/man/man7/workspaces.7 +++ b/deps/npm/man/man7/workspaces.7 @@ -1,4 +1,4 @@ -.TH "WORKSPACES" "7" "May 2022" "" "" +.TH "WORKSPACES" "7" "June 2022" "" "" .SH "NAME" \fBworkspaces\fR \- Working with workspaces .SS Description diff --git a/deps/npm/node_modules/@npmcli/arborist/README.md b/deps/npm/node_modules/@npmcli/arborist/README.md index e4a58239a0e085..81d79cbf3021b9 100644 --- a/deps/npm/node_modules/@npmcli/arborist/README.md +++ b/deps/npm/node_modules/@npmcli/arborist/README.md @@ -9,7 +9,7 @@ Inspect and manage `node_modules` trees. ![a tree with the word ARBORIST superimposed on it](https://raw.githubusercontent.com/npm/arborist/main/docs/logo.svg?sanitize=true) There's more documentation [in the docs -folder](https://github.com/npm/arborist/tree/main/docs). +folder](https://github.com/npm/cli/tree/latest/workspaces/arborist/docs). ## USAGE diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/edge.js b/deps/npm/node_modules/@npmcli/arborist/lib/edge.js index d72f312569466c..a04404f2265633 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/edge.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/edge.js @@ -92,7 +92,12 @@ class Edge { return false } - return depValid(node, this.spec, this.accept, this.from) + // NOTE: this condition means we explicitly do not support overriding + // bundled or shrinkwrapped dependencies + const spec = (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) + ? this.rawSpec + : this.spec + return depValid(node, spec, this.accept, this.from) } explain (seen = []) { diff --git a/deps/npm/node_modules/@npmcli/arborist/package.json b/deps/npm/node_modules/@npmcli/arborist/package.json index e6d2d9613c206f..baae74e25ac7b8 100644 --- a/deps/npm/node_modules/@npmcli/arborist/package.json +++ b/deps/npm/node_modules/@npmcli/arborist/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/arborist", - "version": "5.2.0", + "version": "5.2.1", "description": "Manage node_modules trees", "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", diff --git a/deps/npm/node_modules/glob/common.js b/deps/npm/node_modules/glob/common.js index fc193ee6fbda5d..e094f750472f78 100644 --- a/deps/npm/node_modules/glob/common.js +++ b/deps/npm/node_modules/glob/common.js @@ -13,7 +13,7 @@ function ownProp (obj, field) { var fs = require("fs") var path = require("path") var minimatch = require("minimatch") -var isAbsolute = require("path-is-absolute") +var isAbsolute = require("path").isAbsolute var Minimatch = minimatch.Minimatch function alphasort (a, b) { @@ -88,7 +88,7 @@ function setopts (self, pattern, options) { self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) - self.cwd = cwd + self.cwd = path.resolve(cwd) else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd @@ -96,16 +96,18 @@ function setopts (self, pattern, options) { self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount + if (process.platform === "win32") { + self.root = self.root.replace(/\\/g, "/") + self.cwd = self.cwd.replace(/\\/g, "/") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + } + // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true diff --git a/deps/npm/node_modules/glob/glob.js b/deps/npm/node_modules/glob/glob.js index 37a4d7e60775a3..2112a957dc5016 100644 --- a/deps/npm/node_modules/glob/glob.js +++ b/deps/npm/node_modules/glob/glob.js @@ -47,7 +47,7 @@ var inherits = require('inherits') var EE = require('events').EventEmitter var path = require('path') var assert = require('assert') -var isAbsolute = require('path-is-absolute') +var isAbsolute = require('path').isAbsolute var globSync = require('./sync.js') var common = require('./common.js') var setopts = common.setopts diff --git a/deps/npm/node_modules/glob/package.json b/deps/npm/node_modules/glob/package.json index 54940cbeb42080..5134253e32226f 100644 --- a/deps/npm/node_modules/glob/package.json +++ b/deps/npm/node_modules/glob/package.json @@ -2,7 +2,7 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "glob", "description": "a little globber", - "version": "8.0.1", + "version": "8.0.3", "repository": { "type": "git", "url": "git://github.com/isaacs/node-glob.git" @@ -21,8 +21,7 @@ "inflight": "^1.0.4", "inherits": "2", "minimatch": "^5.0.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "once": "^1.3.0" }, "devDependencies": { "memfs": "^3.2.0", diff --git a/deps/npm/node_modules/glob/sync.js b/deps/npm/node_modules/glob/sync.js index c705a9c0291dd9..af4600dd595081 100644 --- a/deps/npm/node_modules/glob/sync.js +++ b/deps/npm/node_modules/glob/sync.js @@ -8,7 +8,7 @@ var Glob = require('./glob.js').Glob var util = require('util') var path = require('path') var assert = require('assert') -var isAbsolute = require('path-is-absolute') +var isAbsolute = require('path').isAbsolute var common = require('./common.js') var setopts = common.setopts var ownProp = common.ownProp @@ -48,7 +48,7 @@ function GlobSync (pattern, options) { } GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { @@ -72,7 +72,7 @@ GlobSync.prototype._finish = function () { GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 diff --git a/deps/npm/node_modules/libnpmexec/lib/index.js b/deps/npm/node_modules/libnpmexec/lib/index.js index fbe5c5520c381e..dfe7560120702d 100644 --- a/deps/npm/node_modules/libnpmexec/lib/index.js +++ b/deps/npm/node_modules/libnpmexec/lib/index.js @@ -166,7 +166,7 @@ const exec = async (opts) => { const add = manis .filter(mani => !mani[_localManifest]) .filter(filterMissingPackagesFromInstallDir) - .map(mani => mani._from) + .map(mani => mani._id || mani._from) .sort((a, b) => a.localeCompare(b, 'en')) // no need to install if already present diff --git a/deps/npm/node_modules/libnpmexec/package.json b/deps/npm/node_modules/libnpmexec/package.json index 9fe45c7ef6d049..dfe40b0d9f7ad0 100644 --- a/deps/npm/node_modules/libnpmexec/package.json +++ b/deps/npm/node_modules/libnpmexec/package.json @@ -1,6 +1,6 @@ { "name": "libnpmexec", - "version": "4.0.5", + "version": "4.0.6", "files": [ "bin/", "lib/" diff --git a/deps/npm/node_modules/make-fetch-happen/lib/remote.js b/deps/npm/node_modules/make-fetch-happen/lib/remote.js index 763fc0d48802b1..068c73a8a7a7e3 100644 --- a/deps/npm/node_modules/make-fetch-happen/lib/remote.js +++ b/deps/npm/node_modules/make-fetch-happen/lib/remote.js @@ -52,7 +52,11 @@ const remoteFetch = (request, options) => { if (_opts.integrity && res.status === 200) { // we got a 200 response and the user has specified an expected // integrity value, so wrap the response in an ssri stream to verify it - const integrityStream = ssri.integrityStream({ integrity: _opts.integrity }) + const integrityStream = ssri.integrityStream({ + algorithms: _opts.algorithms, + integrity: _opts.integrity, + size: _opts.size, + }) const pipeline = new CachingMinipassPipeline({ events: ['integrity', 'size'], }, res.body, integrityStream) diff --git a/deps/npm/node_modules/make-fetch-happen/package.json b/deps/npm/node_modules/make-fetch-happen/package.json index 2e6153b99fa0d1..e3d42bb2110d1f 100644 --- a/deps/npm/node_modules/make-fetch-happen/package.json +++ b/deps/npm/node_modules/make-fetch-happen/package.json @@ -1,6 +1,6 @@ { "name": "make-fetch-happen", - "version": "10.1.5", + "version": "10.1.6", "description": "Opinionated, caching, retrying fetch client", "main": "lib/index.js", "files": [ @@ -69,7 +69,8 @@ "tap": { "color": 1, "files": "test/*.js", - "check-coverage": true + "check-coverage": true, + "timeout": 60 }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", diff --git a/deps/npm/node_modules/minimatch/minimatch.js b/deps/npm/node_modules/minimatch/minimatch.js index f3b491dd1073ed..71c96a1fb71cce 100644 --- a/deps/npm/node_modules/minimatch/minimatch.js +++ b/deps/npm/node_modules/minimatch/minimatch.js @@ -168,6 +168,11 @@ class Minimatch { this.options = options this.set = [] this.pattern = pattern + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/') + } this.regexp = null this.negate = false this.comment = false diff --git a/deps/npm/node_modules/minimatch/package.json b/deps/npm/node_modules/minimatch/package.json index 2cc856968c0b29..8e1a84285d38f3 100644 --- a/deps/npm/node_modules/minimatch/package.json +++ b/deps/npm/node_modules/minimatch/package.json @@ -2,7 +2,7 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me)", "name": "minimatch", "description": "a glob matcher in javascript", - "version": "5.0.1", + "version": "5.1.0", "repository": { "type": "git", "url": "git://github.com/isaacs/minimatch.git" diff --git a/deps/npm/node_modules/node-gyp/node_modules/glob/common.js b/deps/npm/node_modules/node-gyp/node_modules/glob/common.js index 8e363b6c1f16a1..424c46e1dab1be 100644 --- a/deps/npm/node_modules/node-gyp/node_modules/glob/common.js +++ b/deps/npm/node_modules/node-gyp/node_modules/glob/common.js @@ -110,6 +110,8 @@ function setopts (self, pattern, options) { // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options diff --git a/deps/npm/node_modules/node-gyp/node_modules/glob/glob.js b/deps/npm/node_modules/node-gyp/node_modules/glob/glob.js index afcf82752c390a..37a4d7e60775a3 100644 --- a/deps/npm/node_modules/node-gyp/node_modules/glob/glob.js +++ b/deps/npm/node_modules/node-gyp/node_modules/glob/glob.js @@ -342,7 +342,10 @@ Glob.prototype._process = function (pattern, index, inGlobStar, cb) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix diff --git a/deps/npm/node_modules/node-gyp/node_modules/glob/package.json b/deps/npm/node_modules/node-gyp/node_modules/glob/package.json index cc1a57a896e9eb..5940b649b7e65a 100644 --- a/deps/npm/node_modules/node-gyp/node_modules/glob/package.json +++ b/deps/npm/node_modules/node-gyp/node_modules/glob/package.json @@ -2,7 +2,10 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "glob", "description": "a little globber", - "version": "7.2.0", + "version": "7.2.3", + "publishConfig": { + "tag": "v7-legacy" + }, "repository": { "type": "git", "url": "git://github.com/isaacs/node-glob.git" @@ -20,7 +23,7 @@ "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, diff --git a/deps/npm/node_modules/node-gyp/node_modules/glob/sync.js b/deps/npm/node_modules/node-gyp/node_modules/glob/sync.js index 4f46f90559a0ca..2c4f480192d28d 100644 --- a/deps/npm/node_modules/node-gyp/node_modules/glob/sync.js +++ b/deps/npm/node_modules/node-gyp/node_modules/glob/sync.js @@ -48,7 +48,7 @@ function GlobSync (pattern, options) { } GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { @@ -72,7 +72,7 @@ GlobSync.prototype._finish = function () { GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 @@ -109,7 +109,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix diff --git a/deps/npm/node_modules/pacote/README.md b/deps/npm/node_modules/pacote/README.md index eac48f69fe39fc..4403ad113a0b5c 100644 --- a/deps/npm/node_modules/pacote/README.md +++ b/deps/npm/node_modules/pacote/README.md @@ -237,6 +237,7 @@ In addition to the common `package.json` fields, manifests include: artifact can be found. * `manifest._from` A normalized form of the spec passed in as an argument. * `manifest._integrity` The integrity value for the package artifact. +* `manifest._id` The canonical spec of this package version: name@version. * `manifest.dist` Registry manifests (those included in a packument) have a `dist` object. Only `tarball` is required, though at least one of `shasum` or `integrity` is almost always present. @@ -274,3 +275,8 @@ For Pacote's purposes, the following fields are relevant: `foo@latest` gets turned into `foo@1.2.3`. * `time` In the full packument, an object mapping version numbers to publication times, for the `opts.before` functionality. + +Pacote adds the following fields, regardless of the accept header: + +* `_cached` Whether the packument was fetched from the network or the local cache. +* `_contentLength` The size of the packument. diff --git a/deps/npm/node_modules/pacote/lib/fetcher.js b/deps/npm/node_modules/pacote/lib/fetcher.js index d88724c5d19731..5f93e703bca4b8 100644 --- a/deps/npm/node_modules/pacote/lib/fetcher.js +++ b/deps/npm/node_modules/pacote/lib/fetcher.js @@ -18,6 +18,7 @@ const removeTrailingSlashes = require('./util/trailing-slashes.js') const getContents = require('@npmcli/installed-package-contents') const readPackageJsonFast = require('read-package-json-fast') const readPackageJson = promisify(require('read-package-json')) +const Minipass = require('minipass') // we only change ownership on unix platforms, and only if uid is 0 const selfOwner = process.getuid && process.getuid() === 0 ? { @@ -105,15 +106,10 @@ class FetcherBase { this[_readPackageJson] = readPackageJsonFast } - // config values: npmjs (default), never, always - // we don't want to mutate the original value - if (opts.replaceRegistryHost !== 'never' - && opts.replaceRegistryHost !== 'always' - ) { - this.replaceRegistryHost = 'npmjs' - } else { - this.replaceRegistryHost = opts.replaceRegistryHost - } + // rrh is a registry hostname or 'never' or 'always' + // defaults to registry.npmjs.org + this.replaceRegistryHost = (!opts.replaceRegistryHost || opts.replaceRegistryHost === 'npmjs') ? + 'registry.npmjs.org' : opts.replaceRegistryHost this.defaultTag = opts.defaultTag || 'latest' this.registry = removeTrailingSlashes(opts.registry || 'https://registry.npmjs.org') @@ -224,18 +220,18 @@ class FetcherBase { } [_istream] (stream) { - // everyone will need one of these, either for verifying or calculating - // We always set it, because we have might only have a weak legacy hex - // sha1 in the packument, and this MAY upgrade it to a stronger algo. - // If we had an integrity, and it doesn't match, then this does not - // override that error; the istream will raise the error before it - // gets to the point of re-setting the integrity. - const istream = ssri.integrityStream(this.opts) - istream.on('integrity', i => this.integrity = i) - stream.on('error', er => istream.emit('error', er)) - - // if not caching this, just pipe through to the istream and return it + // if not caching this, just return it if (!this.opts.cache || !this[_cacheFetches]) { + // instead of creating a new integrity stream, we only piggyback on the + // provided stream's events + if (stream.hasIntegrityEmitter) { + stream.on('integrity', i => this.integrity = i) + return stream + } + + const istream = ssri.integrityStream(this.opts) + istream.on('integrity', i => this.integrity = i) + stream.on('error', err => istream.emit('error', err)) return stream.pipe(istream) } @@ -243,21 +239,23 @@ class FetcherBase { // but then pipe from the original tarball stream into the cache as well. // To do this without losing any data, and since the cacache put stream // is not a passthrough, we have to pipe from the original stream into - // the cache AFTER we pipe into the istream. Since the cache stream + // the cache AFTER we pipe into the middleStream. Since the cache stream // has an asynchronous flush to write its contents to disk, we need to - // defer the istream end until the cache stream ends. - stream.pipe(istream, { end: false }) + // defer the middleStream end until the cache stream ends. + const middleStream = new Minipass() + stream.on('error', err => middleStream.emit('error', err)) + stream.pipe(middleStream, { end: false }) const cstream = cacache.put.stream( this.opts.cache, `pacote:tarball:${this.from}`, this.opts ) + cstream.on('integrity', i => this.integrity = i) + cstream.on('error', err => stream.emit('error', err)) stream.pipe(cstream) - // defer istream end until after cstream - // cache write errors should not crash the fetch, this is best-effort. - cstream.promise().catch(() => {}).then(() => istream.end()) - return istream + cstream.promise().catch(() => {}).then(() => middleStream.end()) + return middleStream } pickIntegrityAlgorithm () { diff --git a/deps/npm/node_modules/pacote/lib/registry.js b/deps/npm/node_modules/pacote/lib/registry.js index 2eb37bceccebc6..c8eb6b02907022 100644 --- a/deps/npm/node_modules/pacote/lib/registry.js +++ b/deps/npm/node_modules/pacote/lib/registry.js @@ -122,11 +122,12 @@ class RegistryFetcher extends Fetcher { } const packument = await this.packument() - const mani = await pickManifest(packument, this.spec.fetchSpec, { + let mani = await pickManifest(packument, this.spec.fetchSpec, { ...this.opts, defaultTag: this.defaultTag, before: this.before, }) + mani = rpj.normalize(mani) /* XXX add ETARGET and E403 revalidation of cached packuments here */ // add _resolved and _integrity from dist object @@ -165,49 +166,53 @@ class RegistryFetcher extends Fetcher { mani._integrity = String(this.integrity) if (dist.signatures) { if (this.opts.verifySignatures) { - if (this.registryKeys) { - // validate and throw on error, then set _signatures - const message = `${mani._id}:${mani._integrity}` - for (const signature of dist.signatures) { - const publicKey = this.registryKeys.filter(key => (key.keyid === signature.keyid))[0] - if (!publicKey) { - throw Object.assign(new Error( - `${mani._id} has a signature with keyid: ${signature.keyid} ` + - 'but no corresponding public key can be found.' - ), { code: 'EMISSINGSIGNATUREKEY' }) - } - const validPublicKey = - !publicKey.expires || (Date.parse(publicKey.expires) > Date.now()) - if (!validPublicKey) { - throw Object.assign(new Error( - `${mani._id} has a signature with keyid: ${signature.keyid} ` + + // validate and throw on error, then set _signatures + const message = `${mani._id}:${mani._integrity}` + for (const signature of dist.signatures) { + const publicKey = this.registryKeys && + this.registryKeys.filter(key => (key.keyid === signature.keyid))[0] + if (!publicKey) { + throw Object.assign(new Error( + `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + + 'but no corresponding public key can be found' + ), { code: 'EMISSINGSIGNATUREKEY' }) + } + const validPublicKey = + !publicKey.expires || (Date.parse(publicKey.expires) > Date.now()) + if (!validPublicKey) { + throw Object.assign(new Error( + `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + `but the corresponding public key has expired ${publicKey.expires}` - ), { code: 'EEXPIREDSIGNATUREKEY' }) - } - const verifier = crypto.createVerify('SHA256') - verifier.write(message) - verifier.end() - const valid = verifier.verify( - publicKey.pemkey, - signature.sig, - 'base64' - ) - if (!valid) { - throw Object.assign(new Error( - 'Integrity checksum signature failed: ' + - `key ${publicKey.keyid} signature ${signature.sig}` - ), { code: 'EINTEGRITYSIGNATURE' }) - } + ), { code: 'EEXPIREDSIGNATUREKEY' }) + } + const verifier = crypto.createVerify('SHA256') + verifier.write(message) + verifier.end() + const valid = verifier.verify( + publicKey.pemkey, + signature.sig, + 'base64' + ) + if (!valid) { + throw Object.assign(new Error( + `${mani._id} has an invalid registry signature with ` + + `keyid: ${publicKey.keyid} and signature: ${signature.sig}` + ), { + code: 'EINTEGRITYSIGNATURE', + keyid: publicKey.keyid, + signature: signature.sig, + resolved: mani._resolved, + integrity: mani._integrity, + }) } - mani._signatures = dist.signatures } - // if no keys, don't set _signatures + mani._signatures = dist.signatures } else { mani._signatures = dist.signatures } } } - this.package = rpj.normalize(mani) + this.package = mani return this.package } diff --git a/deps/npm/node_modules/pacote/lib/remote.js b/deps/npm/node_modules/pacote/lib/remote.js index 14e687805d47a8..6759dbba3ed2f2 100644 --- a/deps/npm/node_modules/pacote/lib/remote.js +++ b/deps/npm/node_modules/pacote/lib/remote.js @@ -4,8 +4,6 @@ const _tarballFromResolved = Symbol.for('pacote.Fetcher._tarballFromResolved') const pacoteVersion = require('../package.json').version const fetch = require('npm-registry-fetch') const Minipass = require('minipass') -// The default registry URL is a string of great magic. -const magicHost = 'https://registry.npmjs.org' const _cacheFetches = Symbol.for('pacote.Fetcher._cacheFetches') const _headers = Symbol('_headers') @@ -14,11 +12,9 @@ class RemoteFetcher extends Fetcher { super(spec, opts) this.resolved = this.spec.fetchSpec const resolvedURL = new URL(this.resolved) - if ( - (this.replaceRegistryHost === 'npmjs' - && resolvedURL.origin === magicHost) - || this.replaceRegistryHost === 'always' - ) { + if (this.replaceRegistryHost !== 'never' + && (this.replaceRegistryHost === 'always' + || this.replaceRegistryHost === resolvedURL.host)) { this.resolved = new URL(resolvedURL.pathname, this.registry).href } @@ -35,6 +31,8 @@ class RemoteFetcher extends Fetcher { [_tarballFromResolved] () { const stream = new Minipass() + stream.hasIntegrityEmitter = true + const fetchOpts = { ...this.opts, headers: this[_headers](), @@ -42,16 +40,19 @@ class RemoteFetcher extends Fetcher { integrity: this.integrity, algorithms: [this.pickIntegrityAlgorithm()], } - fetch(this.resolved, fetchOpts).then(res => { - const hash = res.headers.get('x-local-cache-hash') - if (hash) { - this.integrity = decodeURIComponent(hash) - } + fetch(this.resolved, fetchOpts).then(res => { res.body.on('error', /* istanbul ignore next - exceedingly rare and hard to simulate */ er => stream.emit('error', er) - ).pipe(stream) + ) + + res.body.on('integrity', i => { + this.integrity = i + stream.emit('integrity', i) + }) + + res.body.pipe(stream) }).catch(er => stream.emit('error', er)) return stream diff --git a/deps/npm/node_modules/pacote/package.json b/deps/npm/node_modules/pacote/package.json index 5045e3f06a0788..af100fa8d6bfa2 100644 --- a/deps/npm/node_modules/pacote/package.json +++ b/deps/npm/node_modules/pacote/package.json @@ -1,6 +1,6 @@ { "name": "pacote", - "version": "13.5.0", + "version": "13.6.0", "description": "JavaScript package downloader", "author": "GitHub Inc.", "bin": { @@ -21,8 +21,7 @@ "template-oss-apply": "template-oss-apply --force" }, "tap": { - "timeout": 300, - "coverage-map": "map.js" + "timeout": 300 }, "devDependencies": { "@npmcli/eslint-config": "^3.0.1", diff --git a/deps/npm/node_modules/rimraf/node_modules/glob/common.js b/deps/npm/node_modules/rimraf/node_modules/glob/common.js index 8e363b6c1f16a1..424c46e1dab1be 100644 --- a/deps/npm/node_modules/rimraf/node_modules/glob/common.js +++ b/deps/npm/node_modules/rimraf/node_modules/glob/common.js @@ -110,6 +110,8 @@ function setopts (self, pattern, options) { // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options diff --git a/deps/npm/node_modules/rimraf/node_modules/glob/glob.js b/deps/npm/node_modules/rimraf/node_modules/glob/glob.js index afcf82752c390a..37a4d7e60775a3 100644 --- a/deps/npm/node_modules/rimraf/node_modules/glob/glob.js +++ b/deps/npm/node_modules/rimraf/node_modules/glob/glob.js @@ -342,7 +342,10 @@ Glob.prototype._process = function (pattern, index, inGlobStar, cb) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix diff --git a/deps/npm/node_modules/rimraf/node_modules/glob/package.json b/deps/npm/node_modules/rimraf/node_modules/glob/package.json index cc1a57a896e9eb..5940b649b7e65a 100644 --- a/deps/npm/node_modules/rimraf/node_modules/glob/package.json +++ b/deps/npm/node_modules/rimraf/node_modules/glob/package.json @@ -2,7 +2,10 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "glob", "description": "a little globber", - "version": "7.2.0", + "version": "7.2.3", + "publishConfig": { + "tag": "v7-legacy" + }, "repository": { "type": "git", "url": "git://github.com/isaacs/node-glob.git" @@ -20,7 +23,7 @@ "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", + "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, diff --git a/deps/npm/node_modules/rimraf/node_modules/glob/sync.js b/deps/npm/node_modules/rimraf/node_modules/glob/sync.js index 4f46f90559a0ca..2c4f480192d28d 100644 --- a/deps/npm/node_modules/rimraf/node_modules/glob/sync.js +++ b/deps/npm/node_modules/rimraf/node_modules/glob/sync.js @@ -48,7 +48,7 @@ function GlobSync (pattern, options) { } GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { @@ -72,7 +72,7 @@ GlobSync.prototype._finish = function () { GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 @@ -109,7 +109,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix diff --git a/deps/npm/package.json b/deps/npm/package.json index f616f038dbf921..fbfabe9365cd03 100644 --- a/deps/npm/package.json +++ b/deps/npm/package.json @@ -1,5 +1,5 @@ { - "version": "8.11.0", + "version": "8.12.1", "name": "npm", "description": "a package manager for JavaScript", "workspaces": [ @@ -90,7 +90,7 @@ "libnpmsearch": "^5.0.2", "libnpmteam": "^4.0.2", "libnpmversion": "^3.0.1", - "make-fetch-happen": "^10.1.5", + "make-fetch-happen": "^10.1.6", "minipass": "^3.1.6", "minipass-pipeline": "^1.2.4", "mkdirp": "^1.0.4", @@ -107,7 +107,7 @@ "npm-user-validate": "^1.0.1", "npmlog": "^6.0.2", "opener": "^1.5.2", - "pacote": "^13.4.1", + "pacote": "^13.6.0", "parse-conflict-json": "^2.0.2", "proc-log": "^2.0.1", "qrcode-terminal": "^0.12.0", diff --git a/deps/npm/tap-snapshots/test/lib/commands/init.js.test.cjs b/deps/npm/tap-snapshots/test/lib/commands/init.js.test.cjs index 9dd0b4b6be36b7..a544b864035417 100644 --- a/deps/npm/tap-snapshots/test/lib/commands/init.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/commands/init.js.test.cjs @@ -10,26 +10,53 @@ Array [] ` exports[`test/lib/commands/init.js TAP workspaces no args > should print helper info 1`] = ` +Array [] +` + +exports[`test/lib/commands/init.js TAP workspaces no args, existing folder > should print helper info 1`] = ` +Array [] +` + +exports[`test/lib/commands/init.js TAP workspaces post workspace-init reify > should print helper info 1`] = ` Array [ Array [ String( - This utility will walk you through creating a package.json file. - It only covers the most common items, and tries to guess sensible defaults. - - See \`npm help init\` for definitive documentation on these fields - and exactly what they do. - - Use \`npm install \` afterwards to install a package and - save it as a dependency in the package.json file. - Press ^C at any time to quit. + added 1 package in 100ms ), ], ] ` -exports[`test/lib/commands/init.js TAP workspaces no args, existing folder > should print helper info 1`] = ` -Array [] +exports[`test/lib/commands/init.js TAP workspaces post workspace-init reify > should reify tree on init ws complete 1`] = ` +{ + "name": "top-level", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "top-level", + "workspaces": [ + "a" + ] + }, + "a": { + "version": "1.0.0", + "license": "ISC", + "devDependencies": {} + }, + "node_modules/a": { + "resolved": "a", + "link": true + } + }, + "dependencies": { + "a": { + "version": "file:a" + } + } +} + ` exports[`test/lib/commands/init.js TAP workspaces with arg but missing workspace folder > should print helper info 1`] = ` diff --git a/deps/npm/tap-snapshots/test/lib/load-all-commands.js.test.cjs b/deps/npm/tap-snapshots/test/lib/load-all-commands.js.test.cjs index b8c274b085a7a5..802fa8de935166 100644 --- a/deps/npm/tap-snapshots/test/lib/load-all-commands.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/load-all-commands.js.test.cjs @@ -33,6 +33,7 @@ npm adduser Options: [--registry ] [--scope <@scope>] +[--auth-type ] aliases: login, add-user @@ -396,7 +397,7 @@ npm init [<@scope>/] (same as \`npx [<@scope>/]create-\`) Options: [-y|--yes] [-f|--force] [-w|--workspace [-w|--workspace ...]] -[-ws|--workspaces] [--include-workspace-root] +[-ws|--workspaces] [--no-workspaces-update] [--include-workspace-root] aliases: create, innit @@ -523,6 +524,7 @@ npm adduser Options: [--registry ] [--scope <@scope>] +[--auth-type ] aliases: login, add-user diff --git a/deps/npm/tap-snapshots/test/lib/npm.js.test.cjs b/deps/npm/tap-snapshots/test/lib/npm.js.test.cjs index c7c75ce84b6685..d08935a14d1772 100644 --- a/deps/npm/tap-snapshots/test/lib/npm.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/npm.js.test.cjs @@ -190,6 +190,7 @@ All commands: Options: [--registry ] [--scope <@scope>] + [--auth-type ] aliases: login, add-user @@ -486,7 +487,7 @@ All commands: Options: [-y|--yes] [-f|--force] [-w|--workspace [-w|--workspace ...]] - [-ws|--workspaces] [--include-workspace-root] + [-ws|--workspaces] [--no-workspaces-update] [--include-workspace-root] aliases: create, innit @@ -601,6 +602,7 @@ All commands: Options: [--registry ] [--scope <@scope>] + [--auth-type ] aliases: login, add-user diff --git a/deps/npm/tap-snapshots/test/lib/utils/config/definitions.js.test.cjs b/deps/npm/tap-snapshots/test/lib/utils/config/definitions.js.test.cjs index b12dccdb76c317..33d6e4fb7a00f7 100644 --- a/deps/npm/tap-snapshots/test/lib/utils/config/definitions.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/utils/config/definitions.js.test.cjs @@ -253,11 +253,13 @@ exports[`test/lib/utils/config/definitions.js TAP > config description for auth- #### \`auth-type\` * Default: "legacy" -* Type: "legacy", "sso", "saml", or "oauth" -* DEPRECATED: This method of SSO/SAML/OAuth is deprecated and will be removed - in a future version of npm in favor of web-based login. +* Type: "legacy", "webauthn", "sso", "saml", or "oauth" +* DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in + a future version of npm in favor of web-based login. What authentication strategy to use with \`adduser\`/\`login\`. + +Pass \`webauthn\` to use a web-based login. ` exports[`test/lib/utils/config/definitions.js TAP > config description for before 1`] = ` @@ -731,8 +733,6 @@ exports[`test/lib/utils/config/definitions.js TAP > config description for globa * Default: false * Type: Boolean -* DEPRECATED: \`--global\`, \`--local\` are deprecated. Use \`--location=global\` - instead. Operates in "global" mode, so that packages are installed into the \`prefix\` folder instead of the current working directory. See diff --git a/deps/npm/tap-snapshots/test/lib/utils/config/describe-all.js.test.cjs b/deps/npm/tap-snapshots/test/lib/utils/config/describe-all.js.test.cjs index cacbe96a74f351..77f2c876841ede 100644 --- a/deps/npm/tap-snapshots/test/lib/utils/config/describe-all.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/utils/config/describe-all.js.test.cjs @@ -560,6 +560,23 @@ results in no commit being made at all. +#### \`global\` + +* Default: false +* Type: Boolean + +Operates in "global" mode, so that packages are installed into the \`prefix\` +folder instead of the current working directory. See +[folders](/configuring-npm/folders) for more on the differences in behavior. + +* packages are installed into the \`{prefix}/lib/node_modules\` folder, instead + of the current working directory. +* bin files are linked to \`{prefix}/bin\` +* man pages are linked to \`{prefix}/share/man\` + + + + #### \`global-style\` * Default: false @@ -1764,12 +1781,14 @@ When set to \`dev\` or \`development\`, this is an alias for \`--include=dev\`. #### \`auth-type\` * Default: "legacy" -* Type: "legacy", "sso", "saml", or "oauth" -* DEPRECATED: This method of SSO/SAML/OAuth is deprecated and will be removed - in a future version of npm in favor of web-based login. +* Type: "legacy", "webauthn", "sso", "saml", or "oauth" +* DEPRECATED: The SSO/SAML/OAuth methods are deprecated and will be removed in + a future version of npm in favor of web-based login. What authentication strategy to use with \`adduser\`/\`login\`. +Pass \`webauthn\` to use a web-based login. + @@ -1806,25 +1825,6 @@ Alias for \`--include=dev\`. -#### \`global\` - -* Default: false -* Type: Boolean -* DEPRECATED: \`--global\`, \`--local\` are deprecated. Use \`--location=global\` - instead. - -Operates in "global" mode, so that packages are installed into the \`prefix\` -folder instead of the current working directory. See -[folders](/configuring-npm/folders) for more on the differences in behavior. - -* packages are installed into the \`{prefix}/lib/node_modules\` folder, instead - of the current working directory. -* bin files are linked to \`{prefix}/bin\` -* man pages are linked to \`{prefix}/share/man\` - - - - #### \`init.author.email\` * Default: "" diff --git a/deps/npm/test/lib/commands/init.js b/deps/npm/test/lib/commands/init.js index 82e7e0524cee9b..32816adbc272ee 100644 --- a/deps/npm/test/lib/commands/init.js +++ b/deps/npm/test/lib/commands/init.js @@ -288,6 +288,7 @@ t.test('workspaces', t => { t.teardown(() => { npm._mockOutputs.length = 0 }) + npm._mockOutputs.length = 0 npm.localPrefix = t.testdir({ 'package.json': JSON.stringify({ name: 'top-level', @@ -306,6 +307,39 @@ t.test('workspaces', t => { t.matchSnapshot(npm._mockOutputs, 'should print helper info') }) + t.test('post workspace-init reify', async t => { + const _consolelog = console.log + console.log = () => null + t.teardown(() => { + console.log = _consolelog + npm._mockOutputs.length = 0 + delete npm.flatOptions.workspacesUpdate + }) + npm.started = Date.now() + npm._mockOutputs.length = 0 + npm.flatOptions.workspacesUpdate = true + npm.localPrefix = t.testdir({ + 'package.json': JSON.stringify({ + name: 'top-level', + }), + }) + + const Init = t.mock('../../../lib/commands/init.js', { + ...mocks, + 'init-package-json': (dir, initFile, config, cb) => { + t.equal(dir, resolve(npm.localPrefix, 'a'), 'should use the ws path') + return require('init-package-json')(dir, initFile, config, cb) + }, + }) + const init = new Init(npm) + await init.execWorkspaces([], ['a']) + const output = npm._mockOutputs.map(arr => arr.map(i => i.replace(/[0-9]*ms$/, '100ms'))) + t.matchSnapshot(output, 'should print helper info') + const lockFilePath = resolve(npm.localPrefix, 'package-lock.json') + const lockFile = fs.readFileSync(lockFilePath, { encoding: 'utf8' }) + t.matchSnapshot(lockFile, 'should reify tree on init ws complete') + }) + t.test('no args, existing folder', async t => { t.teardown(() => { npm._mockOutputs.length = 0 From 42c2115a821528752346e74fb3551323de4a6749 Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Mon, 13 Jun 2022 15:21:51 -0400 Subject: [PATCH 80/96] test: mark test_buffer/test_finalizer flaky MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: https://github.com/nodejs/node/issues/43389 Mark new test as flaky as it seems to have had intermittent failures since it was added. Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/43414 Reviewed-By: Richard Lau Reviewed-By: Tobias Nießen Reviewed-By: Darshan Sen Reviewed-By: Benjamin Gruenbaum Reviewed-By: Chengzhong Wu --- test/node-api/node-api.status | 1 + 1 file changed, 1 insertion(+) diff --git a/test/node-api/node-api.status b/test/node-api/node-api.status index 9395bfe1f6bbe0..be3a2761c414fc 100644 --- a/test/node-api/node-api.status +++ b/test/node-api/node-api.status @@ -5,5 +5,6 @@ prefix node-api # sample-test : PASS,FLAKY [true] # This section applies to all platforms +test_buffer/test_finalizer : PASS,FLAKY [$system==win32] From 36e5684ae023ac90456c4224c73ced40e30d1ace Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Wed, 1 Jun 2022 15:26:39 -0400 Subject: [PATCH 81/96] doc: clarify use of deps/icu-small Add some additional info about use of icu subset in deps/icu-small Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/43287 Reviewed-By: Steven R Loomis --- doc/contributing/maintaining-icu.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/doc/contributing/maintaining-icu.md b/doc/contributing/maintaining-icu.md index f33cde56763305..a8ce43d3a3b4aa 100644 --- a/doc/contributing/maintaining-icu.md +++ b/doc/contributing/maintaining-icu.md @@ -11,6 +11,12 @@ functionality. To quote from icu-project.org: > widely portable and gives applications the same results on all platforms > and between C/C++ and Java software. +If Node.js is configured to use its built-in ICU, +it uses a strict subset of ICU which is in +[deps/icu-small](https://github.com/nodejs/node/tree/HEAD/deps/icu-small). +A good description of the different ways Node.js can be built with ICU +support is in [api/intl.html](https://nodejs.org/api/intl.html). + ## Data dependencies ICU consumes and includes: @@ -51,7 +57,7 @@ files. #### Example: updating the ICU `.dat` file -* Decompress `deps/icu/source/data/in/icudt##l.dat.bz2`, where `##` is +* Decompress `deps/icu-small/source/data/in/icudt##l.dat.bz2`, where `##` is the ICU major version number. * Clone the icu/icu-data repository and copy the latest `tzdata` release `le` files into the `source/data/in` directory. From 066f963ec1424084f023c911c853ce404b04dcd1 Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Mon, 30 May 2022 15:27:55 -0400 Subject: [PATCH 82/96] doc: add initial doc on how to update cjs-module-lexer Add some initial doc based on discussion with Guy Bedford. Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/43255 Reviewed-By: Guy Bedford --- .../maintaining-cjs-module-lexer.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 doc/contributing/maintaining-cjs-module-lexer.md diff --git a/doc/contributing/maintaining-cjs-module-lexer.md b/doc/contributing/maintaining-cjs-module-lexer.md new file mode 100644 index 00000000000000..d049702ed65ab7 --- /dev/null +++ b/doc/contributing/maintaining-cjs-module-lexer.md @@ -0,0 +1,59 @@ +# Maintaining cjs-module-lexer + +The [cjs-module-lexer](https://github.com/nodejs/node/tree/HEAD/deps/cjs-module-lexer) +dependency is used within the Node.js ESM implementation to detect the +named exports of a CommonJS module. + +It is used within +[`node:internal/modules/esm/translators`](https://github.com/nodejs/node/blob/HEAD/lib/internal/modules/esm/translators.js) +in which both `internal/deps/cjs-module-lexer/lexer` and +`internal/deps/cjs-module-lexer/dist/lexer` are required and used. + +`internal/deps/cjs-module-lexer/lexer` +is a regular JavaScript implementation that is +used when WebAssembly is not available on a platform. +`internal/deps/cjs-module-lexer/dist/lexer` is a faster +implementation using WebAssembly which is generated from a +C based implementation. These two paths +resolve to the files in `deps/cjs-module-lexer` due to their +inclusion in the `deps_files` entry in +[node.gyp](https://github.com/nodejs/node/blob/master/node.gyp). + +The two different versions of lexer.js are maintained in the +[nodejs/cjs-module-lexer][] project. + +In order to update the Node.js dependencies to use to a newer verion +of cjs-module-lexer, complete the following steps: + +* Clone [nodejs/cjs-module-lexer][] + and check out the version that you want Node.js to use. +* Follow the WASM build steps outlined in + [wasm-build-steps](https://github.com/nodejs/cjs-module-lexer#wasm-build-steps). + This will generate the WASM based dist/lexer.js file. +* Preserving the same directory structure, copy the following files over + to `deps/cjs-module-lexer` directory where you have checked out Node.js. + +```text +├── CHANGELOG.md +├── dist +│   ├── lexer.js +│   └── lexer.mjs +├── lexer.js +├── LICENSE +├── package.json +└── README.md +``` + +* Update the link to the cjs-module-lexer in the list at the end of + [doc/api/esm.md](../api/esm.md) + to point to the updated version. + +* Create a PR, adding the files in the deps/cjs-module-lexer that + were modified. + +If updates are needed to cjs-module-lexer for Node.js, first PR +those updates into +[nodejs/cjs-module-lexer][], +request a release and then pull in the updated version once available. + +[nodejs/cjs-module-lexer]: https://github.com/nodejs/cjs-module-lexer From d2a98dc6cfcc4ee5193774064c62b2a1604e33c9 Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Mon, 30 May 2022 14:48:14 -0400 Subject: [PATCH 83/96] inspector: add missing initialization Add missing initialization reported by coverity. With proper usage it looks like it will be initialized but still good to have it initialized to a known state in case that changes or invalide usage. The method used to create object ids newObjectId() starts at 1 so initializing to 0 should be safe and what we get now when compiled in a way that auto initializes (for example debug) Signed-off-by: Michael Dawson PR-URL: https://github.com/nodejs/node/pull/43254 Reviewed-By: Darshan Sen Reviewed-By: Minwoo Jung Reviewed-By: Luigi Pinca --- src/inspector/tracing_agent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/inspector/tracing_agent.h b/src/inspector/tracing_agent.h index e23d2fadae9354..b8274de2be9bc6 100644 --- a/src/inspector/tracing_agent.h +++ b/src/inspector/tracing_agent.h @@ -31,7 +31,7 @@ class TracingAgent : public NodeTracing::Backend { Environment* env_; std::shared_ptr main_thread_; tracing::AgentWriterHandle trace_writer_; - int frontend_object_id_; + int frontend_object_id_ = 0; std::shared_ptr frontend_; }; From 517f17b214ee103d6f442d8d5473b49de7439901 Mon Sep 17 00:00:00 2001 From: "Node.js GitHub Bot" Date: Tue, 14 Jun 2022 17:35:43 +0200 Subject: [PATCH 84/96] deps: update undici to 5.5.1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/43412 Reviewed-By: Tobias Nießen Reviewed-By: Darshan Sen Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum Reviewed-By: LiviaMedeiros Reviewed-By: James M Snell --- deps/undici/src/README.md | 27 +++---- deps/undici/src/lib/api/api-connect.js | 22 +++++- deps/undici/src/lib/core/connect.js | 4 +- deps/undici/src/lib/core/request.js | 15 ++-- deps/undici/src/lib/fetch/body.js | 4 +- deps/undici/src/lib/fetch/formdata.js | 71 +++++++++++++---- deps/undici/src/lib/fetch/headers.js | 34 +------- deps/undici/src/lib/fetch/index.js | 2 +- deps/undici/src/lib/fetch/util.js | 30 ++++++- deps/undici/src/lib/proxy-agent.js | 78 +++++++++++++++++-- deps/undici/src/package.json | 2 +- deps/undici/src/types/connector.d.ts | 9 +-- deps/undici/src/types/fetch.d.ts | 20 ++--- deps/undici/src/types/formdata.d.ts | 26 ++++--- deps/undici/src/types/proxy-agent.d.ts | 4 + deps/undici/undici.js | 103 +++++++++++++++---------- 16 files changed, 297 insertions(+), 154 deletions(-) diff --git a/deps/undici/src/README.md b/deps/undici/src/README.md index c8dc260e12a613..c2639bb7633d89 100644 --- a/deps/undici/src/README.md +++ b/deps/undici/src/README.md @@ -185,13 +185,12 @@ Help us improve the test coverage by following instructions at [nodejs/undici/#9 Basic usage example: ```js - import {fetch} from 'undici'; +import { fetch } from 'undici'; - async function fetchJson() { - const res = await fetch('https://example.com') - const json = await res.json() - console.log(json); - } + +const res = await fetch('https://example.com') +const json = await res.json() +console.log(json); ``` You can pass an optional dispatcher to `fetch` as: @@ -235,9 +234,7 @@ const data = { }, }; -(async () => { - await fetch("https://example.com", { body: data, method: 'POST' }); -})(); +await fetch("https://example.com", { body: data, method: 'POST' }); ``` #### `response.body` @@ -245,14 +242,12 @@ const data = { Nodejs has two kinds of streams: [web streams](https://nodejs.org/dist/latest-v16.x/docs/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`. ```js - import {fetch} from 'undici'; - import {Readable} from 'node:stream'; +import { fetch } from 'undici'; +import { Readable } from 'node:stream'; - async function fetchStream() { - const response = await fetch('https://example.com') - const readableWebStream = response.body; - const readableNodeStream = Readable.fromWeb(readableWebStream); - } +const response = await fetch('https://example.com') +const readableWebStream = response.body; +const readableNodeStream = Readable.fromWeb(readableWebStream); ``` #### Specification Compliance diff --git a/deps/undici/src/lib/api/api-connect.js b/deps/undici/src/lib/api/api-connect.js index 0503b1a2f0eb10..e4981af00de1b7 100644 --- a/deps/undici/src/lib/api/api-connect.js +++ b/deps/undici/src/lib/api/api-connect.js @@ -15,7 +15,7 @@ class ConnectHandler extends AsyncResource { throw new InvalidArgumentError('invalid callback') } - const { signal, opaque, responseHeaders } = opts + const { signal, opaque, responseHeaders, httpTunnel } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') @@ -27,6 +27,7 @@ class ConnectHandler extends AsyncResource { this.responseHeaders = responseHeaders || null this.callback = callback this.abort = null + this.httpTunnel = httpTunnel addSignal(this, signal) } @@ -40,8 +41,23 @@ class ConnectHandler extends AsyncResource { this.context = context } - onHeaders () { - throw new SocketError('bad connect', null) + onHeaders (statusCode) { + // when httpTunnel headers are allowed + if (this.httpTunnel) { + const { callback, opaque } = this + if (statusCode !== 200) { + if (callback) { + this.callback = null + const err = new RequestAbortedError('Proxy response !== 200 when HTTP Tunneling') + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + return 1 + } + } else { + throw new SocketError('bad connect', null) + } } onUpgrade (statusCode, rawHeaders, socket) { diff --git a/deps/undici/src/lib/core/connect.js b/deps/undici/src/lib/core/connect.js index 33a07e6d02dc73..57667a1314afa0 100644 --- a/deps/undici/src/lib/core/connect.js +++ b/deps/undici/src/lib/core/connect.js @@ -21,7 +21,7 @@ function buildConnector ({ maxCachedSessions, socketPath, timeout, ...opts }) { timeout = timeout == null ? 10e3 : timeout maxCachedSessions = maxCachedSessions == null ? 100 : maxCachedSessions - return function connect ({ hostname, host, protocol, port, servername }, callback) { + return function connect ({ hostname, host, protocol, port, servername, httpSocket }, callback) { let socket if (protocol === 'https:') { if (!tls) { @@ -39,6 +39,7 @@ function buildConnector ({ maxCachedSessions, socketPath, timeout, ...opts }) { ...options, servername, session, + socket: httpSocket, // upgrade socket connection port: port || 443, host: hostname }) @@ -65,6 +66,7 @@ function buildConnector ({ maxCachedSessions, socketPath, timeout, ...opts }) { } }) } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') socket = net.connect({ highWaterMark: 64 * 1024, // Same as nodejs fs streams. ...options, diff --git a/deps/undici/src/lib/core/request.js b/deps/undici/src/lib/core/request.js index 2a13b0549a80ff..1969f84deb186b 100644 --- a/deps/undici/src/lib/core/request.js +++ b/deps/undici/src/lib/core/request.js @@ -48,7 +48,11 @@ class Request { }, handler) { if (typeof path !== 'string') { throw new InvalidArgumentError('path must be a string') - } else if (path[0] !== '/' && !(path.startsWith('http://') || path.startsWith('https://'))) { + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { throw new InvalidArgumentError('path must be an absolute URL or start with a slash') } @@ -80,13 +84,12 @@ class Request { this.body = null } else if (util.isStream(body)) { this.body = body - } else if (body instanceof DataView) { - // TODO: Why is DataView special? - this.body = body.buffer.byteLength ? Buffer.from(body.buffer) : null - } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) { - this.body = body.byteLength ? Buffer.from(body) : null } else if (util.isBuffer(body)) { this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null } else if (typeof body === 'string') { this.body = body.length ? Buffer.from(body) : null } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { diff --git a/deps/undici/src/lib/fetch/body.js b/deps/undici/src/lib/fetch/body.js index 415e4ea34dacb2..beb1e027c98af6 100644 --- a/deps/undici/src/lib/fetch/body.js +++ b/deps/undici/src/lib/fetch/body.js @@ -9,7 +9,7 @@ const { kBodyUsed } = require('../core/symbols') const assert = require('assert') const { NotSupportedError } = require('../core/errors') const { isErrored } = require('../core/util') -const { isUint8Array } = require('util/types') +const { isUint8Array, isArrayBuffer } = require('util/types') let ReadableStream @@ -61,7 +61,7 @@ function extractBody (object, keepalive = false) { // Set Content-Type to `application/x-www-form-urlencoded;charset=UTF-8`. contentType = 'application/x-www-form-urlencoded;charset=UTF-8' - } else if (object instanceof ArrayBuffer || ArrayBuffer.isView(object)) { + } else if (isArrayBuffer(object) || ArrayBuffer.isView(object)) { // BufferSource if (object instanceof DataView) { diff --git a/deps/undici/src/lib/fetch/formdata.js b/deps/undici/src/lib/fetch/formdata.js index 40df747e843f05..965e47c3a7f6ca 100644 --- a/deps/undici/src/lib/fetch/formdata.js +++ b/deps/undici/src/lib/fetch/formdata.js @@ -1,6 +1,6 @@ 'use strict' -const { isBlobLike, isFileLike, toUSVString } = require('./util') +const { isBlobLike, isFileLike, toUSVString, makeIterator } = require('./util') const { kState } = require('./symbols') const { File, FileLike } = require('./file') const { Blob } = require('buffer') @@ -187,45 +187,68 @@ class FormData { return this.constructor.name } - * entries () { + entries () { if (!(this instanceof FormData)) { throw new TypeError('Illegal invocation') } - for (const pair of this) { - yield pair - } + return makeIterator( + makeIterable(this[kState], 'entries'), + 'FormData' + ) } - * keys () { + keys () { if (!(this instanceof FormData)) { throw new TypeError('Illegal invocation') } - for (const [key] of this) { - yield key + return makeIterator( + makeIterable(this[kState], 'keys'), + 'FormData' + ) + } + + values () { + if (!(this instanceof FormData)) { + throw new TypeError('Illegal invocation') } + + return makeIterator( + makeIterable(this[kState], 'values'), + 'FormData' + ) } - * values () { + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { if (!(this instanceof FormData)) { throw new TypeError('Illegal invocation') } - for (const [, value] of this) { - yield value + if (arguments.length < 1) { + throw new TypeError( + `Failed to execute 'forEach' on 'FormData': 1 argument required, but only ${arguments.length} present.` + ) } - } - * [Symbol.iterator] () { - // The value pairs to iterate over are this’s entry list’s entries with - // the key being the name and the value being the value. - for (const { name, value } of this[kState]) { - yield [name, value] + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) } } } +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + function makeEntry (name, value, filename) { // To create an entry for name, value, and optionally a filename, run these // steps: @@ -267,4 +290,18 @@ function makeEntry (name, value, filename) { return entry } +function * makeIterable (entries, type) { + // The value pairs to iterate over are this’s entry list’s entries + // with the key being the name and the value being the value. + for (const { name, value } of entries) { + if (type === 'entries') { + yield [name, value] + } else if (type === 'values') { + yield value + } else { + yield name + } + } +} + module.exports = { FormData } diff --git a/deps/undici/src/lib/fetch/headers.js b/deps/undici/src/lib/fetch/headers.js index 0c6e5584d33003..582e0c0f576ff1 100644 --- a/deps/undici/src/lib/fetch/headers.js +++ b/deps/undici/src/lib/fetch/headers.js @@ -6,6 +6,7 @@ const { validateHeaderName, validateHeaderValue } = require('http') const { kHeadersList } = require('../core/symbols') const { kGuard } = require('./symbols') const { kEnumerableProperty } = require('../core/util') +const { makeIterator } = require('./util') const kHeadersMap = Symbol('headers map') const kHeadersSortedMap = Symbol('headers map sorted') @@ -73,33 +74,6 @@ function fill (headers, object) { } } -// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object -const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) - -// https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object -function makeHeadersIterator (iterator) { - const i = { - next () { - if (Object.getPrototypeOf(this) !== i) { - throw new TypeError( - '\'next\' called on an object that does not implement interface Headers Iterator.' - ) - } - - return iterator.next() - }, - // The class string of an iterator prototype object for a given interface is the - // result of concatenating the identifier of the interface and the string " Iterator". - [Symbol.toStringTag]: 'Headers Iterator' - } - - // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. - Object.setPrototypeOf(i, esIteratorPrototype) - // esIteratorPrototype needs to be the prototype of i - // which is the prototype of an empty object. Yes, it's confusing. - return Object.setPrototypeOf({}, i) -} - class HeadersList { constructor (init) { if (init instanceof HeadersList) { @@ -306,7 +280,7 @@ class Headers { throw new TypeError('Illegal invocation') } - return makeHeadersIterator(this[kHeadersSortedMap].keys()) + return makeIterator(this[kHeadersSortedMap].keys(), 'Headers') } values () { @@ -314,7 +288,7 @@ class Headers { throw new TypeError('Illegal invocation') } - return makeHeadersIterator(this[kHeadersSortedMap].values()) + return makeIterator(this[kHeadersSortedMap].values(), 'Headers') } entries () { @@ -322,7 +296,7 @@ class Headers { throw new TypeError('Illegal invocation') } - return makeHeadersIterator(this[kHeadersSortedMap].entries()) + return makeIterator(this[kHeadersSortedMap].entries(), 'Headers') } /** diff --git a/deps/undici/src/lib/fetch/index.js b/deps/undici/src/lib/fetch/index.js index c1f3391995e357..ddf4b03d4cbab8 100644 --- a/deps/undici/src/lib/fetch/index.js +++ b/deps/undici/src/lib/fetch/index.js @@ -1164,7 +1164,7 @@ async function httpRedirectFetch (fetchParams, response) { if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && - !['GET', 'HEADER'].includes(request.method)) + !['GET', 'HEAD'].includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. diff --git a/deps/undici/src/lib/fetch/util.js b/deps/undici/src/lib/fetch/util.js index 1c67f9c7c841fa..3c088fbc6e92ad 100644 --- a/deps/undici/src/lib/fetch/util.js +++ b/deps/undici/src/lib/fetch/util.js @@ -361,6 +361,33 @@ function serializeJavascriptValueToJSONString (value) { return result } +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +// https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object +function makeIterator (iterator, name) { + const i = { + next () { + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + return iterator.next() + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + module.exports = { isAborted, isCancelled, @@ -390,5 +417,6 @@ module.exports = { isValidReasonPhrase, sameOrigin, normalizeMethod, - serializeJavascriptValueToJSONString + serializeJavascriptValueToJSONString, + makeIterator } diff --git a/deps/undici/src/lib/proxy-agent.js b/deps/undici/src/lib/proxy-agent.js index 37a416806178c1..8799650e62d30e 100644 --- a/deps/undici/src/lib/proxy-agent.js +++ b/deps/undici/src/lib/proxy-agent.js @@ -1,28 +1,46 @@ 'use strict' const { kProxy, kClose, kDestroy } = require('./core/symbols') +const Client = require('./agent') const Agent = require('./agent') const DispatcherBase = require('./dispatcher-base') const { InvalidArgumentError } = require('./core/errors') +const buildConnector = require('./core/connect') const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') class ProxyAgent extends DispatcherBase { constructor (opts) { super(opts) this[kProxy] = buildProxyOptions(opts) - this[kAgent] = new Agent(opts) + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = {} + + if (opts.auth) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = new Client({ origin: opts.origin, connect }) + this[kAgent] = new Agent({ ...opts, connect: this.connectTunnel.bind(this) }) } dispatch (opts, handler) { const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) return this[kAgent].dispatch( { ...opts, - origin: this[kProxy].uri, - path: opts.origin + opts.path, headers: { - ...buildHeaders(opts.headers), + ...headers, host } }, @@ -30,12 +48,43 @@ class ProxyAgent extends DispatcherBase { ) } + async connectTunnel (opts, callback) { + try { + const { socket } = await this[kClient].connect({ + origin: this[kProxy].origin, + port: this[kProxy].port, + path: opts.host, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host: opts.host + }, + httpTunnel: true + }) + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + async [kClose] () { await this[kAgent].close() + await this[kClient].close() } async [kDestroy] () { await this[kAgent].destroy() + await this[kClient].destroy() } } @@ -48,10 +97,7 @@ function buildProxyOptions (opts) { throw new InvalidArgumentError('Proxy opts.uri is mandatory') } - return { - uri: opts.uri, - protocol: opts.protocol || 'https' - } + return new URL(opts.uri) } /** @@ -75,4 +121,20 @@ function buildHeaders (headers) { return headers } +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + module.exports = ProxyAgent diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json index 3fda0f8e557088..dd029b6cfb0e06 100644 --- a/deps/undici/src/package.json +++ b/deps/undici/src/package.json @@ -1,6 +1,6 @@ { "name": "undici", - "version": "5.4.0", + "version": "5.5.1", "description": "An HTTP/1.1 client, written from scratch for Node.js", "homepage": "https://undici.nodejs.org", "bugs": { diff --git a/deps/undici/src/types/connector.d.ts b/deps/undici/src/types/connector.d.ts index 0794903cf0879b..38016b00008091 100644 --- a/deps/undici/src/types/connector.d.ts +++ b/deps/undici/src/types/connector.d.ts @@ -1,16 +1,15 @@ -import { URL } from 'url' -import { TLSSocket, TlsOptions } from 'tls' -import { Socket } from 'net' +import {TLSSocket, ConnectionOptions} from 'tls' +import {IpcNetConnectOpts, Socket, TcpNetConnectOpts} from 'net' export = buildConnector declare function buildConnector (options?: buildConnector.BuildOptions): typeof buildConnector.connector declare namespace buildConnector { - export interface BuildOptions extends TlsOptions { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { maxCachedSessions?: number | null; socketPath?: string | null; timeout?: number | null; - servername?: string | null; + port?: number; } export interface Options { diff --git a/deps/undici/src/types/fetch.d.ts b/deps/undici/src/types/fetch.d.ts index 47a08dd0510f05..87980bed40b3df 100644 --- a/deps/undici/src/types/fetch.d.ts +++ b/deps/undici/src/types/fetch.d.ts @@ -38,21 +38,21 @@ export interface BodyMixin { readonly text: () => Promise } -export interface HeadersIterator { +export interface SpecIterator { next(...args: [] | [TNext]): IteratorResult; } -export interface HeadersIterableIterator extends HeadersIterator { - [Symbol.iterator](): HeadersIterableIterator; +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; } -export interface HeadersIterable { - [Symbol.iterator](): HeadersIterator; +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; } export type HeadersInit = string[][] | Record> | Headers -export declare class Headers implements HeadersIterable<[string, string]> { +export declare class Headers implements SpecIterable<[string, string]> { constructor (init?: HeadersInit) readonly append: (name: string, value: string) => void readonly delete: (name: string) => void @@ -64,10 +64,10 @@ export declare class Headers implements HeadersIterable<[string, string]> { thisArg?: unknown ) => void - readonly keys: () => HeadersIterableIterator - readonly values: () => HeadersIterableIterator - readonly entries: () => HeadersIterableIterator<[string, string]> - readonly [Symbol.iterator]: () => HeadersIterator<[string, string]> + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> } export type RequestCache = diff --git a/deps/undici/src/types/formdata.d.ts b/deps/undici/src/types/formdata.d.ts index 2e652bacdb731f..df29a572d6bd4f 100644 --- a/deps/undici/src/types/formdata.d.ts +++ b/deps/undici/src/types/formdata.d.ts @@ -2,6 +2,7 @@ /// import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' /** * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. @@ -73,32 +74,35 @@ export declare class FormData { delete(name: string): void /** - * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. - * Each key is a `string`. + * Executes given callback function for each field of the FormData instance */ - keys(): Generator + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void /** - * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. - * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. */ - entries(): Generator<[string, FormDataEntryValue]> + keys: () => SpecIterableIterator /** * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). */ - values(): Generator + values: () => SpecIterableIterator /** - * An alias for FormData#entries() + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). */ - [Symbol.iterator](): Generator<[string, FormDataEntryValue], void> + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> /** - * Executes given callback function for each field of the FormData instance + * An alias for FormData#entries() */ - forEach(callback: (value: FormDataEntryValue, key: string, formData: FormData) => void, thisArg?: unknown): void + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> readonly [Symbol.toStringTag]: string } diff --git a/deps/undici/src/types/proxy-agent.d.ts b/deps/undici/src/types/proxy-agent.d.ts index c22369e96ee1ec..30fef450215380 100644 --- a/deps/undici/src/types/proxy-agent.d.ts +++ b/deps/undici/src/types/proxy-agent.d.ts @@ -1,3 +1,4 @@ +import { TlsOptions } from 'tls' import Agent = require('./agent') import Dispatcher = require('./dispatcher') @@ -13,5 +14,8 @@ declare class ProxyAgent extends Dispatcher { declare namespace ProxyAgent { export interface Options extends Agent.Options { uri: string; + auth?: string; + requestTls?: TlsOptions & { servername?: string }; + proxyTls?: TlsOptions & { servername?: string }; } } diff --git a/deps/undici/undici.js b/deps/undici/undici.js index 25de978273c344..5716d965a9618b 100644 --- a/deps/undici/undici.js +++ b/deps/undici/undici.js @@ -1415,6 +1415,20 @@ var require_util2 = __commonJS({ assert(typeof result === "string"); return result; } + var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); + function makeIterator(iterator, name) { + const i = { + next() { + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError(`'next' called on an object that does not implement interface ${name} Iterator.`); + } + return iterator.next(); + }, + [Symbol.toStringTag]: `${name} Iterator` + }; + Object.setPrototypeOf(i, esIteratorPrototype); + return Object.setPrototypeOf({}, i); + } module2.exports = { isAborted, isCancelled, @@ -1444,7 +1458,8 @@ var require_util2 = __commonJS({ isValidReasonPhrase, sameOrigin, normalizeMethod, - serializeJavascriptValueToJSONString + serializeJavascriptValueToJSONString, + makeIterator }; } }); @@ -1453,7 +1468,7 @@ var require_util2 = __commonJS({ var require_formdata = __commonJS({ "lib/fetch/formdata.js"(exports2, module2) { "use strict"; - var { isBlobLike, isFileLike, toUSVString } = require_util2(); + var { isBlobLike, isFileLike, toUSVString, makeIterator } = require_util2(); var { kState } = require_symbols2(); var { File, FileLike } = require_file(); var { Blob } = require("buffer"); @@ -1558,38 +1573,42 @@ var require_formdata = __commonJS({ get [Symbol.toStringTag]() { return this.constructor.name; } - *entries() { + entries() { if (!(this instanceof _FormData)) { throw new TypeError("Illegal invocation"); } - for (const pair of this) { - yield pair; - } + return makeIterator(makeIterable(this[kState], "entries"), "FormData"); } - *keys() { + keys() { if (!(this instanceof _FormData)) { throw new TypeError("Illegal invocation"); } - for (const [key] of this) { - yield key; + return makeIterator(makeIterable(this[kState], "keys"), "FormData"); + } + values() { + if (!(this instanceof _FormData)) { + throw new TypeError("Illegal invocation"); } + return makeIterator(makeIterable(this[kState], "values"), "FormData"); } - *values() { + forEach(callbackFn, thisArg = globalThis) { if (!(this instanceof _FormData)) { throw new TypeError("Illegal invocation"); } - for (const [, value] of this) { - yield value; + if (arguments.length < 1) { + throw new TypeError(`Failed to execute 'forEach' on 'FormData': 1 argument required, but only ${arguments.length} present.`); } - } - *[Symbol.iterator]() { - for (const { name, value } of this[kState]) { - yield [name, value]; + if (typeof callbackFn !== "function") { + throw new TypeError("Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."); + } + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]); } } }; var FormData = _FormData; __publicField(FormData, "name", "FormData"); + FormData.prototype[Symbol.iterator] = FormData.prototype.entries; function makeEntry(name, value, filename) { const entry = { name: null, @@ -1605,6 +1624,17 @@ var require_formdata = __commonJS({ entry.value = value; return entry; } + function* makeIterable(entries, type) { + for (const { name, value } of entries) { + if (type === "entries") { + yield [name, value]; + } else if (type === "values") { + yield value; + } else { + yield name; + } + } + } module2.exports = { FormData }; } }); @@ -1622,7 +1652,7 @@ var require_body = __commonJS({ var assert = require("assert"); var { NotSupportedError } = require_errors(); var { isErrored } = require_util(); - var { isUint8Array } = require("util/types"); + var { isUint8Array, isArrayBuffer } = require("util/types"); var ReadableStream; async function* blobGen(blob) { if (blob.stream) { @@ -1644,7 +1674,7 @@ var require_body = __commonJS({ } else if (object instanceof URLSearchParams) { source = object.toString(); contentType = "application/x-www-form-urlencoded;charset=UTF-8"; - } else if (object instanceof ArrayBuffer || ArrayBuffer.isView(object)) { + } else if (isArrayBuffer(object) || ArrayBuffer.isView(object)) { if (object instanceof DataView) { object = object.buffer; } @@ -1880,7 +1910,7 @@ var require_request = __commonJS({ }, handler) { if (typeof path !== "string") { throw new InvalidArgumentError("path must be a string"); - } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://"))) { + } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); } if (typeof method !== "string") { @@ -1903,12 +1933,12 @@ var require_request = __commonJS({ this.body = null; } else if (util.isStream(body)) { this.body = body; - } else if (body instanceof DataView) { - this.body = body.buffer.byteLength ? Buffer.from(body.buffer) : null; - } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) { - this.body = body.byteLength ? Buffer.from(body) : null; } else if (util.isBuffer(body)) { this.body = body.byteLength ? body : null; + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null; } else if (typeof body === "string") { this.body = body.length ? Buffer.from(body) : null; } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { @@ -2221,7 +2251,7 @@ var require_connect = __commonJS({ const sessionCache = /* @__PURE__ */ new Map(); timeout = timeout == null ? 1e4 : timeout; maxCachedSessions = maxCachedSessions == null ? 100 : maxCachedSessions; - return function connect({ hostname, host, protocol, port, servername }, callback) { + return function connect({ hostname, host, protocol, port, servername, httpSocket }, callback) { let socket; if (protocol === "https:") { if (!tls) { @@ -2236,6 +2266,7 @@ var require_connect = __commonJS({ ...options, servername, session, + socket: httpSocket, port: port || 443, host: hostname }); @@ -2254,6 +2285,7 @@ var require_connect = __commonJS({ } }); } else { + assert(!httpSocket, "httpSocket can only be sent on TLS update"); socket = net.connect({ highWaterMark: 64 * 1024, ...options, @@ -4205,6 +4237,7 @@ var require_headers = __commonJS({ var { kHeadersList } = require_symbols(); var { kGuard } = require_symbols2(); var { kEnumerableProperty } = require_util(); + var { makeIterator } = require_util2(); var kHeadersMap = Symbol("headers map"); var kHeadersSortedMap = Symbol("headers map sorted"); function normalizeAndValidateHeaderName(name) { @@ -4248,20 +4281,6 @@ var require_headers = __commonJS({ throw TypeError(); } } - var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); - function makeHeadersIterator(iterator) { - const i = { - next() { - if (Object.getPrototypeOf(this) !== i) { - throw new TypeError("'next' called on an object that does not implement interface Headers Iterator."); - } - return iterator.next(); - }, - [Symbol.toStringTag]: "Headers Iterator" - }; - Object.setPrototypeOf(i, esIteratorPrototype); - return Object.setPrototypeOf({}, i); - } var HeadersList = class { constructor(init) { if (init instanceof HeadersList) { @@ -4396,19 +4415,19 @@ var require_headers = __commonJS({ if (!(this instanceof Headers)) { throw new TypeError("Illegal invocation"); } - return makeHeadersIterator(this[kHeadersSortedMap].keys()); + return makeIterator(this[kHeadersSortedMap].keys(), "Headers"); } values() { if (!(this instanceof Headers)) { throw new TypeError("Illegal invocation"); } - return makeHeadersIterator(this[kHeadersSortedMap].values()); + return makeIterator(this[kHeadersSortedMap].values(), "Headers"); } entries() { if (!(this instanceof Headers)) { throw new TypeError("Illegal invocation"); } - return makeHeadersIterator(this[kHeadersSortedMap].entries()); + return makeIterator(this[kHeadersSortedMap].entries(), "Headers"); } forEach(callbackFn, thisArg = globalThis) { if (!(this instanceof Headers)) { @@ -5950,7 +5969,7 @@ var require_fetch = __commonJS({ if (actualResponse.status !== 303 && request.body != null && request.body.source == null) { return makeNetworkError(); } - if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !["GET", "HEADER"].includes(request.method)) { + if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !["GET", "HEAD"].includes(request.method)) { request.method = "GET"; request.body = null; for (const headerName of requestBodyHeader) { From 0c5092c51c7778bb019fc2b88528e5f5e5646047 Mon Sep 17 00:00:00 2001 From: Daeyeon Jeong Date: Wed, 15 Jun 2022 04:30:51 +0900 Subject: [PATCH 85/96] events: fix adding abort listener in `events.once` Event listeners passed to un/subscribe the abort event are mismatched. This removes the wrapper function in `eventTargetAgnosticAddListener()` and directly passes the given listener to the `EventTarget`. IMO, removing the wrapper seems harmless, and the `AbortSignal` is seemingly the only `EventTarget` passed to this function for now. Fixes: https://github.com/nodejs/node/issues/43337 Refs: https://github.com/nodejs/node/pull/33659 Refs: https://github.com/nodejs/node/pull/34997 Signed-off-by: Daeyeon Jeong daeyeon.dev@gmail.com PR-URL: https://github.com/nodejs/node/pull/43373 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum --- lib/events.js | 6 +++--- test/parallel/test-events-once.js | 35 +++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/lib/events.js b/lib/events.js index 603f3083ed2ce0..422231deea40e1 100644 --- a/lib/events.js +++ b/lib/events.js @@ -972,6 +972,8 @@ async function once(emitter, name, options = kEmptyObject) { }; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error' && typeof emitter.once === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we listen to `error` events only on EventEmitters. emitter.once('error', errorListener); } function abortListener() { @@ -1011,9 +1013,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen to `error` events here. - emitter.addEventListener(name, (arg) => { listener(arg); }, flags); + emitter.addEventListener(name, listener, flags); } else { throw new ERR_INVALID_ARG_TYPE('emitter', 'EventEmitter', emitter); } diff --git a/test/parallel/test-events-once.js b/test/parallel/test-events-once.js index 56042b1ecee4f9..6acb795653590b 100644 --- a/test/parallel/test-events-once.js +++ b/test/parallel/test-events-once.js @@ -1,5 +1,5 @@ 'use strict'; -// Flags: --no-warnings +// Flags: --expose-internals --no-warnings const common = require('../common'); const { once, EventEmitter } = require('events'); @@ -9,6 +9,7 @@ const { fail, rejects, } = require('assert'); +const { kEvents } = require('internal/event_target'); async function onceAnEvent() { const ee = new EventEmitter(); @@ -65,6 +66,32 @@ async function catchesErrors() { strictEqual(ee.listenerCount('myevent'), 0); } +async function catchesErrorsWithAbortSignal() { + const ee = new EventEmitter(); + const ac = new AbortController(); + const signal = ac.signal; + + const expected = new Error('boom'); + let err; + process.nextTick(() => { + ee.emit('error', expected); + }); + + try { + const promise = once(ee, 'myevent', { signal }); + strictEqual(ee.listenerCount('error'), 1); + strictEqual(signal[kEvents].size, 1); + + await promise; + } catch (e) { + err = e; + } + strictEqual(err, expected); + strictEqual(ee.listenerCount('error'), 0); + strictEqual(ee.listenerCount('myevent'), 0); + strictEqual(signal[kEvents].size, 0); +} + async function stopListeningAfterCatchingError() { const ee = new EventEmitter(); @@ -165,7 +192,10 @@ async function abortSignalAfterEvent() { ee.emit('foo'); ac.abort(); }); - await once(ee, 'foo', { signal: ac.signal }); + const promise = once(ee, 'foo', { signal: ac.signal }); + strictEqual(ac.signal[kEvents].size, 1); + await promise; + strictEqual(ac.signal[kEvents].size, 0); } async function abortSignalRemoveListener() { @@ -221,6 +251,7 @@ Promise.all([ onceAnEventWithNullOptions(), onceAnEventWithTwoArgs(), catchesErrors(), + catchesErrorsWithAbortSignal(), stopListeningAfterCatchingError(), onceError(), onceWithEventTarget(), From fe7fd851092a1a1ca436f11092f69616c9b22aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Nison?= Date: Wed, 15 Jun 2022 05:05:50 +0200 Subject: [PATCH 86/96] deps: update Corepack to 0.11.2 PR-URL: https://github.com/nodejs/node/pull/43402 Reviewed-By: Antoine du Hamel Reviewed-By: Mohammed Keyvanzadeh Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Darshan Sen Reviewed-By: Jiawen Geng --- deps/corepack/CHANGELOG.md | 37 + deps/corepack/README.md | 8 +- deps/corepack/dist/corepack.js | 27558 ++++++----- deps/corepack/dist/vcc.js | 10 +- ...9_zip_node_modules_proxy-agent_index_js.js | 40843 ++++++++++++++++ deps/corepack/package.json | 68 +- deps/corepack/shims/corepack | 2 +- deps/corepack/shims/corepack.cmd | 4 +- deps/corepack/shims/nodewin/corepack | 2 +- deps/corepack/shims/nodewin/corepack.cmd | 4 +- deps/corepack/shims/nodewin/npm | 2 +- deps/corepack/shims/nodewin/npm.cmd | 4 +- deps/corepack/shims/nodewin/npx | 2 +- deps/corepack/shims/nodewin/npx.cmd | 4 +- deps/corepack/shims/nodewin/pnpm | 2 +- deps/corepack/shims/nodewin/pnpm.cmd | 4 +- deps/corepack/shims/nodewin/pnpx | 2 +- deps/corepack/shims/nodewin/pnpx.cmd | 4 +- deps/corepack/shims/nodewin/vcc | 12 - deps/corepack/shims/nodewin/vcc.cmd | 7 - deps/corepack/shims/nodewin/vcc.ps1 | 28 - deps/corepack/shims/nodewin/yarn | 2 +- deps/corepack/shims/nodewin/yarn.cmd | 4 +- deps/corepack/shims/nodewin/yarnpkg | 2 +- deps/corepack/shims/nodewin/yarnpkg.cmd | 4 +- deps/corepack/shims/npm | 2 +- deps/corepack/shims/npm.cmd | 4 +- deps/corepack/shims/npx | 2 +- deps/corepack/shims/npx.cmd | 4 +- deps/corepack/shims/pnpm | 2 +- deps/corepack/shims/pnpm.cmd | 4 +- deps/corepack/shims/pnpx | 2 +- deps/corepack/shims/pnpx.cmd | 4 +- deps/corepack/shims/yarn | 2 +- deps/corepack/shims/yarn.cmd | 4 +- deps/corepack/shims/yarnpkg | 2 +- deps/corepack/shims/yarnpkg.cmd | 4 +- 37 files changed, 55821 insertions(+), 12834 deletions(-) create mode 100644 deps/corepack/CHANGELOG.md create mode 100644 deps/corepack/dist/vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js.js delete mode 100644 deps/corepack/shims/nodewin/vcc delete mode 100644 deps/corepack/shims/nodewin/vcc.cmd delete mode 100644 deps/corepack/shims/nodewin/vcc.ps1 diff --git a/deps/corepack/CHANGELOG.md b/deps/corepack/CHANGELOG.md new file mode 100644 index 00000000000000..1867c788f32932 --- /dev/null +++ b/deps/corepack/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +## [0.11.2](https://github.com/nodejs/corepack/compare/v0.11.1...v0.11.2) (2022-06-13) + +### Bug Fixes + +* only set bins on pack ([#127](https://github.com/nodejs/corepack/issues/127)) ([7ae489a](https://github.com/nodejs/corepack/commit/7ae489a86c3fe584b9915f4ec57deb7c316c1a25)) + +## [0.11.1](https://github.com/nodejs/corepack/compare/v0.11.0...v0.11.1) (2022-06-12) + + +### Bug Fixes + +* **ci:** YAML formatting in publish workflow ([#124](https://github.com/nodejs/corepack/issues/124)) ([01c7d63](https://github.com/nodejs/corepack/commit/01c7d638b04a1340b3939a7985e24b586e344995)) + +## 0.11.0 (2022-06-12) + + +### Features + +* auto setup proxy for http requests ([#69](https://github.com/nodejs/corepack/issues/69)) ([876ce02](https://github.com/nodejs/corepack/commit/876ce02fe7385ea5bc896b2dc93d1fb320361c64)) + + +### Bug Fixes + +* avoid symlinks to work on Windows ([#13](https://github.com/nodejs/corepack/issues/13)) ([b56df30](https://github.com/nodejs/corepack/commit/b56df30796da9c7cb0ba5e1bb7152c81582abba6)) +* avoid using eval to get the corepack version ([#45](https://github.com/nodejs/corepack/issues/45)) ([78d94eb](https://github.com/nodejs/corepack/commit/78d94eb297444d7558e8b4395f0108c97117f8ab)) +* bin file name for pnpm >=6.0 ([#35](https://github.com/nodejs/corepack/issues/35)) ([8ff2499](https://github.com/nodejs/corepack/commit/8ff2499e831c8cf2dea604ea985d830afc8a479e)) +* generate cmd shim files ([a900b4d](https://github.com/nodejs/corepack/commit/a900b4db12fcd4d99c0a4d011b426cdc6485d323)) +* handle package managers with a bin array correctly ([#20](https://github.com/nodejs/corepack/issues/20)) ([1836d17](https://github.com/nodejs/corepack/commit/1836d17b4fc4c0164df2fe1ccaca4d2f16f6f2d1)) +* handle parallel installs ([#84](https://github.com/nodejs/corepack/issues/84)) ([5cfc6c9](https://github.com/nodejs/corepack/commit/5cfc6c9df0dbec8e4de4324be37aa0a54a300552)) +* handle prereleases ([#32](https://github.com/nodejs/corepack/issues/32)) ([2a46b6d](https://github.com/nodejs/corepack/commit/2a46b6d13adae139141012254ef670d6ddcb5d11)) + + +### Performance Improvements + +* load binaries in the same process ([#97](https://github.com/nodejs/corepack/issues/97)) ([5ff6e82](https://github.com/nodejs/corepack/commit/5ff6e82028e58448ba5ba986854b61ecdc69885b)) diff --git a/deps/corepack/README.md b/deps/corepack/README.md index d58811c4cdaaee..6fc940814cdd4e 100644 --- a/deps/corepack/README.md +++ b/deps/corepack/README.md @@ -8,7 +8,7 @@ Corepack is a zero-runtime-dependency Node.js script that acts as a bridge betwe ### Default Installs -Corepack is distributed by default with Node.js 16.9, but is opt-in for the time being. Run `corepack enable` to install the required shims. +Corepack is distributed by default with Node.js 14.19.0 and 16.9.0, but is opt-in for the time being. Run `corepack enable` to install the required shims. ### Manual Installs @@ -104,8 +104,14 @@ This command will retrieve the given package manager from the specified archive ## Environment Variables +- `COREPACK_ENABLE_NETWORK` can be set to `0` to prevent Corepack from accessing the network (in which case you'll be responsible for hydrating the package manager versions that will be required for the projects you'll run, using `corepack hydrate`). + +- `COREPACK_HOME` can be set in order to define where Corepack should install the package managers. By default it is set to `$HOME/.node/corepack`. + - `COREPACK_ROOT` has no functional impact on Corepack itself; it's automatically being set in your environment by Corepack when it shells out to the underlying package managers, so that they can feature-detect its presence (useful for commands like `yarn init`). +- `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` are supported through [`node-proxy-agent`](https://github.com/TooTallNate/node-proxy-agent). + ## Contributing If you want to build corepack yourself, you can build the project like this: diff --git a/deps/corepack/dist/corepack.js b/deps/corepack/dist/corepack.js index f540b108b0a305..3290a0ff392bb4 100755 --- a/deps/corepack/dist/corepack.js +++ b/deps/corepack/dist/corepack.js @@ -3,14616 +3,16810 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Cli.js": -/*!*********************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Cli.js ***! - \*********************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/@zkochan-cmd-shim-npm-5.2.2-ae7b6d5b86-9.zip/node_modules/@zkochan/cmd-shim/index.js": +/*!***********************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/@zkochan-cmd-shim-npm-5.2.2-ae7b6d5b86-9.zip/node_modules/@zkochan/cmd-shim/index.js ***! + \***********************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var constants = __webpack_require__(/*! ../constants.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/constants.js"); -var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); -var core = __webpack_require__(/*! ../core.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/core.js"); -var format = __webpack_require__(/*! ../format.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/format.js"); -var HelpCommand = __webpack_require__(/*! ./HelpCommand.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/HelpCommand.js"); - -const errorCommandSymbol = Symbol(`clipanion/errorCommand`); -function getDefaultColorSettings() { - if (process.env.FORCE_COLOR === `0`) - return false; - if (process.env.FORCE_COLOR === `1`) - return true; - if (typeof process.stdout !== `undefined` && process.stdout.isTTY) - return true; - return false; +cmdShim.ifExists = cmdShimIfExists; +const util_1 = __webpack_require__(/*! util */ "util"); +const path = __webpack_require__(/*! path */ "path"); +const isWindows = __webpack_require__(/*! is-windows */ "../../../.yarn/berry/cache/is-windows-npm-1.0.2-898cd6f3d7-9.zip/node_modules/is-windows/index.js"); +const CMD_EXTENSION = __webpack_require__(/*! cmd-extension */ "../../../.yarn/berry/cache/cmd-extension-npm-1.0.2-11aa204c4b-9.zip/node_modules/cmd-extension/index.js"); +const shebangExpr = /^#!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/; +const DEFAULT_OPTIONS = { + // Create PowerShell file by default if the option hasn't been specified + createPwshFile: true, + createCmdFile: isWindows(), + fs: __webpack_require__(/*! fs */ "fs") +}; +/** + * Map from extensions of files that this module is frequently used for to their runtime. + * @type {Map} + */ +const extensionToProgramMap = new Map([ + ['.js', 'node'], + ['.cjs', 'node'], + ['.mjs', 'node'], + ['.cmd', 'cmd'], + ['.bat', 'cmd'], + ['.ps1', 'pwsh'], + ['.sh', 'sh'] +]); +function ingestOptions(opts) { + const opts_ = { ...DEFAULT_OPTIONS, ...opts }; + const fs = opts_.fs; + opts_.fs_ = { + chmod: fs.chmod ? util_1.promisify(fs.chmod) : (async () => { }), + mkdir: util_1.promisify(fs.mkdir), + readFile: util_1.promisify(fs.readFile), + stat: util_1.promisify(fs.stat), + unlink: util_1.promisify(fs.unlink), + writeFile: util_1.promisify(fs.writeFile) + }; + return opts_; } /** - * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`. + * Try to create shims. + * + * @param src Path to program (executable or script). + * @param to Path to shims. + * Don't add an extension if you will create multiple types of shims. + * @param opts Options. + * @throws If `src` is missing. */ -class Cli { - constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableColors = getDefaultColorSettings() } = {}) { - this.registrations = new Map(); - this.builder = new core.CliBuilder({ binaryName: binaryNameOpt }); - this.binaryLabel = binaryLabel; - this.binaryName = binaryNameOpt; - this.binaryVersion = binaryVersion; - this.enableColors = enableColors; - } - /** - * Creates a new Cli and registers all commands passed as parameters. - * - * @param commandClasses The Commands to register - * @returns The created `Cli` instance - */ - static from(commandClasses, options = {}) { - const cli = new Cli(options); - for (const commandClass of commandClasses) - cli.register(commandClass); - return cli; +async function cmdShim(src, to, opts) { + const opts_ = ingestOptions(opts); + await opts_.fs_.stat(src); + await cmdShim_(src, to, opts_); +} +/** + * Try to create shims. + * + * Does nothing if `src` doesn't exist. + * + * @param src Path to program (executable or script). + * @param to Path to shims. + * Don't add an extension if you will create multiple types of shims. + * @param opts Options. + */ +function cmdShimIfExists(src, to, opts) { + return cmdShim(src, to, opts).catch(() => { }); +} +/** + * Try to unlink, but ignore errors. + * Any problems will surface later. + * + * @param path File to be removed. + */ +function rm(path, opts) { + return opts.fs_.unlink(path).catch(() => { }); +} +/** + * Try to create shims **even if `src` is missing**. + * + * @param src Path to program (executable or script). + * @param to Path to shims. + * Don't add an extension if you will create multiple types of shims. + * @param opts Options. + */ +async function cmdShim_(src, to, opts) { + const srcRuntimeInfo = await searchScriptRuntime(src, opts); + // Always tries to create all types of shims by calling `writeAllShims` as of now. + // Append your code here to change the behavior in response to `srcRuntimeInfo`. + // Create 3 shims for (Ba)sh in Cygwin / MSYS, no extension) & CMD (.cmd) & PowerShell (.ps1) + await writeShimsPreCommon(to, opts); + return writeAllShims(src, to, srcRuntimeInfo, opts); +} +/** + * Do processes before **all** shims are created. + * This must be called **only once** for one call of `cmdShim(IfExists)`. + * + * @param target Path of shims that are going to be created. + */ +function writeShimsPreCommon(target, opts) { + return opts.fs_.mkdir(path.dirname(target), { recursive: true }); +} +/** + * Write all types (sh & cmd & pwsh) of shims to files. + * Extensions (`.cmd` and `.ps1`) are appended to cmd and pwsh shims. + * + * + * @param src Path to program (executable or script). + * @param to Path to shims **without extensions**. + * Extensions are added for CMD and PowerShell shims. + * @param srcRuntimeInfo Return value of `await searchScriptRuntime(src)`. + * @param opts Options. + */ +function writeAllShims(src, to, srcRuntimeInfo, opts) { + const opts_ = ingestOptions(opts); + const generatorAndExts = [{ generator: generateShShim, extension: '' }]; + if (opts_.createCmdFile) { + generatorAndExts.push({ generator: generateCmdShim, extension: CMD_EXTENSION }); } - /** - * Registers a command inside the CLI. - */ - register(commandClass) { - var _a; - const specs = new Map(); - const command = new commandClass(); - for (const key in command) { - const value = command[key]; - if (typeof value === `object` && value !== null && value[Command.Command.isOption]) { - specs.set(key, value); - } - } - const builder = this.builder.command(); - const index = builder.cliIndex; - const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths; - if (typeof paths !== `undefined`) - for (const path of paths) - builder.addPath(path); - this.registrations.set(commandClass, { specs, builder, index }); - for (const [key, { definition }] of specs.entries()) - definition(builder, key); - builder.setContext({ - commandClass, - }); + if (opts_.createPwshFile) { + generatorAndExts.push({ generator: generatePwshShim, extension: '.ps1' }); } - process(input) { - const { contexts, process } = this.builder.compile(); - const state = process(input); - switch (state.selectedIndex) { - case constants.HELP_COMMAND_INDEX: - { - return HelpCommand.HelpCommand.from(state, contexts); - } - default: - { - const { commandClass } = contexts[state.selectedIndex]; - const record = this.registrations.get(commandClass); - if (typeof record === `undefined`) - throw new Error(`Assertion failed: Expected the command class to have been registered.`); - const command = new commandClass(); - command.path = state.path; - try { - for (const [key, { transformer }] of record.specs.entries()) - command[key] = transformer(record.builder, key, state); - return command; - } - catch (error) { - error[errorCommandSymbol] = command; - throw error; - } - } - break; - } + return Promise.all(generatorAndExts.map((generatorAndExt) => writeShim(src, to + generatorAndExt.extension, srcRuntimeInfo, generatorAndExt.generator, opts_))); +} +/** + * Do processes before writing shim. + * + * @param target Path to shim that is going to be created. + */ +function writeShimPre(target, opts) { + return rm(target, opts); +} +/** + * Do processes after writing the shim. + * + * @param target Path to just created shim. + */ +function writeShimPost(target, opts) { + // Only chmoding shims as of now. + // Some other processes may be appended. + return chmodShim(target, opts); +} +/** + * Look into runtime (e.g. `node` & `sh` & `pwsh`) and its arguments + * of the target program (script or executable). + * + * @param target Path to the executable or script. + * @return Promise of infomation of runtime of `target`. + */ +async function searchScriptRuntime(target, opts) { + const data = await opts.fs_.readFile(target, 'utf8'); + // First, check if the bin is a #! of some sort. + const firstLine = data.trim().split(/\r*\n/)[0]; + const shebang = firstLine.match(shebangExpr); + if (!shebang) { + // If not, infer script type from its extension. + // If the inference fails, it's something that'll be compiled, or some other + // sort of script, and just call it directly. + const targetExtension = path.extname(target).toLowerCase(); + return { + // undefined if extension is unknown but it's converted to null. + program: extensionToProgramMap.get(targetExtension) || null, + additionalArgs: '' + }; } - async run(input, context) { - let command; - if (!Array.isArray(input)) { - command = input; - } - else { - try { - command = this.process(input); - } - catch (error) { - context.stdout.write(this.error(error)); - return 1; - } - } - if (command.help) { - context.stdout.write(this.usage(command, { detailed: true })); - return 0; - } - command.context = context; - command.cli = { - binaryLabel: this.binaryLabel, - binaryName: this.binaryName, - binaryVersion: this.binaryVersion, - enableColors: this.enableColors, - definitions: () => this.definitions(), - error: (error, opts) => this.error(error, opts), - process: input => this.process(input), - run: (input, subContext) => this.run(input, { ...context, ...subContext }), - usage: (command, opts) => this.usage(command, opts), - }; - let exitCode; - try { - exitCode = await command.validateAndExecute().catch(error => command.catch(error).then(() => 0)); - } - catch (error) { - context.stdout.write(this.error(error, { command })); - return 1; - } - return exitCode; + return { + program: shebang[1], + additionalArgs: shebang[2] + }; +} +/** + * Write shim to the file system while executing the pre- and post-processes + * defined in `WriteShimPre` and `WriteShimPost`. + * + * @param src Path to the executable or script. + * @param to Path to the (sh) shim(s) that is going to be created. + * @param srcRuntimeInfo Result of `await searchScriptRuntime(src)`. + * @param generateShimScript Generator of shim script. + * @param opts Other options. + */ +async function writeShim(src, to, srcRuntimeInfo, generateShimScript, opts) { + const defaultArgs = opts.preserveSymlinks ? '--preserve-symlinks' : ''; + // `Array.prototype.filter` removes ''. + // ['--foo', '--bar'].join(' ') and [].join(' ') returns '--foo --bar' and '' respectively. + const args = [srcRuntimeInfo.additionalArgs, defaultArgs].filter(arg => arg).join(' '); + opts = Object.assign({}, opts, { + prog: srcRuntimeInfo.program, + args: args + }); + await writeShimPre(to, opts); + await opts.fs_.writeFile(to, generateShimScript(src, to, opts), 'utf8'); + return writeShimPost(to, opts); +} +/** + * Generate the content of a shim for CMD. + * + * @param src Path to the executable or script. + * @param to Path to the shim to be created. + * It is highly recommended to end with `.cmd` (or `.bat`). + * @param opts Options. + * @return The content of shim. + */ +function generateCmdShim(src, to, opts) { + // `shTarget` is not used to generate the content. + const shTarget = path.relative(path.dirname(to), src); + let target = shTarget.split('/').join('\\'); + const quotedPathToTarget = path.isAbsolute(target) ? `"${target}"` : `"%~dp0\\${target}"`; + let longProg; + let prog = opts.prog; + let args = opts.args || ''; + const nodePath = normalizePathEnvVar(opts.nodePath).win32; + if (!prog) { + prog = quotedPathToTarget; + args = ''; + target = ''; } - /** - * Runs a command and exits the current `process` with the exit code returned by the command. - * - * @param input An array containing the name of the command and its arguments. - * - * @example - * cli.runExit(process.argv.slice(2), Cli.defaultContext) - */ - async runExit(input, context) { - process.exitCode = await this.run(input, context); + else if (prog === 'node' && opts.nodeExecPath) { + prog = `"${opts.nodeExecPath}"`; + target = quotedPathToTarget; } - suggest(input, partial) { - const { suggest } = this.builder.compile(); - return suggest(input, partial); + else { + longProg = `"%~dp0\\${prog}.exe"`; + target = quotedPathToTarget; } - definitions({ colored = false } = {}) { - const data = []; - for (const [commandClass, { index }] of this.registrations) { - if (typeof commandClass.usage === `undefined`) - continue; - const { usage: path } = this.getUsageByIndex(index, { detailed: false }); - const { usage, options } = this.getUsageByIndex(index, { detailed: true, inlineOptions: false }); - const category = typeof commandClass.usage.category !== `undefined` - ? format.formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) - : undefined; - const description = typeof commandClass.usage.description !== `undefined` - ? format.formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false }) - : undefined; - const details = typeof commandClass.usage.details !== `undefined` - ? format.formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true }) - : undefined; - const examples = typeof commandClass.usage.examples !== `undefined` - ? commandClass.usage.examples.map(([label, cli]) => [format.formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\$0/g, this.binaryName)]) - : undefined; - data.push({ path, usage, category, description, details, examples, options }); - } - return data; + let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; + // @IF EXIST "%~dp0\node.exe" ( + // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) ELSE ( + // SETLOCAL + // SET PATHEXT=%PATHEXT:;.JS;=;% + // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) + let cmd = '@SETLOCAL\r\n'; + if (nodePath) { + cmd += `\ +@IF NOT DEFINED NODE_PATH (\r + @SET "NODE_PATH=${nodePath}"\r +) ELSE (\r + @SET "NODE_PATH=%NODE_PATH%;${nodePath}"\r +)\r +`; } - usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) { - var _a; - // In case the default command is the only one, we can just show the command help rather than the general one - if (command === null) { - for (const commandClass of this.registrations.keys()) { - const paths = commandClass.paths; - const isDocumented = typeof commandClass.usage !== `undefined`; - const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0); - const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false); - if (isDefault) { - if (command) { - command = null; - break; - } - else { - command = commandClass; - } - } - else { - if (isDocumented) { - command = null; - continue; - } - } - } - if (command) { - detailed = true; - } - } - // @ts-ignore - const commandClass = command !== null && command instanceof Command.Command - ? command.constructor - : command; - let result = ``; - if (!commandClass) { - const commandsByCategories = new Map(); - for (const [commandClass, { index }] of this.registrations.entries()) { - if (typeof commandClass.usage === `undefined`) - continue; - const category = typeof commandClass.usage.category !== `undefined` - ? format.formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) - : null; - let categoryCommands = commandsByCategories.get(category); - if (typeof categoryCommands === `undefined`) - commandsByCategories.set(category, categoryCommands = []); - const { usage } = this.getUsageByIndex(index); - categoryCommands.push({ commandClass, usage }); - } - const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => { - if (a === null) - return -1; - if (b === null) - return +1; - return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` }); - }); - const hasLabel = typeof this.binaryLabel !== `undefined`; - const hasVersion = typeof this.binaryVersion !== `undefined`; - if (hasLabel || hasVersion) { - if (hasLabel && hasVersion) - result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\n\n`; - else if (hasLabel) - result += `${this.format(colored).header(`${this.binaryLabel}`)}\n`; - else - result += `${this.format(colored).header(`${this.binaryVersion}`)}\n`; - result += ` ${this.format(colored).bold(prefix)}${this.binaryName} \n`; - } - else { - result += `${this.format(colored).bold(prefix)}${this.binaryName} \n`; - } - for (const categoryName of categoryNames) { - const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => { - return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` }); - }); - const header = categoryName !== null - ? categoryName.trim() - : `General commands`; - result += `\n`; - result += `${this.format(colored).header(`${header}`)}\n`; - for (const { commandClass, usage } of commands) { - const doc = commandClass.usage.description || `undocumented`; - result += `\n`; - result += ` ${this.format(colored).bold(usage)}\n`; - result += ` ${format.formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`; - } - } - result += `\n`; - result += format.formatMarkdownish(`You can also print more details about any of these commands by calling them with the \`-h,--help\` flag right after the command name.`, { format: this.format(colored), paragraphs: true }); - } - else { - if (!detailed) { - const { usage } = this.getUsageByRegistration(commandClass); - result += `${this.format(colored).bold(prefix)}${usage}\n`; - } - else { - const { description = ``, details = ``, examples = [], } = commandClass.usage || {}; - if (description !== ``) { - result += format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase()); - result += `\n`; - } - if (details !== `` || examples.length > 0) { - result += `${this.format(colored).header(`Usage`)}\n`; - result += `\n`; - } - const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false }); - result += `${this.format(colored).bold(prefix)}${usage}\n`; - if (options.length > 0) { - result += `\n`; - result += `${format.richFormat.header(`Options`)}\n`; - const maxDefinitionLength = options.reduce((length, option) => { - return Math.max(length, option.definition.length); - }, 0); - result += `\n`; - for (const { definition, description } of options) { - result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`; - } - } - if (details !== ``) { - result += `\n`; - result += `${this.format(colored).header(`Details`)}\n`; - result += `\n`; - result += format.formatMarkdownish(details, { format: this.format(colored), paragraphs: true }); - } - if (examples.length > 0) { - result += `\n`; - result += `${this.format(colored).header(`Examples`)}\n`; - for (const [description, example] of examples) { - result += `\n`; - result += format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false }); - result += `${example - .replace(/^/m, ` ${this.format(colored).bold(prefix)}`) - .replace(/\$0/g, this.binaryName)}\n`; - } - } - } - } - return result; + if (longProg) { + cmd += `\ +@IF EXIST ${longProg} (\r + ${longProg} ${args} ${target} ${progArgs}%*\r +) ELSE (\r + @SET PATHEXT=%PATHEXT:;.JS;=;%\r + ${prog} ${args} ${target} ${progArgs}%*\r +)\r +`; } - error(error, _a) { - var _b; - var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a; - if (!(error instanceof Error)) - error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`); - let result = ``; - let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`); - if (name === `Error`) - name = `Internal Error`; - result += `${this.format(colored).error(name)}: ${error.message}\n`; - const meta = error.clipanion; - if (typeof meta !== `undefined`) { - if (meta.type === `usage`) { - result += `\n`; - result += this.usage(command); - } - } - else { - if (error.stack) { - result += `${error.stack.replace(/^.*\n/, ``)}\n`; - } - } - return result; + else { + cmd += `@${prog} ${args} ${target} ${progArgs}%*\r\n`; } - getUsageByRegistration(klass, opts) { - const record = this.registrations.get(klass); - if (typeof record === `undefined`) - throw new Error(`Assertion failed: Unregistered command`); - return this.getUsageByIndex(record.index, opts); + return cmd; +} +/** + * Generate the content of a shim for (Ba)sh in, for example, Cygwin and MSYS(2). + * + * @param src Path to the executable or script. + * @param to Path to the shim to be created. + * It is highly recommended to end with `.sh` or to contain no extension. + * @param opts Options. + * @return The content of shim. + */ +function generateShShim(src, to, opts) { + let shTarget = path.relative(path.dirname(to), src); + let shProg = opts.prog && opts.prog.split('\\').join('/'); + let shLongProg; + shTarget = shTarget.split('\\').join('/'); + const quotedPathToTarget = path.isAbsolute(shTarget) ? `"${shTarget}"` : `"$basedir/${shTarget}"`; + let args = opts.args || ''; + const shNodePath = normalizePathEnvVar(opts.nodePath).posix; + if (!shProg) { + shProg = quotedPathToTarget; + args = ''; + shTarget = ''; } - getUsageByIndex(n, opts) { - return this.builder.getBuilderByIndex(n).usage(opts); + else if (opts.prog === 'node' && opts.nodeExecPath) { + shProg = `"${opts.nodeExecPath}"`; + shTarget = quotedPathToTarget; } - format(colored = this.enableColors) { - return colored ? format.richFormat : format.textFormat; + else { + shLongProg = `"$basedir/${opts.prog}"`; + shTarget = quotedPathToTarget; + } + let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // export NODE_PATH="" + // + // if [ -x "$basedir/node.exe" ]; then + // exec "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // else + // exec node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // fi + let sh = `\ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')") + +case \`uname\` in + *CYGWIN*) basedir=\`cygpath -w "$basedir"\`;; +esac + +`; + if (shNodePath) { + sh += `\ +if [ -z "$NODE_PATH" ]; then + export NODE_PATH="${shNodePath}" +else + export NODE_PATH="$NODE_PATH:${shNodePath}" +fi +`; + } + if (shLongProg) { + sh += `\ +if [ -x ${shLongProg} ]; then + exec ${shLongProg} ${args} ${shTarget} ${progArgs}"$@" +else + exec ${shProg} ${args} ${shTarget} ${progArgs}"$@" +fi +`; + } + else { + sh += `\ +${shProg} ${args} ${shTarget} ${progArgs}"$@" +exit $? +`; } + return sh; } /** - * The default context of the CLI. + * Generate the content of a shim for PowerShell. * - * Contains the stdio of the current `process`. + * @param src Path to the executable or script. + * @param to Path to the shim to be created. + * It is highly recommended to end with `.ps1`. + * @param opts Options. + * @return The content of shim. */ -Cli.defaultContext = { - stdin: process.stdin, - stdout: process.stdout, - stderr: process.stderr, -}; - -exports.Cli = Cli; - +function generatePwshShim(src, to, opts) { + let shTarget = path.relative(path.dirname(to), src); + const shProg = opts.prog && opts.prog.split('\\').join('/'); + let pwshProg = shProg && `"${shProg}$exe"`; + let pwshLongProg; + shTarget = shTarget.split('\\').join('/'); + const quotedPathToTarget = path.isAbsolute(shTarget) ? `"${shTarget}"` : `"$basedir/${shTarget}"`; + let args = opts.args || ''; + let normalizedPathEnvVar = normalizePathEnvVar(opts.nodePath); + const nodePath = normalizedPathEnvVar.win32; + const shNodePath = normalizedPathEnvVar.posix; + if (!pwshProg) { + pwshProg = quotedPathToTarget; + args = ''; + shTarget = ''; + } + else if (opts.prog === 'node' && opts.nodeExecPath) { + pwshProg = `"${opts.nodeExecPath}"`; + shTarget = quotedPathToTarget; + } + else { + pwshLongProg = `"$basedir/${opts.prog}$exe"`; + shTarget = quotedPathToTarget; + } + let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; + // #!/usr/bin/env pwsh + // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + // + // $ret=0 + // $exe = "" + // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + // # Fix case when both the Windows and Linux builds of Node + // # are installed in the same directory + // $exe = ".exe" + // } + // if (Test-Path "$basedir/node") { + // # Support pipeline input + // if ($MyInvocation.ExpectingInput) { + // $input | & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // } else { + // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // } + // $ret=$LASTEXITCODE + // } else { + // # Support pipeline input + // if ($MyInvocation.ExpectingInput) { + // $input | & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // } else { + // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args + // } + // $ret=$LASTEXITCODE + // } + // exit $ret + let pwsh = `\ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +${nodePath ? `\ +$pathsep=":" +$env_node_path=$env:NODE_PATH +$new_node_path="${nodePath}" +` : ''}\ +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +${nodePath ? ' $pathsep=";"\n' : ''}\ +}`; + if (shNodePath) { + pwsh += `\ + else { + $new_node_path="${shNodePath}" +} +if ([string]::IsNullOrEmpty($env_node_path)) { + $env:NODE_PATH=$new_node_path +} else { + $env:NODE_PATH="$env_node_path$pathsep$new_node_path" +} +`; + } + if (pwshLongProg) { + pwsh += ` +$ret=0 +if (Test-Path ${pwshLongProg}) { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & ${pwshLongProg} ${args} ${shTarget} ${progArgs}$args + } else { + & ${pwshLongProg} ${args} ${shTarget} ${progArgs}$args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & ${pwshProg} ${args} ${shTarget} ${progArgs}$args + } else { + & ${pwshProg} ${args} ${shTarget} ${progArgs}$args + } + $ret=$LASTEXITCODE +} +${nodePath ? '$env:NODE_PATH=$env_node_path\n' : ''}\ +exit $ret +`; + } + else { + pwsh += ` +# Support pipeline input +if ($MyInvocation.ExpectingInput) { + $input | & ${pwshProg} ${args} ${shTarget} ${progArgs}$args +} else { + & ${pwshProg} ${args} ${shTarget} ${progArgs}$args +} +${nodePath ? '$env:NODE_PATH=$env_node_path\n' : ''}\ +exit $LASTEXITCODE +`; + } + return pwsh; +} +/** + * Chmod just created shim and make it executable + * + * @param to Path to shim. + */ +function chmodShim(to, opts) { + return opts.fs_.chmod(to, 0o755); +} +function normalizePathEnvVar(nodePath) { + if (!nodePath || !nodePath.length) { + return { + win32: '', + posix: '' + }; + } + let split = (typeof nodePath === 'string' ? nodePath.split(path.delimiter) : Array.from(nodePath)); + let result = {}; + for (let i = 0; i < split.length; i++) { + const win32 = split[i].split('/').join('\\'); + const posix = isWindows() ? split[i].split('\\').join('/').replace(/^([^:\\/]*):/, (_, $1) => `/mnt/${$1.toLowerCase()}`) : split[i]; + result.win32 = result.win32 ? `${result.win32};${win32}` : win32; + result.posix = result.posix ? `${result.posix}:${posix}` : posix; + result[i] = { win32, posix }; + } + return result; +} +module.exports = cmdShim; +//# sourceMappingURL=index.js.map /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js": -/*!*************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js ***! - \*************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/chownr-npm-2.0.0-638f1c9c61-9.zip/node_modules/chownr/chownr.js": +/*!**************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/chownr-npm-2.0.0-638f1c9c61-9.zip/node_modules/chownr/chownr.js ***! + \**************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; +const fs = __webpack_require__(/*! fs */ "fs") +const path = __webpack_require__(/*! path */ "path") -Object.defineProperty(exports, "__esModule", ({ value: true })); +/* istanbul ignore next */ +const LCHOWN = fs.lchown ? 'lchown' : 'chown' +/* istanbul ignore next */ +const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' -var utils = __webpack_require__(/*! ./options/utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); +/* istanbul ignore next */ +const needEISDIRHandled = fs.lchown && + !process.version.match(/v1[1-9]+\./) && + !process.version.match(/v10\.[6-9]/) -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { - return e[k]; - } - }); - } - }); - } - n['default'] = e; - return Object.freeze(n); +const lchownSync = (path, uid, gid) => { + try { + return fs[LCHOWNSYNC](path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } } -class Command { - constructor() { - /** - * Predefined that will be set to true if `-h,--help` has been used, in - * which case `Command#execute` won't be called. - */ - this.help = false; - } - /** - * Defines the usage information for the given command. - */ - static Usage(usage) { - return usage; - } - /** - * Standard error handler which will simply rethrow the error. Can be used - * to add custom logic to handle errors from the command or simply return - * the parent class error handling. - */ - async catch(error) { - throw error; - } - async validateAndExecute() { - const commandClass = this.constructor; - const cascade = commandClass.schema; - if (typeof cascade !== `undefined`) { - const { isDict, isUnknown, applyCascade } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(__webpack_require__(/*! typanion */ "./.yarn/cache/typanion-npm-3.3.1-ee9997c7cf-212d2beb55.zip/node_modules/typanion/lib/index.js")); }); - const schema = applyCascade(isDict(isUnknown()), cascade); - const errors = []; - const coercions = []; - const check = schema(this, { errors, coercions }); - if (!check) - throw utils.formatError(`Invalid option schema`, errors); - for (const [, op] of coercions) { - op(); - } - } - const exitCode = await this.execute(); - if (typeof exitCode !== `undefined`) { - return exitCode; - } - else { - return 0; - } - } +/* istanbul ignore next */ +const chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } } -/** - * Used to detect option definitions. - */ -Command.isOption = utils.isOptionSymbol; -/** - * Just an helper to use along with the `paths` fields, to make it - * clearer that a command is the default one. - * - * @example - * class MyCommand extends Command { - * static paths = [Command.Default]; - * } - */ -Command.Default = []; - -exports.Command = Command; +/* istanbul ignore next */ +const handleEISDIR = + needEISDIRHandled ? (path, uid, gid, cb) => er => { + // Node prior to v10 had a very questionable implementation of + // fs.lchown, which would always try to call fs.open on a directory + // Fall back to fs.chown in those cases. + if (!er || er.code !== 'EISDIR') + cb(er) + else + fs.chown(path, uid, gid, cb) + } + : (_, __, ___, cb) => cb -/***/ }), +/* istanbul ignore next */ +const handleEISDirSync = + needEISDIRHandled ? (path, uid, gid) => { + try { + return lchownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'EISDIR') + throw er + chownSync(path, uid, gid) + } + } + : (path, uid, gid) => lchownSync(path, uid, gid) -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/HelpCommand.js": -/*!*****************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/HelpCommand.js ***! - \*****************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +// fs.readdir could only accept an options object as of node v6 +const nodeVersion = process.version +let readdir = (path, options, cb) => fs.readdir(path, options, cb) +let readdirSync = (path, options) => fs.readdirSync(path, options) +/* istanbul ignore next */ +if (/^v4\./.test(nodeVersion)) + readdir = (path, options, cb) => fs.readdir(path, cb) -"use strict"; +const chown = (cpath, uid, gid, cb) => { + fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { + // Skip ENOENT error + cb(er && er.code !== 'ENOENT' ? er : null) + })) +} +const chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === 'string') + return fs.lstat(path.resolve(p, child), (er, stats) => { + // Skip ENOENT error + if (er) + return cb(er.code !== 'ENOENT' ? er : null) + stats.name = child + chownrKid(p, stats, uid, gid, cb) + }) -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, er => { + if (er) + return cb(er) + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + }) + } else { + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + } +} -var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); -class HelpCommand extends Command.Command { - constructor(contexts) { - super(); - this.contexts = contexts; - this.commands = []; - } - static from(state, contexts) { - const command = new HelpCommand(contexts); - command.path = state.path; - for (const opt of state.options) { - switch (opt.name) { - case `-c`: - { - command.commands.push(Number(opt.value)); - } - break; - case `-i`: - { - command.index = Number(opt.value); - } - break; - } - } - return command; - } - async execute() { - let commands = this.commands; - if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length) - commands = [commands[this.index]]; - if (commands.length === 0) { - this.context.stdout.write(this.cli.usage()); - } - else if (commands.length === 1) { - this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true })); - } - else if (commands.length > 1) { - this.context.stdout.write(`Multiple commands match your selection:\n`); - this.context.stdout.write(`\n`); - let index = 0; - for (const command of this.commands) - this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) })); - this.context.stdout.write(`\n`); - this.context.stdout.write(`Run again with -h= to see the longer details of any of those commands.\n`); - } +const chownr = (p, uid, gid, cb) => { + readdir(p, { withFileTypes: true }, (er, children) => { + // any error other than ENOTDIR or ENOTSUP means it's not readable, + // or doesn't exist. give up. + if (er) { + if (er.code === 'ENOENT') + return cb() + else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') + return cb(er) } -} - -exports.HelpCommand = HelpCommand; + if (er || !children.length) + return chown(p, uid, gid, cb) + let len = children.length + let errState = null + const then = er => { + if (errState) + return + if (er) + return cb(errState = er) + if (-- len === 0) + return chown(p, uid, gid, cb) + } -/***/ }), + children.forEach(child => chownrKid(p, child, uid, gid, then)) + }) +} -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js": -/*!**************************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js ***! - \**************************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +const chownrKidSync = (p, child, uid, gid) => { + if (typeof child === 'string') { + try { + const stats = fs.lstatSync(path.resolve(p, child)) + stats.name = child + child = stats + } catch (er) { + if (er.code === 'ENOENT') + return + else + throw er + } + } -"use strict"; + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid) + handleEISDirSync(path.resolve(p, child.name), uid, gid) +} -Object.defineProperty(exports, "__esModule", ({ value: true })); +const chownrSync = (p, uid, gid) => { + let children + try { + children = readdirSync(p, { withFileTypes: true }) + } catch (er) { + if (er.code === 'ENOENT') + return + else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') + return handleEISDirSync(p, uid, gid) + else + throw er + } -var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); + if (children && children.length) + children.forEach(child => chownrKidSync(p, child, uid, gid)) -/** - * A command that prints the clipanion definitions. - */ -class DefinitionsCommand extends Command.Command { - async execute() { - this.context.stdout.write(`${JSON.stringify(this.cli.definitions(), null, 2)}\n`); - } + return handleEISDirSync(p, uid, gid) } -DefinitionsCommand.paths = [[`--clipanion=definitions`]]; -exports.DefinitionsCommand = DefinitionsCommand; +module.exports = chownr +chownr.sync = chownrSync /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/help.js": -/*!*******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/help.js ***! - \*******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/cmd-extension-npm-1.0.2-11aa204c4b-9.zip/node_modules/cmd-extension/index.js": +/*!***************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/cmd-extension-npm-1.0.2-11aa204c4b-9.zip/node_modules/cmd-extension/index.js ***! + \***************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; +const path = __webpack_require__(/*! path */ "path") -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); +let cmdExtension -/** - * A command that prints the usage of all commands. - * - * Paths: `-h`, `--help` - */ -class HelpCommand extends Command.Command { - async execute() { - this.context.stdout.write(this.cli.usage()); - } +if (process.env.PATHEXT) { + cmdExtension = process.env.PATHEXT + .split(path.delimiter) + .find(ext => ext.toUpperCase() === '.CMD') } -HelpCommand.paths = [[`-h`], [`--help`]]; -exports.HelpCommand = HelpCommand; +module.exports = cmdExtension || '.cmd' /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/index.js": -/*!********************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/index.js ***! - \********************************************************************************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js ***! + \***********************************************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +const MiniPass = __webpack_require__(/*! minipass */ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js") +const EE = (__webpack_require__(/*! events */ "events").EventEmitter) +const fs = __webpack_require__(/*! fs */ "fs") -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var definitions = __webpack_require__(/*! ./definitions.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js"); -var help = __webpack_require__(/*! ./help.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/help.js"); -var version = __webpack_require__(/*! ./version.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/version.js"); - +let writev = fs.writev +/* istanbul ignore next */ +if (!writev) { + // This entire block can be removed if support for earlier than Node.js + // 12.9.0 is not needed. + const binding = process.binding('fs') + const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback + writev = (fd, iovec, pos, cb) => { + const done = (er, bw) => cb(er, bw, iovec) + const req = new FSReqWrap() + req.oncomplete = done + binding.writeBuffers(fd, iovec, pos, req) + } +} -exports.DefinitionsCommand = definitions.DefinitionsCommand; -exports.HelpCommand = help.HelpCommand; -exports.VersionCommand = version.VersionCommand; +const _autoClose = Symbol('_autoClose') +const _close = Symbol('_close') +const _ended = Symbol('_ended') +const _fd = Symbol('_fd') +const _finished = Symbol('_finished') +const _flags = Symbol('_flags') +const _flush = Symbol('_flush') +const _handleChunk = Symbol('_handleChunk') +const _makeBuf = Symbol('_makeBuf') +const _mode = Symbol('_mode') +const _needDrain = Symbol('_needDrain') +const _onerror = Symbol('_onerror') +const _onopen = Symbol('_onopen') +const _onread = Symbol('_onread') +const _onwrite = Symbol('_onwrite') +const _open = Symbol('_open') +const _path = Symbol('_path') +const _pos = Symbol('_pos') +const _queue = Symbol('_queue') +const _read = Symbol('_read') +const _readSize = Symbol('_readSize') +const _reading = Symbol('_reading') +const _remain = Symbol('_remain') +const _size = Symbol('_size') +const _write = Symbol('_write') +const _writing = Symbol('_writing') +const _defaultFlag = Symbol('_defaultFlag') +const _errored = Symbol('_errored') +class ReadStream extends MiniPass { + constructor (path, opt) { + opt = opt || {} + super(opt) -/***/ }), + this.readable = true + this.writable = false -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/version.js": -/*!**********************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/version.js ***! - \**********************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (typeof path !== 'string') + throw new TypeError('path must be a string') -"use strict"; + this[_errored] = false + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_path] = path + this[_readSize] = opt.readSize || 16*1024*1024 + this[_reading] = false + this[_size] = typeof opt.size === 'number' ? opt.size : Infinity + this[_remain] = this[_size] + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true + + if (typeof this[_fd] === 'number') + this[_read]() + else + this[_open]() + } + get fd () { return this[_fd] } + get path () { return this[_path] } -Object.defineProperty(exports, "__esModule", ({ value: true })); + write () { + throw new TypeError('this is a readable stream') + } -var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); + end () { + throw new TypeError('this is a readable stream') + } -/** - * A command that prints the version of the binary (`cli.binaryVersion`). - * - * Paths: `-v`, `--version` - */ -class VersionCommand extends Command.Command { - async execute() { - var _a; - this.context.stdout.write(`${(_a = this.cli.binaryVersion) !== null && _a !== void 0 ? _a : ``}\n`); + [_open] () { + fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) + } + + [_onopen] (er, fd) { + if (er) + this[_onerror](er) + else { + this[_fd] = fd + this.emit('open', fd) + this[_read]() } -} -VersionCommand.paths = [[`-v`], [`--version`]]; + } -exports.VersionCommand = VersionCommand; + [_makeBuf] () { + return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) + } + [_read] () { + if (!this[_reading]) { + this[_reading] = true + const buf = this[_makeBuf]() + /* istanbul ignore if */ + if (buf.length === 0) + return process.nextTick(() => this[_onread](null, 0, buf)) + fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => + this[_onread](er, br, buf)) + } + } -/***/ }), + [_onread] (er, br, buf) { + this[_reading] = false + if (er) + this[_onerror](er) + else if (this[_handleChunk](br, buf)) + this[_read]() + } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js": -/*!***********************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js ***! - \***********************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) + } + } -"use strict"; + [_onerror] (er) { + this[_reading] = true + this[_close]() + this.emit('error', er) + } + [_handleChunk] (br, buf) { + let ret = false + // no effect if infinite + this[_remain] -= br + if (br > 0) + ret = super.write(br < buf.length ? buf.slice(0, br) : buf) -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (br === 0 || this[_remain] <= 0) { + ret = false + this[_close]() + super.end() + } -var errors = __webpack_require__(/*! ../errors.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/errors.js"); -var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Command.js"); -var Cli = __webpack_require__(/*! ./Cli.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/Cli.js"); -var index = __webpack_require__(/*! ./builtins/index.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/builtins/index.js"); -var index$1 = __webpack_require__(/*! ./options/index.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/index.js"); + return ret + } + emit (ev, data) { + switch (ev) { + case 'prefinish': + case 'finish': + break + case 'drain': + if (typeof this[_fd] === 'number') + this[_read]() + break -exports.UsageError = errors.UsageError; -exports.Command = Command.Command; -exports.Cli = Cli.Cli; -exports.Builtins = index; -exports.Option = index$1; + case 'error': + if (this[_errored]) + return + this[_errored] = true + return super.emit(ev, data) + default: + return super.emit(ev, data) + } + } +} -/***/ }), +class ReadStreamSync extends ReadStream { + [_open] () { + let threw = true + try { + this[_onopen](null, fs.openSync(this[_path], 'r')) + threw = false + } finally { + if (threw) + this[_close]() + } + } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Array.js": -/*!*******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Array.js ***! - \*******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + [_read] () { + let threw = true + try { + if (!this[_reading]) { + this[_reading] = true + do { + const buf = this[_makeBuf]() + /* istanbul ignore next */ + const br = buf.length === 0 ? 0 + : fs.readSync(this[_fd], buf, 0, buf.length, null) + if (!this[_handleChunk](br, buf)) + break + } while (true) + this[_reading] = false + } + threw = false + } finally { + if (threw) + this[_close]() + } + } -"use strict"; + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } +} +class WriteStream extends EE { + constructor (path, opt) { + opt = opt || {} + super(opt) + this.readable = false + this.writable = true + this[_errored] = false + this[_writing] = false + this[_ended] = false + this[_needDrain] = false + this[_queue] = [] + this[_path] = path + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_mode] = opt.mode === undefined ? 0o666 : opt.mode + this[_pos] = typeof opt.start === 'number' ? opt.start : null + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true -Object.defineProperty(exports, "__esModule", ({ value: true })); + // truncating makes no sense when writing into the middle + const defaultFlag = this[_pos] !== null ? 'r+' : 'w' + this[_defaultFlag] = opt.flags === undefined + this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); + if (this[_fd] === null) + this[_open]() + } -function Array(descriptor, initialValueBase, optsBase) { - const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); - const { arity = 1 } = opts; - const optNames = descriptor.split(`,`); - const nameSet = new Set(optNames); - return utils.makeCommandOption({ - definition(builder) { - builder.addOption({ - names: optNames, - arity, - hidden: opts === null || opts === void 0 ? void 0 : opts.hidden, - description: opts === null || opts === void 0 ? void 0 : opts.description, - required: opts.required, - }); - }, - transformer(builder, key, state) { - let currentValue = typeof initialValue !== `undefined` - ? [...initialValue] - : undefined; - for (const { name, value } of state.options) { - if (!nameSet.has(name)) - continue; - currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : []; - currentValue.push(value); - } - return currentValue; - }, - }); -} - -exports.Array = Array; + emit (ev, data) { + if (ev === 'error') { + if (this[_errored]) + return + this[_errored] = true + } + return super.emit(ev, data) + } -/***/ }), + get fd () { return this[_fd] } + get path () { return this[_path] } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Boolean.js": -/*!*********************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Boolean.js ***! - \*********************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + [_onerror] (er) { + this[_close]() + this[_writing] = true + this.emit('error', er) + } -"use strict"; + [_open] () { + fs.open(this[_path], this[_flags], this[_mode], + (er, fd) => this[_onopen](er, fd)) + } + [_onopen] (er, fd) { + if (this[_defaultFlag] && + this[_flags] === 'r+' && + er && er.code === 'ENOENT') { + this[_flags] = 'w' + this[_open]() + } else if (er) + this[_onerror](er) + else { + this[_fd] = fd + this.emit('open', fd) + this[_flush]() + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + end (buf, enc) { + if (buf) + this.write(buf, enc) -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); + this[_ended] = true -function Boolean(descriptor, initialValueBase, optsBase) { - const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); - const optNames = descriptor.split(`,`); - const nameSet = new Set(optNames); - return utils.makeCommandOption({ - definition(builder) { - builder.addOption({ - names: optNames, - allowBinding: false, - arity: 0, - hidden: opts.hidden, - description: opts.description, - required: opts.required, - }); - }, - transformer(builer, key, state) { - let currentValue = initialValue; - for (const { name, value } of state.options) { - if (!nameSet.has(name)) - continue; - currentValue = value; - } - return currentValue; - }, - }); -} + // synthetic after-write logic, where drain/finish live + if (!this[_writing] && !this[_queue].length && + typeof this[_fd] === 'number') + this[_onwrite](null, 0) + return this + } -exports.Boolean = Boolean; + write (buf, enc) { + if (typeof buf === 'string') + buf = Buffer.from(buf, enc) + if (this[_ended]) { + this.emit('error', new Error('write() after end()')) + return false + } -/***/ }), + if (this[_fd] === null || this[_writing] || this[_queue].length) { + this[_queue].push(buf) + this[_needDrain] = true + return false + } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Counter.js": -/*!*********************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Counter.js ***! - \*********************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + this[_writing] = true + this[_write](buf) + return true + } -"use strict"; + [_write] (buf) { + fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => + this[_onwrite](er, bw)) + } + [_onwrite] (er, bw) { + if (er) + this[_onerror](er) + else { + if (this[_pos] !== null) + this[_pos] += bw + if (this[_queue].length) + this[_flush]() + else { + this[_writing] = false -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (this[_ended] && !this[_finished]) { + this[_finished] = true + this[_close]() + this.emit('finish') + } else if (this[_needDrain]) { + this[_needDrain] = false + this.emit('drain') + } + } + } + } -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); + [_flush] () { + if (this[_queue].length === 0) { + if (this[_ended]) + this[_onwrite](null, 0) + } else if (this[_queue].length === 1) + this[_write](this[_queue].pop()) + else { + const iovec = this[_queue] + this[_queue] = [] + writev(this[_fd], iovec, this[_pos], + (er, bw) => this[_onwrite](er, bw)) + } + } -function Counter(descriptor, initialValueBase, optsBase) { - const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); - const optNames = descriptor.split(`,`); - const nameSet = new Set(optNames); - return utils.makeCommandOption({ - definition(builder) { - builder.addOption({ - names: optNames, - allowBinding: false, - arity: 0, - hidden: opts.hidden, - description: opts.description, - required: opts.required, - }); - }, - transformer(builder, key, state) { - let currentValue = initialValue; - for (const { name, value } of state.options) { - if (!nameSet.has(name)) - continue; - currentValue !== null && currentValue !== void 0 ? currentValue : (currentValue = 0); - // Negated options reset the counter - if (!value) { - currentValue = 0; - } - else { - currentValue += 1; - } - } - return currentValue; - }, - }); + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) + } + } } -exports.Counter = Counter; +class WriteStreamSync extends WriteStream { + [_open] () { + let fd + // only wrap in a try{} block if we know we'll retry, to avoid + // the rethrow obscuring the error's source frame in most cases. + if (this[_defaultFlag] && this[_flags] === 'r+') { + try { + fd = fs.openSync(this[_path], this[_flags], this[_mode]) + } catch (er) { + if (er.code === 'ENOENT') { + this[_flags] = 'w' + return this[_open]() + } else + throw er + } + } else + fd = fs.openSync(this[_path], this[_flags], this[_mode]) + this[_onopen](null, fd) + } -/***/ }), + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Proxy.js": -/*!*******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Proxy.js ***! - \*******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + [_write] (buf) { + // throw the original, but try to close if it fails + let threw = true + try { + this[_onwrite](null, + fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) + threw = false + } finally { + if (threw) + try { this[_close]() } catch (_) {} + } + } +} -"use strict"; +exports.ReadStream = ReadStream +exports.ReadStreamSync = ReadStreamSync + +exports.WriteStream = WriteStream +exports.WriteStreamSync = WriteStreamSync -Object.defineProperty(exports, "__esModule", ({ value: true })); +/***/ }), -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); +/***/ "../../../.yarn/berry/cache/is-windows-npm-1.0.2-898cd6f3d7-9.zip/node_modules/is-windows/index.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/is-windows-npm-1.0.2-898cd6f3d7-9.zip/node_modules/is-windows/index.js ***! + \*********************************************************************************************************/ +/***/ ((module, exports) => { -/** - * Used to annotate that the command wants to retrieve all trailing - * arguments that cannot be tied to a declared option. - * - * Be careful: this function is order-dependent! Make sure to define it - * after any positional argument you want to declare. - * - * This function is mutually exclusive with Option.Rest. +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! + * is-windows * - * @example - * yarn run foo hello --foo=bar world - * ► proxy = ["hello", "--foo=bar", "world"] + * Copyright © 2015-2018, Jon Schlinkert. + * Released under the MIT License. */ -function Proxy(opts = {}) { - return utils.makeCommandOption({ - definition(builder, key) { - var _a; - builder.addProxy({ - name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, - required: opts.required, - }); - }, - transformer(builder, key, state) { - return state.positionals.map(({ value }) => value); - }, - }); -} -exports.Proxy = Proxy; +(function(factory) { + if (exports && typeof exports === 'object' && "object" !== 'undefined') { + module.exports = factory(); + } else if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(function() { + 'use strict'; + return function isWindows() { + return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); + }; +}); /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Rest.js": -/*!******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Rest.js ***! - \******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/index.js": +/*!***********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/index.js ***! + \***********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +var fs = __webpack_require__(/*! fs */ "fs") +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __webpack_require__(/*! ./windows.js */ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/windows.js") +} else { + core = __webpack_require__(/*! ./mode.js */ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/mode.js") +} +module.exports = isexe +isexe.sync = sync -Object.defineProperty(exports, "__esModule", ({ value: true })); +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); -var core = __webpack_require__(/*! ../../core.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/core.js"); + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } -/** - * Used to annotate that the command supports any number of positional - * arguments. - * - * Be careful: this function is order-dependent! Make sure to define it - * after any positional argument you want to declare. - * - * This function is mutually exclusive with Option.Proxy. - * - * @example - * yarn add hello world - * ► rest = ["hello", "world"] - */ -function Rest(opts = {}) { - return utils.makeCommandOption({ - definition(builder, key) { - var _a; - builder.addRest({ - name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, - required: opts.required, - }); - }, - transformer(builder, key, state) { - // The builder's arity.extra will always be NoLimits, - // because it is set when we call registerDefinition - const isRestPositional = (index) => { - const positional = state.positionals[index]; - // A NoLimits extra (i.e. an optional rest argument) - if (positional.extra === core.NoLimits) - return true; - // A leading positional (i.e. a required rest argument) - if (positional.extra === false && index < builder.arity.leading.length) - return true; - return false; - }; - let count = 0; - while (count < state.positionals.length && isRestPositional(count)) - count += 1; - return state.positionals.splice(0, count).map(({ value }) => value); - }, - }); + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) } -exports.Rest = Rest; +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/String.js": -/*!********************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/String.js ***! - \********************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - +/***/ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/mode.js": +/*!**********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/mode.js ***! + \**********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); +module.exports = isexe +isexe.sync = sync -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); -var core = __webpack_require__(/*! ../../core.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/core.js"); +var fs = __webpack_require__(/*! fs */ "fs") -function StringOption(descriptor, initialValueBase, optsBase) { - const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); - const { arity = 1 } = opts; - const optNames = descriptor.split(`,`); - const nameSet = new Set(optNames); - return utils.makeCommandOption({ - definition(builder) { - builder.addOption({ - names: optNames, - arity: opts.tolerateBoolean ? 0 : arity, - hidden: opts.hidden, - description: opts.description, - required: opts.required, - }); - }, - transformer(builder, key, state) { - let usedName; - let currentValue = initialValue; - for (const { name, value } of state.options) { - if (!nameSet.has(name)) - continue; - usedName = name; - currentValue = value; - } - if (typeof currentValue === `string`) { - return utils.applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator); - } - else { - return currentValue; - } - }, - }); +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) } -function StringPositional(opts = {}) { - const { required = true } = opts; - return utils.makeCommandOption({ - definition(builder, key) { - var _a; - builder.addPositional({ - name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, - required: opts.required, - }); - }, - transformer(builder, key, state) { - var _a; - for (let i = 0; i < state.positionals.length; ++i) { - // We skip NoLimits extras. We only care about - // required and optional finite positionals. - if (state.positionals[i].extra === core.NoLimits) - continue; - // We skip optional positionals when we only - // care about required positionals. - if (required && state.positionals[i].extra === true) - continue; - // We skip required positionals when we only - // care about optional positionals. - if (!required && state.positionals[i].extra === false) - continue; - // We remove the positional from the list - const [positional] = state.positionals.splice(i, 1); - return utils.applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator); - } - return undefined; - }, - }); + +function sync (path, options) { + return checkStat(fs.statSync(path), options) } -// This function is badly typed, but it doesn't matter because the overloads provide the true public typings -function String(descriptor, ...args) { - if (typeof descriptor === `string`) { - return StringOption(descriptor, ...args); - } - else { - return StringPositional(descriptor); - } + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) } -exports.String = String; +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() -/***/ }), + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/index.js": -/*!*******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/index.js ***! - \*******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 -"use strict"; + return ret +} -Object.defineProperty(exports, "__esModule", ({ value: true })); +/***/ }), -var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js"); -var _Array = __webpack_require__(/*! ./Array.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Array.js"); -var _Boolean = __webpack_require__(/*! ./Boolean.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Boolean.js"); -var Counter = __webpack_require__(/*! ./Counter.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Counter.js"); -var _Proxy = __webpack_require__(/*! ./Proxy.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Proxy.js"); -var Rest = __webpack_require__(/*! ./Rest.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/Rest.js"); -var _String = __webpack_require__(/*! ./String.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/String.js"); +/***/ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/windows.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/windows.js ***! + \*************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = isexe +isexe.sync = sync +var fs = __webpack_require__(/*! fs */ "fs") -exports.applyValidator = utils.applyValidator; -exports.cleanValidationError = utils.cleanValidationError; -exports.formatError = utils.formatError; -exports.isOptionSymbol = utils.isOptionSymbol; -exports.makeCommandOption = utils.makeCommandOption; -exports.rerouteArguments = utils.rerouteArguments; -exports.Array = _Array.Array; -exports.Boolean = _Boolean.Boolean; -exports.Counter = Counter.Counter; -exports.Proxy = _Proxy.Proxy; -exports.Rest = Rest.Rest; -exports.String = _String.String; +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js": -/*!*******************************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/options/utils.js ***! - \*******************************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/lru-cache-npm-6.0.0-b4c8668fe1-9.zip/node_modules/lru-cache/index.js": +/*!*******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/lru-cache-npm-6.0.0-b4c8668fe1-9.zip/node_modules/lru-cache/index.js ***! + \*******************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +// A linked list to keep track of recently-used-ness +const Yallist = __webpack_require__(/*! yallist */ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js") -var errors = __webpack_require__(/*! ../../errors.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/errors.js"); +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') -const isOptionSymbol = Symbol(`clipanion/isOption`); -function makeCommandOption(spec) { - // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation. - return { ...spec, [isOptionSymbol]: true }; -} -function rerouteArguments(a, b) { - if (typeof a === `undefined`) - return [a, b]; - if (typeof a === `object` && a !== null && !Array.isArray(a)) { - return [undefined, a]; +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) } - else { - return [a, b]; + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev } -} -function cleanValidationError(message, lowerCase = false) { - let cleaned = message.replace(/^\.: /, ``); - if (lowerCase) - cleaned = cleaned[0].toLowerCase() + cleaned.slice(1); - return cleaned; -} -function formatError(message, errors$1) { - if (errors$1.length === 1) { - return new errors.UsageError(`${message}: ${cleanValidationError(errors$1[0], true)}`); + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next } - else { - return new errors.UsageError(`${message}:\n${errors$1.map(error => `\n- ${cleanValidationError(error)}`).join(``)}`); + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } -} -function applyValidator(name, value, validator) { - if (typeof validator === `undefined`) - return value; - const errors = []; - const coercions = []; - const coercion = (v) => { - const orig = value; - value = v; - return coercion.bind(null, orig); - }; - const check = validator(value, { errors, coercions, coercion }); - if (!check) - throw formatError(`Invalid value for ${name}`, errors); - for (const [, op] of coercions) - op(); - return value; -} -exports.applyValidator = applyValidator; -exports.cleanValidationError = cleanValidationError; -exports.formatError = formatError; -exports.isOptionSymbol = isOptionSymbol; -exports.makeCommandOption = makeCommandOption; -exports.rerouteArguments = rerouteArguments; + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } -/***/ }), + dumpLru () { + return this[LRU_LIST] + } -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/constants.js": -/*!******************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/constants.js ***! - \******************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] -"use strict"; + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } -const NODE_INITIAL = 0; -const NODE_SUCCESS = 1; -const NODE_ERRORED = 2; -const START_OF_INPUT = `\u0001`; -const END_OF_INPUT = `\u0000`; -const HELP_COMMAND_INDEX = -1; -const HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/; -const OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/; -const BATCH_REGEX = /^-[a-zA-Z]{2,}$/; -const BINDING_REGEX = /^([^=]+)=([\s\S]*)$/; -const DEBUG = process.env.DEBUG_CLI === `1`; + const node = this[CACHE].get(key) + const item = node.value -exports.BATCH_REGEX = BATCH_REGEX; -exports.BINDING_REGEX = BINDING_REGEX; -exports.DEBUG = DEBUG; -exports.END_OF_INPUT = END_OF_INPUT; -exports.HELP_COMMAND_INDEX = HELP_COMMAND_INDEX; -exports.HELP_REGEX = HELP_REGEX; -exports.NODE_ERRORED = NODE_ERRORED; -exports.NODE_INITIAL = NODE_INITIAL; -exports.NODE_SUCCESS = NODE_SUCCESS; -exports.OPTION_REGEX = OPTION_REGEX; -exports.START_OF_INPUT = START_OF_INPUT; + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } -/***/ }), + const hit = new Entry(key, value, len, now, maxAge) -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/core.js": -/*!*************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/core.js ***! - \*************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) -"use strict"; + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + get (key) { + return get(this, key, true) + } -var constants = __webpack_require__(/*! ./constants.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/constants.js"); -var errors = __webpack_require__(/*! ./errors.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/errors.js"); + peek (key) { + return get(this, key, false) + } -// ------------------------------------------------------------------------ -function debug(str) { - if (constants.DEBUG) { - console.log(str); + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } } -const basicHelpState = { - candidateUsage: null, - requiredOptions: [], - errorMessage: null, - ignoreOptions: false, - path: [], - positionals: [], - options: [], - remainder: null, - selectedIndex: constants.HELP_COMMAND_INDEX, -}; -function makeStateMachine() { - return { - nodes: [makeNode(), makeNode(), makeNode()], - }; + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } } -function makeAnyOfMachine(inputs) { - const output = makeStateMachine(); - const heads = []; - let offset = output.nodes.length; - for (const input of inputs) { - heads.push(offset); - for (let t = 0; t < input.nodes.length; ++t) - if (!isTerminalNode(t)) - output.nodes.push(cloneNode(input.nodes[t], offset)); - offset += input.nodes.length - 2; + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev } - for (const head of heads) - registerShortcut(output, constants.NODE_INITIAL, head); - return output; + } } -function injectNode(machine, node) { - machine.nodes.push(node); - return machine.nodes.length - 1; + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } } -function simplifyMachine(input) { - const visited = new Set(); - const process = (node) => { - if (visited.has(node)) - return; - visited.add(node); - const nodeDef = input.nodes[node]; - for (const transitions of Object.values(nodeDef.statics)) - for (const { to } of transitions) - process(to); - for (const [, { to }] of nodeDef.dynamics) - process(to); - for (const { to } of nodeDef.shortcuts) - process(to); - const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to)); - while (nodeDef.shortcuts.length > 0) { - const { to } = nodeDef.shortcuts.shift(); - const toDef = input.nodes[to]; - for (const [segment, transitions] of Object.entries(toDef.statics)) { - const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) - ? nodeDef.statics[segment] = [] - : nodeDef.statics[segment]; - for (const transition of transitions) { - if (!store.some(({ to }) => transition.to === to)) { - store.push(transition); - } - } - } - for (const [test, transition] of toDef.dynamics) - if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to)) - nodeDef.dynamics.push([test, transition]); - for (const transition of toDef.shortcuts) { - if (!shortcuts.has(transition.to)) { - nodeDef.shortcuts.push(transition); - shortcuts.add(transition.to); - } - } - } - }; - process(constants.NODE_INITIAL); + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } } -function debugMachine(machine, { prefix = `` } = {}) { - // Don't iterate unless it's needed - if (constants.DEBUG) { - debug(`${prefix}Nodes are:`); - for (let t = 0; t < machine.nodes.length; ++t) { - debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`); - } - } + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) } -function runMachineInternal(machine, input, partial = false) { - debug(`Running a vm on ${JSON.stringify(input)}`); - let branches = [{ node: constants.NODE_INITIAL, state: { - candidateUsage: null, - requiredOptions: [], - errorMessage: null, - ignoreOptions: false, - options: [], - path: [], - positionals: [], - remainder: null, - selectedIndex: null, - } }]; - debugMachine(machine, { prefix: ` ` }); - const tokens = [constants.START_OF_INPUT, ...input]; - for (let t = 0; t < tokens.length; ++t) { - const segment = tokens[t]; - debug(` Processing ${JSON.stringify(segment)}`); - const nextBranches = []; - for (const { node, state } of branches) { - debug(` Current node is ${node}`); - const nodeDef = machine.nodes[node]; - if (node === constants.NODE_ERRORED) { - nextBranches.push({ node, state }); - continue; - } - console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`); - const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment); - if (!partial || t < tokens.length - 1 || hasExactMatch) { - if (hasExactMatch) { - const transitions = nodeDef.statics[segment]; - for (const { to, reducer } of transitions) { - nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); - debug(` Static transition to ${to} found`); - } - } - else { - debug(` No static transition found`); - } - } - else { - let hasMatches = false; - for (const candidate of Object.keys(nodeDef.statics)) { - if (!candidate.startsWith(segment)) - continue; - if (segment === candidate) { - for (const { to, reducer } of nodeDef.statics[candidate]) { - nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); - debug(` Static transition to ${to} found`); - } - } - else { - for (const { to } of nodeDef.statics[candidate]) { - nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } }); - debug(` Static transition to ${to} found (partial match)`); - } - } - hasMatches = true; - } - if (!hasMatches) { - debug(` No partial static transition found`); - } - } - if (segment !== constants.END_OF_INPUT) { - for (const [test, { to, reducer }] of nodeDef.dynamics) { - if (execute(tests, test, state, segment)) { - nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); - debug(` Dynamic transition to ${to} found (via ${test})`); - } - } - } - } - if (nextBranches.length === 0 && segment === constants.END_OF_INPUT && input.length === 1) { - return [{ - node: constants.NODE_INITIAL, - state: basicHelpState, - }]; - } - if (nextBranches.length === 0) { - throw new errors.UnknownSyntaxError(input, branches.filter(({ node }) => { - return node !== constants.NODE_ERRORED; - }).map(({ state }) => { - return { usage: state.candidateUsage, reason: null }; - })); - } - if (nextBranches.every(({ node }) => node === constants.NODE_ERRORED)) { - throw new errors.UnknownSyntaxError(input, nextBranches.map(({ state }) => { - return { usage: state.candidateUsage, reason: state.errorMessage }; - })); - } - branches = trimSmallerBranches(nextBranches); + +module.exports = LRUCache + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js": +/*!*****************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js ***! + \*****************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, +} +const EE = __webpack_require__(/*! events */ "events") +const Stream = __webpack_require__(/*! stream */ "stream") +const Yallist = __webpack_require__(/*! yallist */ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js") +const SD = (__webpack_require__(/*! string_decoder */ "string_decoder").StringDecoder) + +const EOF = Symbol('EOF') +const MAYBE_EMIT_END = Symbol('maybeEmitEnd') +const EMITTED_END = Symbol('emittedEnd') +const EMITTING_END = Symbol('emittingEnd') +const EMITTED_ERROR = Symbol('emittedError') +const CLOSED = Symbol('closed') +const READ = Symbol('read') +const FLUSH = Symbol('flush') +const FLUSHCHUNK = Symbol('flushChunk') +const ENCODING = Symbol('encoding') +const DECODER = Symbol('decoder') +const FLOWING = Symbol('flowing') +const PAUSED = Symbol('paused') +const RESUME = Symbol('resume') +const BUFFERLENGTH = Symbol('bufferLength') +const BUFFERPUSH = Symbol('bufferPush') +const BUFFERSHIFT = Symbol('bufferShift') +const OBJECTMODE = Symbol('objectMode') +const DESTROYED = Symbol('destroyed') + +// TODO remove when Node v8 support drops +const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' +const ASYNCITERATOR = doIter && Symbol.asyncIterator + || Symbol('asyncIterator not implemented') +const ITERATOR = doIter && Symbol.iterator + || Symbol('iterator not implemented') + +// events that mean 'the stream is over' +// these are treated specially, and re-emitted +// if they are listened for after emitting. +const isEndish = ev => + ev === 'end' || + ev === 'finish' || + ev === 'prefinish' + +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 + +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + +module.exports = class Minipass extends Stream { + constructor (options) { + super() + this[FLOWING] = false + // whether we're explicitly paused + this[PAUSED] = false + this.pipes = new Yallist() + this.buffer = new Yallist() + this[OBJECTMODE] = options && options.objectMode || false + if (this[OBJECTMODE]) + this[ENCODING] = null + else + this[ENCODING] = options && options.encoding || null + if (this[ENCODING] === 'buffer') + this[ENCODING] = null + this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null + this[EOF] = false + this[EMITTED_END] = false + this[EMITTING_END] = false + this[CLOSED] = false + this[EMITTED_ERROR] = null + this.writable = true + this.readable = true + this[BUFFERLENGTH] = 0 + this[DESTROYED] = false + } + + get bufferLength () { return this[BUFFERLENGTH] } + + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') + + if (this[ENCODING] && enc !== this[ENCODING] && + (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) + throw new Error('cannot change encoding') + + if (this[ENCODING] !== enc) { + this[DECODER] = enc ? new SD(enc) : null + if (this.buffer.length) + this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } - if (branches.length > 0) { - debug(` Results:`); - for (const branch of branches) { - debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`); - } + + this[ENCODING] = enc + } + + setEncoding (enc) { + this.encoding = enc + } + + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } + + write (chunk, encoding, cb) { + if (this[EOF]) + throw new Error('write after end') + + if (this[DESTROYED]) { + this.emit('error', Object.assign( + new Error('Cannot call write after a stream was destroyed'), + { code: 'ERR_STREAM_DESTROYED' } + )) + return true } - else { - debug(` No results`); + + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + + if (!encoding) + encoding = 'utf8' + + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything else switches us into object mode + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + else if (isArrayBuffer(chunk)) + chunk = Buffer.from(chunk) + else if (typeof chunk !== 'string') + // use the setter so we throw if we have encoding set + this.objectMode = true } - return branches; -} -function checkIfNodeIsFinished(node, state) { - if (state.selectedIndex !== null) - return true; - if (Object.prototype.hasOwnProperty.call(node.statics, constants.END_OF_INPUT)) - for (const { to } of node.statics[constants.END_OF_INPUT]) - if (to === constants.NODE_SUCCESS) - return true; - return false; -} -function suggestMachine(machine, input, partial) { - // If we're accepting partial matches, then exact matches need to be - // prefixed with an extra space. - const prefix = partial && input.length > 0 ? [``] : []; - const branches = runMachineInternal(machine, input, partial); - const suggestions = []; - const suggestionsJson = new Set(); - const traverseSuggestion = (suggestion, node, skipFirst = true) => { - let nextNodes = [node]; - while (nextNodes.length > 0) { - const currentNodes = nextNodes; - nextNodes = []; - for (const node of currentNodes) { - const nodeDef = machine.nodes[node]; - const keys = Object.keys(nodeDef.statics); - // The fact that `key` is unused is likely a bug, but no one has investigated it yet. - // TODO: Investigate it. - // eslint-disable-next-line @typescript-eslint/no-unused-vars - for (const key of Object.keys(nodeDef.statics)) { - const segment = keys[0]; - for (const { to, reducer } of nodeDef.statics[segment]) { - if (reducer !== `pushPath`) - continue; - if (!skipFirst) - suggestion.push(segment); - nextNodes.push(to); - } - } - } - skipFirst = false; - } - const json = JSON.stringify(suggestion); - if (suggestionsJson.has(json)) - return; - suggestions.push(suggestion); - suggestionsJson.add(json); - }; - for (const { node, state } of branches) { - if (state.remainder !== null) { - traverseSuggestion([state.remainder], node); - continue; - } - const nodeDef = machine.nodes[node]; - const isFinished = checkIfNodeIsFinished(nodeDef, state); - for (const [candidate, transitions] of Object.entries(nodeDef.statics)) - if ((isFinished && candidate !== constants.END_OF_INPUT) || (!candidate.startsWith(`-`) && transitions.some(({ reducer }) => reducer === `pushPath`))) - traverseSuggestion([...prefix, candidate], node); - if (!isFinished) - continue; - for (const [test, { to }] of nodeDef.dynamics) { - if (to === constants.NODE_ERRORED) - continue; - const tokens = suggest(test, state); - if (tokens === null) - continue; - for (const token of tokens) { - traverseSuggestion([...prefix, token], node); - } - } + + // this ensures at this point that the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!this.objectMode && !chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + cb() + return this.flowing } - return [...suggestions].sort(); -} -function runMachine(machine, input) { - const branches = runMachineInternal(machine, [...input, constants.END_OF_INPUT]); - return selectBestState(input, branches.map(({ state }) => { - return state; - })); -} -function trimSmallerBranches(branches) { - let maxPathSize = 0; - for (const { state } of branches) - if (state.path.length > maxPathSize) - maxPathSize = state.path.length; - return branches.filter(({ state }) => { - return state.path.length === maxPathSize; - }); -} -function selectBestState(input, states) { - const terminalStates = states.filter(state => { - return state.selectedIndex !== null; - }); - if (terminalStates.length === 0) - throw new Error(); - const requiredOptionsSetStates = terminalStates.filter(state => state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name)))); - if (requiredOptionsSetStates.length === 0) { - throw new errors.UnknownSyntaxError(input, terminalStates.map(state => ({ - usage: state.candidateUsage, - reason: null, - }))); + + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && !this[OBJECTMODE] && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { + chunk = Buffer.from(chunk, encoding) } - let maxPathSize = 0; - for (const state of requiredOptionsSetStates) - if (state.path.length > maxPathSize) - maxPathSize = state.path.length; - const bestPathBranches = requiredOptionsSetStates.filter(state => { - return state.path.length === maxPathSize; - }); - const getPositionalCount = (state) => state.positionals.filter(({ extra }) => { - return !extra; - }).length + state.options.length; - const statesWithPositionalCount = bestPathBranches.map(state => { - return { state, positionalCount: getPositionalCount(state) }; - }); - let maxPositionalCount = 0; - for (const { positionalCount } of statesWithPositionalCount) - if (positionalCount > maxPositionalCount) - maxPositionalCount = positionalCount; - const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => { - return positionalCount === maxPositionalCount; - }).map(({ state }) => { - return state; - }); - const fixedStates = aggregateHelpStates(bestPositionalStates); - if (fixedStates.length > 1) - throw new errors.AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage)); - return fixedStates[0]; -} -function aggregateHelpStates(states) { - const notHelps = []; - const helps = []; - for (const state of states) { - if (state.selectedIndex === constants.HELP_COMMAND_INDEX) { - helps.push(state); - } - else { - notHelps.push(state); - } + + if (Buffer.isBuffer(chunk) && this[ENCODING]) + chunk = this[DECODER].write(chunk) + + if (this.flowing) { + // if we somehow have something in the buffer, but we think we're + // flowing, then we need to flush all that out first, or we get + // chunks coming in out of order. Can't emit 'drain' here though, + // because we're mid-write, so that'd be bad. + if (this[BUFFERLENGTH] !== 0) + this[FLUSH](true) + + // if we are still flowing after flushing the buffer we can emit the + // chunk otherwise we have to buffer it. + this.flowing + ? this.emit('data', chunk) + : this[BUFFERPUSH](chunk) + } else + this[BUFFERPUSH](chunk) + + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + + if (cb) + cb() + + return this.flowing + } + + read (n) { + if (this[DESTROYED]) + return null + + try { + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) + return null + + if (this[OBJECTMODE]) + n = null + + if (this.buffer.length > 1 && !this[OBJECTMODE]) { + if (this.encoding) + this.buffer = new Yallist([ + Array.from(this.buffer).join('') + ]) + else + this.buffer = new Yallist([ + Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) + ]) + } + + return this[READ](n || null, this.buffer.head.value) + } finally { + this[MAYBE_EMIT_END]() } - if (helps.length > 0) { - notHelps.push({ - ...basicHelpState, - path: findCommonPrefix(...helps.map(state => state.path)), - options: helps.reduce((options, state) => options.concat(state.options), []), - }); + } + + [READ] (n, chunk) { + if (n === chunk.length || n === null) + this[BUFFERSHIFT]() + else { + this.buffer.head.value = chunk.slice(n) + chunk = chunk.slice(0, n) + this[BUFFERLENGTH] -= n } - return notHelps; -} -function findCommonPrefix(firstPath, secondPath, ...rest) { - if (secondPath === undefined) - return Array.from(firstPath); - return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest); -} -function makeNode() { - return { - dynamics: [], - shortcuts: [], - statics: {}, - }; -} -function isTerminalNode(node) { - return node === constants.NODE_SUCCESS || node === constants.NODE_ERRORED; -} -function cloneTransition(input, offset = 0) { - return { - to: !isTerminalNode(input.to) ? input.to > 2 ? input.to + offset - 2 : input.to + offset : input.to, - reducer: input.reducer, - }; -} -function cloneNode(input, offset = 0) { - const output = makeNode(); - for (const [test, transition] of input.dynamics) - output.dynamics.push([test, cloneTransition(transition, offset)]); - for (const transition of input.shortcuts) - output.shortcuts.push(cloneTransition(transition, offset)); - for (const [segment, transitions] of Object.entries(input.statics)) - output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset)); - return output; -} -function registerDynamic(machine, from, test, to, reducer) { - machine.nodes[from].dynamics.push([ - test, - { to, reducer: reducer }, - ]); -} -function registerShortcut(machine, from, to, reducer) { - machine.nodes[from].shortcuts.push({ to, reducer: reducer }); -} -function registerStatic(machine, from, test, to, reducer) { - const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) - ? machine.nodes[from].statics[test] = [] - : machine.nodes[from].statics[test]; - store.push({ to, reducer: reducer }); -} -function execute(store, callback, state, segment) { - // TypeScript's control flow can't properly narrow - // generic conditionals for some mysterious reason - if (Array.isArray(callback)) { - const [name, ...args] = callback; - return store[name](state, segment, ...args); + + this.emit('data', chunk) + + if (!this.buffer.length && !this[EOF]) + this.emit('drain') + + return chunk + } + + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + if (cb) + this.once('end', cb) + this[EOF] = true + this.writable = false + + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this.flowing || !this[PAUSED]) + this[MAYBE_EMIT_END]() + return this + } + + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return + + this[PAUSED] = false + this[FLOWING] = true + this.emit('resume') + if (this.buffer.length) + this[FLUSH]() + else if (this[EOF]) + this[MAYBE_EMIT_END]() + else + this.emit('drain') + } + + resume () { + return this[RESUME]() + } + + pause () { + this[FLOWING] = false + this[PAUSED] = true + } + + get destroyed () { + return this[DESTROYED] + } + + get flowing () { + return this[FLOWING] + } + + get paused () { + return this[PAUSED] + } + + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + return this.buffer.push(chunk) + } + + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer.head.value.length } - else { - return store[callback](state, segment); + return this.buffer.shift() + } + + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') + } + + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false + } + + pipe (dest, opts) { + if (this[DESTROYED]) + return + + const ended = this[EMITTED_END] + opts = opts || {} + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false + else + opts.end = opts.end !== false + + const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() } + this.pipes.push(p) + + dest.on('drain', p.ondrain) + this[RESUME]() + // piping an ended stream ends immediately + if (ended && p.opts.end) + p.dest.end() + return dest + } + + addListener (ev, fn) { + return this.on(ev, fn) + } + + on (ev, fn) { + try { + return super.on(ev, fn) + } finally { + if (ev === 'data' && !this.pipes.length && !this.flowing) + this[RESUME]() + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev) + this.removeAllListeners(ev) + } else if (ev === 'error' && this[EMITTED_ERROR]) { + fn.call(this, this[EMITTED_ERROR]) + } } -} -function suggest(callback, state) { - const fn = Array.isArray(callback) - ? tests[callback[0]] - : tests[callback]; - // @ts-ignore - if (typeof fn.suggest === `undefined`) - return null; - const args = Array.isArray(callback) - ? callback.slice(1) - : []; - // @ts-ignore - return fn.suggest(state, ...args); -} -const tests = { - always: () => { - return true; - }, - isOptionLike: (state, segment) => { - return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`)); - }, - isNotOptionLike: (state, segment) => { - return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`); - }, - isOption: (state, segment, name, hidden) => { - return !state.ignoreOptions && segment === name; - }, - isBatchOption: (state, segment, names) => { - return !state.ignoreOptions && constants.BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.includes(`-${name}`)); - }, - isBoundOption: (state, segment, names, options) => { - const optionParsing = segment.match(constants.BINDING_REGEX); - return !state.ignoreOptions && !!optionParsing && constants.OPTION_REGEX.test(optionParsing[1]) && names.includes(optionParsing[1]) - // Disallow bound options with no arguments (i.e. booleans) - && options.filter(opt => opt.names.includes(optionParsing[1])).every(opt => opt.allowBinding); - }, - isNegatedOption: (state, segment, name) => { - return !state.ignoreOptions && segment === `--no-${name.slice(2)}`; - }, - isHelp: (state, segment) => { - return !state.ignoreOptions && constants.HELP_REGEX.test(segment); - }, - isUnsupportedOption: (state, segment, names) => { - return !state.ignoreOptions && segment.startsWith(`-`) && constants.OPTION_REGEX.test(segment) && !names.includes(segment); - }, - isInvalidOption: (state, segment) => { - return !state.ignoreOptions && segment.startsWith(`-`) && !constants.OPTION_REGEX.test(segment); - }, -}; -// @ts-ignore -tests.isOption.suggest = (state, name, hidden = true) => { - return !hidden ? [name] : null; -}; -const reducers = { - setCandidateState: (state, segment, candidateState) => { - return { ...state, ...candidateState }; - }, - setSelectedIndex: (state, segment, index) => { - return { ...state, selectedIndex: index }; - }, - pushBatch: (state, segment) => { - return { ...state, options: state.options.concat([...segment.slice(1)].map(name => ({ name: `-${name}`, value: true }))) }; - }, - pushBound: (state, segment) => { - const [, name, value] = segment.match(constants.BINDING_REGEX); - return { ...state, options: state.options.concat({ name, value }) }; - }, - pushPath: (state, segment) => { - return { ...state, path: state.path.concat(segment) }; - }, - pushPositional: (state, segment) => { - return { ...state, positionals: state.positionals.concat({ value: segment, extra: false }) }; - }, - pushExtra: (state, segment) => { - return { ...state, positionals: state.positionals.concat({ value: segment, extra: true }) }; - }, - pushExtraNoLimits: (state, segment) => { - return { ...state, positionals: state.positionals.concat({ value: segment, extra: NoLimits }) }; - }, - pushTrue: (state, segment, name = segment) => { - return { ...state, options: state.options.concat({ name: segment, value: true }) }; - }, - pushFalse: (state, segment, name = segment) => { - return { ...state, options: state.options.concat({ name, value: false }) }; - }, - pushUndefined: (state, segment) => { - return { ...state, options: state.options.concat({ name: segment, value: undefined }) }; - }, - pushStringValue: (state, segment) => { - var _a; - const copy = { ...state, options: [...state.options] }; - const lastOption = state.options[state.options.length - 1]; - lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]); - return copy; - }, - setStringValue: (state, segment) => { - const copy = { ...state, options: [...state.options] }; - const lastOption = state.options[state.options.length - 1]; - lastOption.value = segment; - return copy; - }, - inhibateOptions: (state) => { - return { ...state, ignoreOptions: true }; - }, - useHelp: (state, segment, command) => { - const [, /* name */ , index] = segment.match(constants.HELP_REGEX); - if (typeof index !== `undefined`) { - return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] }; - } - else { - return { ...state, options: [{ name: `-c`, value: String(command) }] }; - } - }, - setError: (state, segment, errorMessage) => { - if (segment === constants.END_OF_INPUT) { - return { ...state, errorMessage: `${errorMessage}.` }; - } - else { - return { ...state, errorMessage: `${errorMessage} ("${segment}").` }; - } - }, - setOptionArityError: (state, segment) => { - const lastOption = state.options[state.options.length - 1]; - return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` }; - }, -}; -// ------------------------------------------------------------------------ -const NoLimits = Symbol(); -class CommandBuilder { - constructor(cliIndex, cliOpts) { - this.allOptionNames = []; - this.arity = { leading: [], trailing: [], extra: [], proxy: false }; - this.options = []; - this.paths = []; - this.cliIndex = cliIndex; - this.cliOpts = cliOpts; - } - addPath(path) { - this.paths.push(path); - } - setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) { - Object.assign(this.arity, { leading, trailing, extra, proxy }); + } + + get emittedEnd () { + return this[EMITTED_END] + } + + [MAYBE_EMIT_END] () { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this.buffer.length === 0 && + this[EOF]) { + this[EMITTING_END] = true + this.emit('end') + this.emit('prefinish') + this.emit('finish') + if (this[CLOSED]) + this.emit('close') + this[EMITTING_END] = false } - addPositional({ name = `arg`, required = true } = {}) { - if (!required && this.arity.extra === NoLimits) - throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`); - if (!required && this.arity.trailing.length > 0) - throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`); - if (!required && this.arity.extra !== NoLimits) { - this.arity.extra.push(name); - } - else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) { - this.arity.leading.push(name); - } - else { - this.arity.trailing.push(name); + } + + emit (ev, data) { + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) + return + else if (ev === 'data') { + if (!data) + return + + if (this.pipes.length) + this.pipes.forEach(p => + p.dest.write(data) === false && this.pause()) + } else if (ev === 'end') { + // only actual end gets this treatment + if (this[EMITTED_END] === true) + return + + this[EMITTED_END] = true + this.readable = false + + if (this[DECODER]) { + data = this[DECODER].end() + if (data) { + this.pipes.forEach(p => p.dest.write(data)) + super.emit('data', data) } + } + + this.pipes.forEach(p => { + p.dest.removeListener('drain', p.ondrain) + if (p.opts.end) + p.dest.end() + }) + } else if (ev === 'close') { + this[CLOSED] = true + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return + } else if (ev === 'error') { + this[EMITTED_ERROR] = data } - addRest({ name = `arg`, required = 0 } = {}) { - if (this.arity.extra === NoLimits) - throw new Error(`Infinite lists cannot be declared multiple times in the same command`); - if (this.arity.trailing.length > 0) - throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`); - for (let t = 0; t < required; ++t) - this.addPositional({ name }); - this.arity.extra = NoLimits; + + // TODO: replace with a spread operator when Node v4 support drops + const args = new Array(arguments.length) + args[0] = ev + args[1] = data + if (arguments.length > 2) { + for (let i = 2; i < arguments.length; i++) { + args[i] = arguments[i] + } } - addProxy({ required = 0 } = {}) { - this.addRest({ required }); - this.arity.proxy = true; + + try { + return super.emit.apply(this, args) + } finally { + if (!isEndish(ev)) + this[MAYBE_EMIT_END]() + else + this.removeAllListeners(ev) } - addOption({ names, description, arity = 0, hidden = false, required = false, allowBinding = true }) { - if (!allowBinding && arity > 1) - throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`); - if (!Number.isInteger(arity)) - throw new Error(`The arity must be an integer, got ${arity}`); - if (arity < 0) - throw new Error(`The arity must be positive, got ${arity}`); - this.allOptionNames.push(...names); - this.options.push({ names, description, arity, hidden, required, allowBinding }); + } + + // const all = await stream.collect() + collect () { + const buf = [] + if (!this[OBJECTMODE]) + buf.dataLength = 0 + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise() + this.on('data', c => { + buf.push(c) + if (!this[OBJECTMODE]) + buf.dataLength += c.length + }) + return p.then(() => buf) + } + + // const data = await stream.concat() + concat () { + return this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this.collect().then(buf => + this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) + } + + // stream.promise().then(() => done, er => emitted error) + promise () { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))) + this.on('error', er => reject(er)) + this.on('end', () => resolve()) + }) + } + + // for await (let chunk of stream) + [ASYNCITERATOR] () { + const next = () => { + const res = this.read() + if (res !== null) + return Promise.resolve({ done: false, value: res }) + + if (this[EOF]) + return Promise.resolve({ done: true }) + + let resolve = null + let reject = null + const onerr = er => { + this.removeListener('data', ondata) + this.removeListener('end', onend) + reject(er) + } + const ondata = value => { + this.removeListener('error', onerr) + this.removeListener('end', onend) + this.pause() + resolve({ value: value, done: !!this[EOF] }) + } + const onend = () => { + this.removeListener('error', onerr) + this.removeListener('data', ondata) + resolve({ done: true }) + } + const ondestroy = () => onerr(new Error('stream destroyed')) + return new Promise((res, rej) => { + reject = rej + resolve = res + this.once(DESTROYED, ondestroy) + this.once('error', onerr) + this.once('end', onend) + this.once('data', ondata) + }) } - setContext(context) { - this.context = context; + + return { next } + } + + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } } - usage({ detailed = true, inlineOptions = true } = {}) { - const segments = [this.cliOpts.binaryName]; - const detailedOptionList = []; - if (this.paths.length > 0) - segments.push(...this.paths[0]); - if (detailed) { - for (const { names, arity, hidden, description, required } of this.options) { - if (hidden) - continue; - const args = []; - for (let t = 0; t < arity; ++t) - args.push(` #${t}`); - const definition = `${names.join(`,`)}${args.join(``)}`; - if (!inlineOptions && description) { - detailedOptionList.push({ definition, description, required }); - } - else { - segments.push(required ? `<${definition}>` : `[${definition}]`); - } - } - segments.push(...this.arity.leading.map(name => `<${name}>`)); - if (this.arity.extra === NoLimits) - segments.push(`...`); - else - segments.push(...this.arity.extra.map(name => `[${name}]`)); - segments.push(...this.arity.trailing.map(name => `<${name}>`)); - } - const usage = segments.join(` `); - return { usage, options: detailedOptionList }; - } - compile() { - if (typeof this.context === `undefined`) - throw new Error(`Assertion failed: No context attached`); - const machine = makeStateMachine(); - let firstNode = constants.NODE_INITIAL; - const candidateUsage = this.usage().usage; - const requiredOptions = this.options - .filter(opt => opt.required) - .map(opt => opt.names); - firstNode = injectNode(machine, makeNode()); - registerStatic(machine, constants.NODE_INITIAL, constants.START_OF_INPUT, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]); - const positionalArgument = this.arity.proxy - ? `always` - : `isNotOptionLike`; - const paths = this.paths.length > 0 - ? this.paths - : [[]]; - for (const path of paths) { - let lastPathNode = firstNode; - // We allow options to be specified before the path. Note that we - // only do this when there is a path, otherwise there would be - // some redundancy with the options attached later. - if (path.length > 0) { - const optionPathNode = injectNode(machine, makeNode()); - registerShortcut(machine, lastPathNode, optionPathNode); - this.registerOptions(machine, optionPathNode); - lastPathNode = optionPathNode; - } - for (let t = 0; t < path.length; ++t) { - const nextPathNode = injectNode(machine, makeNode()); - registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`); - lastPathNode = nextPathNode; - } - if (this.arity.leading.length > 0 || !this.arity.proxy) { - const helpNode = injectNode(machine, makeNode()); - registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]); - registerStatic(machine, helpNode, constants.END_OF_INPUT, constants.NODE_SUCCESS, [`setSelectedIndex`, constants.HELP_COMMAND_INDEX]); - this.registerOptions(machine, lastPathNode); - } - if (this.arity.leading.length > 0) - registerStatic(machine, lastPathNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); - let lastLeadingNode = lastPathNode; - for (let t = 0; t < this.arity.leading.length; ++t) { - const nextLeadingNode = injectNode(machine, makeNode()); - if (!this.arity.proxy) - this.registerOptions(machine, nextLeadingNode); - if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) - registerStatic(machine, nextLeadingNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); - registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`); - lastLeadingNode = nextLeadingNode; - } - let lastExtraNode = lastLeadingNode; - if (this.arity.extra === NoLimits || this.arity.extra.length > 0) { - const extraShortcutNode = injectNode(machine, makeNode()); - registerShortcut(machine, lastLeadingNode, extraShortcutNode); - if (this.arity.extra === NoLimits) { - const extraNode = injectNode(machine, makeNode()); - if (!this.arity.proxy) - this.registerOptions(machine, extraNode); - registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`); - registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`); - registerShortcut(machine, extraNode, extraShortcutNode); - } - else { - for (let t = 0; t < this.arity.extra.length; ++t) { - const nextExtraNode = injectNode(machine, makeNode()); - if (!this.arity.proxy) - this.registerOptions(machine, nextExtraNode); - registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`); - registerShortcut(machine, nextExtraNode, extraShortcutNode); - lastExtraNode = nextExtraNode; - } - } - lastExtraNode = extraShortcutNode; - } - if (this.arity.trailing.length > 0) - registerStatic(machine, lastExtraNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); - let lastTrailingNode = lastExtraNode; - for (let t = 0; t < this.arity.trailing.length; ++t) { - const nextTrailingNode = injectNode(machine, makeNode()); - if (!this.arity.proxy) - this.registerOptions(machine, nextTrailingNode); - if (t + 1 < this.arity.trailing.length) - registerStatic(machine, nextTrailingNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); - registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`); - lastTrailingNode = nextTrailingNode; - } - registerDynamic(machine, lastTrailingNode, positionalArgument, constants.NODE_ERRORED, [`setError`, `Extraneous positional argument`]); - registerStatic(machine, lastTrailingNode, constants.END_OF_INPUT, constants.NODE_SUCCESS, [`setSelectedIndex`, this.cliIndex]); - } - return { - machine, - context: this.context, - }; - } - registerOptions(machine, node) { - registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`); - registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, `pushBatch`); - registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`); - registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], constants.NODE_ERRORED, [`setError`, `Unsupported option name`]); - registerDynamic(machine, node, [`isInvalidOption`], constants.NODE_ERRORED, [`setError`, `Invalid option name`]); - for (const option of this.options) { - const longestName = option.names.reduce((longestName, name) => { - return name.length > longestName.length ? name : longestName; - }, ``); - if (option.arity === 0) { - for (const name of option.names) { - registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], node, `pushTrue`); - if (name.startsWith(`--`) && !name.startsWith(`--no-`)) { - registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, name]); - } - } - } - else { - // We inject a new node at the end of the state machine - let lastNode = injectNode(machine, makeNode()); - // We register transitions from the starting node to this new node - for (const name of option.names) - registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], lastNode, `pushUndefined`); - // For each argument, we inject a new node at the end and we - // register a transition from the current node to this new node - for (let t = 0; t < option.arity; ++t) { - const nextNode = injectNode(machine, makeNode()); - // We can provide better errors when another option or END_OF_INPUT is encountered - registerStatic(machine, lastNode, constants.END_OF_INPUT, constants.NODE_ERRORED, `setOptionArityError`); - registerDynamic(machine, lastNode, `isOptionLike`, constants.NODE_ERRORED, `setOptionArityError`); - // If the option has a single argument, no need to store it in an array - const action = option.arity === 1 - ? `setStringValue` - : `pushStringValue`; - registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action); - lastNode = nextNode; - } - // In the end, we register a shortcut from - // the last node back to the starting node - registerShortcut(machine, lastNode, node); - } - } - } -} -class CliBuilder { - constructor({ binaryName = `...` } = {}) { - this.builders = []; - this.opts = { binaryName }; - } - static build(cbs, opts = {}) { - return new CliBuilder(opts).commands(cbs).compile(); - } - getBuilderByIndex(n) { - if (!(n >= 0 && n < this.builders.length)) - throw new Error(`Assertion failed: Out-of-bound command index (${n})`); - return this.builders[n]; - } - commands(cbs) { - for (const cb of cbs) - cb(this.command()); - return this; - } - command() { - const builder = new CommandBuilder(this.builders.length, this.opts); - this.builders.push(builder); - return builder; - } - compile() { - const machines = []; - const contexts = []; - for (const builder of this.builders) { - const { machine, context } = builder.compile(); - machines.push(machine); - contexts.push(context); - } - const machine = makeAnyOfMachine(machines); - simplifyMachine(machine); - return { - machine, - contexts, - process: (input) => { - return runMachine(machine, input); - }, - suggest: (input, partial) => { - return suggestMachine(machine, input, partial); - }, - }; + return { next } + } + + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) + return this } -} -exports.CliBuilder = CliBuilder; -exports.CommandBuilder = CommandBuilder; -exports.NoLimits = NoLimits; -exports.aggregateHelpStates = aggregateHelpStates; -exports.cloneNode = cloneNode; -exports.cloneTransition = cloneTransition; -exports.debug = debug; -exports.debugMachine = debugMachine; -exports.execute = execute; -exports.injectNode = injectNode; -exports.isTerminalNode = isTerminalNode; -exports.makeAnyOfMachine = makeAnyOfMachine; -exports.makeNode = makeNode; -exports.makeStateMachine = makeStateMachine; -exports.reducers = reducers; -exports.registerDynamic = registerDynamic; -exports.registerShortcut = registerShortcut; -exports.registerStatic = registerStatic; -exports.runMachineInternal = runMachineInternal; -exports.selectBestState = selectBestState; -exports.simplifyMachine = simplifyMachine; -exports.suggest = suggest; -exports.tests = tests; -exports.trimSmallerBranches = trimSmallerBranches; + this[DESTROYED] = true + // throw away all buffered data, it's never coming out + this.buffer = new Yallist() + this[BUFFERLENGTH] = 0 -/***/ }), + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/errors.js": -/*!***************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/errors.js ***! - \***************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) -"use strict"; + return this + } + static isStream (s) { + return !!s && (s instanceof Minipass || s instanceof Stream || + s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable + )) + } +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var constants = __webpack_require__(/*! ./constants.js */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/constants.js"); +/***/ }), -/** - * A generic usage error with the name `UsageError`. - * - * It should be used over `Error` only when it's the user's fault. - */ -class UsageError extends Error { - constructor(message) { - super(message); - this.clipanion = { type: `usage` }; - this.name = `UsageError`; - } -} -class UnknownSyntaxError extends Error { - constructor(input, candidates) { - super(); - this.input = input; - this.candidates = candidates; - this.clipanion = { type: `none` }; - this.name = `UnknownSyntaxError`; - if (this.candidates.length === 0) { - this.message = `Command not found, but we're not sure what's the alternative.`; - } - else if (this.candidates.every(candidate => candidate.reason !== null && candidate.reason === candidates[0].reason)) { - const [{ reason }] = this.candidates; - this.message = `${reason}\n\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\n`)}`; - } - else if (this.candidates.length === 1) { - const [{ usage }] = this.candidates; - this.message = `Command not found; did you mean:\n\n$ ${usage}\n${whileRunning(input)}`; - } - else { - this.message = `Command not found; did you mean one of:\n\n${this.candidates.map(({ usage }, index) => { - return `${`${index}.`.padStart(4)} ${usage}`; - }).join(`\n`)}\n\n${whileRunning(input)}`; - } - } -} -class AmbiguousSyntaxError extends Error { - constructor(input, usages) { - super(); - this.input = input; - this.usages = usages; - this.clipanion = { type: `none` }; - this.name = `AmbiguousSyntaxError`; - this.message = `Cannot find which to pick amongst the following alternatives:\n\n${this.usages.map((usage, index) => { - return `${`${index}.`.padStart(4)} ${usage}`; - }).join(`\n`)}\n\n${whileRunning(input)}`; - } -} -const whileRunning = (input) => `While running ${input.filter(token => { - return token !== constants.END_OF_INPUT; -}).map(token => { - const json = JSON.stringify(token); - if (token.match(/\s/) || token.length === 0 || json !== `"${token}"`) { - return json; - } - else { - return token; - } -}).join(` `)}`; +/***/ "../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/constants.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/constants.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -exports.AmbiguousSyntaxError = AmbiguousSyntaxError; -exports.UnknownSyntaxError = UnknownSyntaxError; -exports.UsageError = UsageError; +// Update with any zlib constants that are added or changed in the future. +// Node v6 didn't export this, so we just hard code the version and rely +// on all the other hard-coded values from zlib v4736. When node v6 +// support drops, we can just export the realZlibConstants object. +const realZlibConstants = (__webpack_require__(/*! zlib */ "zlib").constants) || + /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } + +module.exports = Object.freeze(Object.assign(Object.create(null), { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + Z_VERSION_ERROR: -6, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + DEFLATE: 1, + INFLATE: 2, + GZIP: 3, + GUNZIP: 4, + DEFLATERAW: 5, + INFLATERAW: 6, + UNZIP: 7, + BROTLI_DECODE: 8, + BROTLI_ENCODE: 9, + Z_MIN_WINDOWBITS: 8, + Z_MAX_WINDOWBITS: 15, + Z_DEFAULT_WINDOWBITS: 15, + Z_MIN_CHUNK: 64, + Z_MAX_CHUNK: Infinity, + Z_DEFAULT_CHUNK: 16384, + Z_MIN_MEMLEVEL: 1, + Z_MAX_MEMLEVEL: 9, + Z_DEFAULT_MEMLEVEL: 8, + Z_MIN_LEVEL: -1, + Z_MAX_LEVEL: 9, + Z_DEFAULT_LEVEL: -1, + BROTLI_OPERATION_PROCESS: 0, + BROTLI_OPERATION_FLUSH: 1, + BROTLI_OPERATION_FINISH: 2, + BROTLI_OPERATION_EMIT_METADATA: 3, + BROTLI_MODE_GENERIC: 0, + BROTLI_MODE_TEXT: 1, + BROTLI_MODE_FONT: 2, + BROTLI_DEFAULT_MODE: 0, + BROTLI_MIN_QUALITY: 0, + BROTLI_MAX_QUALITY: 11, + BROTLI_DEFAULT_QUALITY: 11, + BROTLI_MIN_WINDOW_BITS: 10, + BROTLI_MAX_WINDOW_BITS: 24, + BROTLI_LARGE_MAX_WINDOW_BITS: 30, + BROTLI_DEFAULT_WINDOW: 22, + BROTLI_MIN_INPUT_BLOCK_BITS: 16, + BROTLI_MAX_INPUT_BLOCK_BITS: 24, + BROTLI_PARAM_MODE: 0, + BROTLI_PARAM_QUALITY: 1, + BROTLI_PARAM_LGWIN: 2, + BROTLI_PARAM_LGBLOCK: 3, + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, + BROTLI_PARAM_SIZE_HINT: 5, + BROTLI_PARAM_LARGE_WINDOW: 6, + BROTLI_PARAM_NPOSTFIX: 7, + BROTLI_PARAM_NDIRECT: 8, + BROTLI_DECODER_RESULT_ERROR: 0, + BROTLI_DECODER_RESULT_SUCCESS: 1, + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, + BROTLI_DECODER_NO_ERROR: 0, + BROTLI_DECODER_SUCCESS: 1, + BROTLI_DECODER_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, + BROTLI_DECODER_ERROR_UNREACHABLE: -31, +}, realZlibConstants)) /***/ }), -/***/ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/format.js": -/*!***************************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/format.js ***! - \***************************************************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { +/***/ "../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/index.js": +/*!*****************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/index.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - -const MAX_LINE_LENGTH = 80; -const richLine = Array(MAX_LINE_LENGTH).fill(`━`); -for (let t = 0; t <= 24; ++t) - richLine[richLine.length - t] = `\x1b[38;5;${232 + t}m━`; -const richFormat = { - header: str => `\x1b[1m━━━ ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\x1b[0m`, - bold: str => `\x1b[1m${str}\x1b[22m`, - error: str => `\x1b[31m\x1b[1m${str}\x1b[22m\x1b[39m`, - code: str => `\x1b[36m${str}\x1b[39m`, -}; -const textFormat = { - header: str => str, - bold: str => str, - error: str => str, - code: str => str, -}; -function dedent(text) { - const lines = text.split(`\n`); - const nonEmptyLines = lines.filter(line => line.match(/\S/)); - const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0; - return lines - .map(line => line.slice(indent).trimRight()) - .join(`\n`); -} -function formatMarkdownish(text, { format, paragraphs }) { - // Enforce \n as newline character - text = text.replace(/\r\n?/g, `\n`); - // Remove the indentation, since it got messed up with the JS indentation - text = dedent(text); - // Remove surrounding newlines, since they got added for JS formatting - text = text.replace(/^\n+|\n+$/g, ``); - // List items always end with at least two newlines (in order to not be collapsed) - text = text.replace(/^(\s*)-([^\n]*?)\n+/gm, `$1-$2\n\n`); - // Single newlines are removed; larger than that are collapsed into one - text = text.replace(/\n(\n)?\n*/g, `$1`); - if (paragraphs) { - text = text.split(/\n/).map(paragraph => { - // Does the paragraph starts with a list? - const bulletMatch = paragraph.match(/^\s*[*-][\t ]+(.*)/); - if (!bulletMatch) - // No, cut the paragraphs into segments of 80 characters - return paragraph.match(/(.{1,80})(?: |$)/g).join(`\n`); - const indent = paragraph.length - paragraph.trimStart().length; - // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix) - return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => { - return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line; - }).join(`\n`); - }).join(`\n\n`); - } - // Highlight the code segments - text = text.replace(/(`+)((?:.|[\n])*?)\1/g, ($0, $1, $2) => { - return format.code($1 + $2 + $1); - }); - // Highlight the code segments - text = text.replace(/(\*\*)((?:.|[\n])*?)\1/g, ($0, $1, $2) => { - return format.bold($1 + $2 + $1); - }); - return text ? `${text}\n` : ``; -} +const assert = __webpack_require__(/*! assert */ "assert") +const Buffer = (__webpack_require__(/*! buffer */ "buffer").Buffer) +const realZlib = __webpack_require__(/*! zlib */ "zlib") -exports.formatMarkdownish = formatMarkdownish; -exports.richFormat = richFormat; -exports.textFormat = textFormat; +const constants = exports.constants = __webpack_require__(/*! ./constants.js */ "../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/constants.js") +const Minipass = __webpack_require__(/*! minipass */ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js") +const OriginalBufferConcat = Buffer.concat -/***/ }), +const _superWrite = Symbol('_superWrite') +class ZlibError extends Error { + constructor (err) { + super('zlib: ' + err.message) + this.code = err.code + this.errno = err.errno + /* istanbul ignore if */ + if (!this.code) + this.code = 'ZLIB_ERROR' -/***/ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/browser.js": -/*!****************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/browser.js ***! - \****************************************************************************************************************************************/ -/***/ ((module, exports, __webpack_require__) => { + this.message = 'zlib: ' + err.message + Error.captureStackTrace(this, this.constructor) + } -/* eslint-env browser */ + get name () { + return 'ZlibError' + } +} -/** - * This is the web browser implementation of `debug()`. - */ +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _opts = Symbol('opts') +const _flushFlag = Symbol('flushFlag') +const _finishFlushFlag = Symbol('finishFlushFlag') +const _fullFlushFlag = Symbol('fullFlushFlag') +const _handle = Symbol('handle') +const _onError = Symbol('onError') +const _sawError = Symbol('sawError') +const _level = Symbol('level') +const _strategy = Symbol('strategy') +const _ended = Symbol('ended') +const _defaultFullFlush = Symbol('_defaultFullFlush') -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); +class ZlibBase extends Minipass { + constructor (opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor') -/** - * Colors. - */ + super(opts) + this[_sawError] = false + this[_ended] = false + this[_opts] = opts -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + this[_flushFlag] = opts.flush + this[_finishFlushFlag] = opts.finishFlush + // this will throw if any options are invalid for the class selected + try { + this[_handle] = new realZlib[mode](opts) + } catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er) + } -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + this[_onError] = (err) => { + // no sense raising multiple errors, since we abort on the first one. + if (this[_sawError]) + return -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + this[_sawError] = true - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close() + this.emit('error', err) + } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + this[_handle].on('error', er => this[_onError](new ZlibError(er))) + this.once('end', () => this.close) + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + close () { + if (this[_handle]) { + this[_handle].close() + this[_handle] = null + this.emit('close') + } + } -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + reset () { + if (!this[_sawError]) { + assert(this[_handle], 'zlib binding closed') + return this[_handle].reset() + } + } - if (!this.useColors) { - return; - } + flush (flushFlag) { + if (this.ended) + return - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + if (typeof flushFlag !== 'number') + flushFlag = this[_fullFlushFlag] + this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) + } - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + end (chunk, encoding, cb) { + if (chunk) + this.write(chunk, encoding) + this.flush(this[_finishFlushFlag]) + this[_ended] = true + return super.end(null, null, cb) + } - args.splice(lastC, 0, c); -} + get ended () { + return this[_ended] + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ -function log(...args) { - // This hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return typeof console === 'object' && - console.log && - console.log(...args); -} + write (chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + if (typeof chunk === 'string') + chunk = Buffer.from(chunk, encoding) -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + if (this[_sawError]) + return + assert(this[_handle], 'zlib binding closed') - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + const nativeHandle = this[_handle]._handle + const originalNativeClose = nativeHandle.close + nativeHandle.close = () => {} + const originalClose = this[_handle].close + this[_handle].close = () => {} + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + Buffer.concat = (args) => args + let result + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] : this[_flushFlag] + result = this[_handle]._processChunk(chunk, flushFlag) + // if we don't throw, reset it back how it was + Buffer.concat = OriginalBufferConcat + } catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + Buffer.concat = OriginalBufferConcat + this[_onError](new ZlibError(err)) + } finally { + if (this[_handle]) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + this[_handle]._handle = nativeHandle + nativeHandle.close = originalNativeClose + this[_handle].close = originalClose + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this[_handle].removeAllListeners('error') + // make sure OUR error listener is still attached tho + } + } - return r; -} + if (this[_handle]) + this[_handle].on('error', er => this[_onError](new ZlibError(er))) -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + let writeReturn + if (result) { + if (Array.isArray(result) && result.length > 0) { + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = this[_superWrite](Buffer.from(result[0])) + for (let i = 1; i < result.length; i++) { + writeReturn = this[_superWrite](result[i]) + } + } else { + writeReturn = this[_superWrite](Buffer.from(result)) + } + } -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + if (cb) + cb() + return writeReturn + } -module.exports = __webpack_require__(/*! ./common */ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/common.js")(exports); + [_superWrite] (data) { + return super.write(data) + } +} -const {formatters} = module.exports; +class Zlib extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + opts.flush = opts.flush || constants.Z_NO_FLUSH + opts.finishFlush = opts.finishFlush || constants.Z_FINISH + super(opts, mode) -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; + this[_fullFlushFlag] = constants.Z_FULL_FLUSH + this[_level] = opts.level + this[_strategy] = opts.strategy + } + params (level, strategy) { + if (this[_sawError]) + return -/***/ }), + if (!this[_handle]) + throw new Error('cannot switch params when binding is closed') -/***/ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/common.js": -/*!***************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/common.js ***! - \***************************************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // no way to test this without also not supporting params at all + /* istanbul ignore if */ + if (!this[_handle].params) + throw new Error('not supported in this implementation') + if (this[_level] !== level || this[_strategy] !== strategy) { + this.flush(constants.Z_SYNC_FLUSH) + assert(this[_handle], 'zlib binding closed') + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this[_handle].flush + this[_handle].flush = (flushFlag, cb) => { + this.flush(flushFlag) + cb() + } + try { + this[_handle].params(level, strategy) + } finally { + this[_handle].flush = origFlush + } + /* istanbul ignore else */ + if (this[_handle]) { + this[_level] = level + this[_strategy] = strategy + } + } + } +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ +// minimal 2-byte header +class Deflate extends Zlib { + constructor (opts) { + super(opts, 'Deflate') + } +} -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(/*! ms */ "./.yarn/cache/ms-npm-2.1.2-ec0c1512ff-673cdb2c31.zip/node_modules/ms/index.js"); +class Inflate extends Zlib { + constructor (opts) { + super(opts, 'Inflate') + } +} - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +// gzip - bigger header, same deflate compression +const _portable = Symbol('_portable') +class Gzip extends Zlib { + constructor (opts) { + super(opts, 'Gzip') + this[_portable] = opts && !!opts.portable + } - /** - * Active `debug` instances. - */ - createDebug.instances = []; + [_superWrite] (data) { + if (!this[_portable]) + return super[_superWrite](data) - /** - * The currently active debug mode names, and names to skip. - */ + // we'll always get the header emitted in one first chunk + // overwrite the OS indicator byte with 0xFF + this[_portable] = false + data[9] = 255 + return super[_superWrite](data) + } +} - createDebug.names = []; - createDebug.skips = []; +class Gunzip extends Zlib { + constructor (opts) { + super(opts, 'Gunzip') + } +} - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +// raw - no header +class DeflateRaw extends Zlib { + constructor (opts) { + super(opts, 'DeflateRaw') + } +} - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +class InflateRaw extends Zlib { + constructor (opts) { + super(opts, 'InflateRaw') + } +} - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +// auto-detect header. +class Unzip extends Zlib { + constructor (opts) { + super(opts, 'Unzip') + } +} - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; +class Brotli extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; + opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS + opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + super(opts, mode) - const self = debug; + this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH + } +} - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +class BrotliCompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliCompress') + } +} - args[0] = createDebug.coerce(args[0]); +class BrotliDecompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliDecompress') + } +} - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +exports.Deflate = Deflate +exports.Inflate = Inflate +exports.Gzip = Gzip +exports.Gunzip = Gunzip +exports.DeflateRaw = DeflateRaw +exports.InflateRaw = InflateRaw +exports.Unzip = Unzip +/* istanbul ignore else */ +if (typeof realZlib.BrotliCompress === 'function') { + exports.BrotliCompress = BrotliCompress + exports.BrotliDecompress = BrotliDecompress +} else { + exports.BrotliCompress = exports.BrotliDecompress = class { + constructor () { + throw new Error('Brotli is not supported in this version of Node.js') + } + } +} - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return match; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/***/ }), - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/index.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/index.js ***! + \*************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +const optsArg = __webpack_require__(/*! ./lib/opts-arg.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/opts-arg.js") +const pathArg = __webpack_require__(/*! ./lib/path-arg.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/path-arg.js") - debug.namespace = namespace; - debug.enabled = createDebug.enabled(namespace); - debug.useColors = createDebug.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - debug.extend = extend; - // Debug.formatArgs = formatArgs; - // debug.rawLog = rawLog; +const {mkdirpNative, mkdirpNativeSync} = __webpack_require__(/*! ./lib/mkdirp-native.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-native.js") +const {mkdirpManual, mkdirpManualSync} = __webpack_require__(/*! ./lib/mkdirp-manual.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-manual.js") +const {useNative, useNativeSync} = __webpack_require__(/*! ./lib/use-native.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/use-native.js") - // env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - createDebug.instances.push(debug); +const mkdirp = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNative(opts) + ? mkdirpNative(path, opts) + : mkdirpManual(path, opts) +} - return debug; - } +const mkdirpSync = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNativeSync(opts) + ? mkdirpNativeSync(path, opts) + : mkdirpManualSync(path, opts) +} - function destroy() { - const index = createDebug.instances.indexOf(this); - if (index !== -1) { - createDebug.instances.splice(index, 1); - return true; - } - return false; - } +mkdirp.sync = mkdirpSync +mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) +mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) +mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) +mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +module.exports = mkdirp - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.names = []; - createDebug.skips = []; +/***/ }), - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/find-made.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/find-made.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +const {dirname} = __webpack_require__(/*! path */ "path") - namespaces = split[i].replace(/\*/g, '.*?'); +const findMade = (opts, parent, path = undefined) => { + // we never want the 'made' return value to be a root directory + if (path === parent) + return Promise.resolve() - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } + return opts.statAsync(parent).then( + st => st.isDirectory() ? path : undefined, // will fail later + er => er.code === 'ENOENT' + ? findMade(opts, dirname(parent), parent) + : undefined + ) +} - for (i = 0; i < createDebug.instances.length; i++) { - const instance = createDebug.instances[i]; - instance.enabled = createDebug.enabled(instance.namespace); - } - } +const findMadeSync = (opts, parent, path = undefined) => { + if (path === parent) + return undefined - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + try { + return opts.statSync(parent).isDirectory() ? path : undefined + } catch (er) { + return er.code === 'ENOENT' + ? findMadeSync(opts, dirname(parent), parent) + : undefined + } +} - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } +module.exports = {findMade, findMadeSync} - let i; - let len; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +/***/ }), - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-manual.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-manual.js ***! + \*************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return false; - } +const {dirname} = __webpack_require__(/*! path */ "path") - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +const mkdirpManual = (path, opts, made) => { + opts.recursive = false + const parent = dirname(path) + if (parent === path) { + return opts.mkdirAsync(path, opts).catch(er => { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + }) + } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + return opts.mkdirAsync(path, opts).then(() => made || path, er => { + if (er.code === 'ENOENT') + return mkdirpManual(parent, opts) + .then(made => mkdirpManual(path, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + return opts.statAsync(path).then(st => { + if (st.isDirectory()) + return made + else + throw er + }, () => { throw er }) + }) +} - createDebug.enable(createDebug.load()); +const mkdirpManualSync = (path, opts, made) => { + const parent = dirname(path) + opts.recursive = false - return createDebug; + if (parent === path) { + try { + return opts.mkdirSync(path, opts) + } catch (er) { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + else + return + } + } + + try { + opts.mkdirSync(path, opts) + return made || path + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + try { + if (!opts.statSync(path).isDirectory()) + throw er + } catch (_) { + throw er + } + } } -module.exports = setup; +module.exports = {mkdirpManual, mkdirpManualSync} /***/ }), -/***/ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/index.js": -/*!**************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/index.js ***! - \**************************************************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-native.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-native.js ***! + \*************************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ +const {dirname} = __webpack_require__(/*! path */ "path") +const {findMade, findMadeSync} = __webpack_require__(/*! ./find-made.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/find-made.js") +const {mkdirpManual, mkdirpManualSync} = __webpack_require__(/*! ./mkdirp-manual.js */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/mkdirp-manual.js") -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(/*! ./browser.js */ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/browser.js"); -} else { - module.exports = __webpack_require__(/*! ./node.js */ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/node.js"); +const mkdirpNative = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirAsync(path, opts) + + return findMade(opts, path).then(made => + opts.mkdirAsync(path, opts).then(() => made) + .catch(er => { + if (er.code === 'ENOENT') + return mkdirpManual(path, opts) + else + throw er + })) +} + +const mkdirpNativeSync = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirSync(path, opts) + + const made = findMadeSync(opts, path) + try { + opts.mkdirSync(path, opts) + return made + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts) + else + throw er + } } +module.exports = {mkdirpNative, mkdirpNativeSync} + /***/ }), -/***/ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/node.js": -/*!*************************************************************************************************************************************!*\ - !*** ./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/node.js ***! - \*************************************************************************************************************************************/ -/***/ ((module, exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/opts-arg.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/opts-arg.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Module dependencies. - */ +const { promisify } = __webpack_require__(/*! util */ "util") +const fs = __webpack_require__(/*! fs */ "fs") +const optsArg = opts => { + if (!opts) + opts = { mode: 0o777, fs } + else if (typeof opts === 'object') + opts = { mode: 0o777, fs, ...opts } + else if (typeof opts === 'number') + opts = { mode: opts, fs } + else if (typeof opts === 'string') + opts = { mode: parseInt(opts, 8), fs } + else + throw new TypeError('invalid options argument') -const tty = __webpack_require__(/*! tty */ "tty"); -const util = __webpack_require__(/*! util */ "util"); + opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir + opts.mkdirAsync = promisify(opts.mkdir) + opts.stat = opts.stat || opts.fs.stat || fs.stat + opts.statAsync = promisify(opts.stat) + opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync + opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync + return opts +} +module.exports = optsArg + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/path-arg.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/path-arg.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform +const { resolve, parse } = __webpack_require__(/*! path */ "path") +const pathArg = path => { + if (/\0/.test(path)) { + // simulate same failure that node raises + throw Object.assign( + new TypeError('path must be a string without null bytes'), + { + path, + code: 'ERR_INVALID_ARG_VALUE', + } + ) + } + + path = resolve(path) + if (platform === 'win32') { + const badWinChars = /[*|"<>?:]/ + const {root} = parse(path) + if (badWinChars.test(path.substr(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }) + } + } + + return path +} +module.exports = pathArg + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/use-native.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/lib/use-native.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const fs = __webpack_require__(/*! fs */ "fs") + +const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version +const versArr = version.replace(/^v/, '').split('.') +const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 + +const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir +const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync + +module.exports = {useNative, useNativeSync} + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ms-npm-2.1.2-ec0c1512ff-9.zip/node_modules/ms/index.js": +/*!*****************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ms-npm-2.1.2-ec0c1512ff-9.zip/node_modules/ms/index.js ***! + \*****************************************************************************************/ +/***/ ((module) => { /** - * This is the Node.js implementation of `debug()`. + * Helpers. */ -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; /** - * Colors. + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -exports.colors = [6, 2, 3, 4, 5, 1]; +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(/*! supports-color */ "./.yarn/cache/supports-color-npm-7.1.0-df2ba1e338-899480ac85.zip/node_modules/supports-color/index.js"); +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } /** - * Build up the default `inspectOpts` object from the environment variables. + * Short format for `ms`. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. + * @param {Number} ms + * @return {String} + * @api private */ -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Adds ANSI color escape codes if enabled. + * Long format for `ms`. * - * @api public + * @param {Number} ms + * @return {String} + * @api private */ -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; } /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Pluralization helper. */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +/***/ }), -function load() { - return process.env.DEBUG; -} +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js ***! + \**************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } -function init(debug) { - debug.inspectOpts = {}; + constructor (comp, options) { + options = parseOptions(options) - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } -module.exports = __webpack_require__(/*! ./common */ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/common.js")(exports); + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) -const {formatters} = module.exports; + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } -/** - * Map %o to `util.inspect()`, all on a single line. - */ + debug('comp', this) + } -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .replace(/\s*\n\s*/g, ' '); -}; + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + toString () { + return this.value + } -/***/ }), + test (version) { + debug('Comparator.test', version, this.options.loose) -/***/ "./sources/Engine.ts": -/*!***************************!*\ - !*** ./sources/Engine.ts ***! - \***************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + if (this.semver === ANY || version === ANY) { + return true + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Engine": () => (/* binding */ Engine) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js"); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _config_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.json */ "./config.json"); -/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./folderUtils */ "./sources/folderUtils.ts"); -/* harmony import */ var _corepackUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./corepackUtils */ "./sources/corepackUtils.ts"); -/* harmony import */ var _semverUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./semverUtils */ "./sources/semverUtils.ts"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./sources/types.ts"); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false, + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} +module.exports = Comparator +const parseOptions = __webpack_require__(/*! ../internal/parse-options */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js") +const { re, t } = __webpack_require__(/*! ../internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") +const cmp = __webpack_require__(/*! ../functions/cmp */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/cmp.js") +const debug = __webpack_require__(/*! ../internal/debug */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js") +const SemVer = __webpack_require__(/*! ./semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const Range = __webpack_require__(/*! ./range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +/***/ }), +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) -class Engine { - constructor(config = _config_json__WEBPACK_IMPORTED_MODULE_3__) { - this.config = config; - } - getPackageManagerFor(binaryName) { - for (const packageManager of _types__WEBPACK_IMPORTED_MODULE_7__.SupportedPackageManagerSet) { - for (const rangeDefinition of Object.values(this.config.definitions[packageManager].ranges)) { - const bins = Array.isArray(rangeDefinition.bin) - ? rangeDefinition.bin - : Object.keys(rangeDefinition.bin); - if (bins.includes(binaryName)) { - return packageManager; - } - } - } - return null; + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } } - getBinariesFor(name) { - const binNames = new Set(); - for (const rangeDefinition of Object.values(this.config.definitions[name].ranges)) { - const bins = Array.isArray(rangeDefinition.bin) - ? rangeDefinition.bin - : Object.keys(rangeDefinition.bin); - for (const name of bins) { - binNames.add(name); - } - } - return binNames; + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this } - async getDefaultDescriptors() { - const locators = []; - for (const name of _types__WEBPACK_IMPORTED_MODULE_7__.SupportedPackageManagerSet) - locators.push({ name, range: await this.getDefaultVersion(name) }); - return locators; + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) } - async getDefaultVersion(packageManager) { - const definition = this.config.definitions[packageManager]; - if (typeof definition === `undefined`) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${packageManager}) isn't supported by this corepack build`); - let lastKnownGood; - try { - lastKnownGood = JSON.parse(await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(this.getLastKnownGoodFile(), `utf8`)); - } - catch (_a) { - // Ignore errors; too bad + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } } - if (typeof lastKnownGood !== `object` || lastKnownGood === null) - return definition.default; - if (!Object.prototype.hasOwnProperty.call(lastKnownGood, packageManager)) - return definition.default; - const override = lastKnownGood[packageManager]; - if (typeof override !== `string`) - return definition.default; - return override; + } } - async activatePackageManager(locator) { - const lastKnownGoodFile = this.getLastKnownGoodFile(); - let lastKnownGood; - try { - lastKnownGood = JSON.parse(await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(lastKnownGoodFile, `utf8`)); - } - catch (_a) { - // Ignore errors; too bad - } - if (typeof lastKnownGood !== `object` || lastKnownGood === null) - lastKnownGood = {}; - lastKnownGood[locator.name] = locator.reference; - await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.mkdir(path__WEBPACK_IMPORTED_MODULE_1___default().dirname(lastKnownGoodFile), { recursive: true }); - await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.writeFile(lastKnownGoodFile, `${JSON.stringify(lastKnownGood, null, 2)}\n`); - } - async ensurePackageManager(locator) { - const definition = this.config.definitions[locator.name]; - if (typeof definition === `undefined`) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${locator.name}) isn't supported by this corepack build`); - const ranges = Object.keys(definition.ranges).reverse(); - const range = ranges.find(range => _semverUtils__WEBPACK_IMPORTED_MODULE_6__.satisfiesWithPrereleases(locator.reference, range)); - if (typeof range === `undefined`) - throw new Error(`Assertion failed: Specified resolution (${locator.reference}) isn't supported by any of ${ranges.join(`, `)}`); - const installedLocation = await _corepackUtils__WEBPACK_IMPORTED_MODULE_5__.installVersion(_folderUtils__WEBPACK_IMPORTED_MODULE_4__.getInstallFolder(), locator, { - spec: definition.ranges[range], - }); - return { - location: installedLocation, - spec: definition.ranges[range], - }; - } - async resolveDescriptor(descriptor, { allowTags = false, useCache = true } = {}) { - const definition = this.config.definitions[descriptor.name]; - if (typeof definition === `undefined`) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${descriptor.name}) isn't supported by this corepack build`); - let finalDescriptor = descriptor; - if (descriptor.range.match(/^[a-z-]+$/)) { - if (!allowTags) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Packages managers can't be referended via tags in this context`); - // We only resolve tags from the latest registry entry - const ranges = Object.keys(definition.ranges); - const tagRange = ranges[ranges.length - 1]; - const tags = await _corepackUtils__WEBPACK_IMPORTED_MODULE_5__.fetchAvailableTags(definition.ranges[tagRange].registry); - if (!Object.prototype.hasOwnProperty.call(tags, descriptor.range)) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Tag not found (${descriptor.range})`); - finalDescriptor = { - name: descriptor.name, - range: tags[descriptor.range], - }; - } - // If a compatible version is already installed, no need to query one - // from the remote listings - const cachedVersion = await _corepackUtils__WEBPACK_IMPORTED_MODULE_5__.findInstalledVersion(_folderUtils__WEBPACK_IMPORTED_MODULE_4__.getInstallFolder(), finalDescriptor); - if (cachedVersion !== null && useCache) - return { name: finalDescriptor.name, reference: cachedVersion }; - const candidateRangeDefinitions = Object.keys(definition.ranges).filter(range => { - return _semverUtils__WEBPACK_IMPORTED_MODULE_6__.satisfiesWithPrereleases(finalDescriptor.range, range); - }); - const tagResolutions = await Promise.all(candidateRangeDefinitions.map(async (range) => { - return [range, await _corepackUtils__WEBPACK_IMPORTED_MODULE_5__.fetchAvailableVersions(definition.ranges[range].registry)]; - })); - // If a version is available under multiple strategies (for example if - // Yarn is published to both the v1 package and git), we only care - // about the latest one - const resolutionMap = new Map(); - for (const [range, resolutions] of tagResolutions) - for (const entry of resolutions) - resolutionMap.set(entry, range); - const candidates = [...resolutionMap.keys()]; - const maxSatisfying = semver__WEBPACK_IMPORTED_MODULE_2___default().maxSatisfying(candidates, finalDescriptor.range); - if (maxSatisfying === null) - return null; - return { name: finalDescriptor.name, reference: maxSatisfying }; - } - getLastKnownGoodFile() { - return path__WEBPACK_IMPORTED_MODULE_1___default().join(_folderUtils__WEBPACK_IMPORTED_MODULE_4__.getInstallFolder(), `lastKnownGood.json`); - } -} + this.format() + } -/***/ }), - -/***/ "./sources/commands/Disable.ts": -/*!*************************************!*\ - !*** ./sources/commands/Disable.ts ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DisableCommand": () => (/* binding */ DisableCommand) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! which */ "./.yarn/cache/which-npm-2.0.2-320ddf72f7-1a5c563d3c.zip/node_modules/which/which.js"); -/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(which__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + toString () { + return this.range + } + parseRange (range) { + range = range.trim() + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(',') + const memoKey = `parseRange:${memoOpts}:${range}` + const cached = cache.get(memoKey) + if (cached) { + return cached + } + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) -class DisableCommand extends clipanion__WEBPACK_IMPORTED_MODULE_4__.Command { - constructor() { - super(...arguments); - this.installDirectory = clipanion__WEBPACK_IMPORTED_MODULE_4__.Option.String(`--install-directory`, { - description: `Where the shims are located`, - }); - this.names = clipanion__WEBPACK_IMPORTED_MODULE_4__.Option.Rest(); - } - async execute() { - let installDirectory = this.installDirectory; - // Node always call realpath on the module it executes, so we already - // lost track of how the binary got called. To find it back, we need to - // iterate over the PATH variable. - if (typeof installDirectory === `undefined`) - installDirectory = path__WEBPACK_IMPORTED_MODULE_1___default().dirname(await which__WEBPACK_IMPORTED_MODULE_2___default()(`corepack`)); - const names = this.names.length === 0 - ? _types__WEBPACK_IMPORTED_MODULE_3__.SupportedPackageManagerSetWithoutNpm - : this.names; - for (const name of new Set(names)) { - if (!(0,_types__WEBPACK_IMPORTED_MODULE_3__.isSupportedPackageManager)(name)) - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager name '${name}'`); - for (const binName of this.context.engine.getBinariesFor(name)) { - if (process.platform === `win32`) { - await this.removeWin32Link(installDirectory, binName); - } - else { - await this.removePosixLink(installDirectory, binName); - } - } - } - } - async removePosixLink(installDirectory, binName) { - const file = path__WEBPACK_IMPORTED_MODULE_1___default().join(installDirectory, binName); - try { - await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.unlink(file); - } - catch (err) { - if (err.code !== `ENOENT`) { - throw err; - } - } - } - async removeWin32Link(installDirectory, binName) { - for (const ext of [``, `.ps1`, `.cmd`]) { - const file = path__WEBPACK_IMPORTED_MODULE_1___default().join(installDirectory, `${binName}${ext}`); - try { - await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.unlink(file); - } - catch (err) { - if (err.code !== `ENOENT`) { - throw err; - } - } - } - } -} -DisableCommand.paths = [ - [`disable`], -]; -DisableCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_4__.Command.Usage({ - description: `Remove the Corepack shims from the install directory`, - details: ` - When run, this command will remove the shims for the specified package managers from the install directory, or all shims if no parameters are passed. + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--bin-folder\` flag. - `, - examples: [[ - `Disable all shims, removing them if they're next to the \`coreshim\` binary`, - `$0 disable`, - ], [ - `Disable all shims, removing them from the specified directory`, - `$0 disable --install-directory /path/to/bin`, - ], [ - `Disable the Yarn shim only`, - `$0 disable yarn`, - ]], -}); + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + // normalize spaces + range = range.split(/\s+/).join(' ') -/***/ }), + // At this point, the range is completely trimmed and + // ready to be split into comparators. -/***/ "./sources/commands/Enable.ts": -/*!************************************!*\ - !*** ./sources/commands/Enable.ts ***! - \************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "EnableCommand": () => (/* binding */ EnableCommand) -/* harmony export */ }); -/* harmony import */ var _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @zkochan/cmd-shim */ "./.yarn/cache/@zkochan-cmd-shim-npm-5.0.0-9e90407ba0-ace99c7c36.zip/node_modules/@zkochan/cmd-shim/index.js"); -/* harmony import */ var _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! which */ "./.yarn/cache/which-npm-2.0.2-320ddf72f7-1a5c563d3c.zip/node_modules/which/which.js"); -/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(which__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } -class EnableCommand extends clipanion__WEBPACK_IMPORTED_MODULE_5__.Command { - constructor() { - super(...arguments); - this.installDirectory = clipanion__WEBPACK_IMPORTED_MODULE_5__.Option.String(`--install-directory`, { - description: `Where the shims are to be installed`, - }); - this.names = clipanion__WEBPACK_IMPORTED_MODULE_5__.Option.Rest(); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } } - async execute() { - let installDirectory = this.installDirectory; - // Node always call realpath on the module it executes, so we already - // lost track of how the binary got called. To find it back, we need to - // iterate over the PATH variable. - if (typeof installDirectory === `undefined`) - installDirectory = path__WEBPACK_IMPORTED_MODULE_2___default().dirname(await which__WEBPACK_IMPORTED_MODULE_3___default()(`corepack`)); - // Otherwise the relative symlink we'll compute will be incorrect, if the - // install directory is within a symlink - installDirectory = fs__WEBPACK_IMPORTED_MODULE_1___default().realpathSync(installDirectory); - // We use `eval` so that Webpack doesn't statically transform it. - const manifestPath = eval(`require`).resolve(`corepack/package.json`); - const distFolder = path__WEBPACK_IMPORTED_MODULE_2___default().join(path__WEBPACK_IMPORTED_MODULE_2___default().dirname(manifestPath), `dist`); - if (!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(distFolder)) - throw new Error(`Assertion failed: The stub folder doesn't exist`); - const names = this.names.length === 0 - ? _types__WEBPACK_IMPORTED_MODULE_4__.SupportedPackageManagerSetWithoutNpm - : this.names; - for (const name of new Set(names)) { - if (!(0,_types__WEBPACK_IMPORTED_MODULE_4__.isSupportedPackageManager)(name)) - throw new clipanion__WEBPACK_IMPORTED_MODULE_5__.UsageError(`Invalid package manager name '${name}'`); - for (const binName of this.context.engine.getBinariesFor(name)) { - if (process.platform === `win32`) { - await this.generateWin32Link(installDirectory, distFolder, binName); - } - else { - await this.generatePosixLink(installDirectory, distFolder, binName); - } - } - } - } - async generatePosixLink(installDirectory, distFolder, binName) { - const file = path__WEBPACK_IMPORTED_MODULE_2___default().join(installDirectory, binName); - const symlink = path__WEBPACK_IMPORTED_MODULE_2___default().relative(installDirectory, path__WEBPACK_IMPORTED_MODULE_2___default().join(distFolder, `${binName}.js`)); - if (fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(file)) { - const currentSymlink = await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.readlink(file); - if (currentSymlink !== symlink) { - await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.unlink(file); - } - else { - return; - } - } - await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.symlink(symlink, file); - } - async generateWin32Link(installDirectory, distFolder, binName) { - const file = path__WEBPACK_IMPORTED_MODULE_2___default().join(installDirectory, binName); - await _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0___default()(path__WEBPACK_IMPORTED_MODULE_2___default().join(distFolder, `${binName}.js`), file, { - createCmdFile: true, - }); + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } } + return false + } } -EnableCommand.paths = [ - [`enable`], -]; -EnableCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_5__.Command.Usage({ - description: `Add the Corepack shims to the install directories`, - details: ` - When run, this commmand will check whether the shims for the specified package managers can be found with the correct values inside the install directory. If not, or if they don't exist, they will be created. - - By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--bin-folder\` flag. - `, - examples: [[ - `Enable all shims, putting them next to the \`corepath\` binary`, - `$0 enable`, - ], [ - `Enable all shims, putting them in the specified directory`, - `$0 enable --install-directory /path/to/folder`, - ], [ - `Enable the Yarn shim only`, - `$0 enable yarn`, - ]], -}); +module.exports = Range +const LRU = __webpack_require__(/*! lru-cache */ "../../../.yarn/berry/cache/lru-cache-npm-6.0.0-b4c8668fe1-9.zip/node_modules/lru-cache/index.js") +const cache = new LRU({ max: 1000 }) -/***/ }), +const parseOptions = __webpack_require__(/*! ../internal/parse-options */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js") +const Comparator = __webpack_require__(/*! ./comparator */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js") +const debug = __webpack_require__(/*! ../internal/debug */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js") +const SemVer = __webpack_require__(/*! ./semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __webpack_require__(/*! ../internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") -/***/ "./sources/commands/Hydrate.ts": -/*!*************************************!*\ - !*** ./sources/commands/Hydrate.ts ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "HydrateCommand": () => (/* binding */ HydrateCommand) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../folderUtils */ "./sources/folderUtils.ts"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + testComparator = remainingComparators.pop() + } + return result +} -class HydrateCommand extends clipanion__WEBPACK_IMPORTED_MODULE_3__.Command { - constructor() { - super(...arguments); - this.activate = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--activate`, false, { - description: `If true, this release will become the default one for this package manager`, - }); - this.fileName = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.String(); - } - async execute() { - const installFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_1__.getInstallFolder(); - const fileName = path__WEBPACK_IMPORTED_MODULE_0___default().resolve(this.context.cwd, this.fileName); - const archiveEntries = new Map(); - let hasShortEntries = false; - const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/index.js", 19)); - await tar.t({ file: fileName, onentry: entry => { - const segments = entry.header.path.split(/\//g); - if (segments.length < 3) { - hasShortEntries = true; - } - else { - let references = archiveEntries.get(segments[0]); - if (typeof references === `undefined`) - archiveEntries.set(segments[0], references = new Set()); - references.add(segments[1]); - } - } }); - if (hasShortEntries || archiveEntries.size < 1) - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Invalid archive format; did it get generated by 'corepack prepare'?`); - for (const [name, references] of archiveEntries) { - for (const reference of references) { - if (!(0,_types__WEBPACK_IMPORTED_MODULE_2__.isSupportedPackageManager)(name)) - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Unsupported package manager '${name}'`); - if (this.activate) - this.context.stdout.write(`Hydrating ${name}@${reference} for immediate activation...\n`); - else - this.context.stdout.write(`Hydrating ${name}@${reference}...\n`); - await tar.x({ file: fileName, cwd: installFolder }, [`${name}/${reference}`]); - if (this.activate) { - await this.context.engine.activatePackageManager({ name, reference }); - } - } - } - this.context.stdout.write(`All done!\n`); - } +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp } -HydrateCommand.paths = [ - [`hydrate`], -]; -HydrateCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_3__.Command.Usage({ - description: `Import a package manager into the cache`, - details: ` - This command unpacks a package manager archive into the cache. The archive must have been generated by the \`corepack prepare\` command - no other will work. - `, - examples: [[ - `Import a package manager in the cache`, - `$0 hydrate corepack.tgz`, - ]], -}); +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' -/***/ }), +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceTilde(c, options) + }).join(' ') -/***/ "./sources/commands/Prepare.ts": -/*!*************************************!*\ - !*** ./sources/commands/Prepare.ts ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "PrepareCommand": () => (/* binding */ PrepareCommand) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../folderUtils */ "./sources/folderUtils.ts"); -/* harmony import */ var _specUtils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../specUtils */ "./sources/specUtils.ts"); + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + debug('tilde return', ret) + return ret + }) +} +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceCaret(c, options) + }).join(' ') +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret -class PrepareCommand extends clipanion__WEBPACK_IMPORTED_MODULE_3__.Command { - constructor() { - super(...arguments); - this.activate = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--activate`, false, { - description: `If true, this release will become the default one for this package manager`, - }); - this.all = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--all`, false, { - description: `If true, all available default package managers will be installed`, - }); - this.json = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--json`, false, { - description: `If true, the output will be the path of the generated tarball`, - }); - this.output = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.String(`-o,--output`, { - description: `If true, the installed package managers will also be stored in a tarball`, - tolerateBoolean: true, - }); - this.specs = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Rest(); - } - async execute() { - if (this.all && this.specs.length > 0) - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`The --all option cannot be used along with an explicit package manager specification`); - const specs = this.all - ? await this.context.engine.getDefaultDescriptors() - : this.specs; - const installLocations = []; - for (const request of specs) { - let spec; - if (typeof request === `undefined`) { - const lookup = await _specUtils__WEBPACK_IMPORTED_MODULE_2__.loadSpec(this.context.cwd); - switch (lookup.type) { - case `NoProject`: - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Couldn't find a project in the local directory - please explicit the package manager to pack, or run this command from a valid project`); - case `NoSpec`: - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`The local project doesn't feature a 'packageManager' field - please explicit the package manager to pack, or update the manifest to reference it`); - default: { - spec = lookup.spec; - } - } - } - else { - spec = typeof request === `string` - ? _specUtils__WEBPACK_IMPORTED_MODULE_2__.parseSpec(request, `CLI arguments`) - : request; - } - const resolved = await this.context.engine.resolveDescriptor(spec); - if (resolved === null) - throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Failed to successfully resolve '${spec.range}' to a valid ${spec.name} release`); - if (!this.json) { - if (this.activate) { - this.context.stdout.write(`Preparing ${spec.name}@${spec.range} for immediate activation...\n`); - } - else { - this.context.stdout.write(`Preparing ${spec.name}@${spec.range}...\n`); - } - } - const installSpec = await this.context.engine.ensurePackageManager(resolved); - installLocations.push(installSpec.location); - if (this.activate) { - await this.context.engine.activatePackageManager(resolved); - } + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` } - if (this.output) { - const outputName = typeof this.output === `string` - ? this.output - : `corepack.tgz`; - const baseInstallFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_1__.getInstallFolder(); - const outputPath = path__WEBPACK_IMPORTED_MODULE_0___default().resolve(this.context.cwd, outputName); - if (!this.json) - this.context.stdout.write(`Packing the selected tools in ${path__WEBPACK_IMPORTED_MODULE_0___default().basename(outputPath)}...\n`); - const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/index.js", 19)); - await tar.c({ gzip: true, cwd: baseInstallFolder, file: path__WEBPACK_IMPORTED_MODULE_0___default().resolve(outputPath) }, installLocations.map(location => { - return path__WEBPACK_IMPORTED_MODULE_0___default().relative(baseInstallFolder, location); - })); - if (this.json) { - this.context.stdout.write(`${JSON.stringify(outputPath)}\n`); - } - else { - this.context.stdout.write(`All done!\n`); - } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } } + + debug('caret return', ret) + return ret + }) } -PrepareCommand.paths = [ - [`prepare`], -]; -PrepareCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_3__.Command.Usage({ - description: `Generate a package manager archive`, - details: ` - This command makes sure that the specified package managers are installed in the local cache. Calling this command explicitly unless you operate in an environment without network access (in which case you'd have to call \`prepare\` while building your image, to make sure all tools are available for later use). - When the \`-o,--output\` flag is set, Corepack will also compress the resulting package manager into a format suitable for \`corepack hydrate\`, and will store it at the specified location on the disk. - `, - examples: [[ - `Prepare the package manager from the active project`, - `$0 prepare`, - ], [ - `Prepare a specific Yarn version`, - `$0 prepare yarn@2.2.2`, - ], [ - `Generate an archive for a specific Yarn version`, - `$0 prepare yarn@2.2.2 -o`, - ], [ - `Generate a named archive`, - `$0 prepare yarn@2.2.2 --output=yarn.tgz`, - ]], -}); +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((c) => { + return replaceXRange(c, options) + }).join(' ') +} +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp -/***/ }), + if (gtlt === '=' && anyX) { + gtlt = '' + } -/***/ "./sources/corepackUtils.ts": -/*!**********************************!*\ - !*** ./sources/corepackUtils.ts ***! - \**********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "fetchAvailableTags": () => (/* binding */ fetchAvailableTags), -/* harmony export */ "fetchAvailableVersions": () => (/* binding */ fetchAvailableVersions), -/* harmony export */ "findInstalledVersion": () => (/* binding */ findInstalledVersion), -/* harmony export */ "installVersion": () => (/* binding */ installVersion), -/* harmony export */ "runVersion": () => (/* binding */ runVersion) -/* harmony export */ }); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! child_process */ "child_process"); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js"); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _debugUtils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./debugUtils */ "./sources/debugUtils.ts"); -/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./folderUtils */ "./sources/folderUtils.ts"); -/* harmony import */ var _fsUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fsUtils */ "./sources/fsUtils.ts"); -/* harmony import */ var _httpUtils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./httpUtils */ "./sources/httpUtils.ts"); + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + if (gtlt === '<') { + pr = '-0' + } + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + debug('xRange return', ret) + return ret + }) +} +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} -async function fetchAvailableTags(spec) { - switch (spec.type) { - case `npm`: { - const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_7__.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, { headers: { [`Accept`]: `application/vnd.npm.install-v1+json` } }); - return data[`dist-tags`]; - } - case `url`: { - const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_7__.fetchAsJson(spec.url); - return data[spec.fields.tags]; - } - default: { - throw new Error(`Unsupported specification ${JSON.stringify(spec)}`); - } - } +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() } -async function fetchAvailableVersions(spec) { - switch (spec.type) { - case `npm`: { - const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_7__.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, { headers: { [`Accept`]: `application/vnd.npm.install-v1+json` } }); - return Object.keys(data.versions); - } - case `url`: { - const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_7__.fetchAsJson(spec.url); - const field = data[spec.fields.versions]; - return Array.isArray(field) ? field : Object.keys(field); - } - default: { - throw new Error(`Unsupported specification ${JSON.stringify(spec)}`); + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } + } } -} -async function findInstalledVersion(installTarget, descriptor) { - const installFolder = path__WEBPACK_IMPORTED_MODULE_2___default().join(installTarget, descriptor.name); - let folderContent; - try { - folderContent = await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.readdir(installFolder); - } - catch (error) { - if (error.code === `ENOENT`) { - folderContent = []; - } - else { - throw error; - } - } - const candidateVersions = []; - for (const entry of folderContent) { - // Some dot-folders tend to pop inside directories, especially on OSX - if (entry.startsWith(`.`)) - continue; - candidateVersions.push(entry); - } - const bestMatch = semver__WEBPACK_IMPORTED_MODULE_3___default().maxSatisfying(candidateVersions, descriptor.range); - if (bestMatch === null) - return null; - return bestMatch; -} -async function installVersion(installTarget, locator, { spec }) { - const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/index.js", 19)); - const installFolder = path__WEBPACK_IMPORTED_MODULE_2___default().join(installTarget, locator.name, locator.reference); - if (fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(installFolder)) { - _debugUtils__WEBPACK_IMPORTED_MODULE_4__.log(`Reusing ${locator.name}@${locator.reference}`); - return installFolder; - } - const url = spec.url.replace(`{}`, locator.reference); - _debugUtils__WEBPACK_IMPORTED_MODULE_4__.log(`Installing ${locator.name}@${locator.reference} from ${url}`); - return await _fsUtils__WEBPACK_IMPORTED_MODULE_6__.mutex(installFolder, async () => { - // Creating a temporary folder inside the install folder means that we - // are sure it'll be in the same drive as the destination, so we can - // just move it there atomically once we are done - const tmpFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_5__.getTemporaryFolder(installTarget); - const stream = await _httpUtils__WEBPACK_IMPORTED_MODULE_7__.fetchUrlStream(url); - const parsedUrl = new URL(url); - const ext = path__WEBPACK_IMPORTED_MODULE_2___default().posix.extname(parsedUrl.pathname); - let outputFile = null; - let sendTo; - if (ext === `.tgz`) { - sendTo = tar.x({ strip: 1, cwd: tmpFolder }); - } - else if (ext === `.js`) { - outputFile = path__WEBPACK_IMPORTED_MODULE_2___default().join(tmpFolder, path__WEBPACK_IMPORTED_MODULE_2___default().posix.basename(parsedUrl.pathname)); - sendTo = fs__WEBPACK_IMPORTED_MODULE_1___default().createWriteStream(outputFile); - } - stream.pipe(sendTo); - await new Promise(resolve => { - sendTo.on(`finish`, resolve); - }); - await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.mkdir(path__WEBPACK_IMPORTED_MODULE_2___default().dirname(installFolder), { recursive: true }); - await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.rename(tmpFolder, installFolder); - _debugUtils__WEBPACK_IMPORTED_MODULE_4__.log(`Install finished`); - return installFolder; - }); -} -async function runVersion(installSpec, locator, binName, args, context) { - let binPath = null; - if (Array.isArray(installSpec.spec.bin)) { - if (installSpec.spec.bin.some(bin => bin === binName)) { - const parsedUrl = new URL(installSpec.spec.url); - const ext = path__WEBPACK_IMPORTED_MODULE_2___default().posix.extname(parsedUrl.pathname); - if (ext === `.js`) { - binPath = path__WEBPACK_IMPORTED_MODULE_2___default().join(installSpec.location, path__WEBPACK_IMPORTED_MODULE_2___default().posix.basename(parsedUrl.pathname)); - } - } - } - else { - for (const [name, dest] of Object.entries(installSpec.spec.bin)) { - if (name === binName) { - binPath = path__WEBPACK_IMPORTED_MODULE_2___default().join(installSpec.location, dest); - break; - } - } - } - if (!binPath) - throw new Error(`Assertion failed: Unable to locate path for bin '${binName}'`); - return new Promise((resolve, reject) => { - process.on(`SIGINT`, () => { - // We don't want to exit the process before the child, so we just - // ignore SIGINT and wait for the regular exit to happen (the child - // will receive SIGINT too since it's part of the same process grp) - }); - const stdio = [`pipe`, `pipe`, `pipe`]; - if (context.stdin === process.stdin) - stdio[0] = `inherit`; - if (context.stdout === process.stdout) - stdio[1] = `inherit`; - if (context.stderr === process.stderr) - stdio[2] = `inherit`; - const v8CompileCache = typeof require !== `undefined` - ? eval(`require`).resolve(`./vcc.js`) - : eval(`require`).resolve(`corepack/dist/vcc.js`); - const child = (0,child_process__WEBPACK_IMPORTED_MODULE_0__.spawn)(process.execPath, [`--require`, v8CompileCache, binPath, ...args], { - cwd: context.cwd, - stdio, - env: Object.assign(Object.assign({}, process.env), { COREPACK_ROOT: path__WEBPACK_IMPORTED_MODULE_2___default().dirname(eval(`__dirname`)) }), - }); - activeChildren.add(child); - if (activeChildren.size === 1) { - process.on(`SIGINT`, sigintHandler); - process.on(`SIGTERM`, sigtermHandler); - } - if (context.stdin !== process.stdin) - context.stdin.pipe(child.stdin); - if (context.stdout !== process.stdout) - child.stdout.pipe(context.stdout); - if (context.stderr !== process.stderr) - child.stderr.pipe(context.stderr); - child.on(`error`, error => { - activeChildren.delete(child); - if (activeChildren.size === 0) { - process.off(`SIGINT`, sigintHandler); - process.off(`SIGTERM`, sigtermHandler); - } - reject(error); - }); - child.on(`exit`, exitCode => { - activeChildren.delete(child); - if (activeChildren.size === 0) { - process.off(`SIGINT`, sigintHandler); - process.off(`SIGTERM`, sigtermHandler); - } - resolve(exitCode !== null ? exitCode : 1); - }); - }); -} -const activeChildren = new Set(); -function sigintHandler() { - // We don't want SIGINT to kill our process; we want it to kill the - // innermost process, whose end will cause our own to exit. -} -function sigtermHandler() { - for (const child of activeChildren) { - child.kill(); - } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true } /***/ }), -/***/ "./sources/debugUtils.ts": -/*!*******************************!*\ - !*** ./sources/debugUtils.ts ***! - \*******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "log": () => (/* binding */ log) -/* harmony export */ }); -/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! debug */ "./.yarn/__virtual__/debug-virtual-d208043b83/0/cache/debug-npm-4.1.1-540248b3aa-1e681f5cce.zip/node_modules/debug/src/index.js"); -/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(debug__WEBPACK_IMPORTED_MODULE_0__); +const debug = __webpack_require__(/*! ../internal/debug */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js") +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(/*! ../internal/constants */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js") +const { re, t } = __webpack_require__(/*! ../internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") -const log = debug__WEBPACK_IMPORTED_MODULE_0___default()(`corepack`); +const parseOptions = __webpack_require__(/*! ../internal/parse-options */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js") +const { compareIdentifiers } = __webpack_require__(/*! ../internal/identifiers */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/identifiers.js") +class SemVer { + constructor (version, options) { + options = parseOptions(options) + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } -/***/ }), + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } -/***/ "./sources/folderUtils.ts": -/*!********************************!*\ - !*** ./sources/folderUtils.ts ***! - \********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getInstallFolder": () => (/* binding */ getInstallFolder), -/* harmony export */ "getTemporaryFolder": () => (/* binding */ getTemporaryFolder) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! os */ "os"); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + this.raw = version + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -function getInstallFolder() { - var _a; - return (_a = process.env.COREPACK_HOME) !== null && _a !== void 0 ? _a : (0,path__WEBPACK_IMPORTED_MODULE_2__.join)((0,os__WEBPACK_IMPORTED_MODULE_1__.homedir)(), `.node/corepack`); -} -function getTemporaryFolder(target = (0,os__WEBPACK_IMPORTED_MODULE_1__.tmpdir)()) { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync)(target, { recursive: true }); - while (true) { - const rnd = Math.random() * 0x100000000; - const hex = rnd.toString(16).padStart(8, `0`); - const path = (0,path__WEBPACK_IMPORTED_MODULE_2__.join)(target, `corepack-${process.pid}-${hex}`); - try { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync)(path); - return path; - } - catch (error) { - if (error.code === `EEXIST`) { - continue; - } - else { - throw error; - } + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } } + return id + }) } -} + this.build = m[5] ? m[5].split('.') : [] + this.format() + } -/***/ }), + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } -/***/ "./sources/fsUtils.ts": -/*!****************************!*\ - !*** ./sources/fsUtils.ts ***! - \****************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + toString () { + return this.version + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "mutex": () => (/* binding */ mutex) -/* harmony export */ }); -async function mutex(p, cb) { - return await cb(); -} + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + if (other.version === this.version) { + return 0 + } -/***/ }), + return this.compareMain(other) || this.comparePre(other) + } -/***/ "./sources/httpUtils.ts": -/*!******************************!*\ - !*** ./sources/httpUtils.ts ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "fetchUrlStream": () => (/* binding */ fetchUrlStream), -/* harmony export */ "fetchAsBuffer": () => (/* binding */ fetchAsBuffer), -/* harmony export */ "fetchAsJson": () => (/* binding */ fetchAsJson) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } -async function fetchUrlStream(url, options = {}) { - if (process.env.COREPACK_ENABLE_NETWORK === `0`) - throw new clipanion__WEBPACK_IMPORTED_MODULE_0__.UsageError(`Network access disabled by the environment; can't reach ${url}`); - const { default: https } = await Promise.resolve(/*! import() */).then(__webpack_require__.t.bind(__webpack_require__, /*! https */ "https", 23)); - return new Promise((resolve, reject) => { - const request = https.get(url, options, response => { - var _a; - const statusCode = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 500; - if (!(statusCode >= 200 && statusCode < 300)) - return reject(new Error(`Server answered with HTTP ${statusCode}`)); - return resolve(response); - }); - request.on(`error`, err => { - reject(new Error(`Error when performing the request`)); - }); - }); -} -async function fetchAsBuffer(url, options) { - const response = await fetchUrlStream(url, options); - return new Promise((resolve, reject) => { - const chunks = []; - response.on(`data`, chunk => { - chunks.push(chunk); - }); - response.on(`error`, error => { - reject(error); - }); - response.on(`end`, () => { - resolve(Buffer.concat(chunks)); - }); - }); -} -async function fetchAsJson(url, options) { - const buffer = await fetchAsBuffer(url, options); - const asText = buffer.toString(); - try { - return JSON.parse(asText); - } - catch (error) { - const truncated = asText.length > 30 - ? `${asText.slice(0, 30)}...` - : asText; - throw new Error(`Couldn't parse JSON data: ${JSON.stringify(truncated)}`); + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) } -} - - -/***/ }), - -/***/ "./sources/miscUtils.ts": -/*!******************************!*\ - !*** ./sources/miscUtils.ts ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Cancellation": () => (/* binding */ Cancellation) -/* harmony export */ }); -class Cancellation extends Error { - constructor() { - super(`Cancelled operation`); + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 } -} + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -/***/ }), + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -/***/ "./sources/semverUtils.ts": -/*!********************************!*\ - !*** ./sources/semverUtils.ts ***! - \********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "satisfiesWithPrereleases": () => (/* binding */ satisfiesWithPrereleases) -/* harmony export */ }); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js"); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_0__); + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break -/** - * Returns whether the given semver version satisfies the given range. Notably - * this supports prerelease versions so that "2.0.0-rc.0" satisfies the range - * ">=1.0.0", for example. - * - * This function exists because the semver.satisfies method does not include - * pre releases. This means ranges such as * would not satisfy 1.0.0-rc. The - * includePrerelease flag has a weird behavior and cannot be used (if you want - * to try it out, just run the `semverUtils` testsuite using this flag instead - * of our own implementation, and you'll see the failing cases). - * - * See https://github.com/yarnpkg/berry/issues/575 for more context. - */ -function satisfiesWithPrereleases(version, range, loose = false) { - let semverRange; - try { - semverRange = new (semver__WEBPACK_IMPORTED_MODULE_0___default().Range)(range, loose); - } - catch (err) { - return false; - } - if (!version) - return false; - let semverVersion; - try { - semverVersion = new (semver__WEBPACK_IMPORTED_MODULE_0___default().SemVer)(version, semverRange.loose); - if (semverVersion.prerelease) { - semverVersion.prerelease = []; + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) } - catch (err) { - return false; - } - // A range has multiple sets of comparators. A version must satisfy all - // comparators in a set and at least one set to satisfy the range. - return semverRange.set.some(comparatorSet => { - for (const comparator of comparatorSet) - if (comparator.semver.prerelease) - comparator.semver.prerelease = []; - return comparatorSet.every(comparator => { - return comparator.test(semverVersion); - }); - }); + this.format() + this.raw = this.version + return this + } } +module.exports = SemVer + /***/ }), -/***/ "./sources/specUtils.ts": -/*!******************************!*\ - !*** ./sources/specUtils.ts ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/clean.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/clean.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "parseSpec": () => (/* binding */ parseSpec), -/* harmony export */ "findProjectSpec": () => (/* binding */ findProjectSpec), -/* harmony export */ "loadSpec": () => (/* binding */ loadSpec) -/* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js"); -/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./sources/types.ts"); +const parse = __webpack_require__(/*! ./parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js") +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean +/***/ }), +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/cmp.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/cmp.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const eq = __webpack_require__(/*! ./eq */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/eq.js") +const neq = __webpack_require__(/*! ./neq */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/neq.js") +const gt = __webpack_require__(/*! ./gt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js") +const gte = __webpack_require__(/*! ./gte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gte.js") +const lt = __webpack_require__(/*! ./lt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lt.js") +const lte = __webpack_require__(/*! ./lte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lte.js") -const nodeModulesRegExp = /[\\/]node_modules[\\/](@[^\\/]*[\\/])?([^@\\/][^\\/]*)$/; -function parseSpec(raw, source) { - if (typeof raw !== `string`) - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager specification in ${source}; expected a string`); - const match = raw.match(/^(?!_)(.+)@(.+)$/); - if (match === null || !semver__WEBPACK_IMPORTED_MODULE_2___default().valid(match[2])) - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager specification in ${source}; expected a semver version`); - if (!(0,_types__WEBPACK_IMPORTED_MODULE_3__.isSupportedPackageManager)(match[1])) - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Unsupported package manager specification (${match})`); - return { - name: match[1], - range: match[2], - }; -} -/** - * Locates the active project's package manager specification. - * - * If the specification exists but doesn't match the active package manager, - * an error is thrown to prevent users from using the wrong package manager, - * which would lead to inconsistent project layouts. - * - * If the project doesn't include a specification file, we just assume that - * whatever the user uses is exactly what they want to use. Since the version - * isn't explicited, we fallback on known good versions. - * - * Finally, if the project doesn't exist at all, we ask the user whether they - * want to create one in the current project. If they do, we initialize a new - * project using the default package managers, and configure it so that we - * don't need to ask again in the future. - */ -async function findProjectSpec(initialCwd, locator, { transparent = false } = {}) { - // A locator is a valid descriptor (but not the other way around) - const fallbackLocator = { name: locator.name, range: locator.reference }; - while (true) { - const result = await loadSpec(initialCwd); - switch (result.type) { - case `NoProject`: - case `NoSpec`: - { - return fallbackLocator; - } - break; - case `Found`: - { - if (result.spec.name !== locator.name) { - if (transparent) { - return fallbackLocator; - } - else { - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`This project is configured to use ${result.spec.name}`); - } - } - else { - return result.spec; - } - } - break; - } - } +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } } -async function loadSpec(initialCwd) { - let nextCwd = initialCwd; - let currCwd = ``; - let selection = null; - while (nextCwd !== currCwd && (!selection || !selection.data.packageManager)) { - currCwd = nextCwd; - nextCwd = path__WEBPACK_IMPORTED_MODULE_1___default().dirname(currCwd); - if (nodeModulesRegExp.test(currCwd)) - continue; - const manifestPath = path__WEBPACK_IMPORTED_MODULE_1___default().join(currCwd, `package.json`); - if (!fs__WEBPACK_IMPORTED_MODULE_0___default().existsSync(manifestPath)) - continue; - const content = await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(manifestPath, `utf8`); - let data; - try { - data = JSON.parse(content); - } - catch (_a) { } - if (typeof data !== `object` || data === null) - throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package.json in ${path__WEBPACK_IMPORTED_MODULE_1___default().relative(initialCwd, manifestPath)}`); - selection = { data, manifestPath }; +module.exports = cmp + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/coerce.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/coerce.js ***! + \************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const parse = __webpack_require__(/*! ./parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js") +const { re, t } = __webpack_require__(/*! ../internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } - if (selection === null) - return { type: `NoProject`, target: path__WEBPACK_IMPORTED_MODULE_1___default().join(initialCwd, `package.json`) }; - const rawPmSpec = selection.data.packageManager; - if (typeof rawPmSpec === `undefined`) - return { type: `NoSpec`, target: selection.manifestPath }; - return { - type: `Found`, - spec: parseSpec(rawPmSpec, path__WEBPACK_IMPORTED_MODULE_1___default().relative(initialCwd, selection.manifestPath)), - }; + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } +module.exports = coerce /***/ }), -/***/ "./sources/types.ts": -/*!**************************!*\ - !*** ./sources/types.ts ***! - \**************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-build.js": +/*!*******************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-build.js ***! + \*******************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SupportedPackageManagers": () => (/* binding */ SupportedPackageManagers), -/* harmony export */ "SupportedPackageManagerSet": () => (/* binding */ SupportedPackageManagerSet), -/* harmony export */ "SupportedPackageManagerSetWithoutNpm": () => (/* binding */ SupportedPackageManagerSetWithoutNpm), -/* harmony export */ "isSupportedPackageManager": () => (/* binding */ isSupportedPackageManager) -/* harmony export */ }); -var SupportedPackageManagers; -(function (SupportedPackageManagers) { - SupportedPackageManagers["Npm"] = "npm"; - SupportedPackageManagers["Pnpm"] = "pnpm"; - SupportedPackageManagers["Yarn"] = "yarn"; -})(SupportedPackageManagers || (SupportedPackageManagers = {})); -const SupportedPackageManagerSet = new Set(Object.values(SupportedPackageManagers)); -const SupportedPackageManagerSetWithoutNpm = new Set(Object.values(SupportedPackageManagers)); -// npm is distributed with Node as a builtin; we don't want Corepack to override it unless the npm team is on board -SupportedPackageManagerSetWithoutNpm.delete(SupportedPackageManagers.Npm); -function isSupportedPackageManager(value) { - return SupportedPackageManagerSet.has(value); +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) } +module.exports = compareBuild /***/ }), -/***/ "./.yarn/cache/@zkochan-cmd-shim-npm-5.0.0-9e90407ba0-ace99c7c36.zip/node_modules/@zkochan/cmd-shim/index.js": +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-loose.js": /*!*******************************************************************************************************************!*\ - !*** ./.yarn/cache/@zkochan-cmd-shim-npm-5.0.0-9e90407ba0-ace99c7c36.zip/node_modules/@zkochan/cmd-shim/index.js ***! + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-loose.js ***! \*******************************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose -cmdShim.ifExists = cmdShimIfExists; -const util_1 = __webpack_require__(/*! util */ "util"); -const path = __webpack_require__(/*! path */ "path"); -const isWindows = __webpack_require__(/*! is-windows */ "./.yarn/cache/is-windows-npm-1.0.2-898cd6f3d7-438b7e5265.zip/node_modules/is-windows/index.js"); -const shebangExpr = /^#!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/; -const DEFAULT_OPTIONS = { - // Create PowerShell file by default if the option hasn't been specified - createPwshFile: true, - createCmdFile: isWindows(), - fs: __webpack_require__(/*! fs */ "fs") -}; -/** - * Map from extensions of files that this module is frequently used for to their runtime. - * @type {Map} - */ -const extensionToProgramMap = new Map([ - ['.js', 'node'], - ['.cmd', 'cmd'], - ['.bat', 'cmd'], - ['.ps1', 'pwsh'], - ['.sh', 'sh'] -]); -function ingestOptions(opts) { - const opts_ = { ...DEFAULT_OPTIONS, ...opts }; - const fs = opts_.fs; - opts_.fs_ = { - chmod: fs.chmod ? util_1.promisify(fs.chmod) : (async () => { }), - mkdir: util_1.promisify(fs.mkdir), - readFile: util_1.promisify(fs.readFile), - stat: util_1.promisify(fs.stat), - unlink: util_1.promisify(fs.unlink), - writeFile: util_1.promisify(fs.writeFile) - }; - return opts_; + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js ***! + \*************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/diff.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/diff.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(/*! ./parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js") +const eq = __webpack_require__(/*! ./eq */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/eq.js") + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + const hasPre = v1.prerelease.length || v2.prerelease.length + const prefix = hasPre ? 'pre' : '' + const defaultResult = hasPre ? 'prerelease' : '' + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } } -/** - * Try to create shims. - * - * @param src Path to program (executable or script). - * @param to Path to shims. - * Don't add an extension if you will create multiple types of shims. - * @param opts Options. - * @throws If `src` is missing. - */ -async function cmdShim(src, to, opts) { - const opts_ = ingestOptions(opts); - await opts_.fs_.stat(src); - await cmdShim_(src, to, opts_); +module.exports = diff + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/eq.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/eq.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gte.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gte.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/inc.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/inc.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier).version + } catch (er) { + return null + } } -/** - * Try to create shims. - * - * Does nothing if `src` doesn't exist. - * - * @param src Path to program (executable or script). - * @param to Path to shims. - * Don't add an extension if you will create multiple types of shims. - * @param opts Options. - */ -function cmdShimIfExists(src, to, opts) { - return cmdShim(src, to, opts).catch(() => { }); +module.exports = inc + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lt.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lt.js ***! + \********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lte.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lte.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/major.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/major.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/minor.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/minor.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/neq.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/neq.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const { MAX_LENGTH } = __webpack_require__(/*! ../internal/constants */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js") +const { re, t } = __webpack_require__(/*! ../internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") + +const parseOptions = __webpack_require__(/*! ../internal/parse-options */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js") +const parse = (version, options) => { + options = parseOptions(options) + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } } -/** - * Try to unlink, but ignore errors. - * Any problems will surface later. - * - * @param path File to be removed. - */ -function rm(path, opts) { - return opts.fs_.unlink(path).catch(() => { }); + +module.exports = parse + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/patch.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/patch.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/prerelease.js": +/*!****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/prerelease.js ***! + \****************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(/*! ./parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js") +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } -/** - * Try to create shims **even if `src` is missing**. - * - * @param src Path to program (executable or script). - * @param to Path to shims. - * Don't add an extension if you will create multiple types of shims. - * @param opts Options. - */ -async function cmdShim_(src, to, opts) { - const srcRuntimeInfo = await searchScriptRuntime(src, opts); - // Always tries to create all types of shims by calling `writeAllShims` as of now. - // Append your code here to change the behavior in response to `srcRuntimeInfo`. - // Create 3 shims for (Ba)sh in Cygwin / MSYS, no extension) & CMD (.cmd) & PowerShell (.ps1) - await writeShimsPreCommon(to, opts); - return writeAllShims(src, to, srcRuntimeInfo, opts); -} -/** - * Do processes before **all** shims are created. - * This must be called **only once** for one call of `cmdShim(IfExists)`. - * - * @param target Path of shims that are going to be created. - */ -function writeShimsPreCommon(target, opts) { - return opts.fs_.mkdir(path.dirname(target), { recursive: true }); +module.exports = prerelease + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rcompare.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rcompare.js ***! + \**************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compare = __webpack_require__(/*! ./compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rsort.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rsort.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compareBuild = __webpack_require__(/*! ./compare-build */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-build.js") +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js": +/*!***************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js ***! + \***************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } -/** - * Write all types (sh & cmd & pwsh) of shims to files. - * Extensions (`.cmd` and `.ps1`) are appended to cmd and pwsh shims. - * - * - * @param src Path to program (executable or script). - * @param to Path to shims **without extensions**. - * Extensions are added for CMD and PowerShell shims. - * @param srcRuntimeInfo Return value of `await searchScriptRuntime(src)`. - * @param opts Options. - */ -function writeAllShims(src, to, srcRuntimeInfo, opts) { - const opts_ = ingestOptions(opts); - const generatorAndExts = [{ generator: generateShShim, extension: '' }]; - if (opts_.createCmdFile) { - generatorAndExts.push({ generator: generateCmdShim, extension: '.cmd' }); - } - if (opts_.createPwshFile) { - generatorAndExts.push({ generator: generatePwshShim, extension: '.ps1' }); - } - return Promise.all(generatorAndExts.map((generatorAndExt) => writeShim(src, to + generatorAndExt.extension, srcRuntimeInfo, generatorAndExt.generator, opts_))); +module.exports = satisfies + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/sort.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/sort.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const compareBuild = __webpack_require__(/*! ./compare-build */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-build.js") +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/valid.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/valid.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(/*! ./parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js") +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null } -/** - * Do processes before writing shim. - * - * @param target Path to shim that is going to be created. - */ -function writeShimPre(target, opts) { - return rm(target, opts); +module.exports = valid + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js ***! + \*************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// just pre-load all the stuff that index.js lazily exports +const internalRe = __webpack_require__(/*! ./internal/re */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js") +module.exports = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: (__webpack_require__(/*! ./internal/constants */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js").SEMVER_SPEC_VERSION), + SemVer: __webpack_require__(/*! ./classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js"), + compareIdentifiers: (__webpack_require__(/*! ./internal/identifiers */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/identifiers.js").compareIdentifiers), + rcompareIdentifiers: (__webpack_require__(/*! ./internal/identifiers */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/identifiers.js").rcompareIdentifiers), + parse: __webpack_require__(/*! ./functions/parse */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/parse.js"), + valid: __webpack_require__(/*! ./functions/valid */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/valid.js"), + clean: __webpack_require__(/*! ./functions/clean */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/clean.js"), + inc: __webpack_require__(/*! ./functions/inc */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/inc.js"), + diff: __webpack_require__(/*! ./functions/diff */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/diff.js"), + major: __webpack_require__(/*! ./functions/major */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/major.js"), + minor: __webpack_require__(/*! ./functions/minor */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/minor.js"), + patch: __webpack_require__(/*! ./functions/patch */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/patch.js"), + prerelease: __webpack_require__(/*! ./functions/prerelease */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/prerelease.js"), + compare: __webpack_require__(/*! ./functions/compare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js"), + rcompare: __webpack_require__(/*! ./functions/rcompare */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rcompare.js"), + compareLoose: __webpack_require__(/*! ./functions/compare-loose */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-loose.js"), + compareBuild: __webpack_require__(/*! ./functions/compare-build */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare-build.js"), + sort: __webpack_require__(/*! ./functions/sort */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/sort.js"), + rsort: __webpack_require__(/*! ./functions/rsort */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/rsort.js"), + gt: __webpack_require__(/*! ./functions/gt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js"), + lt: __webpack_require__(/*! ./functions/lt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lt.js"), + eq: __webpack_require__(/*! ./functions/eq */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/eq.js"), + neq: __webpack_require__(/*! ./functions/neq */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/neq.js"), + gte: __webpack_require__(/*! ./functions/gte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gte.js"), + lte: __webpack_require__(/*! ./functions/lte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lte.js"), + cmp: __webpack_require__(/*! ./functions/cmp */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/cmp.js"), + coerce: __webpack_require__(/*! ./functions/coerce */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/coerce.js"), + Comparator: __webpack_require__(/*! ./classes/comparator */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js"), + Range: __webpack_require__(/*! ./classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js"), + satisfies: __webpack_require__(/*! ./functions/satisfies */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js"), + toComparators: __webpack_require__(/*! ./ranges/to-comparators */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/to-comparators.js"), + maxSatisfying: __webpack_require__(/*! ./ranges/max-satisfying */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/max-satisfying.js"), + minSatisfying: __webpack_require__(/*! ./ranges/min-satisfying */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-satisfying.js"), + minVersion: __webpack_require__(/*! ./ranges/min-version */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-version.js"), + validRange: __webpack_require__(/*! ./ranges/valid */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/valid.js"), + outside: __webpack_require__(/*! ./ranges/outside */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/outside.js"), + gtr: __webpack_require__(/*! ./ranges/gtr */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/gtr.js"), + ltr: __webpack_require__(/*! ./ranges/ltr */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/ltr.js"), + intersects: __webpack_require__(/*! ./ranges/intersects */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/intersects.js"), + simplifyRange: __webpack_require__(/*! ./ranges/simplify */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/simplify.js"), + subset: __webpack_require__(/*! ./ranges/subset */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/subset.js"), } -/** - * Do processes after writing the shim. - * - * @param target Path to just created shim. - */ -function writeShimPost(target, opts) { - // Only chmoding shims as of now. - // Some other processes may be appended. - return chmodShim(target, opts); + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js ***! + \**************************************************************************************************************/ +/***/ ((module) => { + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH, } -/** - * Look into runtime (e.g. `node` & `sh` & `pwsh`) and its arguments - * of the target program (script or executable). - * - * @param target Path to the executable or script. - * @return Promise of infomation of runtime of `target`. - */ -async function searchScriptRuntime(target, opts) { - const data = await opts.fs_.readFile(target, 'utf8'); - // First, check if the bin is a #! of some sort. - const firstLine = data.trim().split(/\r*\n/)[0]; - const shebang = firstLine.match(shebangExpr); - if (!shebang) { - // If not, infer script type from its extension. - // If the inference fails, it's something that'll be compiled, or some other - // sort of script, and just call it directly. - const targetExtension = path.extname(target).toLowerCase(); - return { - // undefined if extension is unknown but it's converted to null. - program: extensionToProgramMap.get(targetExtension) || null, - additionalArgs: '' - }; - } - return { - program: shebang[1], - additionalArgs: shebang[2] - }; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js ***! + \**********************************************************************************************************/ +/***/ ((module) => { + +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/identifiers.js": +/*!****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/identifiers.js ***! + \****************************************************************************************************************/ +/***/ ((module) => { + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -/** - * Write shim to the file system while executing the pre- and post-processes - * defined in `WriteShimPre` and `WriteShimPost`. - * - * @param src Path to the executable or script. - * @param to Path to the (sh) shim(s) that is going to be created. - * @param srcRuntimeInfo Result of `await searchScriptRuntime(src)`. - * @param generateShimScript Generator of shim script. - * @param opts Other options. - */ -async function writeShim(src, to, srcRuntimeInfo, generateShimScript, opts) { - const defaultArgs = opts.preserveSymlinks ? '--preserve-symlinks' : ''; - // `Array.prototype.filter` removes ''. - // ['--foo', '--bar'].join(' ') and [].join(' ') returns '--foo --bar' and '' respectively. - const args = [srcRuntimeInfo.additionalArgs, defaultArgs].filter(arg => arg).join(' '); - opts = Object.assign({}, opts, { - prog: srcRuntimeInfo.program, - args: args - }); - await writeShimPre(to, opts); - await opts.fs_.writeFile(to, generateShimScript(src, to, opts), 'utf8'); - return writeShimPost(to, opts); + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, } -/** - * Generate the content of a shim for CMD. - * - * @param src Path to the executable or script. - * @param to Path to the shim to be created. - * It is highly recommended to end with `.cmd` (or `.bat`). - * @param opts Options. - * @return The content of shim. - */ -function generateCmdShim(src, to, opts) { - // `shTarget` is not used to generate the content. - const shTarget = path.relative(path.dirname(to), src); - let target = shTarget.split('/').join('\\'); - const quotedPathToTarget = path.isAbsolute(target) ? `"${target}"` : `"%~dp0\\${target}"`; - let longProg; - let prog = opts.prog; - let args = opts.args || ''; - const nodePath = normalizePathEnvVar(opts.nodePath).win32; - if (!prog) { - prog = quotedPathToTarget; - args = ''; - target = ''; - } - else { - longProg = `"%~dp0\\${prog}.exe"`; - target = quotedPathToTarget; - } - let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; - // @IF EXIST "%~dp0\node.exe" ( - // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) ELSE ( - // SETLOCAL - // SET PATHEXT=%PATHEXT:;.JS;=;% - // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) - let cmd = nodePath ? `@SET NODE_PATH=${nodePath}\r\n` : ''; - if (longProg) { - cmd += `@IF EXIST ${longProg} (\r\n` + - ` ${longProg} ${args} ${target} ${progArgs}%*\r\n` + - ') ELSE (\r\n' + - ' @SETLOCAL\r\n' + - ' @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n' + - ` ${prog} ${args} ${target} ${progArgs}%*\r\n` + - ')'; - } - else { - cmd += `@${prog} ${args} ${target} ${progArgs}%*\r\n`; - } - return cmd; -} -/** - * Generate the content of a shim for (Ba)sh in, for example, Cygwin and MSYS(2). - * - * @param src Path to the executable or script. - * @param to Path to the shim to be created. - * It is highly recommended to end with `.sh` or to contain no extension. - * @param opts Options. - * @return The content of shim. - */ -function generateShShim(src, to, opts) { - let shTarget = path.relative(path.dirname(to), src); - let shProg = opts.prog && opts.prog.split('\\').join('/'); - let shLongProg; - shTarget = shTarget.split('\\').join('/'); - const quotedPathToTarget = path.isAbsolute(shTarget) ? `"${shTarget}"` : `"$basedir/${shTarget}"`; - let args = opts.args || ''; - const shNodePath = normalizePathEnvVar(opts.nodePath).posix; - if (!shProg) { - shProg = quotedPathToTarget; - args = ''; - shTarget = ''; - } - else { - shLongProg = `"$basedir/${opts.prog}"`; - shTarget = quotedPathToTarget; - } - let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; - // #!/bin/sh - // basedir=`dirname "$0"` - // - // case `uname` in - // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; - // esac - // - // export NODE_PATH="" - // - // if [ -x "$basedir/node.exe" ]; then - // exec "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // else - // exec node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // fi - let sh = '#!/bin/sh\n'; - sh = sh + - "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" + - '\n' + - 'case `uname` in\n' + - ' *CYGWIN*) basedir=`cygpath -w "$basedir"`;;\n' + - 'esac\n' + - '\n'; - const env = opts.nodePath ? `export NODE_PATH="${shNodePath}"\n` : ''; - if (shLongProg) { - sh += env + - `if [ -x ${shLongProg} ]; then\n` + - ` exec ${shLongProg} ${args} ${shTarget} ${progArgs}"$@"\n` + - 'else \n' + - ` exec ${shProg} ${args} ${shTarget} ${progArgs}"$@"\n` + - 'fi\n'; - } - else { - sh += `${env}${shProg} ${args} ${shTarget} ${progArgs}"$@"\n` + - 'exit $?\n'; - } - return sh; -} -/** - * Generate the content of a shim for PowerShell. - * - * @param src Path to the executable or script. - * @param to Path to the shim to be created. - * It is highly recommended to end with `.ps1`. - * @param opts Options. - * @return The content of shim. - */ -function generatePwshShim(src, to, opts) { - let shTarget = path.relative(path.dirname(to), src); - const shProg = opts.prog && opts.prog.split('\\').join('/'); - let pwshProg = shProg && `"${shProg}$exe"`; - let pwshLongProg; - shTarget = shTarget.split('\\').join('/'); - const quotedPathToTarget = path.isAbsolute(shTarget) ? `"${shTarget}"` : `"$basedir/${shTarget}"`; - let args = opts.args || ''; - let normalizedPathEnvVar = normalizePathEnvVar(opts.nodePath); - const nodePath = normalizedPathEnvVar.win32; - const shNodePath = normalizedPathEnvVar.posix; - if (!pwshProg) { - pwshProg = quotedPathToTarget; - args = ''; - shTarget = ''; - } - else { - pwshLongProg = `"$basedir/${opts.prog}$exe"`; - shTarget = quotedPathToTarget; - } - let progArgs = opts.progArgs ? `${opts.progArgs.join(` `)} ` : ''; - // #!/usr/bin/env pwsh - // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - // - // $ret=0 - // $exe = "" - // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - // # Fix case when both the Windows and Linux builds of Node - // # are installed in the same directory - // $exe = ".exe" - // } - // if (Test-Path "$basedir/node") { - // # Support pipeline input - // if ($MyInvocation.ExpectingInput) { - // $input | & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // } else { - // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // } - // $ret=$LASTEXITCODE - // } else { - // # Support pipeline input - // if ($MyInvocation.ExpectingInput) { - // $input | & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // } else { - // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args - // } - // $ret=$LASTEXITCODE - // } - // exit $ret - let pwsh = '#!/usr/bin/env pwsh\n' + - '$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n' + - '\n' + - '$exe=""\n' + - (opts.nodePath ? '$env_node_path=$env:NODE_PATH\n' + - `$env:NODE_PATH="${nodePath}"\n` : '') + - 'if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {\n' + - ' # Fix case when both the Windows and Linux builds of Node\n' + - ' # are installed in the same directory\n' + - ' $exe=".exe"\n' + - '}'; - if (opts.nodePath) { - pwsh = pwsh + - ' else {\n' + - ` $env:NODE_PATH="${shNodePath}"\n` + - '}'; - } - pwsh += '\n'; - if (pwshLongProg) { - pwsh = pwsh + - '$ret=0\n' + - `if (Test-Path ${pwshLongProg}) {\n` + - ' # Support pipeline input\n' + - ' if ($MyInvocation.ExpectingInput) {\n' + - ` $input | & ${pwshLongProg} ${args} ${shTarget} ${progArgs}$args\n` + - ' } else {\n' + - ` & ${pwshLongProg} ${args} ${shTarget} ${progArgs}$args\n` + - ' }\n' + - ' $ret=$LASTEXITCODE\n' + - '} else {\n' + - ' # Support pipeline input\n' + - ' if ($MyInvocation.ExpectingInput) {\n' + - ` $input | & ${pwshProg} ${args} ${shTarget} ${progArgs}$args\n` + - ' } else {\n' + - ` & ${pwshProg} ${args} ${shTarget} ${progArgs}$args\n` + - ' }\n' + - ' $ret=$LASTEXITCODE\n' + - '}\n' + - (opts.nodePath ? '$env:NODE_PATH=$env_node_path\n' : '') + - 'exit $ret\n'; - } - else { - pwsh = pwsh + - '# Support pipeline input\n' + - 'if ($MyInvocation.ExpectingInput) {\n' + - ` $input | & ${pwshProg} ${args} ${shTarget} ${progArgs}$args\n` + - '} else {\n' + - ` & ${pwshProg} ${args} ${shTarget} ${progArgs}$args\n` + - '}\n' + - (opts.nodePath ? '$env:NODE_PATH=$env_node_path\n' : '') + - 'exit $LASTEXITCODE\n'; - } - return pwsh; -} -/** - * Chmod just created shim and make it executable - * - * @param to Path to shim. - */ -function chmodShim(to, opts) { - return opts.fs_.chmod(to, 0o755); -} -function normalizePathEnvVar(nodePath) { - if (!nodePath) { - return { - win32: '', - posix: '' - }; - } - let split = (typeof nodePath === 'string' ? nodePath.split(path.delimiter) : Array.from(nodePath)); - let result = {}; - for (let i = 0; i < split.length; i++) { - const win32 = split[i].split('/').join('\\'); - const posix = isWindows() ? split[i].split('\\').join('/').replace(/^([^:\\/]*):/, (_, $1) => `/mnt/${$1.toLowerCase()}`) : split[i]; - result.win32 = result.win32 ? `${result.win32};${win32}` : win32; - result.posix = result.posix ? `${result.posix}:${posix}` : posix; - result[i] = { win32, posix }; - } - return result; -} -module.exports = cmdShim; -//# sourceMappingURL=index.js.map + /***/ }), -/***/ "./.yarn/cache/chownr-npm-1.1.4-5bd400ab08-115648f8eb.zip/node_modules/chownr/chownr.js": -/*!**********************************************************************************************!*\ - !*** ./.yarn/cache/chownr-npm-1.1.4-5bd400ab08-115648f8eb.zip/node_modules/chownr/chownr.js ***! - \**********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js": +/*!******************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/parse-options.js ***! + \******************************************************************************************************************/ +/***/ ((module) => { -"use strict"; +// parse out just the options we care about so we always get a consistent +// obj with keys in a consistent order. +const opts = ['includePrerelease', 'loose', 'rtl'] +const parseOptions = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((o, k) => { + o[k] = true + return o + }, {}) +module.exports = parseOptions -const fs = __webpack_require__(/*! fs */ "fs") -const path = __webpack_require__(/*! path */ "path") -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' +/***/ }), -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js": +/*!*******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/re.js ***! + \*******************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} +const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(/*! ./constants */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/constants.js") +const debug = __webpack_require__(/*! ./debug */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/internal/debug.js") +exports = module.exports = {} -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) } -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) -} +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) - } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - } -} +// ## Main Version +// Three dot-separated numeric identifiers. +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) -} +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er - } - } +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - handleEISDirSync(path.resolve(p, child.name), uid, gid) -} +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er - } +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - return handleEISDirSync(p, uid, gid) -} +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') -module.exports = chownr -chownr.sync = chownrSync +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) -/***/ }), +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -/***/ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js ***! - \*******************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -"use strict"; +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) -const MiniPass = __webpack_require__(/*! minipass */ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js") -const EE = __webpack_require__(/*! events */ "events").EventEmitter -const fs = __webpack_require__(/*! fs */ "fs") +createToken('FULL', `^${src[t.FULLPLAIN]}$`) -let writev = fs.writev -/* istanbul ignore next */ -if (!writev) { - // This entire block can be removed if support for earlier than Node.js - // 12.9.0 is not needed. - const binding = process.binding('fs') - const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) - writev = (fd, iovec, pos, cb) => { - const done = (er, bw) => cb(er, bw, iovec) - const req = new FSReqWrap() - req.oncomplete = done - binding.writeBuffers(fd, iovec, pos, req) - } -} +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) -const _autoClose = Symbol('_autoClose') -const _close = Symbol('_close') -const _ended = Symbol('_ended') -const _fd = Symbol('_fd') -const _finished = Symbol('_finished') -const _flags = Symbol('_flags') -const _flush = Symbol('_flush') -const _handleChunk = Symbol('_handleChunk') -const _makeBuf = Symbol('_makeBuf') -const _mode = Symbol('_mode') -const _needDrain = Symbol('_needDrain') -const _onerror = Symbol('_onerror') -const _onopen = Symbol('_onopen') -const _onread = Symbol('_onread') -const _onwrite = Symbol('_onwrite') -const _open = Symbol('_open') -const _path = Symbol('_path') -const _pos = Symbol('_pos') -const _queue = Symbol('_queue') -const _read = Symbol('_read') -const _readSize = Symbol('_readSize') -const _reading = Symbol('_reading') -const _remain = Symbol('_remain') -const _size = Symbol('_size') -const _write = Symbol('_write') -const _writing = Symbol('_writing') -const _defaultFlag = Symbol('_defaultFlag') -const _errored = Symbol('_errored') +createToken('GTLT', '((?:<|>)?=?)') -class ReadStream extends MiniPass { - constructor (path, opt) { - opt = opt || {} - super(opt) +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) - this.readable = true - this.writable = false +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) - if (typeof path !== 'string') - throw new TypeError('path must be a string') +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) - this[_errored] = false - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_path] = path - this[_readSize] = opt.readSize || 16*1024*1024 - this[_reading] = false - this[_size] = typeof opt.size === 'number' ? opt.size : Infinity - this[_remain] = this[_size] - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) - if (typeof this[_fd] === 'number') - this[_read]() - else - this[_open]() - } +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) - get fd () { return this[_fd] } - get path () { return this[_path] } +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') - write () { - throw new TypeError('this is a readable stream') - } +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' - end () { - throw new TypeError('this is a readable stream') - } +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) - [_open] () { - fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) - } +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') - [_onopen] (er, fd) { - if (er) - this[_onerror](er) - else { - this[_fd] = fd - this.emit('open', fd) - this[_read]() - } - } +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' - [_makeBuf] () { - return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) - } +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) - [_read] () { - if (!this[_reading]) { - this[_reading] = true - const buf = this[_makeBuf]() - /* istanbul ignore if */ - if (buf.length === 0) - return process.nextTick(() => this[_onread](null, 0, buf)) - fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => - this[_onread](er, br, buf)) - } - } +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) - [_onread] (er, br, buf) { - this[_reading] = false - if (er) - this[_onerror](er) - else if (this[_handleChunk](br, buf)) - this[_read]() - } +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) - } - } +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) - [_onerror] (er) { - this[_reading] = true - this[_close]() - this.emit('error', er) - } +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) - [_handleChunk] (br, buf) { - let ret = false - // no effect if infinite - this[_remain] -= br - if (br > 0) - ret = super.write(br < buf.length ? buf.slice(0, br) : buf) +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') - if (br === 0 || this[_remain] <= 0) { - ret = false - this[_close]() - super.end() - } - return ret - } +/***/ }), - emit (ev, data) { - switch (ev) { - case 'prefinish': - case 'finish': - break +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/gtr.js": +/*!******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/gtr.js ***! + \******************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - case 'drain': - if (typeof this[_fd] === 'number') - this[_read]() - break +// Determine if version is greater than all the versions possible in the range. +const outside = __webpack_require__(/*! ./outside */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/outside.js") +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr - case 'error': - if (this[_errored]) - return - this[_errored] = true - return super.emit(ev, data) - default: - return super.emit(ev, data) - } - } +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/intersects.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/intersects.js ***! + \*************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) } +module.exports = intersects -class ReadStreamSync extends ReadStream { - [_open] () { - let threw = true - try { - this[_onopen](null, fs.openSync(this[_path], 'r')) - threw = false - } finally { - if (threw) - this[_close]() - } - } - [_read] () { - let threw = true - try { - if (!this[_reading]) { - this[_reading] = true - do { - const buf = this[_makeBuf]() - /* istanbul ignore next */ - const br = buf.length === 0 ? 0 - : fs.readSync(this[_fd], buf, 0, buf.length, null) - if (!this[_handleChunk](br, buf)) - break - } while (true) - this[_reading] = false - } - threw = false - } finally { - if (threw) - this[_close]() - } - } +/***/ }), - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/ltr.js": +/*!******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/ltr.js ***! + \******************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const outside = __webpack_require__(/*! ./outside */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/outside.js") +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/max-satisfying.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/max-satisfying.js ***! + \*****************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max } +module.exports = maxSatisfying -class WriteStream extends EE { - constructor (path, opt) { - opt = opt || {} - super(opt) - this.readable = false - this.writable = true - this[_errored] = false - this[_writing] = false - this[_ended] = false - this[_needDrain] = false - this[_queue] = [] - this[_path] = path - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_mode] = opt.mode === undefined ? 0o666 : opt.mode - this[_pos] = typeof opt.start === 'number' ? opt.start : null - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true - // truncating makes no sense when writing into the middle - const defaultFlag = this[_pos] !== null ? 'r+' : 'w' - this[_defaultFlag] = opt.flags === undefined - this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags +/***/ }), - if (this[_fd] === null) - this[_open]() - } +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-satisfying.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-satisfying.js ***! + \*****************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - emit (ev, data) { - if (ev === 'error') { - if (this[_errored]) - return - this[_errored] = true - } - return super.emit(ev, data) +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying - get fd () { return this[_fd] } - get path () { return this[_path] } +/***/ }), - [_onerror] (er) { - this[_close]() - this[_writing] = true - this.emit('error', er) +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-version.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/min-version.js ***! + \**************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const gt = __webpack_require__(/*! ../functions/gt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js") + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver } - [_open] () { - fs.open(this[_path], this[_flags], this[_mode], - (er, fd) => this[_onopen](er, fd)) + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver } - [_onopen] (er, fd) { - if (this[_defaultFlag] && - this[_flags] === 'r+' && - er && er.code === 'ENOENT') { - this[_flags] = 'w' - this[_open]() - } else if (er) - this[_onerror](er) - else { - this[_fd] = fd - this.emit('open', fd) - this[_flush]() + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin } } - end (buf, enc) { - if (buf) - this.write(buf, enc) + if (minver && range.test(minver)) { + return minver + } - this[_ended] = true + return null +} +module.exports = minVersion - // synthetic after-write logic, where drain/finish live - if (!this[_writing] && !this[_queue].length && - typeof this[_fd] === 'number') - this[_onwrite](null, 0) - return this - } - write (buf, enc) { - if (typeof buf === 'string') - buf = Buffer.from(buf, enc) +/***/ }), - if (this[_ended]) { - this.emit('error', new Error('write() after end()')) - return false - } +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/outside.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/outside.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (this[_fd] === null || this[_writing] || this[_queue].length) { - this[_queue].push(buf) - this[_needDrain] = true - return false - } +const SemVer = __webpack_require__(/*! ../classes/semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/semver.js") +const Comparator = __webpack_require__(/*! ../classes/comparator */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js") +const { ANY } = Comparator +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const satisfies = __webpack_require__(/*! ../functions/satisfies */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js") +const gt = __webpack_require__(/*! ../functions/gt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gt.js") +const lt = __webpack_require__(/*! ../functions/lt */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lt.js") +const lte = __webpack_require__(/*! ../functions/lte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/lte.js") +const gte = __webpack_require__(/*! ../functions/gte */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/gte.js") - this[_writing] = true - this[_write](buf) - return true +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') } - [_write] (buf) { - fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => - this[_onwrite](er, bw)) + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false } - [_onwrite] (er, bw) { - if (er) - this[_onerror](er) - else { - if (this[_pos] !== null) - this[_pos] += bw - if (this[_queue].length) - this[_flush]() - else { - this[_writing] = false + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - if (this[_ended] && !this[_finished]) { - this[_finished] = true - this[_close]() - this.emit('finish') - } else if (this[_needDrain]) { - this[_needDrain] = false - this.emit('drain') - } + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') } - } - } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) - [_flush] () { - if (this[_queue].length === 0) { - if (this[_ended]) - this[_onwrite](null, 0) - } else if (this[_queue].length === 1) - this[_write](this[_queue].pop()) - else { - const iovec = this[_queue] - this[_queue] = [] - writev(this[_fd], iovec, this[_pos], - (er, bw) => this[_onwrite](er, bw)) + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false } - } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false } } + return true } -class WriteStreamSync extends WriteStream { - [_open] () { - let fd - // only wrap in a try{} block if we know we'll retry, to avoid - // the rethrow obscuring the error's source frame in most cases. - if (this[_defaultFlag] && this[_flags] === 'r+') { - try { - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - } catch (er) { - if (er.code === 'ENOENT') { - this[_flags] = 'w' - return this[_open]() - } else - throw er - } - } else - fd = fs.openSync(this[_path], this[_flags], this[_mode]) +module.exports = outside - this[_onopen](null, fd) - } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') +/***/ }), + +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/simplify.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/simplify.js ***! + \***********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __webpack_require__(/*! ../functions/satisfies.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js") +const compare = __webpack_require__(/*! ../functions/compare.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null } } + if (first) { + set.push([first, null]) + } - [_write] (buf) { - // throw the original, but try to close if it fails - let threw = true - try { - this[_onwrite](null, - fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) - threw = false - } finally { - if (threw) - try { this[_close]() } catch (_) {} + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) } } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range } -exports.ReadStream = ReadStream -exports.ReadStreamSync = ReadStreamSync - -exports.WriteStream = WriteStream -exports.WriteStreamSync = WriteStreamSync - /***/ }), -/***/ "./.yarn/cache/has-flag-npm-4.0.0-32af9f0536-261a135703.zip/node_modules/has-flag/index.js": -/*!*************************************************************************************************!*\ - !*** ./.yarn/cache/has-flag-npm-4.0.0-32af9f0536-261a135703.zip/node_modules/has-flag/index.js ***! - \*************************************************************************************************/ -/***/ ((module) => { +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/subset.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/subset.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +const Range = __webpack_require__(/*! ../classes/range.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const Comparator = __webpack_require__(/*! ../classes/comparator.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/comparator.js") +const { ANY } = Comparator +const satisfies = __webpack_require__(/*! ../functions/satisfies.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/satisfies.js") +const compare = __webpack_require__(/*! ../functions/compare.js */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/functions/compare.js") +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} -/***/ }), +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } -/***/ "./.yarn/cache/is-windows-npm-1.0.2-898cd6f3d7-438b7e5265.zip/node_modules/is-windows/index.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/is-windows-npm-1.0.2-898cd6f3d7-438b7e5265.zip/node_modules/is-windows/index.js ***! - \*****************************************************************************************************/ -/***/ ((module, exports) => { + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = [new Comparator('>=0.0.0-0')] + } else { + sub = [new Comparator('>=0.0.0')] + } + } -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! - * is-windows - * - * Copyright © 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = [new Comparator('>=0.0.0')] + } + } -(function(factory) { - if (exports && typeof exports === 'object' && "object" !== 'undefined') { - module.exports = factory(); - } else if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -})(function() { - 'use strict'; - return function isWindows() { - return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); - }; -}); + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + if (eqSet.size > 1) { + return null + } -/***/ }), + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } -/***/ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/index.js": -/*!*******************************************************************************************!*\ - !*** ./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/index.js ***! - \*******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } -var fs = __webpack_require__(/*! fs */ "fs") -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(/*! ./windows.js */ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/windows.js") -} else { - core = __webpack_require__(/*! ./mode.js */ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/mode.js") -} + if (lt && !satisfies(eq, String(lt), options)) { + return null + } -module.exports = isexe -isexe.sync = sync + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} + return true } - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } } - - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false } - }) - }) - } - - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false } } - cb(er, is) - }) -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { + if (!c.operator && (lt || gt) && gtltComp !== 0) { return false - } else { - throw er } } -} - - -/***/ }), -/***/ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/mode.js": -/*!******************************************************************************************!*\ - !*** ./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/mode.js ***! - \******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } -module.exports = isexe -isexe.sync = sync + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } -var fs = __webpack_require__(/*! fs */ "fs") + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) + return true } -function sync (path, options) { - return checkStat(fs.statSync(path), options) +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a } -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a } -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid +module.exports = subset - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g +/***/ }), - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/to-comparators.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/to-comparators.js ***! + \*****************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return ret -} +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators /***/ }), -/***/ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/windows.js": -/*!*********************************************************************************************!*\ - !*** ./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/windows.js ***! - \*********************************************************************************************/ +/***/ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/valid.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/ranges/valid.js ***! + \********************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -module.exports = isexe -isexe.sync = sync +const Range = __webpack_require__(/*! ../classes/range */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/classes/range.js") +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange -var fs = __webpack_require__(/*! fs */ "fs") -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT +/***/ }), - if (!pathext) { - return true - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/index.js": +/*!********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/index.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} +"use strict"; -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} +// high-level commands +exports.c = exports.create = __webpack_require__(/*! ./lib/create.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/create.js") +exports.r = exports.replace = __webpack_require__(/*! ./lib/replace.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/replace.js") +exports.t = exports.list = __webpack_require__(/*! ./lib/list.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/list.js") +exports.u = exports.update = __webpack_require__(/*! ./lib/update.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/update.js") +exports.x = exports.extract = __webpack_require__(/*! ./lib/extract.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/extract.js") -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} +// classes +exports.Pack = __webpack_require__(/*! ./lib/pack.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pack.js") +exports.Unpack = __webpack_require__(/*! ./lib/unpack.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/unpack.js") +exports.Parse = __webpack_require__(/*! ./lib/parse.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/parse.js") +exports.ReadEntry = __webpack_require__(/*! ./lib/read-entry.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/read-entry.js") +exports.WriteEntry = __webpack_require__(/*! ./lib/write-entry.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/write-entry.js") +exports.Header = __webpack_require__(/*! ./lib/header.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js") +exports.Pax = __webpack_require__(/*! ./lib/pax.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pax.js") +exports.types = __webpack_require__(/*! ./lib/types.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/types.js") /***/ }), -/***/ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js": +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/create.js": /*!*************************************************************************************************!*\ - !*** ./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js ***! + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/create.js ***! \*************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -const EE = __webpack_require__(/*! events */ "events") -const Stream = __webpack_require__(/*! stream */ "stream") -const Yallist = __webpack_require__(/*! yallist */ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/yallist.js") -const SD = __webpack_require__(/*! string_decoder */ "string_decoder").StringDecoder -const EOF = Symbol('EOF') -const MAYBE_EMIT_END = Symbol('maybeEmitEnd') -const EMITTED_END = Symbol('emittedEnd') -const EMITTING_END = Symbol('emittingEnd') -const CLOSED = Symbol('closed') -const READ = Symbol('read') -const FLUSH = Symbol('flush') -const FLUSHCHUNK = Symbol('flushChunk') -const ENCODING = Symbol('encoding') -const DECODER = Symbol('decoder') -const FLOWING = Symbol('flowing') -const PAUSED = Symbol('paused') -const RESUME = Symbol('resume') -const BUFFERLENGTH = Symbol('bufferLength') -const BUFFERPUSH = Symbol('bufferPush') -const BUFFERSHIFT = Symbol('bufferShift') -const OBJECTMODE = Symbol('objectMode') -const DESTROYED = Symbol('destroyed') +// tar -c +const hlo = __webpack_require__(/*! ./high-level-opt.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js") -// TODO remove when Node v8 support drops -const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' -const ASYNCITERATOR = doIter && Symbol.asyncIterator - || Symbol('asyncIterator not implemented') -const ITERATOR = doIter && Symbol.iterator - || Symbol('iterator not implemented') +const Pack = __webpack_require__(/*! ./pack.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pack.js") +const fsm = __webpack_require__(/*! fs-minipass */ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js") +const t = __webpack_require__(/*! ./list.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/list.js") +const path = __webpack_require__(/*! path */ "path") -// events that mean 'the stream is over' -// these are treated specially, and re-emitted -// if they are listened for after emitting. -const isEndish = ev => - ev === 'end' || - ev === 'finish' || - ev === 'prefinish' +module.exports = (opt_, files, cb) => { + if (typeof files === 'function') + cb = files -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 + if (Array.isArray(opt_)) + files = opt_, opt_ = {} -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') -module.exports = class Minipass extends Stream { - constructor (options) { - super() - this[FLOWING] = false - // whether we're explicitly paused - this[PAUSED] = false - this.pipes = new Yallist() - this.buffer = new Yallist() - this[OBJECTMODE] = options && options.objectMode || false - if (this[OBJECTMODE]) - this[ENCODING] = null - else - this[ENCODING] = options && options.encoding || null - if (this[ENCODING] === 'buffer') - this[ENCODING] = null - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null - this[EOF] = false - this[EMITTED_END] = false - this[EMITTING_END] = false - this[CLOSED] = false - this.writable = true - this.readable = true - this[BUFFERLENGTH] = 0 - this[DESTROYED] = false - } + files = Array.from(files) - get bufferLength () { return this[BUFFERLENGTH] } + const opt = hlo(opt_) - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null - if (this.buffer.length) - this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) - } + return opt.file && opt.sync ? createFileSync(opt, files) + : opt.file ? createFile(opt, files, cb) + : opt.sync ? createSync(opt, files) + : create(opt, files) +} - this[ENCODING] = enc - } +const createFileSync = (opt, files) => { + const p = new Pack.Sync(opt) + const stream = new fsm.WriteStreamSync(opt.file, { + mode: opt.mode || 0o666, + }) + p.pipe(stream) + addFilesSync(p, files) +} - setEncoding (enc) { - this.encoding = enc - } +const createFile = (opt, files, cb) => { + const p = new Pack(opt) + const stream = new fsm.WriteStream(opt.file, { + mode: opt.mode || 0o666, + }) + p.pipe(stream) - get objectMode () { return this[OBJECTMODE] } - set objectMode (ॐ ) { this[OBJECTMODE] = this[OBJECTMODE] || !!ॐ } + const promise = new Promise((res, rej) => { + stream.on('error', rej) + stream.on('close', res) + p.on('error', rej) + }) - write (chunk, encoding, cb) { - if (this[EOF]) - throw new Error('write after end') + addFilesAsync(p, files) - if (this[DESTROYED]) { - this.emit('error', Object.assign( - new Error('Cannot call write after a stream was destroyed'), - { code: 'ERR_STREAM_DESTROYED' } - )) - return true - } + return cb ? promise.then(cb, cb) : promise +} - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +const addFilesSync = (p, files) => { + files.forEach(file => { + if (file.charAt(0) === '@') { + t({ + file: path.resolve(p.cwd, file.substr(1)), + sync: true, + noResume: true, + onentry: entry => p.add(entry), + }) + } else + p.add(file) + }) + p.end() +} - if (!encoding) - encoding = 'utf8' +const addFilesAsync = (p, files) => { + while (files.length) { + const file = files.shift() + if (file.charAt(0) === '@') { + return t({ + file: path.resolve(p.cwd, file.substr(1)), + noResume: true, + onentry: entry => p.add(entry), + }).then(_ => addFilesAsync(p, files)) + } else + p.add(file) + } + p.end() +} - // convert array buffers and typed array views into buffers - // at some point in the future, we may want to do the opposite! - // leave strings and buffers as-is - // anything else switches us into object mode - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk) - else if (typeof chunk !== 'string') - // use the setter so we throw if we have encoding set - this.objectMode = true - } +const createSync = (opt, files) => { + const p = new Pack.Sync(opt) + addFilesSync(p, files) + return p +} - // this ensures at this point that the chunk is a buffer or string - // don't buffer it up or send it to the decoder - if (!this.objectMode && !chunk.length) { - const ret = this.flowing - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - cb() - return ret - } +const create = (opt, files) => { + const p = new Pack(opt) + addFilesAsync(p, files) + return p +} - // fast-path writing strings of same encoding to a stream with - // an empty buffer, skipping the buffer/decoder dance - if (typeof chunk === 'string' && !this[OBJECTMODE] && - // unless it is a string already ready for us to use - !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding) - } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) +/***/ }), - try { - return this.flowing - ? (this.emit('data', chunk), this.flowing) - : (this[BUFFERPUSH](chunk), false) - } finally { - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - cb() - } - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/extract.js": +/*!**************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/extract.js ***! + \**************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - read (n) { - if (this[DESTROYED]) - return null +"use strict"; - try { - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) - return null - if (this[OBJECTMODE]) - n = null +// tar -x +const hlo = __webpack_require__(/*! ./high-level-opt.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js") +const Unpack = __webpack_require__(/*! ./unpack.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/unpack.js") +const fs = __webpack_require__(/*! fs */ "fs") +const fsm = __webpack_require__(/*! fs-minipass */ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js") +const path = __webpack_require__(/*! path */ "path") +const stripSlash = __webpack_require__(/*! ./strip-trailing-slashes.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js") - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = new Yallist([ - Array.from(this.buffer).join('') - ]) - else - this.buffer = new Yallist([ - Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH]) - ]) - } +module.exports = (opt_, files, cb) => { + if (typeof opt_ === 'function') + cb = opt_, files = null, opt_ = {} + else if (Array.isArray(opt_)) + files = opt_, opt_ = {} - return this[READ](n || null, this.buffer.head.value) - } finally { - this[MAYBE_EMIT_END]() - } - } + if (typeof files === 'function') + cb = files, files = null - [READ] (n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT]() - else { - this.buffer.head.value = chunk.slice(n) - chunk = chunk.slice(0, n) - this[BUFFERLENGTH] -= n - } + if (!files) + files = [] + else + files = Array.from(files) - this.emit('data', chunk) + const opt = hlo(opt_) - if (!this.buffer.length && !this[EOF]) - this.emit('drain') + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') - return chunk - } + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - if (cb) - this.once('end', cb) - this[EOF] = true - this.writable = false + if (files.length) + filesFilter(opt, files) - // if we haven't written anything, then go ahead and emit, - // even if we're not reading. - // we'll re-emit if a new 'end' listener is added anyway. - // This makes MP more suitable to write-only use cases. - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END]() - return this + return opt.file && opt.sync ? extractFileSync(opt) + : opt.file ? extractFile(opt, cb) + : opt.sync ? extractSync(opt) + : extract(opt) +} + +// construct a filter that limits the file entries listed +// include child entries if a dir is included +const filesFilter = (opt, files) => { + const map = new Map(files.map(f => [stripSlash(f), true])) + const filter = opt.filter + + const mapHas = (file, r) => { + const root = r || path.parse(file).root || '.' + const ret = file === root ? false + : map.has(file) ? map.get(file) + : mapHas(path.dirname(file), root) + + map.set(file, ret) + return ret } - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return + opt.filter = filter + ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) + : file => mapHas(stripSlash(file)) +} - this[PAUSED] = false - this[FLOWING] = true - this.emit('resume') - if (this.buffer.length) - this[FLUSH]() - else if (this[EOF]) - this[MAYBE_EMIT_END]() - else - this.emit('drain') - } +const extractFileSync = opt => { + const u = new Unpack.Sync(opt) - resume () { - return this[RESUME]() - } + const file = opt.file + const stat = fs.statSync(file) + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + const stream = new fsm.ReadStreamSync(file, { + readSize: readSize, + size: stat.size, + }) + stream.pipe(u) +} - pause () { - this[FLOWING] = false - this[PAUSED] = true - } +const extractFile = (opt, cb) => { + const u = new Unpack(opt) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 - get destroyed () { - return this[DESTROYED] - } + const file = opt.file + const p = new Promise((resolve, reject) => { + u.on('error', reject) + u.on('close', resolve) - get flowing () { - return this[FLOWING] - } + // This trades a zero-byte read() syscall for a stat + // However, it will usually result in less memory allocation + fs.stat(file, (er, stat) => { + if (er) + reject(er) + else { + const stream = new fsm.ReadStream(file, { + readSize: readSize, + size: stat.size, + }) + stream.on('error', reject) + stream.pipe(u) + } + }) + }) + return cb ? p.then(cb, cb) : p +} - get paused () { - return this[PAUSED] - } +const extractSync = opt => new Unpack.Sync(opt) - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - return this.buffer.push(chunk) - } +const extract = opt => new Unpack(opt) - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer.head.value.length - } - return this.buffer.shift() - } - [FLUSH] () { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) +/***/ }), - if (!this.buffer.length && !this[EOF]) - this.emit('drain') - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/get-write-flag.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/get-write-flag.js ***! + \*********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } +// Get the appropriate flag to use for creating files +// We use fmap on Windows platforms for files less than +// 512kb. This is a fairly low limit, but avoids making +// things slower in some cases. Since most of what this +// library is used for is extracting tarballs of many +// relatively small files in npm packages and the like, +// it can be a big boost on Windows platforms. +// Only supported in Node v12.9.0 and above. +const platform = process.env.__FAKE_PLATFORM__ || process.platform +const isWindows = platform === 'win32' +const fs = global.__FAKE_TESTING_FS__ || __webpack_require__(/*! fs */ "fs") - pipe (dest, opts) { - if (this[DESTROYED]) - return +/* istanbul ignore next */ +const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants - const ended = this[EMITTED_END] - opts = opts || {} - if (dest === process.stdout || dest === process.stderr) - opts.end = false - else - opts.end = opts.end !== false +const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP +const fMapLimit = 512 * 1024 +const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY +module.exports = !fMapEnabled ? () => 'w' + : size => size < fMapLimit ? fMapFlag : 'w' - const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() } - this.pipes.push(p) - dest.on('drain', p.ondrain) - this[RESUME]() - // piping an ended stream ends immediately - if (ended && p.opts.end) - p.dest.end() - return dest - } +/***/ }), - addListener (ev, fn) { - return this.on(ev, fn) - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js ***! + \*************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - on (ev, fn) { - try { - return super.on(ev, fn) - } finally { - if (ev === 'data' && !this.pipes.length && !this.flowing) - this[RESUME]() - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev) - this.removeAllListeners(ev) - } - } - } +"use strict"; - get emittedEnd () { - return this[EMITTED_END] - } +// parse a 512-byte header block to a data object, or vice-versa +// encode returns `true` if a pax extended header is needed, because +// the data could not be faithfully encoded in a simple header. +// (Also, check header.needPax to see if it needs a pax header.) - [MAYBE_EMIT_END] () { - if (!this[EMITTING_END] && - !this[EMITTED_END] && - !this[DESTROYED] && - this.buffer.length === 0 && - this[EOF]) { - this[EMITTING_END] = true - this.emit('end') - this.emit('prefinish') - this.emit('finish') - if (this[CLOSED]) - this.emit('close') - this[EMITTING_END] = false - } - } +const types = __webpack_require__(/*! ./types.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/types.js") +const pathModule = (__webpack_require__(/*! path */ "path").posix) +const large = __webpack_require__(/*! ./large-numbers.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/large-numbers.js") - emit (ev, data) { - // error and close are only events allowed after calling destroy() - if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) - return - else if (ev === 'data') { - if (!data) - return +const SLURP = Symbol('slurp') +const TYPE = Symbol('type') - if (this.pipes.length) - this.pipes.forEach(p => - p.dest.write(data) === false && this.pause()) - } else if (ev === 'end') { - // only actual end gets this treatment - if (this[EMITTED_END] === true) - return +class Header { + constructor (data, off, ex, gex) { + this.cksumValid = false + this.needPax = false + this.nullBlock = false - this[EMITTED_END] = true - this.readable = false + this.block = null + this.path = null + this.mode = null + this.uid = null + this.gid = null + this.size = null + this.mtime = null + this.cksum = null + this[TYPE] = '0' + this.linkpath = null + this.uname = null + this.gname = null + this.devmaj = 0 + this.devmin = 0 + this.atime = null + this.ctime = null - if (this[DECODER]) { - data = this[DECODER].end() - if (data) { - this.pipes.forEach(p => p.dest.write(data)) - super.emit('data', data) - } - } + if (Buffer.isBuffer(data)) + this.decode(data, off || 0, ex, gex) + else if (data) + this.set(data) + } - this.pipes.forEach(p => { - p.dest.removeListener('drain', p.ondrain) - if (p.opts.end) - p.dest.end() - }) - } else if (ev === 'close') { - this[CLOSED] = true - // don't emit close before 'end' and 'finish' - if (!this[EMITTED_END] && !this[DESTROYED]) - return - } + decode (buf, off, ex, gex) { + if (!off) + off = 0 - // TODO: replace with a spread operator when Node v4 support drops - const args = new Array(arguments.length) - args[0] = ev - args[1] = data - if (arguments.length > 2) { - for (let i = 2; i < arguments.length; i++) { - args[i] = arguments[i] - } - } + if (!buf || !(buf.length >= off + 512)) + throw new Error('need 512 bytes for header') - try { - return super.emit.apply(this, args) - } finally { - if (!isEndish(ev)) - this[MAYBE_EMIT_END]() - else - this.removeAllListeners(ev) - } - } + this.path = decString(buf, off, 100) + this.mode = decNumber(buf, off + 100, 8) + this.uid = decNumber(buf, off + 108, 8) + this.gid = decNumber(buf, off + 116, 8) + this.size = decNumber(buf, off + 124, 12) + this.mtime = decDate(buf, off + 136, 12) + this.cksum = decNumber(buf, off + 148, 12) - // const all = await stream.collect() - collect () { - const buf = [] - if (!this[OBJECTMODE]) - buf.dataLength = 0 - // set the promise first, in case an error is raised - // by triggering the flow here. - const p = this.promise() - this.on('data', c => { - buf.push(c) - if (!this[OBJECTMODE]) - buf.dataLength += c.length - }) - return p.then(() => buf) - } - - // const data = await stream.concat() - concat () { - return this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this.collect().then(buf => - this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) - } - - // stream.promise().then(() => done, er => emitted error) - promise () { - return new Promise((resolve, reject) => { - this.on(DESTROYED, () => reject(new Error('stream destroyed'))) - this.on('end', () => resolve()) - this.on('error', er => reject(er)) - }) - } + // if we have extended or global extended headers, apply them now + // See https://github.com/npm/node-tar/pull/187 + this[SLURP](ex) + this[SLURP](gex, true) - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) + // old tar versions marked dirs as a file with a trailing / + this[TYPE] = decString(buf, off + 156, 1) + if (this[TYPE] === '') + this[TYPE] = '0' + if (this[TYPE] === '0' && this.path.substr(-1) === '/') + this[TYPE] = '5' - if (this[EOF]) - return Promise.resolve({ done: true }) + // tar implementations sometimes incorrectly put the stat(dir).size + // as the size in the tarball, even though Directory entries are + // not able to have any body at all. In the very rare chance that + // it actually DOES have a body, we weren't going to do anything with + // it anyway, and it'll just be a warning about an invalid header. + if (this[TYPE] === '5') + this.size = 0 - let resolve = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - resolve({ done: true }) + this.linkpath = decString(buf, off + 157, 100) + if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { + this.uname = decString(buf, off + 265, 32) + this.gname = decString(buf, off + 297, 32) + this.devmaj = decNumber(buf, off + 329, 8) + this.devmin = decNumber(buf, off + 337, 8) + if (buf[off + 475] !== 0) { + // definitely a prefix, definitely >130 chars. + const prefix = decString(buf, off + 345, 155) + this.path = prefix + '/' + this.path + } else { + const prefix = decString(buf, off + 345, 130) + if (prefix) + this.path = prefix + '/' + this.path + this.atime = decDate(buf, off + 476, 12) + this.ctime = decDate(buf, off + 488, 12) } - const ondestroy = () => onerr(new Error('stream destroyed')) - return new Promise((res, rej) => { - reject = rej - resolve = res - this.once(DESTROYED, ondestroy) - this.once('error', onerr) - this.once('end', onend) - this.once('data', ondata) - }) } - return { next } + let sum = 8 * 0x20 + for (let i = off; i < off + 148; i++) + sum += buf[i] + + for (let i = off + 156; i < off + 512; i++) + sum += buf[i] + + this.cksumValid = sum === this.cksum + if (this.cksum === null && sum === 8 * 0x20) + this.nullBlock = true } - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } + [SLURP] (ex, global) { + for (const k in ex) { + // we slurp in everything except for the path attribute in + // a global extended header, because that's weird. + if (ex[k] !== null && ex[k] !== undefined && + !(global && k === 'path')) + this[k] = ex[k] } - return { next } } - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this + encode (buf, off) { + if (!buf) { + buf = this.block = Buffer.alloc(512) + off = 0 } - this[DESTROYED] = true + if (!off) + off = 0 - // throw away all buffered data, it's never coming out - this.buffer = new Yallist() - this[BUFFERLENGTH] = 0 + if (!(buf.length >= off + 512)) + throw new Error('need 512 bytes for header') - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() + const prefixSize = this.ctime || this.atime ? 130 : 155 + const split = splitPrefix(this.path || '', prefixSize) + const path = split[0] + const prefix = split[1] + this.needPax = split[2] - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) + this.needPax = encString(buf, off, 100, path) || this.needPax + this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax + this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax + this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax + this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax + this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax + buf[off + 156] = this[TYPE].charCodeAt(0) + this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax + buf.write('ustar\u000000', off + 257, 8) + this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax + this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax + this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax + this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax + this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax + if (buf[off + 475] !== 0) + this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax + else { + this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax + this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax + this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax + } - return this + let sum = 8 * 0x20 + for (let i = off; i < off + 148; i++) + sum += buf[i] + + for (let i = off + 156; i < off + 512; i++) + sum += buf[i] + + this.cksum = sum + encNumber(buf, off + 148, 8, this.cksum) + this.cksumValid = true + + return this.needPax } - static isStream (s) { - return !!s && (s instanceof Minipass || s instanceof Stream || - s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable - )) + set (data) { + for (const i in data) { + if (data[i] !== null && data[i] !== undefined) + this[i] = data[i] + } + } + + get type () { + return types.name.get(this[TYPE]) || this[TYPE] + } + + get typeKey () { + return this[TYPE] + } + + set type (type) { + if (types.code.has(type)) + this[TYPE] = types.code.get(type) + else + this[TYPE] = type } } +const splitPrefix = (p, prefixSize) => { + const pathSize = 100 + let pp = p + let prefix = '' + let ret + const root = pathModule.parse(p).root || '.' -/***/ }), + if (Buffer.byteLength(pp) < pathSize) + ret = [pp, prefix, false] + else { + // first set prefix to the dir, and path to the base + prefix = pathModule.dirname(pp) + pp = pathModule.basename(pp) -/***/ "./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/constants.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/constants.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + do { + // both fit! + if (Buffer.byteLength(pp) <= pathSize && + Buffer.byteLength(prefix) <= prefixSize) + ret = [pp, prefix, false] -// Update with any zlib constants that are added or changed in the future. -// Node v6 didn't export this, so we just hard code the version and rely -// on all the other hard-coded values from zlib v4736. When node v6 -// support drops, we can just export the realZlibConstants object. -const realZlibConstants = __webpack_require__(/*! zlib */ "zlib").constants || - /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } + // prefix fits in prefix, but path doesn't fit in path + else if (Buffer.byteLength(pp) > pathSize && + Buffer.byteLength(prefix) <= prefixSize) + ret = [pp.substr(0, pathSize - 1), prefix, true] -module.exports = Object.freeze(Object.assign(Object.create(null), { - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - Z_VERSION_ERROR: -6, - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - DEFLATE: 1, - INFLATE: 2, - GZIP: 3, - GUNZIP: 4, - DEFLATERAW: 5, - INFLATERAW: 6, - UNZIP: 7, - BROTLI_DECODE: 8, - BROTLI_ENCODE: 9, - Z_MIN_WINDOWBITS: 8, - Z_MAX_WINDOWBITS: 15, - Z_DEFAULT_WINDOWBITS: 15, - Z_MIN_CHUNK: 64, - Z_MAX_CHUNK: Infinity, - Z_DEFAULT_CHUNK: 16384, - Z_MIN_MEMLEVEL: 1, - Z_MAX_MEMLEVEL: 9, - Z_DEFAULT_MEMLEVEL: 8, - Z_MIN_LEVEL: -1, - Z_MAX_LEVEL: 9, - Z_DEFAULT_LEVEL: -1, - BROTLI_OPERATION_PROCESS: 0, - BROTLI_OPERATION_FLUSH: 1, - BROTLI_OPERATION_FINISH: 2, - BROTLI_OPERATION_EMIT_METADATA: 3, - BROTLI_MODE_GENERIC: 0, - BROTLI_MODE_TEXT: 1, - BROTLI_MODE_FONT: 2, - BROTLI_DEFAULT_MODE: 0, - BROTLI_MIN_QUALITY: 0, - BROTLI_MAX_QUALITY: 11, - BROTLI_DEFAULT_QUALITY: 11, - BROTLI_MIN_WINDOW_BITS: 10, - BROTLI_MAX_WINDOW_BITS: 24, - BROTLI_LARGE_MAX_WINDOW_BITS: 30, - BROTLI_DEFAULT_WINDOW: 22, - BROTLI_MIN_INPUT_BLOCK_BITS: 16, - BROTLI_MAX_INPUT_BLOCK_BITS: 24, - BROTLI_PARAM_MODE: 0, - BROTLI_PARAM_QUALITY: 1, - BROTLI_PARAM_LGWIN: 2, - BROTLI_PARAM_LGBLOCK: 3, - BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, - BROTLI_PARAM_SIZE_HINT: 5, - BROTLI_PARAM_LARGE_WINDOW: 6, - BROTLI_PARAM_NPOSTFIX: 7, - BROTLI_PARAM_NDIRECT: 8, - BROTLI_DECODER_RESULT_ERROR: 0, - BROTLI_DECODER_RESULT_SUCCESS: 1, - BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, - BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, - BROTLI_DECODER_NO_ERROR: 0, - BROTLI_DECODER_SUCCESS: 1, - BROTLI_DECODER_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, - BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, - BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, - BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, - BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, - BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, - BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, - BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, - BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, - BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, - BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, - BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, - BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, - BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, - BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, - BROTLI_DECODER_ERROR_UNREACHABLE: -31, -}, realZlibConstants)) - - -/***/ }), - -/***/ "./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/index.js": -/*!*************************************************************************************************!*\ - !*** ./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/index.js ***! - \*************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + else { + // make path take a bit from prefix + pp = pathModule.join(pathModule.basename(prefix), pp) + prefix = pathModule.dirname(prefix) + } + } while (prefix !== root && !ret) -"use strict"; + // at this point, found no resolution, just truncate + if (!ret) + ret = [p.substr(0, pathSize - 1), '', true] + } + return ret +} +const decString = (buf, off, size) => + buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') -const assert = __webpack_require__(/*! assert */ "assert") -const Buffer = __webpack_require__(/*! buffer */ "buffer").Buffer -const realZlib = __webpack_require__(/*! zlib */ "zlib") +const decDate = (buf, off, size) => + numToDate(decNumber(buf, off, size)) -const constants = exports.constants = __webpack_require__(/*! ./constants.js */ "./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/constants.js") -const Minipass = __webpack_require__(/*! minipass */ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js") +const numToDate = num => num === null ? null : new Date(num * 1000) -const OriginalBufferConcat = Buffer.concat +const decNumber = (buf, off, size) => + buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) + : decSmallNumber(buf, off, size) -const _superWrite = Symbol('_superWrite') -class ZlibError extends Error { - constructor (err) { - super('zlib: ' + err.message) - this.code = err.code - this.errno = err.errno - /* istanbul ignore if */ - if (!this.code) - this.code = 'ZLIB_ERROR' +const nanNull = value => isNaN(value) ? null : value - this.message = 'zlib: ' + err.message - Error.captureStackTrace(this, this.constructor) - } +const decSmallNumber = (buf, off, size) => + nanNull(parseInt( + buf.slice(off, off + size) + .toString('utf8').replace(/\0.*$/, '').trim(), 8)) - get name () { - return 'ZlibError' - } +// the maximum encodable as a null-terminated octal, by field size +const MAXNUM = { + 12: 0o77777777777, + 8: 0o7777777, } -// the Zlib class they all inherit from -// This thing manages the queue of requests, and returns -// true or false if there is anything in the queue when -// you call the .write() method. -const _opts = Symbol('opts') -const _flushFlag = Symbol('flushFlag') -const _finishFlushFlag = Symbol('finishFlushFlag') -const _fullFlushFlag = Symbol('fullFlushFlag') -const _handle = Symbol('handle') -const _onError = Symbol('onError') -const _sawError = Symbol('sawError') -const _level = Symbol('level') -const _strategy = Symbol('strategy') -const _ended = Symbol('ended') -const _defaultFullFlush = Symbol('_defaultFullFlush') - -class ZlibBase extends Minipass { - constructor (opts, mode) { - if (!opts || typeof opts !== 'object') - throw new TypeError('invalid options for ZlibBase constructor') - - super(opts) - this[_ended] = false - this[_opts] = opts +const encNumber = (buf, off, size, number) => + number === null ? false : + number > MAXNUM[size] || number < 0 + ? (large.encode(number, buf.slice(off, off + size)), true) + : (encSmallNumber(buf, off, size, number), false) - this[_flushFlag] = opts.flush - this[_finishFlushFlag] = opts.finishFlush - // this will throw if any options are invalid for the class selected - try { - this[_handle] = new realZlib[mode](opts) - } catch (er) { - // make sure that all errors get decorated properly - throw new ZlibError(er) - } +const encSmallNumber = (buf, off, size, number) => + buf.write(octalString(number, size), off, size, 'ascii') - this[_onError] = (err) => { - this[_sawError] = true - // there is no way to cleanly recover. - // continuing only obscures problems. - this.close() - this.emit('error', err) - } +const octalString = (number, size) => + padOctal(Math.floor(number).toString(8), size) - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - this.once('end', () => this.close) - } +const padOctal = (string, size) => + (string.length === size - 1 ? string + : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' - close () { - if (this[_handle]) { - this[_handle].close() - this[_handle] = null - this.emit('close') - } - } +const encDate = (buf, off, size, date) => + date === null ? false : + encNumber(buf, off, size, date.getTime() / 1000) - reset () { - if (!this[_sawError]) { - assert(this[_handle], 'zlib binding closed') - return this[_handle].reset() - } - } +// enough to fill the longest string we've got +const NULLS = new Array(156).join('\0') +// pad with nulls, return true if it's longer or non-ascii +const encString = (buf, off, size, string) => + string === null ? false : + (buf.write(string + NULLS, off, size, 'utf8'), + string.length !== Buffer.byteLength(string) || string.length > size) - flush (flushFlag) { - if (this.ended) - return +module.exports = Header - if (typeof flushFlag !== 'number') - flushFlag = this[_fullFlushFlag] - this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) - } - end (chunk, encoding, cb) { - if (chunk) - this.write(chunk, encoding) - this.flush(this[_finishFlushFlag]) - this[_ended] = true - return super.end(null, null, cb) - } +/***/ }), - get ended () { - return this[_ended] - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js ***! + \*********************************************************************************************************/ +/***/ ((module) => { - write (chunk, encoding, cb) { - // process the chunk using the sync process - // then super.write() all the outputted chunks - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +"use strict"; - if (typeof chunk === 'string') - chunk = Buffer.from(chunk, encoding) - if (this[_sawError]) - return - assert(this[_handle], 'zlib binding closed') +// turn tar(1) style args like `C` into the more verbose things like `cwd` - // _processChunk tries to .close() the native handle after it's done, so we - // intercept that by temporarily making it a no-op. - const nativeHandle = this[_handle]._handle - const originalNativeClose = nativeHandle.close - nativeHandle.close = () => {} - const originalClose = this[_handle].close - this[_handle].close = () => {} - // It also calls `Buffer.concat()` at the end, which may be convenient - // for some, but which we are not interested in as it slows us down. - Buffer.concat = (args) => args - let result - try { - const flushFlag = typeof chunk[_flushFlag] === 'number' - ? chunk[_flushFlag] : this[_flushFlag] - result = this[_handle]._processChunk(chunk, flushFlag) - // if we don't throw, reset it back how it was - Buffer.concat = OriginalBufferConcat - } catch (err) { - // or if we do, put Buffer.concat() back before we emit error - // Error events call into user code, which may call Buffer.concat() - Buffer.concat = OriginalBufferConcat - this[_onError](new ZlibError(err)) - } finally { - if (this[_handle]) { - // Core zlib resets `_handle` to null after attempting to close the - // native handle. Our no-op handler prevented actual closure, but we - // need to restore the `._handle` property. - this[_handle]._handle = nativeHandle - nativeHandle.close = originalNativeClose - this[_handle].close = originalClose - // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. - this[_handle].removeAllListeners('error') - } - } - - let writeReturn - if (result) { - if (Array.isArray(result) && result.length > 0) { - // The first buffer is always `handle._outBuffer`, which would be - // re-used for later invocations; so, we always have to copy that one. - writeReturn = this[_superWrite](Buffer.from(result[0])) - for (let i = 1; i < result.length; i++) { - writeReturn = this[_superWrite](result[i]) - } - } else { - writeReturn = this[_superWrite](Buffer.from(result)) - } - } - - if (cb) - cb() - return writeReturn - } - - [_superWrite] (data) { - return super.write(data) - } -} +const argmap = new Map([ + ['C', 'cwd'], + ['f', 'file'], + ['z', 'gzip'], + ['P', 'preservePaths'], + ['U', 'unlink'], + ['strip-components', 'strip'], + ['stripComponents', 'strip'], + ['keep-newer', 'newer'], + ['keepNewer', 'newer'], + ['keep-newer-files', 'newer'], + ['keepNewerFiles', 'newer'], + ['k', 'keep'], + ['keep-existing', 'keep'], + ['keepExisting', 'keep'], + ['m', 'noMtime'], + ['no-mtime', 'noMtime'], + ['p', 'preserveOwner'], + ['L', 'follow'], + ['h', 'follow'], +]) -class Zlib extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} +module.exports = opt => opt ? Object.keys(opt).map(k => [ + argmap.has(k) ? argmap.get(k) : k, opt[k], +]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} - opts.flush = opts.flush || constants.Z_NO_FLUSH - opts.finishFlush = opts.finishFlush || constants.Z_FINISH - super(opts, mode) - this[_fullFlushFlag] = constants.Z_FULL_FLUSH - this[_level] = opts.level - this[_strategy] = opts.strategy - } +/***/ }), - params (level, strategy) { - if (this[_sawError]) - return +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/large-numbers.js": +/*!********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/large-numbers.js ***! + \********************************************************************************************************/ +/***/ ((module) => { - if (!this[_handle]) - throw new Error('cannot switch params when binding is closed') +"use strict"; - // no way to test this without also not supporting params at all - /* istanbul ignore if */ - if (!this[_handle].params) - throw new Error('not supported in this implementation') +// Tar can encode large and negative numbers using a leading byte of +// 0xff for negative, and 0x80 for positive. - if (this[_level] !== level || this[_strategy] !== strategy) { - this.flush(constants.Z_SYNC_FLUSH) - assert(this[_handle], 'zlib binding closed') - // .params() calls .flush(), but the latter is always async in the - // core zlib. We override .flush() temporarily to intercept that and - // flush synchronously. - const origFlush = this[_handle].flush - this[_handle].flush = (flushFlag, cb) => { - this.flush(flushFlag) - cb() - } - try { - this[_handle].params(level, strategy) - } finally { - this[_handle].flush = origFlush - } - /* istanbul ignore else */ - if (this[_handle]) { - this[_level] = level - this[_strategy] = strategy - } - } - } +const encode = (num, buf) => { + if (!Number.isSafeInteger(num)) + // The number is so large that javascript cannot represent it with integer + // precision. + throw Error('cannot encode number outside of javascript safe integer range') + else if (num < 0) + encodeNegative(num, buf) + else + encodePositive(num, buf) + return buf } -// minimal 2-byte header -class Deflate extends Zlib { - constructor (opts) { - super(opts, 'Deflate') +const encodePositive = (num, buf) => { + buf[0] = 0x80 + + for (var i = buf.length; i > 1; i--) { + buf[i - 1] = num & 0xff + num = Math.floor(num / 0x100) } } -class Inflate extends Zlib { - constructor (opts) { - super(opts, 'Inflate') +const encodeNegative = (num, buf) => { + buf[0] = 0xff + var flipped = false + num = num * -1 + for (var i = buf.length; i > 1; i--) { + var byte = num & 0xff + num = Math.floor(num / 0x100) + if (flipped) + buf[i - 1] = onesComp(byte) + else if (byte === 0) + buf[i - 1] = 0 + else { + flipped = true + buf[i - 1] = twosComp(byte) + } } } -// gzip - bigger header, same deflate compression -const _portable = Symbol('_portable') -class Gzip extends Zlib { - constructor (opts) { - super(opts, 'Gzip') - this[_portable] = opts && !!opts.portable - } +const parse = (buf) => { + const pre = buf[0] + const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) + : pre === 0xff ? twos(buf) + : null + if (value === null) + throw Error('invalid base256 encoding') - [_superWrite] (data) { - if (!this[_portable]) - return super[_superWrite](data) + if (!Number.isSafeInteger(value)) + // The number is so large that javascript cannot represent it with integer + // precision. + throw Error('parsed number outside of javascript safe integer range') - // we'll always get the header emitted in one first chunk - // overwrite the OS indicator byte with 0xFF - this[_portable] = false - data[9] = 255 - return super[_superWrite](data) - } + return value } -class Gunzip extends Zlib { - constructor (opts) { - super(opts, 'Gunzip') +const twos = (buf) => { + var len = buf.length + var sum = 0 + var flipped = false + for (var i = len - 1; i > -1; i--) { + var byte = buf[i] + var f + if (flipped) + f = onesComp(byte) + else if (byte === 0) + f = byte + else { + flipped = true + f = twosComp(byte) + } + if (f !== 0) + sum -= f * Math.pow(256, len - i - 1) } + return sum } -// raw - no header -class DeflateRaw extends Zlib { - constructor (opts) { - super(opts, 'DeflateRaw') +const pos = (buf) => { + var len = buf.length + var sum = 0 + for (var i = len - 1; i > -1; i--) { + var byte = buf[i] + if (byte !== 0) + sum += byte * Math.pow(256, len - i - 1) } + return sum } -class InflateRaw extends Zlib { - constructor (opts) { - super(opts, 'InflateRaw') - } -} +const onesComp = byte => (0xff ^ byte) & 0xff -// auto-detect header. -class Unzip extends Zlib { - constructor (opts) { - super(opts, 'Unzip') - } +const twosComp = byte => ((0xff ^ byte) + 1) & 0xff + +module.exports = { + encode, + parse, } -class Brotli extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} - opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS - opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH +/***/ }), - super(opts, mode) +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/list.js": +/*!***********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/list.js ***! + \***********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH - } -} +"use strict"; -class BrotliCompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliCompress') - } -} -class BrotliDecompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliDecompress') - } -} +// XXX: This shares a lot in common with extract.js +// maybe some DRY opportunity here? -exports.Deflate = Deflate -exports.Inflate = Inflate -exports.Gzip = Gzip -exports.Gunzip = Gunzip -exports.DeflateRaw = DeflateRaw -exports.InflateRaw = InflateRaw -exports.Unzip = Unzip -/* istanbul ignore else */ -if (typeof realZlib.BrotliCompress === 'function') { - exports.BrotliCompress = BrotliCompress - exports.BrotliDecompress = BrotliDecompress -} else { - exports.BrotliCompress = exports.BrotliDecompress = class { - constructor () { - throw new Error('Brotli is not supported in this version of Node.js') - } - } -} - - -/***/ }), +// tar -t +const hlo = __webpack_require__(/*! ./high-level-opt.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js") +const Parser = __webpack_require__(/*! ./parse.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/parse.js") +const fs = __webpack_require__(/*! fs */ "fs") +const fsm = __webpack_require__(/*! fs-minipass */ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js") +const path = __webpack_require__(/*! path */ "path") +const stripSlash = __webpack_require__(/*! ./strip-trailing-slashes.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js") -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/index.js": -/*!*********************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/index.js ***! - \*********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = (opt_, files, cb) => { + if (typeof opt_ === 'function') + cb = opt_, files = null, opt_ = {} + else if (Array.isArray(opt_)) + files = opt_, opt_ = {} -const optsArg = __webpack_require__(/*! ./lib/opts-arg.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/opts-arg.js") -const pathArg = __webpack_require__(/*! ./lib/path-arg.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/path-arg.js") + if (typeof files === 'function') + cb = files, files = null -const {mkdirpNative, mkdirpNativeSync} = __webpack_require__(/*! ./lib/mkdirp-native.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-native.js") -const {mkdirpManual, mkdirpManualSync} = __webpack_require__(/*! ./lib/mkdirp-manual.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-manual.js") -const {useNative, useNativeSync} = __webpack_require__(/*! ./lib/use-native.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/use-native.js") + if (!files) + files = [] + else + files = Array.from(files) + const opt = hlo(opt_) -const mkdirp = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNative(opts) - ? mkdirpNative(path, opts) - : mkdirpManual(path, opts) -} + if (opt.sync && typeof cb === 'function') + throw new TypeError('callback not supported for sync tar functions') -const mkdirpSync = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNativeSync(opts) - ? mkdirpNativeSync(path, opts) - : mkdirpManualSync(path, opts) -} + if (!opt.file && typeof cb === 'function') + throw new TypeError('callback only supported with file option') -mkdirp.sync = mkdirpSync -mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) -mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) -mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) -mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) + if (files.length) + filesFilter(opt, files) -module.exports = mkdirp + if (!opt.noResume) + onentryFunction(opt) + return opt.file && opt.sync ? listFileSync(opt) + : opt.file ? listFile(opt, cb) + : list(opt) +} -/***/ }), +const onentryFunction = opt => { + const onentry = opt.onentry + opt.onentry = onentry ? e => { + onentry(e) + e.resume() + } : e => e.resume() +} -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/find-made.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/find-made.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// construct a filter that limits the file entries listed +// include child entries if a dir is included +const filesFilter = (opt, files) => { + const map = new Map(files.map(f => [stripSlash(f), true])) + const filter = opt.filter -const {dirname} = __webpack_require__(/*! path */ "path") + const mapHas = (file, r) => { + const root = r || path.parse(file).root || '.' + const ret = file === root ? false + : map.has(file) ? map.get(file) + : mapHas(path.dirname(file), root) -const findMade = (opts, parent, path = undefined) => { - // we never want the 'made' return value to be a root directory - if (path === parent) - return Promise.resolve() + map.set(file, ret) + return ret + } - return opts.statAsync(parent).then( - st => st.isDirectory() ? path : undefined, // will fail later - er => er.code === 'ENOENT' - ? findMade(opts, dirname(parent), parent) - : undefined - ) + opt.filter = filter + ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) + : file => mapHas(stripSlash(file)) } -const findMadeSync = (opts, parent, path = undefined) => { - if (path === parent) - return undefined - +const listFileSync = opt => { + const p = list(opt) + const file = opt.file + let threw = true + let fd try { - return opts.statSync(parent).isDirectory() ? path : undefined - } catch (er) { - return er.code === 'ENOENT' - ? findMadeSync(opts, dirname(parent), parent) - : undefined + const stat = fs.statSync(file) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + if (stat.size < readSize) + p.end(fs.readFileSync(file)) + else { + let pos = 0 + const buf = Buffer.allocUnsafe(readSize) + fd = fs.openSync(file, 'r') + while (pos < stat.size) { + const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) + pos += bytesRead + p.write(buf.slice(0, bytesRead)) + } + p.end() + } + threw = false + } finally { + if (threw && fd) { + try { + fs.closeSync(fd) + } catch (er) {} + } } } -module.exports = {findMade, findMadeSync} +const listFile = (opt, cb) => { + const parse = new Parser(opt) + const readSize = opt.maxReadSize || 16 * 1024 * 1024 + + const file = opt.file + const p = new Promise((resolve, reject) => { + parse.on('error', reject) + parse.on('end', resolve) + + fs.stat(file, (er, stat) => { + if (er) + reject(er) + else { + const stream = new fsm.ReadStream(file, { + readSize: readSize, + size: stat.size, + }) + stream.on('error', reject) + stream.pipe(parse) + } + }) + }) + return cb ? p.then(cb, cb) : p +} + +const list = opt => new Parser(opt) /***/ }), -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-manual.js": -/*!*********************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-manual.js ***! - \*********************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mkdir.js": +/*!************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mkdir.js ***! + \************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const {dirname} = __webpack_require__(/*! path */ "path") +"use strict"; -const mkdirpManual = (path, opts, made) => { - opts.recursive = false - const parent = dirname(path) - if (parent === path) { - return opts.mkdirAsync(path, opts).catch(er => { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - }) +// wrapper around mkdirp for tar's needs. + +// TODO: This should probably be a class, not functionally +// passing around state in a gazillion args. + +const mkdirp = __webpack_require__(/*! mkdirp */ "../../../.yarn/berry/cache/mkdirp-npm-1.0.4-37f6ef56b9-9.zip/node_modules/mkdirp/index.js") +const fs = __webpack_require__(/*! fs */ "fs") +const path = __webpack_require__(/*! path */ "path") +const chownr = __webpack_require__(/*! chownr */ "../../../.yarn/berry/cache/chownr-npm-2.0.0-638f1c9c61-9.zip/node_modules/chownr/chownr.js") +const normPath = __webpack_require__(/*! ./normalize-windows-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js") + +class SymlinkError extends Error { + constructor (symlink, path) { + super('Cannot extract through symbolic link') + this.path = path + this.symlink = symlink } - return opts.mkdirAsync(path, opts).then(() => made || path, er => { - if (er.code === 'ENOENT') - return mkdirpManual(parent, opts) - .then(made => mkdirpManual(path, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - return opts.statAsync(path).then(st => { - if (st.isDirectory()) - return made - else - throw er - }, () => { throw er }) - }) + get name () { + return 'SylinkError' + } } -const mkdirpManualSync = (path, opts, made) => { - const parent = dirname(path) - opts.recursive = false - - if (parent === path) { - try { - return opts.mkdirSync(path, opts) - } catch (er) { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - else - return - } +class CwdError extends Error { + constructor (path, code) { + super(code + ': Cannot cd into \'' + path + '\'') + this.path = path + this.code = code } - try { - opts.mkdirSync(path, opts) - return made || path - } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - try { - if (!opts.statSync(path).isDirectory()) - throw er - } catch (_) { - throw er - } + get name () { + return 'CwdError' } } -module.exports = {mkdirpManual, mkdirpManualSync} +const cGet = (cache, key) => cache.get(normPath(key)) +const cSet = (cache, key, val) => cache.set(normPath(key), val) +const checkCwd = (dir, cb) => { + fs.stat(dir, (er, st) => { + if (er || !st.isDirectory()) + er = new CwdError(dir, er && er.code || 'ENOTDIR') + cb(er) + }) +} -/***/ }), +module.exports = (dir, opt, cb) => { + dir = normPath(dir) -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-native.js": -/*!*********************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-native.js ***! - \*********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 -const {dirname} = __webpack_require__(/*! path */ "path") -const {findMade, findMadeSync} = __webpack_require__(/*! ./find-made.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/find-made.js") -const {mkdirpManual, mkdirpManualSync} = __webpack_require__(/*! ./mkdirp-manual.js */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/mkdirp-manual.js") + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + (uid !== opt.processUid || gid !== opt.processGid) -const mkdirpNative = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirAsync(path, opts) + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = normPath(opt.cwd) - return findMade(opts, path).then(made => - opts.mkdirAsync(path, opts).then(() => made) - .catch(er => { - if (er.code === 'ENOENT') - return mkdirpManual(path, opts) + const done = (er, created) => { + if (er) + cb(er) + else { + cSet(cache, dir, true) + if (created && doChown) + chownr(created, uid, gid, er => done(er)) + else if (needChmod) + fs.chmod(dir, mode, cb) else - throw er - })) + cb() + } + } + + if (cache && cGet(cache, dir) === true) + return done() + + if (dir === cwd) + return checkCwd(dir, done) + + if (preserve) + return mkdirp(dir, {mode}).then(made => done(null, made), done) + + const sub = normPath(path.relative(cwd, dir)) + const parts = sub.split('/') + mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } -const mkdirpNativeSync = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirSync(path, opts) +const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { + if (!parts.length) + return cb(null, created) + const p = parts.shift() + const part = normPath(path.resolve(base + '/' + p)) + if (cGet(cache, part)) + return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) +} - const made = findMadeSync(opts, path) +const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { + if (er) { + fs.lstat(part, (statEr, st) => { + if (statEr) { + statEr.path = statEr.path && normPath(statEr.path) + cb(statEr) + } else if (st.isDirectory()) + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + else if (unlink) { + fs.unlink(part, er => { + if (er) + return cb(er) + fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) + }) + } else if (st.isSymbolicLink()) + return cb(new SymlinkError(part, part + '/' + parts.join('/'))) + else + cb(er) + }) + } else { + created = created || part + mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) + } +} + +const checkCwdSync = dir => { + let ok = false + let code = 'ENOTDIR' try { - opts.mkdirSync(path, opts) - return made + ok = fs.statSync(dir).isDirectory() } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts) - else - throw er + code = er.code + } finally { + if (!ok) + throw new CwdError(dir, code) } } -module.exports = {mkdirpNative, mkdirpNativeSync} - - -/***/ }), +module.exports.sync = (dir, opt) => { + dir = normPath(dir) + // if there's any overlap between mask and mode, + // then we'll need an explicit chmod + const umask = opt.umask + const mode = opt.mode | 0o0700 + const needChmod = (mode & umask) !== 0 -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/opts-arg.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/opts-arg.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const uid = opt.uid + const gid = opt.gid + const doChown = typeof uid === 'number' && + typeof gid === 'number' && + (uid !== opt.processUid || gid !== opt.processGid) -const { promisify } = __webpack_require__(/*! util */ "util") -const fs = __webpack_require__(/*! fs */ "fs") -const optsArg = opts => { - if (!opts) - opts = { mode: 0o777 & (~process.umask()), fs } - else if (typeof opts === 'object') - opts = { mode: 0o777 & (~process.umask()), fs, ...opts } - else if (typeof opts === 'number') - opts = { mode: opts, fs } - else if (typeof opts === 'string') - opts = { mode: parseInt(opts, 8), fs } - else - throw new TypeError('invalid options argument') + const preserve = opt.preserve + const unlink = opt.unlink + const cache = opt.cache + const cwd = normPath(opt.cwd) - opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir - opts.mkdirAsync = promisify(opts.mkdir) - opts.stat = opts.stat || opts.fs.stat || fs.stat - opts.statAsync = promisify(opts.stat) - opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync - opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync - return opts -} -module.exports = optsArg + const done = (created) => { + cSet(cache, dir, true) + if (created && doChown) + chownr.sync(created, uid, gid) + if (needChmod) + fs.chmodSync(dir, mode) + } + if (cache && cGet(cache, dir) === true) + return done() -/***/ }), + if (dir === cwd) { + checkCwdSync(cwd) + return done() + } -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/path-arg.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/path-arg.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (preserve) + return done(mkdirp.sync(dir, mode)) -const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform -const { resolve, parse } = __webpack_require__(/*! path */ "path") -const pathArg = path => { - if (/\0/.test(path)) { - // simulate same failure that node raises - throw Object.assign( - new TypeError('path must be a string without null bytes'), - { - path, - code: 'ERR_INVALID_ARG_VALUE', - } - ) - } + const sub = normPath(path.relative(cwd, dir)) + const parts = sub.split('/') + let created = null + for (let p = parts.shift(), part = cwd; + p && (part += '/' + p); + p = parts.shift()) { + part = normPath(path.resolve(part)) + if (cGet(cache, part)) + continue - path = resolve(path) - if (platform === 'win32') { - const badWinChars = /[*|"<>?:]/ - const {root} = parse(path) - if (badWinChars.test(path.substr(root.length))) { - throw Object.assign(new Error('Illegal characters in path.'), { - path, - code: 'EINVAL', - }) + try { + fs.mkdirSync(part, mode) + created = created || part + cSet(cache, part, true) + } catch (er) { + const st = fs.lstatSync(part) + if (st.isDirectory()) { + cSet(cache, part, true) + continue + } else if (unlink) { + fs.unlinkSync(part) + fs.mkdirSync(part, mode) + created = created || part + cSet(cache, part, true) + continue + } else if (st.isSymbolicLink()) + return new SymlinkError(part, part + '/' + parts.join('/')) } } - return path + return done(created) } -module.exports = pathArg /***/ }), -/***/ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/use-native.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/lib/use-native.js ***! - \******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mode-fix.js": +/*!***************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mode-fix.js ***! + \***************************************************************************************************/ +/***/ ((module) => { -const fs = __webpack_require__(/*! fs */ "fs") +"use strict"; -const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version -const versArr = version.replace(/^v/, '').split('.') -const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 +module.exports = (mode, isDir, portable) => { + mode &= 0o7777 -const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir -const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync + // in portable mode, use the minimum reasonable umask + // if this system creates files with 0o664 by default + // (as some linux distros do), then we'll write the + // archive with 0o644 instead. Also, don't ever create + // a file that is not readable/writable by the owner. + if (portable) + mode = (mode | 0o600) & ~0o22 -module.exports = {useNative, useNativeSync} + // if dirs are readable, then they should be listable + if (isDir) { + if (mode & 0o400) + mode |= 0o100 + if (mode & 0o40) + mode |= 0o10 + if (mode & 0o4) + mode |= 0o1 + } + return mode +} /***/ }), -/***/ "./.yarn/cache/ms-npm-2.1.2-ec0c1512ff-673cdb2c31.zip/node_modules/ms/index.js": -/*!*************************************************************************************!*\ - !*** ./.yarn/cache/ms-npm-2.1.2-ec0c1512ff-673cdb2c31.zip/node_modules/ms/index.js ***! - \*************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-unicode.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-unicode.js ***! + \************************************************************************************************************/ /***/ ((module) => { -/** - * Helpers. - */ +// warning: extremely hot code path. +// This has been meticulously optimized for use +// within npm install on large package trees. +// Do not edit without careful benchmarking. +const normalizeCache = Object.create(null) +const {hasOwnProperty} = Object.prototype +module.exports = s => { + if (!hasOwnProperty.call(normalizeCache, s)) + normalizeCache[s] = s.normalize('NFKD') + return normalizeCache[s] +} -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +/***/ }), -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js ***! + \*****************************************************************************************************************/ +/***/ ((module) => { -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +// on windows, either \ or / are valid directory separators. +// on unix, \ is a valid character in filenames. +// so, on windows, and only on windows, we replace all \ chars with /, +// so that we can use / as our one and only directory separator char. -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +module.exports = platform !== 'win32' ? p => p + : p => p && p.replace(/\\/g, '/') -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +/***/ }), -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pack.js": +/*!***********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pack.js ***! + \***********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} +"use strict"; -/** - * Pluralization helper. - */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +// A readable tar stream creator +// Technically, this is a transform stream that you write paths into, +// and tar format comes out of. +// The `add()` method is like `write()` but returns this, +// and end() return `this` as well, so you can +// do `new Pack(opt).add('files').add('dir').end().pipe(output) +// You could also do something like: +// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) + +class PackJob { + constructor (path, absolute) { + this.path = path || './' + this.absolute = absolute + this.entry = null + this.stat = null + this.readdir = null + this.pending = false + this.ignore = false + this.piped = false + } } +const MiniPass = __webpack_require__(/*! minipass */ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js") +const zlib = __webpack_require__(/*! minizlib */ "../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/index.js") +const ReadEntry = __webpack_require__(/*! ./read-entry.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/read-entry.js") +const WriteEntry = __webpack_require__(/*! ./write-entry.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/write-entry.js") +const WriteEntrySync = WriteEntry.Sync +const WriteEntryTar = WriteEntry.Tar +const Yallist = __webpack_require__(/*! yallist */ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js") +const EOF = Buffer.alloc(1024) +const ONSTAT = Symbol('onStat') +const ENDED = Symbol('ended') +const QUEUE = Symbol('queue') +const CURRENT = Symbol('current') +const PROCESS = Symbol('process') +const PROCESSING = Symbol('processing') +const PROCESSJOB = Symbol('processJob') +const JOBS = Symbol('jobs') +const JOBDONE = Symbol('jobDone') +const ADDFSENTRY = Symbol('addFSEntry') +const ADDTARENTRY = Symbol('addTarEntry') +const STAT = Symbol('stat') +const READDIR = Symbol('readdir') +const ONREADDIR = Symbol('onreaddir') +const PIPE = Symbol('pipe') +const ENTRY = Symbol('entry') +const ENTRYOPT = Symbol('entryOpt') +const WRITEENTRYCLASS = Symbol('writeEntryClass') +const WRITE = Symbol('write') +const ONDRAIN = Symbol('ondrain') -/***/ }), +const fs = __webpack_require__(/*! fs */ "fs") +const path = __webpack_require__(/*! path */ "path") +const warner = __webpack_require__(/*! ./warn-mixin.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/warn-mixin.js") +const normPath = __webpack_require__(/*! ./normalize-windows-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js") -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/comparator.js": -/*!**********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/comparator.js ***! - \**********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const Pack = warner(class Pack extends MiniPass { + constructor (opt) { + super(opt) + opt = opt || Object.create(null) + this.opt = opt + this.file = opt.file || '' + this.cwd = opt.cwd || process.cwd() + this.maxReadSize = opt.maxReadSize + this.preservePaths = !!opt.preservePaths + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.prefix = normPath(opt.prefix || '') + this.linkCache = opt.linkCache || new Map() + this.statCache = opt.statCache || new Map() + this.readdirCache = opt.readdirCache || new Map() -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY - } - constructor (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + this[WRITEENTRYCLASS] = WriteEntry + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } + this.portable = !!opt.portable + this.zip = null + if (opt.gzip) { + if (typeof opt.gzip !== 'object') + opt.gzip = {} + if (this.portable) + opt.gzip.portable = true + this.zip = new zlib.Gzip(opt.gzip) + this.zip.on('data', chunk => super.write(chunk)) + this.zip.on('end', _ => super.end()) + this.zip.on('drain', _ => this[ONDRAIN]()) + this.on('resume', _ => this.zip.resume()) + } else + this.on('drain', this[ONDRAIN]) - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + this.noDirRecurse = !!opt.noDirRecurse + this.follow = !!opt.follow + this.noMtime = !!opt.noMtime + this.mtime = opt.mtime || null - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } + this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true - debug('comp', this) + this[QUEUE] = new Yallist() + this[JOBS] = 0 + this.jobs = +opt.jobs || 4 + this[PROCESSING] = false + this[ENDED] = false } - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } + [WRITE] (chunk) { + return super.write(chunk) + } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } + add (path) { + this.write(path) + return this } - toString () { - return this.value + end (path) { + if (path) + this.write(path) + this[ENDED] = true + this[PROCESS]() + return this } - test (version) { - debug('Comparator.test', version, this.options.loose) + write (path) { + if (this[ENDED]) + throw new Error('write after end') - if (this.semver === ANY || version === ANY) { - return true - } + if (path instanceof ReadEntry) + this[ADDTARENTRY](path) + else + this[ADDFSENTRY](path) + return this.flowing + } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } + [ADDTARENTRY] (p) { + const absolute = normPath(path.resolve(this.cwd, p.path)) + // in this case, we don't have to wait for the stat + if (!this.filter(p.path, p)) + p.resume() + else { + const job = new PackJob(p.path, absolute, false) + job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) + job.entry.on('end', _ => this[JOBDONE](job)) + this[JOBS] += 1 + this[QUEUE].push(job) } - return cmp(version, this.operator, this.semver, this.options) + this[PROCESS]() } - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } + [ADDFSENTRY] (p) { + const absolute = normPath(path.resolve(this.cwd, p)) + this[QUEUE].push(new PackJob(p, absolute)) + this[PROCESS]() + } - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + [STAT] (job) { + job.pending = true + this[JOBS] += 1 + const stat = this.follow ? 'stat' : 'lstat' + fs[stat](job.absolute, (er, stat) => { + job.pending = false + this[JOBS] -= 1 + if (er) + this.emit('error', er) + else + this[ONSTAT](job, stat) + }) + } - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } + [ONSTAT] (job, stat) { + this.statCache.set(job.absolute, stat) + job.stat = stat - const sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - const sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - const sameSemVer = this.semver.version === comp.semver.version - const differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - const oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<') - const oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>') + // now we have the stat, we can filter it. + if (!this.filter(job.path, stat)) + job.ignore = true - return ( - sameDirectionIncreasing || - sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || - oppositeDirectionsGreaterThan - ) + this[PROCESS]() } -} -module.exports = Comparator + [READDIR] (job) { + job.pending = true + this[JOBS] += 1 + fs.readdir(job.absolute, (er, entries) => { + job.pending = false + this[JOBS] -= 1 + if (er) + return this.emit('error', er) + this[ONREADDIR](job, entries) + }) + } -const {re, t} = __webpack_require__(/*! ../internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") -const cmp = __webpack_require__(/*! ../functions/cmp */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/cmp.js") -const debug = __webpack_require__(/*! ../internal/debug */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js") -const SemVer = __webpack_require__(/*! ./semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const Range = __webpack_require__(/*! ./range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") + [ONREADDIR] (job, entries) { + this.readdirCache.set(job.absolute, entries) + job.readdir = entries + this[PROCESS]() + } + [PROCESS] () { + if (this[PROCESSING]) + return -/***/ }), + this[PROCESSING] = true + for (let w = this[QUEUE].head; + w !== null && this[JOBS] < this.jobs; + w = w.next) { + this[PROCESSJOB](w.value) + if (w.value.ignore) { + const p = w.next + this[QUEUE].removeNode(w) + w.next = p + } + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this[PROCESSING] = false -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { + if (this.zip) + this.zip.end(EOF) + else { + super.write(EOF) + super.end() } } + } - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } + get [CURRENT] () { + return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value + } + + [JOBDONE] (job) { + this[QUEUE].shift() + this[JOBS] -= 1 + this[PROCESS]() + } + + [PROCESSJOB] (job) { + if (job.pending) + return + + if (job.entry) { + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) + return } - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.format() - return this + if (!job.stat) { + if (this.statCache.has(job.absolute)) + this[ONSTAT](job, this.statCache.get(job.absolute)) + else + this[STAT](job) } + if (!job.stat) + return - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + // filtered out! + if (job.ignore) + return - // First, split based on boolean or || - this.raw = range - this.set = range - .split(/\s*\|\|\s*/) - // map the range to a 2d array of comparators - .map(range => this.parseRange(range.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) + if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { + if (this.readdirCache.has(job.absolute)) + this[ONREADDIR](job, this.readdirCache.get(job.absolute)) + else + this[READDIR](job) + if (!job.readdir) + return + } - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${range}`) + // we know it doesn't have an entry, because that got checked above + job.entry = this[ENTRY](job) + if (!job.entry) { + job.ignore = true + return } - this.format() + if (job === this[CURRENT] && !job.piped) + this[PIPE](job) } - format () { - this.range = this.set - .map((comps) => { - return comps.join(' ').trim() - }) - .join('||') - .trim() - return this.range + [ENTRYOPT] (job) { + return { + onwarn: (code, msg, data) => this.warn(code, msg, data), + noPax: this.noPax, + cwd: this.cwd, + absolute: job.absolute, + preservePaths: this.preservePaths, + maxReadSize: this.maxReadSize, + strict: this.strict, + portable: this.portable, + linkCache: this.linkCache, + statCache: this.statCache, + noMtime: this.noMtime, + mtime: this.mtime, + prefix: this.prefix, + } } - toString () { - return this.range + [ENTRY] (job) { + this[JOBS] += 1 + try { + return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) + .on('end', () => this[JOBDONE](job)) + .on('error', er => this.emit('error', er)) + } catch (er) { + this.emit('error', er) + } } - parseRange (range) { - const loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[t.COMPARATORTRIM]) + [ONDRAIN] () { + if (this[CURRENT] && this[CURRENT].entry) + this[CURRENT].entry.resume() + } - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + // like .pipe() but using super, because our write() is special + [PIPE] (job) { + job.piped = true - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) + if (job.readdir) { + job.readdir.forEach(entry => { + const p = job.path + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) + } - // normalize spaces - range = range.split(/\s+/).join(' ') + const source = job.entry + const zip = this.zip - // At this point, the range is completely trimmed and - // ready to be split into comparators. + if (zip) { + source.on('data', chunk => { + if (!zip.write(chunk)) + source.pause() + }) + } else { + source.on('data', chunk => { + if (!super.write(chunk)) + source.pause() + }) + } + } - const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - return range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // in loose mode, throw out any that are not valid comparators - .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) - .map(comp => new Comparator(comp, this.options)) + pause () { + if (this.zip) + this.zip.pause() + return super.pause() } +}) - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } +class PackSync extends Pack { + constructor (opt) { + super(opt) + this[WRITEENTRYCLASS] = WriteEntrySync + } - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) + // pause/resume are no-ops in sync streams. + pause () {} + resume () {} + + [STAT] (job) { + const stat = this.follow ? 'statSync' : 'lstatSync' + this[ONSTAT](job, fs[stat](job.absolute)) } - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } + [READDIR] (job, stat) { + this[ONREADDIR](job, fs.readdirSync(job.absolute)) + } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } + // gotta get it all in this tick + [PIPE] (job) { + const source = job.entry + const zip = this.zip + + if (job.readdir) { + job.readdir.forEach(entry => { + const p = job.path + const base = p === './' ? '' : p.replace(/\/*$/, '/') + this[ADDFSENTRY](base + entry) + }) } - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } + if (zip) { + source.on('data', chunk => { + zip.write(chunk) + }) + } else { + source.on('data', chunk => { + super[WRITE](chunk) + }) } - return false } } -module.exports = Range -const Comparator = __webpack_require__(/*! ./comparator */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/comparator.js") -const debug = __webpack_require__(/*! ../internal/debug */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js") -const SemVer = __webpack_require__(/*! ./semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const { - re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace -} = __webpack_require__(/*! ../internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") +Pack.Sync = PackSync -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() +module.exports = Pack - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) - testComparator = remainingComparators.pop() - } +/***/ }), - return result -} +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/parse.js": +/*!************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/parse.js ***! + \************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} +"use strict"; -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -const replaceTildes = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceTilde(comp, options) - }).join(' ') +// this[BUFFER] is the remainder of a chunk if we're waiting for +// the full 512 bytes of a header to come in. We will Buffer.concat() +// it to the next write(), which is a mem copy, but a small one. +// +// this[QUEUE] is a Yallist of entries that haven't been emitted +// yet this can only get filled up if the user keeps write()ing after +// a write() returns false, or does a write() with more than one entry +// +// We don't buffer chunks, we always parse them and either create an +// entry, or push it into the active entry. The ReadEntry class knows +// to throw data away if .ignore=true +// +// Shift entry off the buffer when it emits 'end', and emit 'entry' for +// the next one in the list. +// +// At any time, we're pushing body chunks into the entry at WRITEENTRY, +// and waiting for 'end' on the entry at READENTRY +// +// ignored entries get .resume() called on them straight away -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret +const warner = __webpack_require__(/*! ./warn-mixin.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/warn-mixin.js") +const Header = __webpack_require__(/*! ./header.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js") +const EE = __webpack_require__(/*! events */ "events") +const Yallist = __webpack_require__(/*! yallist */ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js") +const maxMetaEntrySize = 1024 * 1024 +const Entry = __webpack_require__(/*! ./read-entry.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/read-entry.js") +const Pax = __webpack_require__(/*! ./pax.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pax.js") +const zlib = __webpack_require__(/*! minizlib */ "../../../.yarn/berry/cache/minizlib-npm-2.1.2-ea89cd0cfb-9.zip/node_modules/minizlib/index.js") - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0` - } +const gzipHeader = Buffer.from([0x1f, 0x8b]) +const STATE = Symbol('state') +const WRITEENTRY = Symbol('writeEntry') +const READENTRY = Symbol('readEntry') +const NEXTENTRY = Symbol('nextEntry') +const PROCESSENTRY = Symbol('processEntry') +const EX = Symbol('extendedHeader') +const GEX = Symbol('globalExtendedHeader') +const META = Symbol('meta') +const EMITMETA = Symbol('emitMeta') +const BUFFER = Symbol('buffer') +const QUEUE = Symbol('queue') +const ENDED = Symbol('ended') +const EMITTEDEND = Symbol('emittedEnd') +const EMIT = Symbol('emit') +const UNZIP = Symbol('unzip') +const CONSUMECHUNK = Symbol('consumeChunk') +const CONSUMECHUNKSUB = Symbol('consumeChunkSub') +const CONSUMEBODY = Symbol('consumeBody') +const CONSUMEMETA = Symbol('consumeMeta') +const CONSUMEHEADER = Symbol('consumeHeader') +const CONSUMING = Symbol('consuming') +const BUFFERCONCAT = Symbol('bufferConcat') +const MAYBEEND = Symbol('maybeEnd') +const WRITING = Symbol('writing') +const ABORTED = Symbol('aborted') +const DONE = Symbol('onDone') +const SAW_VALID_ENTRY = Symbol('sawValidEntry') +const SAW_NULL_BLOCK = Symbol('sawNullBlock') +const SAW_EOF = Symbol('sawEOF') - debug('tilde return', ret) - return ret - }) -} +const noop = _ => true -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -const replaceCarets = (comp, options) => - comp.trim().split(/\s+/).map((comp) => { - return replaceCaret(comp, options) - }).join(' ') +module.exports = warner(class Parser extends EE { + constructor (opt) { + opt = opt || {} + super(opt) -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret + this.file = opt.file || '' - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0` - } else { - ret = `>=${M}.${m}.0 <${+M + 1}.0.0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - } <${M}.${m}.${+p + 1}` - } else { - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0` + // set to boolean false when an entry starts. 1024 bytes of \0 + // is technically a valid tarball, albeit a boring one. + this[SAW_VALID_ENTRY] = null + + // these BADARCHIVE errors can't be detected early. listen on DONE. + this.on(DONE, _ => { + if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { + // either less than 1 block of data, or all entries were invalid. + // Either way, probably not even a tarball. + this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') } + }) + + if (opt.ondone) + this.on(DONE, opt.ondone) + else { + this.on(DONE, _ => { + this.emit('prefinish') + this.emit('finish') + this.emit('end') + this.emit('close') + }) } - debug('caret return', ret) - return ret - }) -} + this.strict = !!opt.strict + this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize + this.filter = typeof opt.filter === 'function' ? opt.filter : noop -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map((comp) => { - return replaceXRange(comp, options) - }).join(' ') -} + // have to set this so that streams are ok piping into it + this.writable = true + this.readable = false -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp + this[QUEUE] = new Yallist() + this[BUFFER] = null + this[READENTRY] = null + this[WRITEENTRY] = null + this[STATE] = 'begin' + this[META] = '' + this[EX] = null + this[GEX] = null + this[ENDED] = false + this[UNZIP] = null + this[ABORTED] = false + this[SAW_NULL_BLOCK] = false + this[SAW_EOF] = false + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) + if (typeof opt.onentry === 'function') + this.on('entry', opt.onentry) + } - if (gtlt === '=' && anyX) { - gtlt = '' + [CONSUMEHEADER] (chunk, position) { + if (this[SAW_VALID_ENTRY] === null) + this[SAW_VALID_ENTRY] = false + let header + try { + header = new Header(chunk, position, this[EX], this[GEX]) + } catch (er) { + return this.warn('TAR_ENTRY_INVALID', er) } - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' + if (header.nullBlock) { + if (this[SAW_NULL_BLOCK]) { + this[SAW_EOF] = true + // ending an archive with no entries. pointless, but legal. + if (this[STATE] === 'begin') + this[STATE] = 'header' + this[EMIT]('eof') } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 + this[SAW_NULL_BLOCK] = true + this[EMIT]('nullBlock') } - p = 0 + } else { + this[SAW_NULL_BLOCK] = false + if (!header.cksumValid) + this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header}) + else if (!header.path) + this.warn('TAR_ENTRY_INVALID', 'path is required', {header}) + else { + const type = header.type + if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) + this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header}) + else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) + this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header}) + else { + const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } + // we do this for meta & ignored entries as well, because they + // are still valid tar, or else we wouldn't know to ignore them + if (!this[SAW_VALID_ENTRY]) { + if (entry.remain) { + // this might be the one! + const onend = () => { + if (!entry.invalid) + this[SAW_VALID_ENTRY] = true + } + entry.on('end', onend) + } else + this[SAW_VALID_ENTRY] = true + } - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0${pr}` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0${pr}` - } + if (entry.meta) { + if (entry.size > this.maxMetaEntrySize) { + entry.ignore = true + this[EMIT]('ignoredEntry', entry) + this[STATE] = 'ignore' + entry.resume() + } else if (entry.size > 0) { + this[META] = '' + entry.on('data', c => this[META] += c) + this[STATE] = 'meta' + } + } else { + this[EX] = null + entry.ignore = entry.ignore || !this.filter(entry.path, entry) - debug('xRange return', ret) + if (entry.ignore) { + // probably valid, just not something we care about + this[EMIT]('ignoredEntry', entry) + this[STATE] = entry.remain ? 'ignore' : 'header' + entry.resume() + } else { + if (entry.remain) + this[STATE] = 'body' + else { + this[STATE] = 'header' + entry.end() + } - return ret - }) -} + if (!this[READENTRY]) { + this[QUEUE].push(entry) + this[NEXTENTRY]() + } else + this[QUEUE].push(entry) + } + } + } + } + } + } -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[t.STAR], '') -} + [PROCESSENTRY] (entry) { + let go = true -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -const hyphenReplace = ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0` - } else { - from = `>=${from}` - } + if (!entry) { + this[READENTRY] = null + go = false + } else if (Array.isArray(entry)) + this.emit.apply(this, entry) + else { + this[READENTRY] = entry + this.emit('entry', entry) + if (!entry.emittedEnd) { + entry.on('end', _ => this[NEXTENTRY]()) + go = false + } + } - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else { - to = `<=${to}` + return go } - return (`${from} ${to}`).trim() -} + [NEXTENTRY] () { + do {} while (this[PROCESSENTRY](this[QUEUE].shift())) -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + if (!this[QUEUE].length) { + // At this point, there's nothing in the queue, but we may have an + // entry which is being consumed (readEntry). + // If we don't, then we definitely can handle more data. + // If we do, and either it's flowing, or it has never had any data + // written to it, then it needs more. + // The only other possibility is that it has returned false from a + // write() call, so we wait for the next drain to continue. + const re = this[READENTRY] + const drainNow = !re || re.flowing || re.size === re.remain + if (drainNow) { + if (!this[WRITING]) + this.emit('drain') + } else + re.once('drain', _ => this.emit('drain')) } } - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } + [CONSUMEBODY] (chunk, position) { + // write up to but no more than writeEntry.blockRemain + const entry = this[WRITEENTRY] + const br = entry.blockRemain + const c = (br >= chunk.length && position === 0) ? chunk + : chunk.slice(position, position + br) - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + entry.write(c) + + if (!entry.blockRemain) { + this[STATE] = 'header' + this[WRITEENTRY] = null + entry.end() } - // Version has a -pre, but it's not one of the ones we like. - return false + return c.length } - return true -} - + [CONSUMEMETA] (chunk, position) { + const entry = this[WRITEENTRY] + const ret = this[CONSUMEBODY](chunk, position) -/***/ }), + // if we finished, then the entry is reset + if (!this[WRITEENTRY]) + this[EMITMETA](entry) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js ***! - \******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return ret + } -const debug = __webpack_require__(/*! ../internal/debug */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js") -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(/*! ../internal/constants */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js") -const { re, t } = __webpack_require__(/*! ../internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") + [EMIT] (ev, data, extra) { + if (!this[QUEUE].length && !this[READENTRY]) + this.emit(ev, data, extra) + else + this[QUEUE].push([ev, data, extra]) + } -const { compareIdentifiers } = __webpack_require__(/*! ../internal/identifiers */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/identifiers.js") -class SemVer { - constructor (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid Version: ${version}`) - } + [EMITMETA] (entry) { + this[EMIT]('meta', this[META]) + switch (entry.type) { + case 'ExtendedHeader': + case 'OldExtendedHeader': + this[EX] = Pax.parse(this[META], this[EX], false) + break - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } + case 'GlobalExtendedHeader': + this[GEX] = Pax.parse(this[META], this[GEX], true) + break - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease + case 'NextFileHasLongPath': + case 'OldGnuLongPath': + this[EX] = this[EX] || Object.create(null) + this[EX].path = this[META].replace(/\0.*/, '') + break - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + case 'NextFileHasLongLinkpath': + this[EX] = this[EX] || Object.create(null) + this[EX].linkpath = this[META].replace(/\0.*/, '') + break - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) + /* istanbul ignore next */ + default: throw new Error('unknown meta: ' + entry.type) } + } - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] + abort (error) { + this[ABORTED] = true + this.emit('abort', error) + // always throws, even in non-strict mode + this.warn('TAR_ABORT', error, { recoverable: false }) + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + write (chunk) { + if (this[ABORTED]) + return - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') + // first write, might be gzipped + if (this[UNZIP] === null && chunk) { + if (this[BUFFER]) { + chunk = Buffer.concat([this[BUFFER], chunk]) + this[BUFFER] = null + } + if (chunk.length < gzipHeader.length) { + this[BUFFER] = chunk + return true + } + for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { + if (chunk[i] !== gzipHeader[i]) + this[UNZIP] = false + } + if (this[UNZIP] === null) { + const ended = this[ENDED] + this[ENDED] = false + this[UNZIP] = new zlib.Unzip() + this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) + this[UNZIP].on('error', er => this.abort(er)) + this[UNZIP].on('end', _ => { + this[ENDED] = true + this[CONSUMECHUNK]() + }) + this[WRITING] = true + const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) + this[WRITING] = false + return ret + } } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + this[WRITING] = true + if (this[UNZIP]) + this[UNZIP].write(chunk) + else + this[CONSUMECHUNK](chunk) + this[WRITING] = false - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } + // return false if there's a queue, or if the current entry isn't flowing + const ret = + this[QUEUE].length ? false : + this[READENTRY] ? this[READENTRY].flowing : + true - this.build = m[5] ? m[5].split('.') : [] - this.format() - } + // if we have no queue, then that means a clogged READENTRY + if (!ret && !this[QUEUE].length) + this[READENTRY].once('drain', _ => this.emit('drain')) - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version + return ret } - toString () { - return this.version + [BUFFERCONCAT] (c) { + if (c && !this[ABORTED]) + this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c } - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 + [MAYBEEND] () { + if (this[ENDED] && + !this[EMITTEDEND] && + !this[ABORTED] && + !this[CONSUMING]) { + this[EMITTEDEND] = true + const entry = this[WRITEENTRY] + if (entry && entry.blockRemain) { + // truncated, likely a damaged file + const have = this[BUFFER] ? this[BUFFER].length : 0 + this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ + entry.blockRemain} more bytes, only ${have} available)`, {entry}) + if (this[BUFFER]) + entry.write(this[BUFFER]) + entry.end() } - other = new SemVer(other, this.options) - } - - if (other.version === this.version) { - return 0 + this[EMIT](DONE) } - - return this.compareMain(other) || this.comparePre(other) } - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + [CONSUMECHUNK] (chunk) { + if (this[CONSUMING]) + this[BUFFERCONCAT](chunk) + else if (!chunk && !this[BUFFER]) + this[MAYBEEND]() + else { + this[CONSUMING] = true + if (this[BUFFER]) { + this[BUFFERCONCAT](chunk) + const c = this[BUFFER] + this[BUFFER] = null + this[CONSUMECHUNKSUB](c) + } else + this[CONSUMECHUNKSUB](chunk) - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + while (this[BUFFER] && + this[BUFFER].length >= 512 && + !this[ABORTED] && + !this[SAW_EOF]) { + const c = this[BUFFER] + this[BUFFER] = null + this[CONSUMECHUNKSUB](c) + } + this[CONSUMING] = false } - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) + if (!this[BUFFER] || this[ENDED]) + this[MAYBEEND]() } - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + [CONSUMECHUNKSUB] (chunk) { + // we know that we are in CONSUMING mode, so anything written goes into + // the buffer. Advance the position and put any remainder in the buffer. + let position = 0 + const length = chunk.length + while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { + switch (this[STATE]) { + case 'begin': + case 'header': + this[CONSUMEHEADER](chunk, position) + position += 512 + break - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } + case 'ignore': + case 'body': + position += this[CONSUMEBODY](chunk, position) + break - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break + case 'meta': + position += this[CONSUMEMETA](chunk, position) + break - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break + /* istanbul ignore next */ + default: + throw new Error('invalid state: ' + this[STATE]) + } + } - default: - throw new Error(`invalid increment argument: ${release}`) + if (position < length) { + if (this[BUFFER]) + this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) + else + this[BUFFER] = chunk.slice(position) } - this.format() - this.raw = this.version - return this } -} -module.exports = SemVer + end (chunk) { + if (!this[ABORTED]) { + if (this[UNZIP]) + this[UNZIP].end(chunk) + else { + this[ENDED] = true + this.write(chunk) + } + } + } +}) /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/clean.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/clean.js ***! - \*******************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/path-reservations.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/path-reservations.js ***! + \************************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const parse = __webpack_require__(/*! ./parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js") -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean +// A path exclusive reservation system +// reserve([list, of, paths], fn) +// When the fn is first in line for all its paths, it +// is called with a cb that clears the reservation. +// +// Used by async unpack to avoid clobbering paths in use, +// while still allowing maximal safe parallelization. +const assert = __webpack_require__(/*! assert */ "assert") +const normalize = __webpack_require__(/*! ./normalize-unicode.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-unicode.js") +const stripSlashes = __webpack_require__(/*! ./strip-trailing-slashes.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js") +const { join } = __webpack_require__(/*! path */ "path") -/***/ }), +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +const isWindows = platform === 'win32' -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/cmp.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/cmp.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = () => { + // path => [function or Set] + // A Set object means a directory reservation + // A fn is a direct reservation on that path + const queues = new Map() -const eq = __webpack_require__(/*! ./eq */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/eq.js") -const neq = __webpack_require__(/*! ./neq */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/neq.js") -const gt = __webpack_require__(/*! ./gt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js") -const gte = __webpack_require__(/*! ./gte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gte.js") -const lt = __webpack_require__(/*! ./lt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lt.js") -const lte = __webpack_require__(/*! ./lte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lte.js") + // fn => {paths:[path,...], dirs:[path, ...]} + const reservations = new Map() -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) + // return a set of parent dirs for a given path + // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] + const getDirs = path => { + const dirs = path.split('/').slice(0, -1).reduce((set, path) => { + if (set.length) + path = join(set[set.length - 1], path) + set.push(path || '/') + return set + }, []) + return dirs + } - case '>=': - return gte(a, b, loose) + // functions currently running + const running = new Set() - case '<': - return lt(a, b, loose) + // return the queues for each path the function cares about + // fn => {paths, dirs} + const getQueues = fn => { + const res = reservations.get(fn) + /* istanbul ignore if - unpossible */ + if (!res) + throw new Error('function does not have any path reservations') + return { + paths: res.paths.map(path => queues.get(path)), + dirs: [...res.dirs].map(path => queues.get(path)), + } + } - case '<=': - return lte(a, b, loose) + // check if fn is first in line for all its paths, and is + // included in the first set for all its dir queues + const check = fn => { + const {paths, dirs} = getQueues(fn) + return paths.every(q => q[0] === fn) && + dirs.every(q => q[0] instanceof Set && q[0].has(fn)) + } - default: - throw new TypeError(`Invalid operator: ${op}`) + // run the function if it's first in line and not already running + const run = fn => { + if (running.has(fn) || !check(fn)) + return false + running.add(fn) + fn(() => clear(fn)) + return true } -} -module.exports = cmp + const clear = fn => { + if (!running.has(fn)) + return false -/***/ }), + const { paths, dirs } = reservations.get(fn) + const next = new Set() -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/coerce.js": -/*!********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/coerce.js ***! - \********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + paths.forEach(path => { + const q = queues.get(path) + assert.equal(q[0], fn) + if (q.length === 1) + queues.delete(path) + else { + q.shift() + if (typeof q[0] === 'function') + next.add(q[0]) + else + q[0].forEach(fn => next.add(fn)) + } + }) -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const parse = __webpack_require__(/*! ./parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js") -const {re, t} = __webpack_require__(/*! ../internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") + dirs.forEach(dir => { + const q = queues.get(dir) + assert(q[0] instanceof Set) + if (q[0].size === 1 && q.length === 1) + queues.delete(dir) + else if (q[0].size === 1) { + q.shift() -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } + // must be a function or else the Set would've been reused + next.add(q[0]) + } else + q[0].delete(fn) + }) + running.delete(fn) - if (typeof version === 'number') { - version = String(version) + next.forEach(fn => run(fn)) + return true } - if (typeof version !== 'string') { - return null - } + const reserve = (paths, fn) => { + // collide on matches across case and unicode normalization + // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally + // impossible to determine whether two paths refer to the same thing on + // disk, without asking the kernel for a shortname. + // So, we just pretend that every path matches every other path here, + // effectively removing all parallelization on windows. + paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { + // don't need normPath, because we skip this entirely for windows + return normalize(stripSlashes(join(p))).toLowerCase() + }) - options = options || {} + const dirs = new Set( + paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) + ) + reservations.set(fn, {dirs, paths}) + paths.forEach(path => { + const q = queues.get(path) + if (!q) + queues.set(path, [fn]) + else + q.push(fn) + }) + dirs.forEach(dir => { + const q = queues.get(dir) + if (!q) + queues.set(dir, [new Set([fn])]) + else if (q[q.length - 1] instanceof Set) + q[q.length - 1].add(fn) + else + q.push(new Set([fn])) + }) - let match = null - if (!options.rtl) { - match = version.match(re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - let next - while ((next = re[t.COERCERTL].exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - re[t.COERCERTL].lastIndex = -1 + return run(fn) } - if (match === null) - return null - - return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) + return { check, reserve } } -module.exports = coerce /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-build.js": -/*!***************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-build.js ***! - \***************************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pax.js": +/*!**********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pax.js ***! + \**********************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild - +"use strict"; -/***/ }), +const Header = __webpack_require__(/*! ./header.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js") +const path = __webpack_require__(/*! path */ "path") -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-loose.js": -/*!***************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-loose.js ***! - \***************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +class Pax { + constructor (obj, global) { + this.atime = obj.atime || null + this.charset = obj.charset || null + this.comment = obj.comment || null + this.ctime = obj.ctime || null + this.gid = obj.gid || null + this.gname = obj.gname || null + this.linkpath = obj.linkpath || null + this.mtime = obj.mtime || null + this.path = obj.path || null + this.size = obj.size || null + this.uid = obj.uid || null + this.uname = obj.uname || null + this.dev = obj.dev || null + this.ino = obj.ino || null + this.nlink = obj.nlink || null + this.global = global || false + } -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose + encode () { + const body = this.encodeBody() + if (body === '') + return null + const bodyLen = Buffer.byteLength(body) + // round up to 512 bytes + // add 512 for header + const bufLen = 512 * Math.ceil(1 + bodyLen / 512) + const buf = Buffer.allocUnsafe(bufLen) -/***/ }), + // 0-fill the header section, it might not hit every field + for (let i = 0; i < 512; i++) + buf[i] = 0 -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js": -/*!*********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js ***! - \*********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + new Header({ + // XXX split the path + // then the path should be PaxHeader + basename, but less than 99, + // prepend with the dirname + path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), + mode: this.mode || 0o644, + uid: this.uid || null, + gid: this.gid || null, + size: bodyLen, + mtime: this.mtime || null, + type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', + linkpath: '', + uname: this.uname || '', + gname: this.gname || '', + devmaj: 0, + devmin: 0, + atime: this.atime || null, + ctime: this.ctime || null, + }).encode(buf) -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) + buf.write(body, 512, bodyLen, 'utf8') -module.exports = compare + // null pad after the body + for (let i = bodyLen + 512; i < buf.length; i++) + buf[i] = 0 + return buf + } -/***/ }), + encodeBody () { + return ( + this.encodeField('path') + + this.encodeField('ctime') + + this.encodeField('atime') + + this.encodeField('dev') + + this.encodeField('ino') + + this.encodeField('nlink') + + this.encodeField('charset') + + this.encodeField('comment') + + this.encodeField('gid') + + this.encodeField('gname') + + this.encodeField('linkpath') + + this.encodeField('mtime') + + this.encodeField('size') + + this.encodeField('uid') + + this.encodeField('uname') + ) + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/diff.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/diff.js ***! - \******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const parse = __webpack_require__(/*! ./parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js") -const eq = __webpack_require__(/*! ./eq */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/eq.js") - -const diff = (version1, version2) => { - if (eq(version1, version2)) { - return null - } else { - const v1 = parse(version1) - const v2 = parse(version2) - const hasPre = v1.prerelease.length || v2.prerelease.length - const prefix = hasPre ? 'pre' : '' - const defaultResult = hasPre ? 'prerelease' : '' - for (const key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined + encodeField (field) { + if (this[field] === null || this[field] === undefined) + return '' + const v = this[field] instanceof Date ? this[field].getTime() / 1000 + : this[field] + const s = ' ' + + (field === 'dev' || field === 'ino' || field === 'nlink' + ? 'SCHILY.' : '') + + field + '=' + v + '\n' + const byteLen = Buffer.byteLength(s) + // the digits includes the length of the digits in ascii base-10 + // so if it's 9 characters, then adding 1 for the 9 makes it 10 + // which makes it 11 chars. + let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 + if (byteLen + digits >= Math.pow(10, digits)) + digits += 1 + const len = digits + byteLen + return len + s } } -module.exports = diff +Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) -/***/ }), +const merge = (a, b) => + b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/eq.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/eq.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const parseKV = string => + string + .replace(/\n$/, '') + .split('\n') + .reduce(parseKVLine, Object.create(null)) -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq +const parseKVLine = (set, line) => { + const n = parseInt(line, 10) + // XXX Values with \n in them will fail this. + // Refactor to not be a naive line-by-line parse. + if (n !== Buffer.byteLength(line) + 1) + return set -/***/ }), + line = line.substr((n + ' ').length) + const kv = line.split('=') + const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') + if (!k) + return set -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const v = kv.join('=') + set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) + ? new Date(v * 1000) + : /^[0-9]+$/.test(v) ? +v + : v + return set +} -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt +module.exports = Pax /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gte.js": +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/read-entry.js": /*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gte.js ***! + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/read-entry.js ***! \*****************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte +"use strict"; +const MiniPass = __webpack_require__(/*! minipass */ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js") +const normPath = __webpack_require__(/*! ./normalize-windows-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js") -/***/ }), +const SLURP = Symbol('slurp') +module.exports = class ReadEntry extends MiniPass { + constructor (header, ex, gex) { + super() + // read entries always start life paused. this is to avoid the + // situation where Minipass's auto-ending empty streams results + // in an entry ending before we're ready for it. + this.pause() + this.extended = ex + this.globalExtended = gex + this.header = header + this.startBlockSize = 512 * Math.ceil(header.size / 512) + this.blockRemain = this.startBlockSize + this.remain = header.size + this.type = header.type + this.meta = false + this.ignore = false + switch (this.type) { + case 'File': + case 'OldFile': + case 'Link': + case 'SymbolicLink': + case 'CharacterDevice': + case 'BlockDevice': + case 'Directory': + case 'FIFO': + case 'ContiguousFile': + case 'GNUDumpDir': + break -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/inc.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/inc.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + case 'NextFileHasLongLinkpath': + case 'NextFileHasLongPath': + case 'OldGnuLongPath': + case 'GlobalExtendedHeader': + case 'ExtendedHeader': + case 'OldExtendedHeader': + this.meta = true + break -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") + // NOTE: gnutar and bsdtar treat unrecognized types as 'File' + // it may be worth doing the same, but with a warning. + default: + this.ignore = true + } -const inc = (version, release, options, identifier) => { - if (typeof (options) === 'string') { - identifier = options - options = undefined - } + this.path = normPath(header.path) + this.mode = header.mode + if (this.mode) + this.mode = this.mode & 0o7777 + this.uid = header.uid + this.gid = header.gid + this.uname = header.uname + this.gname = header.gname + this.size = header.size + this.mtime = header.mtime + this.atime = header.atime + this.ctime = header.ctime + this.linkpath = normPath(header.linkpath) + this.uname = header.uname + this.gname = header.gname - try { - return new SemVer(version, options).inc(release, identifier).version - } catch (er) { - return null + if (ex) + this[SLURP](ex) + if (gex) + this[SLURP](gex, true) } -} -module.exports = inc + write (data) { + const writeLen = data.length + if (writeLen > this.blockRemain) + throw new Error('writing more to entry than is appropriate') -/***/ }), - -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lt.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lt.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - + const r = this.remain + const br = this.blockRemain + this.remain = Math.max(0, r - writeLen) + this.blockRemain = Math.max(0, br - writeLen) + if (this.ignore) + return true -/***/ }), + if (r >= writeLen) + return super.write(data) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lte.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lte.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // r < writeLen + return super.write(data.slice(0, r)) + } -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte + [SLURP] (ex, global) { + for (const k in ex) { + // we slurp in everything except for the path attribute in + // a global extended header, because that's weird. + if (ex[k] !== null && ex[k] !== undefined && + !(global && k === 'path')) + this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] + } + } +} /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/major.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/major.js ***! - \*******************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/replace.js": +/*!**************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/replace.js ***! + \**************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major +"use strict"; -/***/ }), +// tar -r +const hlo = __webpack_require__(/*! ./high-level-opt.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js") +const Pack = __webpack_require__(/*! ./pack.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pack.js") +const fs = __webpack_require__(/*! fs */ "fs") +const fsm = __webpack_require__(/*! fs-minipass */ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js") +const t = __webpack_require__(/*! ./list.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/list.js") +const path = __webpack_require__(/*! path */ "path") -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/minor.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/minor.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// starting at the head of the file, read a Header +// If the checksum is invalid, that's our position to start writing +// If it is, jump forward by the specified size (round up to 512) +// and try again. +// Write the new Pack stream starting there. -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor +const Header = __webpack_require__(/*! ./header.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js") +module.exports = (opt_, files, cb) => { + const opt = hlo(opt_) -/***/ }), + if (!opt.file) + throw new TypeError('file is required') -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/neq.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/neq.js ***! - \*****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (opt.gzip) + throw new TypeError('cannot append to compressed archives') -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') + files = Array.from(files) -/***/ }), + return opt.sync ? replaceSync(opt, files) + : replace(opt, files, cb) +} -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const replaceSync = (opt, files) => { + const p = new Pack.Sync(opt) -const {MAX_LENGTH} = __webpack_require__(/*! ../internal/constants */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js") -const { re, t } = __webpack_require__(/*! ../internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") + let threw = true + let fd + let position -const parse = (version, options) => { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + try { + try { + fd = fs.openSync(opt.file, 'r+') + } catch (er) { + if (er.code === 'ENOENT') + fd = fs.openSync(opt.file, 'w+') + else + throw er } - } - if (version instanceof SemVer) { - return version - } + const st = fs.fstatSync(fd) + const headBuf = Buffer.alloc(512) - if (typeof version !== 'string') { - return null - } + POSITION: for (position = 0; position < st.size; position += 512) { + for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { + bytes = fs.readSync( + fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos + ) - if (version.length > MAX_LENGTH) { - return null - } + if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) + throw new Error('cannot append to compressed archives') - const r = options.loose ? re[t.LOOSE] : re[t.FULL] - if (!r.test(version)) { - return null - } + if (!bytes) + break POSITION + } - try { - return new SemVer(version, options) - } catch (er) { - return null + const h = new Header(headBuf) + if (!h.cksumValid) + break + const entryBlockSize = 512 * Math.ceil(h.size / 512) + if (position + entryBlockSize + 512 > st.size) + break + // the 512 for the header we just parsed will be added as well + // also jump ahead all the blocks for the body + position += entryBlockSize + if (opt.mtimeCache) + opt.mtimeCache.set(h.path, h.mtime) + } + threw = false + + streamSync(opt, p, position, fd, files) + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } } } -module.exports = parse +const streamSync = (opt, p, position, fd, files) => { + const stream = new fsm.WriteStreamSync(opt.file, { + fd: fd, + start: position, + }) + p.pipe(stream) + addFilesSync(p, files) +} +const replace = (opt, files, cb) => { + files = Array.from(files) + const p = new Pack(opt) -/***/ }), + const getPos = (fd, size, cb_) => { + const cb = (er, pos) => { + if (er) + fs.close(fd, _ => cb_(er)) + else + cb_(null, pos) + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/patch.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/patch.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + let position = 0 + if (size === 0) + return cb(null, 0) -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch + let bufPos = 0 + const headBuf = Buffer.alloc(512) + const onread = (er, bytes) => { + if (er) + return cb(er) + bufPos += bytes + if (bufPos < 512 && bytes) { + return fs.read( + fd, headBuf, bufPos, headBuf.length - bufPos, + position + bufPos, onread + ) + } + if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) + return cb(new Error('cannot append to compressed archives')) -/***/ }), + // truncated header + if (bufPos < 512) + return cb(null, position) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/prerelease.js": -/*!************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/prerelease.js ***! - \************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const h = new Header(headBuf) + if (!h.cksumValid) + return cb(null, position) -const parse = __webpack_require__(/*! ./parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js") -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -module.exports = prerelease + const entryBlockSize = 512 * Math.ceil(h.size / 512) + if (position + entryBlockSize + 512 > size) + return cb(null, position) + position += entryBlockSize + 512 + if (position >= size) + return cb(null, position) -/***/ }), + if (opt.mtimeCache) + opt.mtimeCache.set(h.path, h.mtime) + bufPos = 0 + fs.read(fd, headBuf, 0, 512, position, onread) + } + fs.read(fd, headBuf, 0, 512, position, onread) + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rcompare.js": -/*!**********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rcompare.js ***! - \**********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const promise = new Promise((resolve, reject) => { + p.on('error', reject) + let flag = 'r+' + const onopen = (er, fd) => { + if (er && er.code === 'ENOENT' && flag === 'r+') { + flag = 'w+' + return fs.open(opt.file, flag, onopen) + } -const compare = __webpack_require__(/*! ./compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js") -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare + if (er) + return reject(er) + fs.fstat(fd, (er, st) => { + if (er) + return fs.close(fd, () => reject(er)) -/***/ }), + getPos(fd, st.size, (er, position) => { + if (er) + return reject(er) + const stream = new fsm.WriteStream(opt.file, { + fd: fd, + start: position, + }) + p.pipe(stream) + stream.on('error', reject) + stream.on('close', resolve) + addFilesAsync(p, files) + }) + }) + } + fs.open(opt.file, flag, onopen) + }) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rsort.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rsort.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return cb ? promise.then(cb, cb) : promise +} -const compareBuild = __webpack_require__(/*! ./compare-build */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-build.js") -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort +const addFilesSync = (p, files) => { + files.forEach(file => { + if (file.charAt(0) === '@') { + t({ + file: path.resolve(p.cwd, file.substr(1)), + sync: true, + noResume: true, + onentry: entry => p.add(entry), + }) + } else + p.add(file) + }) + p.end() +} + +const addFilesAsync = (p, files) => { + while (files.length) { + const file = files.shift() + if (file.charAt(0) === '@') { + return t({ + file: path.resolve(p.cwd, file.substr(1)), + noResume: true, + onentry: entry => p.add(entry), + }).then(_ => addFilesAsync(p, files)) + } else + p.add(file) + } + p.end() +} /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/satisfies.js": -/*!***********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/satisfies.js ***! - \***********************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-absolute-path.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-absolute-path.js ***! + \**************************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false +// unix absolute paths are also absolute on win32, so we use this for both +const { isAbsolute, parse } = (__webpack_require__(/*! path */ "path").win32) + +// returns [root, stripped] +// Note that windows will think that //x/y/z/a has a "root" of //x/y, and in +// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / +// explicitly if it's the first character. +// drive-specific relative paths on Windows get their root stripped off even +// though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] +module.exports = path => { + let r = '' + + let parsed = parse(path) + while (isAbsolute(path) || parsed.root) { + // windows will think that //x/y/z has a "root" of //x/y/ + // but strip the //?/C:/ off of //?/C:/path + const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' + : parsed.root + path = path.substr(root.length) + r += root + parsed = parse(path) } - return range.test(version) + return [r, path] } -module.exports = satisfies /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/sort.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/sort.js ***! - \******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js ***! + \*****************************************************************************************************************/ +/***/ ((module) => { -const compareBuild = __webpack_require__(/*! ./compare-build */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-build.js") -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort +// warning: extremely hot code path. +// This has been meticulously optimized for use +// within npm install on large package trees. +// Do not edit without careful benchmarking. +module.exports = str => { + let i = str.length - 1 + let slashesStart = -1 + while (i > -1 && str.charAt(i) === '/') { + slashesStart = i + i-- + } + return slashesStart === -1 ? str : str.slice(0, slashesStart) +} /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/valid.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/valid.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/types.js": +/*!************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/types.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { -const parse = __webpack_require__(/*! ./parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js") -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null -} -module.exports = valid +"use strict"; + +// map types from key to human-friendly name +exports.name = new Map([ + ['0', 'File'], + // same as File + ['', 'OldFile'], + ['1', 'Link'], + ['2', 'SymbolicLink'], + // Devices and FIFOs aren't fully supported + // they are parsed, but skipped when unpacking + ['3', 'CharacterDevice'], + ['4', 'BlockDevice'], + ['5', 'Directory'], + ['6', 'FIFO'], + // same as File + ['7', 'ContiguousFile'], + // pax headers + ['g', 'GlobalExtendedHeader'], + ['x', 'ExtendedHeader'], + // vendor-specific stuff + // skip + ['A', 'SolarisACL'], + // like 5, but with data, which should be skipped + ['D', 'GNUDumpDir'], + // metadata only, skip + ['I', 'Inode'], + // data = link path of next file + ['K', 'NextFileHasLongLinkpath'], + // data = path of next file + ['L', 'NextFileHasLongPath'], + // skip + ['M', 'ContinuationFile'], + // like L + ['N', 'OldGnuLongPath'], + // skip + ['S', 'SparseFile'], + // skip + ['V', 'TapeVolumeHeader'], + // like x + ['X', 'OldExtendedHeader'], +]) + +// map the other direction +exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js": -/*!*********************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/index.js ***! - \*********************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/unpack.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/unpack.js ***! + \*************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// just pre-load all the stuff that index.js lazily exports -const internalRe = __webpack_require__(/*! ./internal/re */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js") -module.exports = { - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: __webpack_require__(/*! ./internal/constants */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js").SEMVER_SPEC_VERSION, - SemVer: __webpack_require__(/*! ./classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js"), - compareIdentifiers: __webpack_require__(/*! ./internal/identifiers */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/identifiers.js").compareIdentifiers, - rcompareIdentifiers: __webpack_require__(/*! ./internal/identifiers */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/identifiers.js").rcompareIdentifiers, - parse: __webpack_require__(/*! ./functions/parse */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/parse.js"), - valid: __webpack_require__(/*! ./functions/valid */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/valid.js"), - clean: __webpack_require__(/*! ./functions/clean */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/clean.js"), - inc: __webpack_require__(/*! ./functions/inc */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/inc.js"), - diff: __webpack_require__(/*! ./functions/diff */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/diff.js"), - major: __webpack_require__(/*! ./functions/major */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/major.js"), - minor: __webpack_require__(/*! ./functions/minor */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/minor.js"), - patch: __webpack_require__(/*! ./functions/patch */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/patch.js"), - prerelease: __webpack_require__(/*! ./functions/prerelease */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/prerelease.js"), - compare: __webpack_require__(/*! ./functions/compare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare.js"), - rcompare: __webpack_require__(/*! ./functions/rcompare */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rcompare.js"), - compareLoose: __webpack_require__(/*! ./functions/compare-loose */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-loose.js"), - compareBuild: __webpack_require__(/*! ./functions/compare-build */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/compare-build.js"), - sort: __webpack_require__(/*! ./functions/sort */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/sort.js"), - rsort: __webpack_require__(/*! ./functions/rsort */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/rsort.js"), - gt: __webpack_require__(/*! ./functions/gt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js"), - lt: __webpack_require__(/*! ./functions/lt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lt.js"), - eq: __webpack_require__(/*! ./functions/eq */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/eq.js"), - neq: __webpack_require__(/*! ./functions/neq */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/neq.js"), - gte: __webpack_require__(/*! ./functions/gte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gte.js"), - lte: __webpack_require__(/*! ./functions/lte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lte.js"), - cmp: __webpack_require__(/*! ./functions/cmp */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/cmp.js"), - coerce: __webpack_require__(/*! ./functions/coerce */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/coerce.js"), - Comparator: __webpack_require__(/*! ./classes/comparator */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/comparator.js"), - Range: __webpack_require__(/*! ./classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js"), - satisfies: __webpack_require__(/*! ./functions/satisfies */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/satisfies.js"), - toComparators: __webpack_require__(/*! ./ranges/to-comparators */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/to-comparators.js"), - maxSatisfying: __webpack_require__(/*! ./ranges/max-satisfying */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/max-satisfying.js"), - minSatisfying: __webpack_require__(/*! ./ranges/min-satisfying */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-satisfying.js"), - minVersion: __webpack_require__(/*! ./ranges/min-version */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-version.js"), - validRange: __webpack_require__(/*! ./ranges/valid */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/valid.js"), - outside: __webpack_require__(/*! ./ranges/outside */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/outside.js"), - gtr: __webpack_require__(/*! ./ranges/gtr */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/gtr.js"), - ltr: __webpack_require__(/*! ./ranges/ltr */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/ltr.js"), - intersects: __webpack_require__(/*! ./ranges/intersects */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/intersects.js"), -} - - -/***/ }), - -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js": -/*!**********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js ***! - \**********************************************************************************************************/ -/***/ ((module) => { - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' +"use strict"; -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 - -module.exports = { - SEMVER_SPEC_VERSION, - MAX_LENGTH, - MAX_SAFE_INTEGER, - MAX_SAFE_COMPONENT_LENGTH -} +// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. +// but the path reservations are required to avoid race conditions where +// parallelized unpack ops may mess with one another, due to dependencies +// (like a Link depending on its target) or destructive operations (like +// clobbering an fs object to create one of a different type.) -/***/ }), +const assert = __webpack_require__(/*! assert */ "assert") +const Parser = __webpack_require__(/*! ./parse.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/parse.js") +const fs = __webpack_require__(/*! fs */ "fs") +const fsm = __webpack_require__(/*! fs-minipass */ "../../../.yarn/berry/cache/fs-minipass-npm-2.1.0-501ef87306-9.zip/node_modules/fs-minipass/index.js") +const path = __webpack_require__(/*! path */ "path") +const mkdir = __webpack_require__(/*! ./mkdir.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mkdir.js") +const wc = __webpack_require__(/*! ./winchars.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/winchars.js") +const pathReservations = __webpack_require__(/*! ./path-reservations.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/path-reservations.js") +const stripAbsolutePath = __webpack_require__(/*! ./strip-absolute-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-absolute-path.js") +const normPath = __webpack_require__(/*! ./normalize-windows-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js") +const stripSlash = __webpack_require__(/*! ./strip-trailing-slashes.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js") +const normalize = __webpack_require__(/*! ./normalize-unicode.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-unicode.js") -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js ***! - \******************************************************************************************************/ -/***/ ((module) => { +const ONENTRY = Symbol('onEntry') +const CHECKFS = Symbol('checkFs') +const CHECKFS2 = Symbol('checkFs2') +const PRUNECACHE = Symbol('pruneCache') +const ISREUSABLE = Symbol('isReusable') +const MAKEFS = Symbol('makeFs') +const FILE = Symbol('file') +const DIRECTORY = Symbol('directory') +const LINK = Symbol('link') +const SYMLINK = Symbol('symlink') +const HARDLINK = Symbol('hardlink') +const UNSUPPORTED = Symbol('unsupported') +const CHECKPATH = Symbol('checkPath') +const MKDIR = Symbol('mkdir') +const ONERROR = Symbol('onError') +const PENDING = Symbol('pending') +const PEND = Symbol('pend') +const UNPEND = Symbol('unpend') +const ENDED = Symbol('ended') +const MAYBECLOSE = Symbol('maybeClose') +const SKIP = Symbol('skip') +const DOCHOWN = Symbol('doChown') +const UID = Symbol('uid') +const GID = Symbol('gid') +const CHECKED_CWD = Symbol('checkedCwd') +const crypto = __webpack_require__(/*! crypto */ "crypto") +const getFlag = __webpack_require__(/*! ./get-write-flag.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/get-write-flag.js") +const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform +const isWindows = platform === 'win32' -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} +// Unlinks on Windows are not atomic. +// +// This means that if you have a file entry, followed by another +// file entry with an identical name, and you cannot re-use the file +// (because it's a hardlink, or because unlink:true is set, or it's +// Windows, which does not have useful nlink values), then the unlink +// will be committed to the disk AFTER the new file has been written +// over the old one, deleting the new file. +// +// To work around this, on Windows systems, we rename the file and then +// delete the renamed file. It's a sloppy kludge, but frankly, I do not +// know of a better way to do this, given windows' non-atomic unlink +// semantics. +// +// See: https://github.com/npm/node-tar/issues/183 +/* istanbul ignore next */ +const unlinkFile = (path, cb) => { + if (!isWindows) + return fs.unlink(path, cb) -module.exports = debug + const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') + fs.rename(path, name, er => { + if (er) + return cb(er) + fs.unlink(name, cb) + }) +} +/* istanbul ignore next */ +const unlinkFileSync = path => { + if (!isWindows) + return fs.unlinkSync(path) -/***/ }), + const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') + fs.renameSync(path, name) + fs.unlinkSync(name) +} -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/identifiers.js": -/*!************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/identifiers.js ***! - \************************************************************************************************************/ -/***/ ((module) => { +// this.gid, entry.gid, this.processUid +const uint32 = (a, b, c) => + a === a >>> 0 ? a + : b === b >>> 0 ? b + : c -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - const anum = numeric.test(a) - const bnum = numeric.test(b) +// clear the cache if it's a case-insensitive unicode-squashing match. +// we can't know if the current file system is case-sensitive or supports +// unicode fully, so we check for similarity on the maximally compatible +// representation. Err on the side of pruning, since all it's doing is +// preventing lstats, and it's not the end of the world if we get a false +// positive. +// Note that on windows, we always drop the entire cache whenever a +// symbolic link is encountered, because 8.3 filenames are impossible +// to reason about, and collisions are hazards rather than just failures. +const cacheKeyNormalize = path => normalize(stripSlash(normPath(path))) + .toLowerCase() - if (anum && bnum) { - a = +a - b = +b +const pruneCache = (cache, abs) => { + abs = cacheKeyNormalize(abs) + for (const path of cache.keys()) { + const pnorm = cacheKeyNormalize(path) + if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) + cache.delete(path) } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 } -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - -module.exports = { - compareIdentifiers, - rcompareIdentifiers +const dropCache = cache => { + for (const key of cache.keys()) + cache.delete(key) } +class Unpack extends Parser { + constructor (opt) { + if (!opt) + opt = {} -/***/ }), + opt.ondone = _ => { + this[ENDED] = true + this[MAYBECLOSE]() + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js": -/*!***************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/re.js ***! - \***************************************************************************************************/ -/***/ ((module, exports, __webpack_require__) => { + super(opt) -const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(/*! ./constants */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/constants.js") -const debug = __webpack_require__(/*! ./debug */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/internal/debug.js") -exports = module.exports = {} + this[CHECKED_CWD] = false -// The actual regexps go on exports.re -const re = exports.re = [] -const src = exports.src = [] -const t = exports.t = {} -let R = 0 + this.reservations = pathReservations() -const createToken = (name, value, isGlobal) => { - const index = R++ - debug(index, value) - t[name] = index - src[index] = value - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) -} + this.transform = typeof opt.transform === 'function' ? opt.transform : null -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + this.writable = true + this.readable = false -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + this[PENDING] = 0 + this[ENDED] = false -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + this.dirCache = opt.dirCache || new Map() -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { + // need both or neither + if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') + throw new TypeError('cannot set owner without number uid and gid') + if (opt.preserveOwner) { + throw new TypeError( + 'cannot preserve owner in archive and also set owner explicitly') + } + this.uid = opt.uid + this.gid = opt.gid + this.setOwner = true + } else { + this.uid = null + this.gid = null + this.setOwner = false + } -createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + // default true for root + if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') + this.preserveOwner = process.getuid && process.getuid() === 0 + else + this.preserveOwner = !!opt.preserveOwner -// ## Main Version -// Three dot-separated numeric identifiers. + this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? + process.getuid() : null + this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? + process.getgid() : null -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) + // mostly just for testing, but useful in some cases. + // Forcibly trigger a chown on every entry, no matter what + this.forceChown = opt.forceChown === true -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + // turn > this[ONENTRY](entry)) + } -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + // a bad or damaged archive is a warning for Parser, but an error + // when extracting. Mark those errors as unrecoverable, because + // the Unpack contract cannot be met. + warn (code, msg, data = {}) { + if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') + data.recoverable = false + return super.warn(code, msg, data) + } -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + [MAYBECLOSE] () { + if (this[ENDED] && this[PENDING] === 0) { + this.emit('prefinish') + this.emit('finish') + this.emit('end') + this.emit('close') + } + } -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + [CHECKPATH] (entry) { + if (this.strip) { + const parts = normPath(entry.path).split('/') + if (parts.length < this.strip) + return false + entry.path = parts.slice(this.strip).join('/') -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. + if (entry.type === 'Link') { + const linkparts = normPath(entry.linkpath).split('/') + if (linkparts.length >= this.strip) + entry.linkpath = linkparts.slice(this.strip).join('/') + else + return false + } + } -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) + if (!this.preservePaths) { + const p = normPath(entry.path) + const parts = p.split('/') + if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { + this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { + entry, + path: p, + }) + return false + } -createToken('FULL', `^${src[t.FULLPLAIN]}$`) + // strip off the root + const [root, stripped] = stripAbsolutePath(p) + if (root) { + entry.path = stripped + this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { + entry, + path: p, + }) + } + } -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) + if (path.isAbsolute(entry.path)) + entry.absolute = normPath(path.resolve(entry.path)) + else + entry.absolute = normPath(path.resolve(this.cwd, entry.path)) + + // if we somehow ended up with a path that escapes the cwd, and we are + // not in preservePaths mode, then something is fishy! This should have + // been prevented above, so ignore this for coverage. + /* istanbul ignore if - defense in depth */ + if (!this.preservePaths && + entry.absolute.indexOf(this.cwd + '/') !== 0 && + entry.absolute !== this.cwd) { + this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { + entry, + path: normPath(entry.path), + resolvedPath: entry.absolute, + cwd: this.cwd, + }) + return false + } -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + // an archive can set properties on the extraction directory, but it + // may not replace the cwd with a different kind of thing entirely. + if (entry.absolute === this.cwd && + entry.type !== 'Directory' && + entry.type !== 'GNUDumpDir') + return false -createToken('GTLT', '((?:<|>)?=?)') + // only encode : chars that aren't drive letter indicators + if (this.win32) { + const { root: aRoot } = path.win32.parse(entry.absolute) + entry.absolute = aRoot + wc.encode(entry.absolute.substr(aRoot.length)) + const { root: pRoot } = path.win32.parse(entry.path) + entry.path = pRoot + wc.encode(entry.path.substr(pRoot.length)) + } -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + return true + } -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) + [ONENTRY] (entry) { + if (!this[CHECKPATH](entry)) + return entry.resume() -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) + assert.equal(typeof entry.absolute, 'string') -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + switch (entry.type) { + case 'Directory': + case 'GNUDumpDir': + if (entry.mode) + entry.mode = entry.mode | 0o700 -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCE', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) + case 'File': + case 'OldFile': + case 'ContiguousFile': + case 'Link': + case 'SymbolicLink': + return this[CHECKFS](entry) -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') + case 'CharacterDevice': + case 'BlockDevice': + case 'FIFO': + default: + return this[UNSUPPORTED](entry) + } + } -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' + [ONERROR] (er, entry) { + // Cwd has to exist, or else nothing works. That's serious. + // Other errors are warnings, which raise the error in strict + // mode, but otherwise continue on. + if (er.name === 'CwdError') + this.emit('error', er) + else { + this.warn('TAR_ENTRY_ERROR', er, {entry}) + this[UNPEND]() + entry.resume() + } + } -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + [MKDIR] (dir, mode, cb) { + mkdir(normPath(dir), { + uid: this.uid, + gid: this.gid, + processUid: this.processUid, + processGid: this.processGid, + umask: this.processUmask, + preserve: this.preservePaths, + unlink: this.unlink, + cache: this.dirCache, + cwd: this.cwd, + mode: mode, + noChmod: this.noChmod, + }, cb) + } -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') + [DOCHOWN] (entry) { + // in preserve owner mode, chown if the entry doesn't match process + // in set owner mode, chown if setting doesn't match process + return this.forceChown || + this.preserveOwner && + (typeof entry.uid === 'number' && entry.uid !== this.processUid || + typeof entry.gid === 'number' && entry.gid !== this.processGid) + || + (typeof this.uid === 'number' && this.uid !== this.processUid || + typeof this.gid === 'number' && this.gid !== this.processGid) + } -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' + [UID] (entry) { + return uint32(this.uid, entry.uid, this.processUid) + } -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + [GID] (entry) { + return uint32(this.gid, entry.gid, this.processGid) + } -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + [FILE] (entry, fullyDone) { + const mode = entry.mode & 0o7777 || this.fmode + const stream = new fsm.WriteStream(entry.absolute, { + flags: getFlag(entry.size), + mode: mode, + autoClose: false, + }) + stream.on('error', er => { + if (stream.fd) + fs.close(stream.fd, () => {}) + + // flush all the data out so that we aren't left hanging + // if the error wasn't actually fatal. otherwise the parse + // is blocked, and we never proceed. + stream.write = () => true + this[ONERROR](er, entry) + fullyDone() + }) -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' + let actions = 1 + const done = er => { + if (er) { + /* istanbul ignore else - we should always have a fd by now */ + if (stream.fd) + fs.close(stream.fd, () => {}) -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) + this[ONERROR](er, entry) + fullyDone() + return + } -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) + if (--actions === 0) { + fs.close(stream.fd, er => { + if (er) + this[ONERROR](er, entry) + else + this[UNPEND]() + fullyDone() + }) + } + } -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') + stream.on('finish', _ => { + // if futimes fails, try utimes + // if utimes fails, fail with the original error + // same for fchown/chown + const abs = entry.absolute + const fd = stream.fd + if (entry.mtime && !this.noMtime) { + actions++ + const atime = entry.atime || new Date() + const mtime = entry.mtime + fs.futimes(fd, atime, mtime, er => + er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) + : done()) + } -/***/ }), + if (this[DOCHOWN](entry)) { + actions++ + const uid = this[UID](entry) + const gid = this[GID](entry) + fs.fchown(fd, uid, gid, er => + er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) + : done()) + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/gtr.js": -/*!**************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/gtr.js ***! - \**************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + done() + }) -// Determine if version is greater than all the versions possible in the range. -const outside = __webpack_require__(/*! ./outside */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/outside.js") -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr + const tx = this.transform ? this.transform(entry) || entry : entry + if (tx !== entry) { + tx.on('error', er => { + this[ONERROR](er, entry) + fullyDone() + }) + entry.pipe(tx) + } + tx.pipe(stream) + } + [DIRECTORY] (entry, fullyDone) { + const mode = entry.mode & 0o7777 || this.dmode + this[MKDIR](entry.absolute, mode, er => { + if (er) { + this[ONERROR](er, entry) + fullyDone() + return + } -/***/ }), + let actions = 1 + const done = _ => { + if (--actions === 0) { + fullyDone() + this[UNPEND]() + entry.resume() + } + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/intersects.js": -/*!*********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/intersects.js ***! - \*********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (entry.mtime && !this.noMtime) { + actions++ + fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) + } -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} -module.exports = intersects + if (this[DOCHOWN](entry)) { + actions++ + fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) + } + done() + }) + } -/***/ }), + [UNSUPPORTED] (entry) { + entry.unsupported = true + this.warn('TAR_ENTRY_UNSUPPORTED', + `unsupported entry type: ${entry.type}`, {entry}) + entry.resume() + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/ltr.js": -/*!**************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/ltr.js ***! - \**************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + [SYMLINK] (entry, done) { + this[LINK](entry, entry.linkpath, 'symlink', done) + } -const outside = __webpack_require__(/*! ./outside */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/outside.js") -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr + [HARDLINK] (entry, done) { + const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) + this[LINK](entry, linkpath, 'link', done) + } + [PEND] () { + this[PENDING]++ + } -/***/ }), + [UNPEND] () { + this[PENDING]-- + this[MAYBECLOSE]() + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/max-satisfying.js": -/*!*************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/max-satisfying.js ***! - \*************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + [SKIP] (entry) { + this[UNPEND]() + entry.resume() + } -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") + // Check if we can reuse an existing filesystem entry safely and + // overwrite it, rather than unlinking and recreating + // Windows doesn't report a useful nlink, so we just never reuse entries + [ISREUSABLE] (entry, st) { + return entry.type === 'File' && + !this.unlink && + st.isFile() && + st.nlink <= 1 && + !isWindows + } -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null + // check if a thing is there, and if so, try to clobber it + [CHECKFS] (entry) { + this[PEND]() + const paths = [entry.path] + if (entry.linkpath) + paths.push(entry.linkpath) + this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -module.exports = maxSatisfying + [PRUNECACHE] (entry) { + // if we are not creating a directory, and the path is in the dirCache, + // then that means we are about to delete the directory we created + // previously, and it is no longer going to be a directory, and neither + // is any of its children. + // If a symbolic link is encountered, all bets are off. There is no + // reasonable way to sanitize the cache in such a way we will be able to + // avoid having filesystem collisions. If this happens with a non-symlink + // entry, it'll just fail to unpack, but a symlink to a directory, using an + // 8.3 shortname or certain unicode attacks, can evade detection and lead + // to arbitrary writes to anywhere on the system. + if (entry.type === 'SymbolicLink') + dropCache(this.dirCache) + else if (entry.type !== 'Directory') + pruneCache(this.dirCache, entry.absolute) + } -/***/ }), + [CHECKFS2] (entry, fullyDone) { + this[PRUNECACHE](entry) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-satisfying.js": -/*!*************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-satisfying.js ***! - \*************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const done = er => { + this[PRUNECACHE](entry) + fullyDone(er) + } -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } + const checkCwd = () => { + this[MKDIR](this.cwd, this.dmode, er => { + if (er) { + this[ONERROR](er, entry) + done() + return + } + this[CHECKED_CWD] = true + start() + }) } - }) - return min -} -module.exports = minSatisfying + const start = () => { + if (entry.absolute !== this.cwd) { + const parent = normPath(path.dirname(entry.absolute)) + if (parent !== this.cwd) { + return this[MKDIR](parent, this.dmode, er => { + if (er) { + this[ONERROR](er, entry) + done() + return + } + afterMakeParent() + }) + } + } + afterMakeParent() + } -/***/ }), + const afterMakeParent = () => { + fs.lstat(entry.absolute, (lstatEr, st) => { + if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { + this[SKIP](entry) + done() + return + } + if (lstatEr || this[ISREUSABLE](entry, st)) + return this[MAKEFS](null, entry, done) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-version.js": -/*!**********************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/min-version.js ***! - \**********************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (st.isDirectory()) { + if (entry.type === 'Directory') { + const needChmod = !this.noChmod && + entry.mode && + (st.mode & 0o7777) !== entry.mode + const afterChmod = er => this[MAKEFS](er, entry, done) + if (!needChmod) + return afterChmod() + return fs.chmod(entry.absolute, entry.mode, afterChmod) + } + // Not a dir entry, have to remove it. + // NB: the only way to end up with an entry that is the cwd + // itself, in such a way that == does not detect, is a + // tricky windows absolute path with UNC or 8.3 parts (and + // preservePaths:true, or else it will have been stripped). + // In that case, the user has opted out of path protections + // explicitly, so if they blow away the cwd, c'est la vie. + if (entry.absolute !== this.cwd) { + return fs.rmdir(entry.absolute, er => + this[MAKEFS](er, entry, done)) + } + } -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const gt = __webpack_require__(/*! ../functions/gt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js") + // not a dir, and not reusable + // don't remove if the cwd, we want that error + if (entry.absolute === this.cwd) + return this[MAKEFS](null, entry, done) -const minVersion = (range, loose) => { - range = new Range(range, loose) + unlinkFile(entry.absolute, er => + this[MAKEFS](er, entry, done)) + }) + } - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver + if (this[CHECKED_CWD]) + start() + else + checkCwd() } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } + [MAKEFS] (er, entry, done) { + if (er) { + this[ONERROR](er, entry) + done() + return + } - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] + switch (entry.type) { + case 'File': + case 'OldFile': + case 'ContiguousFile': + return this[FILE](entry, done) - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) + case 'Link': + return this[HARDLINK](entry, done) + + case 'SymbolicLink': + return this[SYMLINK](entry, done) + + case 'Directory': + case 'GNUDumpDir': + return this[DIRECTORY](entry, done) + } + } + + [LINK] (entry, linkpath, link, done) { + // XXX: get the type ('symlink' or 'junction') for windows + fs[link](linkpath, entry.absolute, er => { + if (er) + this[ONERROR](er, entry) + else { + this[UNPEND]() + entry.resume() } + done() }) } +} - if (minver && range.test(minver)) { - return minver +const callSync = fn => { + try { + return [null, fn()] + } catch (er) { + return [er, null] } - - return null } -module.exports = minVersion +class UnpackSync extends Unpack { + [MAKEFS] (er, entry) { + return super[MAKEFS](er, entry, () => {}) + } + [CHECKFS] (entry) { + this[PRUNECACHE](entry) -/***/ }), + if (!this[CHECKED_CWD]) { + const er = this[MKDIR](this.cwd, this.dmode) + if (er) + return this[ONERROR](er, entry) + this[CHECKED_CWD] = true + } -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/outside.js": -/*!******************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/outside.js ***! - \******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // don't bother to make the parent if the current entry is the cwd, + // we've already checked it. + if (entry.absolute !== this.cwd) { + const parent = normPath(path.dirname(entry.absolute)) + if (parent !== this.cwd) { + const mkParent = this[MKDIR](parent, this.dmode) + if (mkParent) + return this[ONERROR](mkParent, entry) + } + } -const SemVer = __webpack_require__(/*! ../classes/semver */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/semver.js") -const Comparator = __webpack_require__(/*! ../classes/comparator */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/comparator.js") -const {ANY} = Comparator -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const satisfies = __webpack_require__(/*! ../functions/satisfies */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/satisfies.js") -const gt = __webpack_require__(/*! ../functions/gt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gt.js") -const lt = __webpack_require__(/*! ../functions/lt */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lt.js") -const lte = __webpack_require__(/*! ../functions/lte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/lte.js") -const gte = __webpack_require__(/*! ../functions/gte */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/functions/gte.js") + const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) + if (st && (this.keep || this.newer && st.mtime > entry.mtime)) + return this[SKIP](entry) -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) + if (lstatEr || this[ISREUSABLE](entry, st)) + return this[MAKEFS](null, entry) - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } + if (st.isDirectory()) { + if (entry.type === 'Directory') { + const needChmod = !this.noChmod && + entry.mode && + (st.mode & 0o7777) !== entry.mode + const [er] = needChmod ? callSync(() => { + fs.chmodSync(entry.absolute, entry.mode) + }) : [] + return this[MAKEFS](er, entry) + } + // not a dir entry, have to remove it + const [er] = callSync(() => fs.rmdirSync(entry.absolute)) + this[MAKEFS](er, entry) + } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false + // not a dir, and not reusable. + // don't remove if it's the cwd, since we want that error. + const [er] = entry.absolute === this.cwd ? [] + : callSync(() => unlinkFileSync(entry.absolute)) + this[MAKEFS](er, entry) } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + [FILE] (entry, done) { + const mode = entry.mode & 0o7777 || this.fmode - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] + const oner = er => { + let closeError + try { + fs.closeSync(fd) + } catch (e) { + closeError = e + } + if (er || closeError) + this[ONERROR](er || closeError, entry) + done() + } - let high = null - let low = null + let fd + try { + fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) + } catch (er) { + return oner(er) + } + const tx = this.transform ? this.transform(entry) || entry : entry + if (tx !== entry) { + tx.on('error', er => this[ONERROR](er, entry)) + entry.pipe(tx) + } - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') + tx.on('data', chunk => { + try { + fs.writeSync(fd, chunk, 0, chunk.length) + } catch (er) { + oner(er) } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator + }) + + tx.on('end', _ => { + let er = null + // try both, falling futimes back to utimes + // if either fails, handle the first error + if (entry.mtime && !this.noMtime) { + const atime = entry.atime || new Date() + const mtime = entry.mtime + try { + fs.futimesSync(fd, atime, mtime) + } catch (futimeser) { + try { + fs.utimesSync(entry.absolute, atime, mtime) + } catch (utimeser) { + er = futimeser + } + } + } + + if (this[DOCHOWN](entry)) { + const uid = this[UID](entry) + const gid = this[GID](entry) + + try { + fs.fchownSync(fd, uid, gid) + } catch (fchowner) { + try { + fs.chownSync(entry.absolute, uid, gid) + } catch (chowner) { + er = er || fchowner + } + } } + + oner(er) }) + } - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false + [DIRECTORY] (entry, done) { + const mode = entry.mode & 0o7777 || this.dmode + const er = this[MKDIR](entry.absolute, mode) + if (er) { + this[ONERROR](er, entry) + done() + return + } + if (entry.mtime && !this.noMtime) { + try { + fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) + } catch (er) {} + } + if (this[DOCHOWN](entry)) { + try { + fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) + } catch (er) {} } + done() + entry.resume() + } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false + [MKDIR] (dir, mode) { + try { + return mkdir.sync(normPath(dir), { + uid: this.uid, + gid: this.gid, + processUid: this.processUid, + processGid: this.processGid, + umask: this.processUmask, + preserve: this.preservePaths, + unlink: this.unlink, + cache: this.dirCache, + cwd: this.cwd, + mode: mode, + }) + } catch (er) { + return er + } + } + + [LINK] (entry, linkpath, link, done) { + try { + fs[link + 'Sync'](linkpath, entry.absolute) + done() + entry.resume() + } catch (er) { + return this[ONERROR](er, entry) } } - return true } -module.exports = outside +Unpack.Sync = UnpackSync +module.exports = Unpack /***/ }), -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/to-comparators.js": -/*!*************************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/to-comparators.js ***! - \*************************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/update.js": +/*!*************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/update.js ***! + \*************************************************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") +"use strict"; -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) -module.exports = toComparators +// tar -u +const hlo = __webpack_require__(/*! ./high-level-opt.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/high-level-opt.js") +const r = __webpack_require__(/*! ./replace.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/replace.js") +// just call tar.r with the filter and mtimeCache -/***/ }), +module.exports = (opt_, files, cb) => { + const opt = hlo(opt_) -/***/ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/valid.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/ranges/valid.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (!opt.file) + throw new TypeError('file is required') -const Range = __webpack_require__(/*! ../classes/range */ "./.yarn/cache/semver-npm-7.1.3-1741df6bad-a7700fd039.zip/node_modules/semver/classes/range.js") -const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } + if (opt.gzip) + throw new TypeError('cannot append to compressed archives') + + if (!files || !Array.isArray(files) || !files.length) + throw new TypeError('no files or directories specified') + + files = Array.from(files) + + mtimeFilter(opt) + return r(opt, files, cb) +} + +const mtimeFilter = opt => { + const filter = opt.filter + + if (!opt.mtimeCache) + opt.mtimeCache = new Map() + + opt.filter = filter ? (path, stat) => + filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) + : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) } -module.exports = validRange /***/ }), -/***/ "./.yarn/cache/supports-color-npm-7.1.0-df2ba1e338-899480ac85.zip/node_modules/supports-color/index.js": -/*!*************************************************************************************************************!*\ - !*** ./.yarn/cache/supports-color-npm-7.1.0-df2ba1e338-899480ac85.zip/node_modules/supports-color/index.js ***! - \*************************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/warn-mixin.js": +/*!*****************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/warn-mixin.js ***! + \*****************************************************************************************************/ +/***/ ((module) => { "use strict"; -const os = __webpack_require__(/*! os */ "os"); -const tty = __webpack_require__(/*! tty */ "tty"); -const hasFlag = __webpack_require__(/*! has-flag */ "./.yarn/cache/has-flag-npm-4.0.0-32af9f0536-261a135703.zip/node_modules/has-flag/index.js"); - -const {env} = process; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} - -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } +module.exports = Base => class extends Base { + warn (code, message, data = {}) { + if (this.file) + data.file = this.file + if (this.cwd) + data.cwd = this.cwd + data.code = message instanceof Error && message.code || code + data.tarCode = code + if (!this.strict && data.recoverable !== false) { + if (message instanceof Error) { + data = Object.assign(message, data) + message = message.message + } + this.emit('warn', data.tarCode, message, data) + } else if (message instanceof Error) + this.emit('error', Object.assign(message, data)) + else + this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) + } } -function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} +/***/ }), -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/winchars.js": +/*!***************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/winchars.js ***! + \***************************************************************************************************/ +/***/ ((module) => { - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } +"use strict"; - if (hasFlag('color=256')) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } +// When writing files on Windows, translate the characters to their +// 0xf000 higher-encoded versions. - const min = forceColor || 0; +const raw = [ + '|', + '<', + '>', + '?', + ':', +] - if (env.TERM === 'dumb') { - return min; - } +const win = raw.map(char => + String.fromCharCode(0xf000 + char.charCodeAt(0))) - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +const toWin = new Map(raw.map((char, i) => [char, win[i]])) +const toRaw = new Map(win.map((char, i) => [char, raw[i]])) - return 1; - } +module.exports = { + encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), + decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), +} - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - return min; - } +/***/ }), - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +/***/ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/write-entry.js": +/*!******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/write-entry.js ***! + \******************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if ('GITHUB_ACTIONS' in env) { - return 1; - } +"use strict"; - if (env.COLORTERM === 'truecolor') { - return 3; - } +const MiniPass = __webpack_require__(/*! minipass */ "../../../.yarn/berry/cache/minipass-npm-3.1.6-f032df1661-9.zip/node_modules/minipass/index.js") +const Pax = __webpack_require__(/*! ./pax.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/pax.js") +const Header = __webpack_require__(/*! ./header.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/header.js") +const fs = __webpack_require__(/*! fs */ "fs") +const path = __webpack_require__(/*! path */ "path") +const normPath = __webpack_require__(/*! ./normalize-windows-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/normalize-windows-path.js") +const stripSlash = __webpack_require__(/*! ./strip-trailing-slashes.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-trailing-slashes.js") - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +const prefixPath = (path, prefix) => { + if (!prefix) + return normPath(path) + path = normPath(path).replace(/^\.(\/|$)/, '') + return stripSlash(prefix) + '/' + path +} - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } +const maxReadSize = 16 * 1024 * 1024 +const PROCESS = Symbol('process') +const FILE = Symbol('file') +const DIRECTORY = Symbol('directory') +const SYMLINK = Symbol('symlink') +const HARDLINK = Symbol('hardlink') +const HEADER = Symbol('header') +const READ = Symbol('read') +const LSTAT = Symbol('lstat') +const ONLSTAT = Symbol('onlstat') +const ONREAD = Symbol('onread') +const ONREADLINK = Symbol('onreadlink') +const OPENFILE = Symbol('openfile') +const ONOPENFILE = Symbol('onopenfile') +const CLOSE = Symbol('close') +const MODE = Symbol('mode') +const AWAITDRAIN = Symbol('awaitDrain') +const ONDRAIN = Symbol('ondrain') +const PREFIX = Symbol('prefix') +const HAD_ERROR = Symbol('hadError') +const warner = __webpack_require__(/*! ./warn-mixin.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/warn-mixin.js") +const winchars = __webpack_require__(/*! ./winchars.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/winchars.js") +const stripAbsolutePath = __webpack_require__(/*! ./strip-absolute-path.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/strip-absolute-path.js") - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +const modeFix = __webpack_require__(/*! ./mode-fix.js */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/lib/mode-fix.js") - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +const WriteEntry = warner(class WriteEntry extends MiniPass { + constructor (p, opt) { + opt = opt || {} + super(opt) + if (typeof p !== 'string') + throw new TypeError('path is required') + this.path = normPath(p) + // suppress atime, ctime, uid, gid, uname, gname + this.portable = !!opt.portable + // until node has builtin pwnam functions, this'll have to do + this.myuid = process.getuid && process.getuid() || 0 + this.myuser = process.env.USER || '' + this.maxReadSize = opt.maxReadSize || maxReadSize + this.linkCache = opt.linkCache || new Map() + this.statCache = opt.statCache || new Map() + this.preservePaths = !!opt.preservePaths + this.cwd = normPath(opt.cwd || process.cwd()) + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.noMtime = !!opt.noMtime + this.mtime = opt.mtime || null + this.prefix = opt.prefix ? normPath(opt.prefix) : null - if ('COLORTERM' in env) { - return 1; - } + this.fd = null + this.blockLen = null + this.blockRemain = null + this.buf = null + this.offset = null + this.length = null + this.pos = null + this.remain = null - return min; -} + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); -} + let pathWarn = false + if (!this.preservePaths) { + const [root, stripped] = stripAbsolutePath(this.path) + if (root) { + this.path = stripped + pathWarn = root + } + } -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; + this.win32 = !!opt.win32 || process.platform === 'win32' + if (this.win32) { + // force the \ to / normalization, since we might not *actually* + // be on windows, but want \ to be considered a path separator. + this.path = winchars.decode(this.path.replace(/\\/g, '/')) + p = p.replace(/\\/g, '/') + } + this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) -/***/ }), + if (this.path === '') + this.path = './' -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/index.js": -/*!***************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/index.js ***! - \***************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (pathWarn) { + this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { + entry: this, + path: pathWarn + this.path, + }) + } -"use strict"; + if (this.statCache.has(this.absolute)) + this[ONLSTAT](this.statCache.get(this.absolute)) + else + this[LSTAT]() + } + emit (ev, ...data) { + if (ev === 'error') + this[HAD_ERROR] = true + return super.emit(ev, ...data) + } -// high-level commands -exports.c = exports.create = __webpack_require__(/*! ./lib/create.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/create.js") -exports.r = exports.replace = __webpack_require__(/*! ./lib/replace.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/replace.js") -exports.t = exports.list = __webpack_require__(/*! ./lib/list.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/list.js") -exports.u = exports.update = __webpack_require__(/*! ./lib/update.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/update.js") -exports.x = exports.extract = __webpack_require__(/*! ./lib/extract.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/extract.js") + [LSTAT] () { + fs.lstat(this.absolute, (er, stat) => { + if (er) + return this.emit('error', er) + this[ONLSTAT](stat) + }) + } -// classes -exports.Pack = __webpack_require__(/*! ./lib/pack.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pack.js") -exports.Unpack = __webpack_require__(/*! ./lib/unpack.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/unpack.js") -exports.Parse = __webpack_require__(/*! ./lib/parse.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js") -exports.ReadEntry = __webpack_require__(/*! ./lib/read-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js") -exports.WriteEntry = __webpack_require__(/*! ./lib/write-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/write-entry.js") -exports.Header = __webpack_require__(/*! ./lib/header.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js") -exports.Pax = __webpack_require__(/*! ./lib/pax.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pax.js") -exports.types = __webpack_require__(/*! ./lib/types.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js") + [ONLSTAT] (stat) { + this.statCache.set(this.absolute, stat) + this.stat = stat + if (!stat.isFile()) + stat.size = 0 + this.type = getType(stat) + this.emit('stat', stat) + this[PROCESS]() + } + [PROCESS] () { + switch (this.type) { + case 'File': return this[FILE]() + case 'Directory': return this[DIRECTORY]() + case 'SymbolicLink': return this[SYMLINK]() + // unsupported types are ignored. + default: return this.end() + } + } -/***/ }), + [MODE] (mode) { + return modeFix(mode, this.type === 'Directory', this.portable) + } -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/create.js": -/*!********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/create.js ***! - \********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + [PREFIX] (path) { + return prefixPath(path, this.prefix) + } -"use strict"; + [HEADER] () { + if (this.type === 'Directory' && this.portable) + this.noMtime = true + this.header = new Header({ + path: this[PREFIX](this.path), + // only apply the prefix to hard links. + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + // only the permissions and setuid/setgid/sticky bitflags + // not the higher-order bits that specify file type + mode: this[MODE](this.stat.mode), + uid: this.portable ? null : this.stat.uid, + gid: this.portable ? null : this.stat.gid, + size: this.stat.size, + mtime: this.noMtime ? null : this.mtime || this.stat.mtime, + type: this.type, + uname: this.portable ? null : + this.stat.uid === this.myuid ? this.myuser : '', + atime: this.portable ? null : this.stat.atime, + ctime: this.portable ? null : this.stat.ctime, + }) -// tar -c -const hlo = __webpack_require__(/*! ./high-level-opt.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js") + if (this.header.encode() && !this.noPax) { + super.write(new Pax({ + atime: this.portable ? null : this.header.atime, + ctime: this.portable ? null : this.header.ctime, + gid: this.portable ? null : this.header.gid, + mtime: this.noMtime ? null : this.mtime || this.header.mtime, + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + size: this.header.size, + uid: this.portable ? null : this.header.uid, + uname: this.portable ? null : this.header.uname, + dev: this.portable ? null : this.stat.dev, + ino: this.portable ? null : this.stat.ino, + nlink: this.portable ? null : this.stat.nlink, + }).encode()) + } + super.write(this.header.block) + } -const Pack = __webpack_require__(/*! ./pack.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pack.js") -const fs = __webpack_require__(/*! fs */ "fs") -const fsm = __webpack_require__(/*! fs-minipass */ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js") -const t = __webpack_require__(/*! ./list.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/list.js") -const path = __webpack_require__(/*! path */ "path") + [DIRECTORY] () { + if (this.path.substr(-1) !== '/') + this.path += '/' + this.stat.size = 0 + this[HEADER]() + this.end() + } -const c = module.exports = (opt_, files, cb) => { - if (typeof files === 'function') - cb = files + [SYMLINK] () { + fs.readlink(this.absolute, (er, linkpath) => { + if (er) + return this.emit('error', er) + this[ONREADLINK](linkpath) + }) + } - if (Array.isArray(opt_)) - files = opt_, opt_ = {} + [ONREADLINK] (linkpath) { + this.linkpath = normPath(linkpath) + this[HEADER]() + this.end() + } - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') + [HARDLINK] (linkpath) { + this.type = 'Link' + this.linkpath = normPath(path.relative(this.cwd, linkpath)) + this.stat.size = 0 + this[HEADER]() + this.end() + } - files = Array.from(files) + [FILE] () { + if (this.stat.nlink > 1) { + const linkKey = this.stat.dev + ':' + this.stat.ino + if (this.linkCache.has(linkKey)) { + const linkpath = this.linkCache.get(linkKey) + if (linkpath.indexOf(this.cwd) === 0) + return this[HARDLINK](linkpath) + } + this.linkCache.set(linkKey, this.absolute) + } - const opt = hlo(opt_) + this[HEADER]() + if (this.stat.size === 0) + return this.end() - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') + this[OPENFILE]() + } - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') + [OPENFILE] () { + fs.open(this.absolute, 'r', (er, fd) => { + if (er) + return this.emit('error', er) + this[ONOPENFILE](fd) + }) + } - return opt.file && opt.sync ? createFileSync(opt, files) - : opt.file ? createFile(opt, files, cb) - : opt.sync ? createSync(opt, files) - : create(opt, files) -} + [ONOPENFILE] (fd) { + this.fd = fd + if (this[HAD_ERROR]) + return this[CLOSE]() + + this.blockLen = 512 * Math.ceil(this.stat.size / 512) + this.blockRemain = this.blockLen + const bufLen = Math.min(this.blockLen, this.maxReadSize) + this.buf = Buffer.allocUnsafe(bufLen) + this.offset = 0 + this.pos = 0 + this.remain = this.stat.size + this.length = this.buf.length + this[READ]() + } + + [READ] () { + const { fd, buf, offset, length, pos } = this + fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { + if (er) { + // ignoring the error from close(2) is a bad practice, but at + // this point we already have an error, don't need another one + return this[CLOSE](() => this.emit('error', er)) + } + this[ONREAD](bytesRead) + }) + } -const createFileSync = (opt, files) => { - const p = new Pack.Sync(opt) - const stream = new fsm.WriteStreamSync(opt.file, { - mode: opt.mode || 0o666 - }) - p.pipe(stream) - addFilesSync(p, files) -} + [CLOSE] (cb) { + fs.close(this.fd, cb) + } -const createFile = (opt, files, cb) => { - const p = new Pack(opt) - const stream = new fsm.WriteStream(opt.file, { - mode: opt.mode || 0o666 - }) - p.pipe(stream) + [ONREAD] (bytesRead) { + if (bytesRead <= 0 && this.remain > 0) { + const er = new Error('encountered unexpected EOF') + er.path = this.absolute + er.syscall = 'read' + er.code = 'EOF' + return this[CLOSE](() => this.emit('error', er)) + } - const promise = new Promise((res, rej) => { - stream.on('error', rej) - stream.on('close', res) - p.on('error', rej) - }) + if (bytesRead > this.remain) { + const er = new Error('did not encounter expected EOF') + er.path = this.absolute + er.syscall = 'read' + er.code = 'EOF' + return this[CLOSE](() => this.emit('error', er)) + } - addFilesAsync(p, files) + // null out the rest of the buffer, if we could fit the block padding + // at the end of this loop, we've incremented bytesRead and this.remain + // to be incremented up to the blockRemain level, as if we had expected + // to get a null-padded file, and read it until the end. then we will + // decrement both remain and blockRemain by bytesRead, and know that we + // reached the expected EOF, without any null buffer to append. + if (bytesRead === this.remain) { + for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { + this.buf[i + this.offset] = 0 + bytesRead++ + this.remain++ + } + } - return cb ? promise.then(cb, cb) : promise -} + const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? + this.buf : this.buf.slice(this.offset, this.offset + bytesRead) -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') - t({ - file: path.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry) - }) + const flushed = this.write(writeBuf) + if (!flushed) + this[AWAITDRAIN](() => this[ONDRAIN]()) else - p.add(file) - }) - p.end() -} + this[ONDRAIN]() + } -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') - return t({ - file: path.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: entry => p.add(entry) - }).then(_ => addFilesAsync(p, files)) - else - p.add(file) + [AWAITDRAIN] (cb) { + this.once('drain', cb) } - p.end() -} -const createSync = (opt, files) => { - const p = new Pack.Sync(opt) - addFilesSync(p, files) - return p -} + write (writeBuf) { + if (this.blockRemain < writeBuf.length) { + const er = new Error('writing more data than expected') + er.path = this.absolute + return this.emit('error', er) + } + this.remain -= writeBuf.length + this.blockRemain -= writeBuf.length + this.pos += writeBuf.length + this.offset += writeBuf.length + return super.write(writeBuf) + } -const create = (opt, files) => { - const p = new Pack(opt) - addFilesAsync(p, files) - return p -} + [ONDRAIN] () { + if (!this.remain) { + if (this.blockRemain) + super.write(Buffer.alloc(this.blockRemain)) + return this[CLOSE](er => er ? this.emit('error', er) : this.end()) + } + if (this.offset >= this.length) { + // if we only have a smaller bit left to read, alloc a smaller buffer + // otherwise, keep it the same length it was before. + this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) + this.offset = 0 + } + this.length = this.buf.length - this.offset + this[READ]() + } +}) -/***/ }), +class WriteEntrySync extends WriteEntry { + [LSTAT] () { + this[ONLSTAT](fs.lstatSync(this.absolute)) + } -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/extract.js": -/*!*********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/extract.js ***! - \*********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + [SYMLINK] () { + this[ONREADLINK](fs.readlinkSync(this.absolute)) + } -"use strict"; + [OPENFILE] () { + this[ONOPENFILE](fs.openSync(this.absolute, 'r')) + } + [READ] () { + let threw = true + try { + const { fd, buf, offset, length, pos } = this + const bytesRead = fs.readSync(fd, buf, offset, length, pos) + this[ONREAD](bytesRead) + threw = false + } finally { + // ignoring the error from close(2) is a bad practice, but at + // this point we already have an error, don't need another one + if (threw) { + try { + this[CLOSE](() => {}) + } catch (er) {} + } + } + } -// tar -x -const hlo = __webpack_require__(/*! ./high-level-opt.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js") -const Unpack = __webpack_require__(/*! ./unpack.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/unpack.js") -const fs = __webpack_require__(/*! fs */ "fs") -const fsm = __webpack_require__(/*! fs-minipass */ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js") -const path = __webpack_require__(/*! path */ "path") + [AWAITDRAIN] (cb) { + cb() + } -const x = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} + [CLOSE] (cb) { + fs.closeSync(this.fd) + cb() + } +} - if (typeof files === 'function') - cb = files, files = null +const WriteEntryTar = warner(class WriteEntryTar extends MiniPass { + constructor (readEntry, opt) { + opt = opt || {} + super(opt) + this.preservePaths = !!opt.preservePaths + this.portable = !!opt.portable + this.strict = !!opt.strict + this.noPax = !!opt.noPax + this.noMtime = !!opt.noMtime - if (!files) - files = [] - else - files = Array.from(files) + this.readEntry = readEntry + this.type = readEntry.type + if (this.type === 'Directory' && this.portable) + this.noMtime = true - const opt = hlo(opt_) + this.prefix = opt.prefix || null - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') + this.path = normPath(readEntry.path) + this.mode = this[MODE](readEntry.mode) + this.uid = this.portable ? null : readEntry.uid + this.gid = this.portable ? null : readEntry.gid + this.uname = this.portable ? null : readEntry.uname + this.gname = this.portable ? null : readEntry.gname + this.size = readEntry.size + this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime + this.atime = this.portable ? null : readEntry.atime + this.ctime = this.portable ? null : readEntry.ctime + this.linkpath = normPath(readEntry.linkpath) - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') + if (typeof opt.onwarn === 'function') + this.on('warn', opt.onwarn) - if (files.length) - filesFilter(opt, files) + let pathWarn = false + if (!this.preservePaths) { + const [root, stripped] = stripAbsolutePath(this.path) + if (root) { + this.path = stripped + pathWarn = root + } + } - return opt.file && opt.sync ? extractFileSync(opt) - : opt.file ? extractFile(opt, cb) - : opt.sync ? extractSync(opt) - : extract(opt) -} + this.remain = readEntry.size + this.blockRemain = readEntry.startBlockSize -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter + this.header = new Header({ + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + // only the permissions and setuid/setgid/sticky bitflags + // not the higher-order bits that specify file type + mode: this.mode, + uid: this.portable ? null : this.uid, + gid: this.portable ? null : this.gid, + size: this.size, + mtime: this.noMtime ? null : this.mtime, + type: this.type, + uname: this.portable ? null : this.uname, + atime: this.portable ? null : this.atime, + ctime: this.portable ? null : this.ctime, + }) - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) + if (pathWarn) { + this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { + entry: this, + path: pathWarn + this.path, + }) + } - map.set(file, ret) - return ret - } + if (this.header.encode() && !this.noPax) { + super.write(new Pax({ + atime: this.portable ? null : this.atime, + ctime: this.portable ? null : this.ctime, + gid: this.portable ? null : this.gid, + mtime: this.noMtime ? null : this.mtime, + path: this[PREFIX](this.path), + linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) + : this.linkpath, + size: this.size, + uid: this.portable ? null : this.uid, + uname: this.portable ? null : this.uname, + dev: this.portable ? null : this.readEntry.dev, + ino: this.portable ? null : this.readEntry.ino, + nlink: this.portable ? null : this.readEntry.nlink, + }).encode()) + } - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) -} + super.write(this.header.block) + readEntry.pipe(this) + } -const extractFileSync = opt => { - const u = new Unpack.Sync(opt) + [PREFIX] (path) { + return prefixPath(path, this.prefix) + } - const file = opt.file - let threw = true - let fd - const stat = fs.statSync(file) - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - const readSize = opt.maxReadSize || 16*1024*1024 - const stream = new fsm.ReadStreamSync(file, { - readSize: readSize, - size: stat.size - }) - stream.pipe(u) -} + [MODE] (mode) { + return modeFix(mode, this.type === 'Directory', this.portable) + } -const extractFile = (opt, cb) => { - const u = new Unpack(opt) - const readSize = opt.maxReadSize || 16*1024*1024 + write (data) { + const writeLen = data.length + if (writeLen > this.blockRemain) + throw new Error('writing more to entry than is appropriate') + this.blockRemain -= writeLen + return super.write(data) + } - const file = opt.file - const p = new Promise((resolve, reject) => { - u.on('error', reject) - u.on('close', resolve) + end () { + if (this.blockRemain) + super.write(Buffer.alloc(this.blockRemain)) + return super.end() + } +}) - // This trades a zero-byte read() syscall for a stat - // However, it will usually result in less memory allocation - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(u) - } - }) - }) - return cb ? p.then(cb, cb) : p -} +WriteEntry.Sync = WriteEntrySync +WriteEntry.Tar = WriteEntryTar -const extractSync = opt => { - return new Unpack.Sync(opt) -} +const getType = stat => + stat.isFile() ? 'File' + : stat.isDirectory() ? 'Directory' + : stat.isSymbolicLink() ? 'SymbolicLink' + : 'Unsupported' -const extract = opt => { - return new Unpack(opt) -} +module.exports = WriteEntry /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/get-write-flag.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/get-write-flag.js ***! - \****************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// Get the appropriate flag to use for creating files -// We use fmap on Windows platforms for files less than -// 512kb. This is a fairly low limit, but avoids making -// things slower in some cases. Since most of what this -// library is used for is extracting tarballs of many -// relatively small files in npm packages and the like, -// it can be a big boost on Windows platforms. -// Only supported in Node v12.9.0 and above. -const platform = process.env.__FAKE_PLATFORM__ || process.platform -const isWindows = platform === 'win32' -const fs = global.__FAKE_TESTING_FS__ || __webpack_require__(/*! fs */ "fs") - -/* istanbul ignore next */ -const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants - -const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP -const fMapLimit = 512 * 1024 -const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY -module.exports = !fMapEnabled ? () => 'w' - : size => size < fMapLimit ? fMapFlag : 'w' - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js": -/*!********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js ***! - \********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "../../../.yarn/berry/cache/typanion-npm-3.9.0-ef0bfe7e8b-9.zip/node_modules/typanion/lib/index.js": +/*!*********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/typanion-npm-3.9.0-ef0bfe7e8b-9.zip/node_modules/typanion/lib/index.js ***! + \*********************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// parse a 512-byte header block to a data object, or vice-versa -// encode returns `true` if a pax extended header is needed, because -// the data could not be faithfully encoded in a simple header. -// (Also, check header.needPax to see if it needs a pax header.) - -const types = __webpack_require__(/*! ./types.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js") -const pathModule = __webpack_require__(/*! path */ "path").posix -const large = __webpack_require__(/*! ./large-numbers.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/large-numbers.js") - -const SLURP = Symbol('slurp') -const TYPE = Symbol('type') - -class Header { - constructor (data, off, ex, gex) { - this.cksumValid = false - this.needPax = false - this.nullBlock = false - - this.block = null - this.path = null - this.mode = null - this.uid = null - this.gid = null - this.size = null - this.mtime = null - this.cksum = null - this[TYPE] = '0' - this.linkpath = null - this.uname = null - this.gname = null - this.devmaj = 0 - this.devmin = 0 - this.atime = null - this.ctime = null - - if (Buffer.isBuffer(data)) - this.decode(data, off || 0, ex, gex) - else if (data) - this.set(data) - } - - decode (buf, off, ex, gex) { - if (!off) - off = 0 - - if (!buf || !(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - this.path = decString(buf, off, 100) - this.mode = decNumber(buf, off + 100, 8) - this.uid = decNumber(buf, off + 108, 8) - this.gid = decNumber(buf, off + 116, 8) - this.size = decNumber(buf, off + 124, 12) - this.mtime = decDate(buf, off + 136, 12) - this.cksum = decNumber(buf, off + 148, 12) - - // if we have extended or global extended headers, apply them now - // See https://github.com/npm/node-tar/pull/187 - this[SLURP](ex) - this[SLURP](gex, true) - - // old tar versions marked dirs as a file with a trailing / - this[TYPE] = decString(buf, off + 156, 1) - if (this[TYPE] === '') - this[TYPE] = '0' - if (this[TYPE] === '0' && this.path.substr(-1) === '/') - this[TYPE] = '5' - - // tar implementations sometimes incorrectly put the stat(dir).size - // as the size in the tarball, even though Directory entries are - // not able to have any body at all. In the very rare chance that - // it actually DOES have a body, we weren't going to do anything with - // it anyway, and it'll just be a warning about an invalid header. - if (this[TYPE] === '5') - this.size = 0 - - this.linkpath = decString(buf, off + 157, 100) - if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { - this.uname = decString(buf, off + 265, 32) - this.gname = decString(buf, off + 297, 32) - this.devmaj = decNumber(buf, off + 329, 8) - this.devmin = decNumber(buf, off + 337, 8) - if (buf[off + 475] !== 0) { - // definitely a prefix, definitely >130 chars. - const prefix = decString(buf, off + 345, 155) - this.path = prefix + '/' + this.path - } else { - const prefix = decString(buf, off + 345, 130) - if (prefix) - this.path = prefix + '/' + this.path - this.atime = decDate(buf, off + 476, 12) - this.ctime = decDate(buf, off + 488, 12) - } - } - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksumValid = sum === this.cksum - if (this.cksum === null && sum === 8 * 0x20) - this.nullBlock = true - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - [SLURP] (ex, global) { - for (let k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) - this[k] = ex[k] +const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/; +function getPrintable(value) { + if (value === null) + return `null`; + if (value === undefined) + return `undefined`; + if (value === ``) + return `an empty string`; + if (typeof value === 'symbol') + return `<${value.toString()}>`; + if (Array.isArray(value)) + return `an array`; + return JSON.stringify(value); +} +function getPrintableArray(value, conjunction) { + if (value.length === 0) + return `nothing`; + if (value.length === 1) + return getPrintable(value[0]); + const rest = value.slice(0, -1); + const trailing = value[value.length - 1]; + const separator = value.length > 2 + ? `, ${conjunction} ` + : ` ${conjunction} `; + return `${rest.map(value => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`; +} +function computeKey(state, key) { + var _a, _b, _c; + if (typeof key === `number`) { + return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`; } - } - - encode (buf, off) { - if (!buf) { - buf = this.block = Buffer.alloc(512) - off = 0 + else if (simpleKeyRegExp.test(key)) { + return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`; } - - if (!off) - off = 0 - - if (!(buf.length >= off + 512)) - throw new Error('need 512 bytes for header') - - const prefixSize = this.ctime || this.atime ? 130 : 155 - const split = splitPrefix(this.path || '', prefixSize) - const path = split[0] - const prefix = split[1] - this.needPax = split[2] - - this.needPax = encString(buf, off, 100, path) || this.needPax - this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax - this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax - this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax - this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax - this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax - buf[off + 156] = this[TYPE].charCodeAt(0) - this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax - buf.write('ustar\u000000', off + 257, 8) - this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax - this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax - this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax - this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax - this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax - if (buf[off + 475] !== 0) - this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax else { - this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax - this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax - this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax - } - - let sum = 8 * 0x20 - for (let i = off; i < off + 148; i++) { - sum += buf[i] - } - for (let i = off + 156; i < off + 512; i++) { - sum += buf[i] - } - this.cksum = sum - encNumber(buf, off + 148, 8, this.cksum) - this.cksumValid = true - - return this.needPax - } - - set (data) { - for (let i in data) { - if (data[i] !== null && data[i] !== undefined) - this[i] = data[i] + return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`; } - } - - get type () { - return types.name.get(this[TYPE]) || this[TYPE] - } +} +function plural(n, singular, plural) { + return n === 1 ? singular : plural; +} - get typeKey () { - return this[TYPE] - } +const colorStringRegExp = /^#[0-9a-f]{6}$/i; +const colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i; +// https://stackoverflow.com/a/475217/880703 +const base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +// https://stackoverflow.com/a/14166194/880703 +const uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i; +// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_ +const iso8601RegExp = /^(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))T(?:[01]\d|2[0-3])(:?)[0-5]\d(?:\3[0-5]\d)?(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$/; - set type (type) { - if (types.code.has(type)) - this[TYPE] = types.code.get(type) - else - this[TYPE] = type - } +function pushError({ errors, p } = {}, message) { + errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`); + return false; +} +function makeSetter(target, key) { + return (v) => { + target[key] = v; + }; +} +function makeCoercionFn(target, key) { + return (v) => { + const previous = target[key]; + target[key] = v; + return makeCoercionFn(target, key).bind(null, previous); + }; +} +function makeLazyCoercionFn(fn, orig, generator) { + const commit = () => { + fn(generator()); + return revert; + }; + const revert = () => { + fn(orig); + return commit; + }; + return commit; } -const splitPrefix = (p, prefixSize) => { - const pathSize = 100 - let pp = p - let prefix = '' - let ret - const root = pathModule.parse(p).root || '.' - - if (Buffer.byteLength(pp) < pathSize) - ret = [pp, prefix, false] - else { - // first set prefix to the dir, and path to the base - prefix = pathModule.dirname(pp) - pp = pathModule.basename(pp) - - do { - // both fit! - if (Buffer.byteLength(pp) <= pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp, prefix, false] - - // prefix fits in prefix, but path doesn't fit in path - else if (Buffer.byteLength(pp) > pathSize && - Buffer.byteLength(prefix) <= prefixSize) - ret = [pp.substr(0, pathSize - 1), prefix, true] - - else { - // make path take a bit from prefix - pp = pathModule.join(pathModule.basename(prefix), pp) - prefix = pathModule.dirname(prefix) - } - } while (prefix !== root && !ret) - - // at this point, found no resolution, just truncate - if (!ret) - ret = [p.substr(0, pathSize - 1), '', true] - } - return ret +/** + * Create a validator that always returns true and never refines the type. + */ +function isUnknown() { + return makeValidator({ + test: (value, state) => { + return true; + }, + }); } - -const decString = (buf, off, size) => - buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') - -const decDate = (buf, off, size) => - numToDate(decNumber(buf, off, size)) - -const numToDate = num => num === null ? null : new Date(num * 1000) - -const decNumber = (buf, off, size) => - buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) - : decSmallNumber(buf, off, size) - -const nanNull = value => isNaN(value) ? null : value - -const decSmallNumber = (buf, off, size) => - nanNull(parseInt( - buf.slice(off, off + size) - .toString('utf8').replace(/\0.*$/, '').trim(), 8)) - -// the maximum encodable as a null-terminated octal, by field size -const MAXNUM = { - 12: 0o77777777777, - 8 : 0o7777777 +function isLiteral(expected) { + return makeValidator({ + test: (value, state) => { + if (value !== expected) + return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`); + return true; + }, + }); } - -const encNumber = (buf, off, size, number) => - number === null ? false : - number > MAXNUM[size] || number < 0 - ? (large.encode(number, buf.slice(off, off + size)), true) - : (encSmallNumber(buf, off, size, number), false) - -const encSmallNumber = (buf, off, size, number) => - buf.write(octalString(number, size), off, size, 'ascii') - -const octalString = (number, size) => - padOctal(Math.floor(number).toString(8), size) - -const padOctal = (string, size) => - (string.length === size - 1 ? string - : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' - -const encDate = (buf, off, size, date) => - date === null ? false : - encNumber(buf, off, size, date.getTime() / 1000) - -// enough to fill the longest string we've got -const NULLS = new Array(156).join('\0') -// pad with nulls, return true if it's longer or non-ascii -const encString = (buf, off, size, string) => - string === null ? false : - (buf.write(string + NULLS, off, size, 'utf8'), - string.length !== Buffer.byteLength(string) || string.length > size) - -module.exports = Header - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js": -/*!****************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js ***! - \****************************************************************************************************/ -/***/ ((module) => { - -"use strict"; - - -// turn tar(1) style args like `C` into the more verbose things like `cwd` - -const argmap = new Map([ - ['C', 'cwd'], - ['f', 'file'], - ['z', 'gzip'], - ['P', 'preservePaths'], - ['U', 'unlink'], - ['strip-components', 'strip'], - ['stripComponents', 'strip'], - ['keep-newer', 'newer'], - ['keepNewer', 'newer'], - ['keep-newer-files', 'newer'], - ['keepNewerFiles', 'newer'], - ['k', 'keep'], - ['keep-existing', 'keep'], - ['keepExisting', 'keep'], - ['m', 'noMtime'], - ['no-mtime', 'noMtime'], - ['p', 'preserveOwner'], - ['L', 'follow'], - ['h', 'follow'] -]) - -const parse = module.exports = opt => opt ? Object.keys(opt).map(k => [ - argmap.has(k) ? argmap.get(k) : k, opt[k] -]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/large-numbers.js": -/*!***************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/large-numbers.js ***! - \***************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// Tar can encode large and negative numbers using a leading byte of -// 0xff for negative, and 0x80 for positive. - -const encode = exports.encode = (num, buf) => { - if (!Number.isSafeInteger(num)) - // The number is so large that javascript cannot represent it with integer - // precision. - throw Error('cannot encode number outside of javascript safe integer range') - else if (num < 0) - encodeNegative(num, buf) - else - encodePositive(num, buf) - return buf +/** + * Create a validator that only returns true when the tested value is a string. + * Refines the type to `string`. + */ +function isString() { + return makeValidator({ + test: (value, state) => { + if (typeof value !== `string`) + return pushError(state, `Expected a string (got ${getPrintable(value)})`); + return true; + }, + }); } - -const encodePositive = (num, buf) => { - buf[0] = 0x80 - - for (var i = buf.length; i > 1; i--) { - buf[i-1] = num & 0xff - num = Math.floor(num / 0x100) - } +function isEnum(enumSpec) { + const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec); + const isAlphaNum = valuesArray.every(item => typeof item === 'string' || typeof item === 'number'); + const values = new Set(valuesArray); + if (values.size === 1) + return isLiteral([...values][0]); + return makeValidator({ + test: (value, state) => { + if (!values.has(value)) { + if (isAlphaNum) { + return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`); + } + else { + return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`); + } + } + return true; + }, + }); } - -const encodeNegative = (num, buf) => { - buf[0] = 0xff - var flipped = false - num = num * -1 - for (var i = buf.length; i > 1; i--) { - var byte = num & 0xff - num = Math.floor(num / 0x100) - if (flipped) - buf[i-1] = onesComp(byte) - else if (byte === 0) - buf[i-1] = 0 - else { - flipped = true - buf[i-1] = twosComp(byte) - } - } +const BOOLEAN_COERCIONS = new Map([ + [`true`, true], + [`True`, true], + [`1`, true], + [1, true], + [`false`, false], + [`False`, false], + [`0`, false], + [0, false], +]); +/** + * Create a validator that only returns true when the tested value is a + * boolean. Refines the type to `boolean`. + * + * Supports coercion: + * - 'true' / 'True' / '1' / 1 will turn to `true` + * - 'false' / 'False' / '0' / 0 will turn to `false` + */ +function isBoolean() { + return makeValidator({ + test: (value, state) => { + var _a; + if (typeof value !== `boolean`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + const coercion = BOOLEAN_COERCIONS.get(value); + if (typeof coercion !== `undefined`) { + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); + return true; + } + } + return pushError(state, `Expected a boolean (got ${getPrintable(value)})`); + } + return true; + }, + }); } - -const parse = exports.parse = (buf) => { - var post = buf[buf.length - 1] - var pre = buf[0] - var value; - if (pre === 0x80) - value = pos(buf.slice(1, buf.length)) - else if (pre === 0xff) - value = twos(buf) - else - throw Error('invalid base256 encoding') - - if (!Number.isSafeInteger(value)) - // The number is so large that javascript cannot represent it with integer - // precision. - throw Error('parsed number outside of javascript safe integer range') - - return value +/** + * Create a validator that only returns true when the tested value is a + * number (including floating numbers; use `cascade` and `isInteger` to + * restrict the range further). Refines the type to `number`. + * + * Supports coercion. + */ +function isNumber() { + return makeValidator({ + test: (value, state) => { + var _a; + if (typeof value !== `number`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + let coercion; + if (typeof value === `string`) { + let val; + try { + val = JSON.parse(value); + } + catch (_b) { } + // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS + if (typeof val === `number`) { + if (JSON.stringify(val) === value) { + coercion = val; + } + else { + return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`); + } + } + } + if (typeof coercion !== `undefined`) { + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); + return true; + } + } + return pushError(state, `Expected a number (got ${getPrintable(value)})`); + } + return true; + }, + }); } - -const twos = (buf) => { - var len = buf.length - var sum = 0 - var flipped = false - for (var i = len - 1; i > -1; i--) { - var byte = buf[i] - var f - if (flipped) - f = onesComp(byte) - else if (byte === 0) - f = byte - else { - flipped = true - f = twosComp(byte) - } - if (f !== 0) - sum -= f * Math.pow(256, len - i - 1) - } - return sum +/** + * Create a validator that only returns true when the tested value is a + * valid date. Refines the type to `Date`. + * + * Supports coercion via one of the following formats: + * - ISO86001 strings + * - Unix timestamps + */ +function isDate() { + return makeValidator({ + test: (value, state) => { + var _a; + if (!(value instanceof Date)) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + let coercion; + if (typeof value === `string` && iso8601RegExp.test(value)) { + coercion = new Date(value); + } + else { + let timestamp; + if (typeof value === `string`) { + let val; + try { + val = JSON.parse(value); + } + catch (_b) { } + if (typeof val === `number`) { + timestamp = val; + } + } + else if (typeof value === `number`) { + timestamp = value; + } + if (typeof timestamp !== `undefined`) { + if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) { + coercion = new Date(timestamp * 1000); + } + else { + return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`); + } + } + } + if (typeof coercion !== `undefined`) { + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); + return true; + } + } + return pushError(state, `Expected a date (got ${getPrintable(value)})`); + } + return true; + }, + }); } - -const pos = (buf) => { - var len = buf.length - var sum = 0 - for (var i = len - 1; i > -1; i--) { - var byte = buf[i] - if (byte !== 0) - sum += byte * Math.pow(256, len - i - 1) - } - return sum +/** + * Create a validator that only returns true when the tested value is an + * array whose all values match the provided subspec. Refines the type to + * `Array`, with `T` being the subspec inferred type. + * + * Supports coercion if the `delimiter` option is set, in which case strings + * will be split accordingly. + */ +function isArray(spec, { delimiter } = {}) { + return makeValidator({ + test: (value, state) => { + var _a; + const originalValue = value; + if (typeof value === `string` && typeof delimiter !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + value = value.split(delimiter); + } + } + if (!Array.isArray(value)) + return pushError(state, `Expected an array (got ${getPrintable(value)})`); + let valid = true; + for (let t = 0, T = value.length; t < T; ++t) { + valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid; + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + } + if (value !== originalValue) + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]); + return valid; + }, + }); } - -const onesComp = byte => (0xff ^ byte) & 0xff - -const twosComp = byte => ((0xff ^ byte) + 1) & 0xff - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/list.js": -/*!******************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/list.js ***! - \******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -// XXX: This shares a lot in common with extract.js -// maybe some DRY opportunity here? - -// tar -t -const hlo = __webpack_require__(/*! ./high-level-opt.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js") -const Parser = __webpack_require__(/*! ./parse.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js") -const fs = __webpack_require__(/*! fs */ "fs") -const fsm = __webpack_require__(/*! fs-minipass */ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js") -const path = __webpack_require__(/*! path */ "path") - -const t = module.exports = (opt_, files, cb) => { - if (typeof opt_ === 'function') - cb = opt_, files = null, opt_ = {} - else if (Array.isArray(opt_)) - files = opt_, opt_ = {} - - if (typeof files === 'function') - cb = files, files = null - - if (!files) - files = [] - else - files = Array.from(files) - - const opt = hlo(opt_) - - if (opt.sync && typeof cb === 'function') - throw new TypeError('callback not supported for sync tar functions') - - if (!opt.file && typeof cb === 'function') - throw new TypeError('callback only supported with file option') - - if (files.length) - filesFilter(opt, files) - - if (!opt.noResume) - onentryFunction(opt) - - return opt.file && opt.sync ? listFileSync(opt) - : opt.file ? listFile(opt, cb) - : list(opt) +/** + * Create a validator that only returns true when the tested value is an + * set whose all values match the provided subspec. Refines the type to + * `Set`, with `T` being the subspec inferred type. + * + * Supports coercion from arrays (or anything that can be coerced into an + * array). + */ +function isSet(spec, { delimiter } = {}) { + const isArrayValidator = isArray(spec, { delimiter }); + return makeValidator({ + test: (value, state) => { + var _a, _b; + if (Object.getPrototypeOf(value).toString() === `[object Set]`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + const originalValues = [...value]; + const coercedValues = [...value]; + if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined }))) + return false; + const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t]) + ? new Set(coercedValues) + : value; + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]); + return true; + } + else { + let valid = true; + for (const subValue of value) { + valid = spec(subValue, Object.assign({}, state)) && valid; + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + } + return valid; + } + } + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + const store = { value }; + if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) }))) + return false; + state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]); + return true; + } + return pushError(state, `Expected a set (got ${getPrintable(value)})`); + } + }); } - -const onentryFunction = opt => { - const onentry = opt.onentry - opt.onentry = onentry ? e => { - onentry(e) - e.resume() - } : e => e.resume() +/** + * Create a validator that only returns true when the tested value is an + * map whose all values match the provided subspecs. Refines the type to + * `Map`, with `U` being the key subspec inferred type and `V` being + * the value subspec inferred type. + * + * Supports coercion from array of tuples (or anything that can be coerced into + * an array of tuples). + */ +function isMap(keySpec, valueSpec) { + const isArrayValidator = isArray(isTuple([keySpec, valueSpec])); + const isRecordValidator = isRecord(valueSpec, { keys: keySpec }); + return makeValidator({ + test: (value, state) => { + var _a, _b, _c; + if (Object.getPrototypeOf(value).toString() === `[object Map]`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + const originalValues = [...value]; + const coercedValues = [...value]; + if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined }))) + return false; + const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1]) + ? new Map(coercedValues) + : value; + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]); + return true; + } + else { + let valid = true; + for (const [key, subValue] of value) { + valid = keySpec(key, Object.assign({}, state)) && valid; + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid; + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + } + return valid; + } + } + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + const store = { value }; + if (Array.isArray(value)) { + if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined }))) + return false; + state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]); + return true; + } + else { + if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) }))) + return false; + state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]); + return true; + } + } + return pushError(state, `Expected a map (got ${getPrintable(value)})`); + } + }); } - -// construct a filter that limits the file entries listed -// include child entries if a dir is included -const filesFilter = (opt, files) => { - const map = new Map(files.map(f => [f.replace(/\/+$/, ''), true])) - const filter = opt.filter - - const mapHas = (file, r) => { - const root = r || path.parse(file).root || '.' - const ret = file === root ? false - : map.has(file) ? map.get(file) - : mapHas(path.dirname(file), root) - - map.set(file, ret) - return ret - } - - opt.filter = filter - ? (file, entry) => filter(file, entry) && mapHas(file.replace(/\/+$/, '')) - : file => mapHas(file.replace(/\/+$/, '')) +/** + * Create a validator that only returns true when the tested value is a + * tuple whose each value matches the corresponding subspec. Refines the type + * into a tuple whose each item has the type inferred by the corresponding + * tuple. + * + * Supports coercion if the `delimiter` option is set, in which case strings + * will be split accordingly. + */ +function isTuple(spec, { delimiter } = {}) { + const lengthValidator = hasExactLength(spec.length); + return makeValidator({ + test: (value, state) => { + var _a; + if (typeof value === `string` && typeof delimiter !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + value = value.split(delimiter); + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]); + } + } + if (!Array.isArray(value)) + return pushError(state, `Expected a tuple (got ${getPrintable(value)})`); + let valid = lengthValidator(value, Object.assign({}, state)); + for (let t = 0, T = value.length; t < T && t < spec.length; ++t) { + valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid; + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + } + return valid; + }, + }); } - -const listFileSync = opt => { - const p = list(opt) - const file = opt.file - let threw = true - let fd - try { - const stat = fs.statSync(file) - const readSize = opt.maxReadSize || 16*1024*1024 - if (stat.size < readSize) { - p.end(fs.readFileSync(file)) - } else { - let pos = 0 - const buf = Buffer.allocUnsafe(readSize) - fd = fs.openSync(file, 'r') - while (pos < stat.size) { - let bytesRead = fs.readSync(fd, buf, 0, readSize, pos) - pos += bytesRead - p.write(buf.slice(0, bytesRead)) - } - p.end() +/** + * Create a validator that only returns true when the tested value is an + * object with any amount of properties that must all match the provided + * subspec. Refines the type to `Record`, with `T` being the + * subspec inferred type. + * + * Keys can be optionally validated as well by using the `keys` optional + * subspec parameter. + */ +function isRecord(spec, { keys: keySpec = null, } = {}) { + const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec])); + return makeValidator({ + test: (value, state) => { + var _a; + if (Array.isArray(value)) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined }))) + return false; + value = Object.fromEntries(value); + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]); + return true; + } + } + if (typeof value !== `object` || value === null) + return pushError(state, `Expected an object (got ${getPrintable(value)})`); + const keys = Object.keys(value); + let valid = true; + for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) { + const key = keys[t]; + const sub = value[key]; + if (key === `__proto__` || key === `constructor`) { + valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`); + continue; + } + if (keySpec !== null && !keySpec(key, state)) { + valid = false; + continue; + } + if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) { + valid = false; + continue; + } + } + return valid; + }, + }); +} +/** + * @deprecated Replace `isDict` by `isRecord` + */ +function isDict(spec, opts = {}) { + return isRecord(spec, opts); +} +/** + * Create a validator that only returns true when the tested value is an + * object whose all properties match their corresponding subspec. Refines + * the type into an object whose each property has the type inferred by the + * corresponding subspec. + * + * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by + * default. This behaviour can be altered by using the `extra` optional + * subspec parameter, which will be called to validate an object only + * containing the extraneous properties. + * + * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is + * essentially the same as calling `t.isPartial(...)`. + */ +function isObject(props, { extra: extraSpec = null, } = {}) { + const specKeys = Object.keys(props); + const validator = makeValidator({ + test: (value, state) => { + if (typeof value !== `object` || value === null) + return pushError(state, `Expected an object (got ${getPrintable(value)})`); + const keys = new Set([...specKeys, ...Object.keys(value)]); + const extra = {}; + let valid = true; + for (const key of keys) { + if (key === `constructor` || key === `__proto__`) { + valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`); + } + else { + const spec = Object.prototype.hasOwnProperty.call(props, key) + ? props[key] + : undefined; + const sub = Object.prototype.hasOwnProperty.call(value, key) + ? value[key] + : undefined; + if (typeof spec !== `undefined`) { + valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid; + } + else if (extraSpec === null) { + valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`); + } + else { + Object.defineProperty(extra, key, { + enumerable: true, + get: () => sub, + set: makeSetter(value, key) + }); + } + } + if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { + break; + } + } + if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null)) + valid = extraSpec(extra, state) && valid; + return valid; + }, + }); + return Object.assign(validator, { + properties: props, + }); +} +/** + * Create a validator that only returns true when the tested value is an + * object whose all properties match their corresponding subspec. Refines + * the type into an object whose each property has the type inferred by the + * corresponding subspec. + * + * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The + * resulting type will reflect this behaviour by including an index + * signature (each extraneous property being typed `unknown`). + * + * Calling `t.isPartial(...)` is essentially the same as calling + * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`. + */ +function isPartial(props) { + return isObject(props, { extra: isRecord(isUnknown()) }); +} +/** + * Create a validator that only returns true when the tested value is an + * object whose prototype is derived from the given class. Refines the type + * into a class instance. + */ +const isInstanceOf = (constructor) => makeValidator({ + test: (value, state) => { + if (!(value instanceof constructor)) + return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`); + return true; + }, +}); +/** + * Create a validator that only returns true when the tested value is an + * object matching any of the provided subspecs. If the optional `exclusive` + * parameter is set to `true`, the behaviour changes so that the validator + * only returns true when exactly one subspec matches. + */ +const isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({ + test: (value, state) => { + var _a, _b, _c; + const matches = []; + const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` + ? [] : undefined; + for (let t = 0, T = specs.length; t < T; ++t) { + const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` + ? [] : undefined; + const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` + ? [] : undefined; + if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) { + matches.push([`#${t + 1}`, subCoercions]); + if (!exclusive) { + break; + } + } + else { + errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]); + } + } + if (matches.length === 1) { + const [, subCoercions] = matches[0]; + if (typeof subCoercions !== `undefined`) + (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions); + return true; + } + if (matches.length > 1) + pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`); + else + (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer); + return false; + }, +}); + +function makeTrait(value) { + return () => { + return value; + }; +} +function makeValidator({ test }) { + return makeTrait(test)(); +} +class TypeAssertionError extends Error { + constructor({ errors } = {}) { + let errorMessage = `Type mismatch`; + if (errors && errors.length > 0) { + errorMessage += `\n`; + for (const error of errors) { + errorMessage += `\n- ${error}`; + } + } + super(errorMessage); + } +} +/** + * Check that the specified value matches the given validator, and throws an + * exception if it doesn't. Refine the type if it passes. + */ +function assert(val, validator) { + if (!validator(val)) { + throw new TypeAssertionError(); + } +} +/** + * Check that the specified value matches the given validator, and throws an + * exception if it doesn't. Refine the type if it passes. + * + * Thrown exceptions include details about what exactly looks invalid in the + * tested value. + */ +function assertWithErrors(val, validator) { + const errors = []; + if (!validator(val, { errors })) { + throw new TypeAssertionError({ errors }); + } +} +/** + * Compile-time only. Refine the type as if the validator was matching the + * tested value, but doesn't actually run it. Similar to the classic `as` + * operator in TypeScript. + */ +function softAssert(val, validator) { + // It's a soft assert; we tell TypeScript about the type, but we don't need to check it +} +function as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) { + const errors = storeErrors ? [] : undefined; + if (!coerce) { + if (validator(value, { errors })) { + return throws ? value : { value, errors: undefined }; + } + else if (!throws) { + return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true }; + } + else { + throw new TypeAssertionError({ errors }); + } + } + const state = { value }; + const coercion = makeCoercionFn(state, `value`); + const coercions = []; + if (!validator(value, { errors, coercion, coercions })) { + if (!throws) { + return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true }; + } + else { + throw new TypeAssertionError({ errors }); + } + } + for (const [, apply] of coercions) + apply(); + if (throws) { + return state.value; + } + else { + return { value: state.value, errors: undefined }; + } +} +/** + * Create and return a new function that apply the given validators to each + * corresponding argument passed to the function and throws an exception in + * case of a mismatch. + */ +function fn(validators, fn) { + const isValidArgList = isTuple(validators); + return ((...args) => { + const check = isValidArgList(args); + if (!check) + throw new TypeAssertionError(); + return fn(...args); + }); +} + +/** + * Create a validator that checks that the tested array or string has at least + * the specified length. + */ +function hasMinLength(length) { + return makeValidator({ + test: (value, state) => { + if (!(value.length >= length)) + return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested array or string has at most + * the specified length. + */ +function hasMaxLength(length) { + return makeValidator({ + test: (value, state) => { + if (!(value.length <= length)) + return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested array or string has exactly + * the specified length. + */ +function hasExactLength(length) { + return makeValidator({ + test: (value, state) => { + if (!(value.length === length)) + return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested array only contains unique + * elements. The optional `map` parameter lets you define a transform to + * apply before making the check (the result of this transform will be + * discarded afterwards). + */ +function hasUniqueItems({ map, } = {}) { + return makeValidator({ + test: (value, state) => { + const set = new Set(); + const dup = new Set(); + for (let t = 0, T = value.length; t < T; ++t) { + const sub = value[t]; + const key = typeof map !== `undefined` + ? map(sub) + : sub; + if (set.has(key)) { + if (dup.has(key)) + continue; + pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`); + dup.add(key); + } + else { + set.add(key); + } + } + return dup.size === 0; + }, + }); +} +/** + * Create a validator that checks that the tested number is strictly less than 0. + */ +function isNegative() { + return makeValidator({ + test: (value, state) => { + if (!(value <= 0)) + return pushError(state, `Expected to be negative (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is equal or greater + * than 0. + */ +function isPositive() { + return makeValidator({ + test: (value, state) => { + if (!(value >= 0)) + return pushError(state, `Expected to be positive (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is equal or greater + * than the specified reference. + */ +function isAtLeast(n) { + return makeValidator({ + test: (value, state) => { + if (!(value >= n)) + return pushError(state, `Expected to be at least ${n} (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is equal or smaller + * than the specified reference. + */ +function isAtMost(n) { + return makeValidator({ + test: (value, state) => { + if (!(value <= n)) + return pushError(state, `Expected to be at most ${n} (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is between the + * specified references (including the upper boundary). + */ +function isInInclusiveRange(a, b) { + return makeValidator({ + test: (value, state) => { + if (!(value >= a && value <= b)) + return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is between the + * specified references (excluding the upper boundary). + */ +function isInExclusiveRange(a, b) { + return makeValidator({ + test: (value, state) => { + if (!(value >= a && value < b)) + return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested number is an integer. + * + * By default Typanion will also check that it's a *safe* integer. For example, + * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53, + * which could put your applications at risk when used in loops. + */ +function isInteger({ unsafe = false, } = {}) { + return makeValidator({ + test: (value, state) => { + if (value !== Math.round(value)) + return pushError(state, `Expected to be an integer (got ${value})`); + if (!unsafe && !Number.isSafeInteger(value)) + return pushError(state, `Expected to be a safe integer (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string matches the given + * regular expression. + */ +function matchesRegExp(regExp) { + return makeValidator({ + test: (value, state) => { + if (!regExp.test(value)) + return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string only contain lowercase + * characters. + */ +function isLowerCase() { + return makeValidator({ + test: (value, state) => { + if (value !== value.toLowerCase()) + return pushError(state, `Expected to be all-lowercase (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string only contain uppercase + * characters. + */ +function isUpperCase() { + return makeValidator({ + test: (value, state) => { + if (value !== value.toUpperCase()) + return pushError(state, `Expected to be all-uppercase (got ${value})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string is a valid UUID v4. + */ +function isUUID4() { + return makeValidator({ + test: (value, state) => { + if (!uuid4RegExp.test(value)) + return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string is a valid ISO8601 + * date. + */ +function isISO8601() { + return makeValidator({ + test: (value, state) => { + if (!iso8601RegExp.test(value)) + return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string is a valid hexadecimal + * color. Setting the optional `alpha` parameter to `true` allows an additional + * transparency channel to be included. + */ +function isHexColor({ alpha = false, }) { + return makeValidator({ + test: (value, state) => { + const res = alpha + ? colorStringRegExp.test(value) + : colorStringAlphaRegExp.test(value); + if (!res) + return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string is valid base64. + */ +function isBase64() { + return makeValidator({ + test: (value, state) => { + if (!base64RegExp.test(value)) + return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested string is valid JSON. A + * optional spec can be passed as parameter, in which case the data will be + * deserialized and validated against the spec (coercion will be disabled + * for this check, and even if successful the returned value will still be + * the original string). + */ +function isJSON(spec = isUnknown()) { + return makeValidator({ + test: (value, state) => { + let data; + try { + data = JSON.parse(value); + } + catch (_a) { + return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`); + } + return spec(data, state); + }, + }); +} + +function cascade(spec, ...followups) { + const resolvedFollowups = Array.isArray(followups[0]) + ? followups[0] + : followups; + return makeValidator({ + test: (value, state) => { + var _a, _b; + const context = { value: value }; + const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` + ? makeCoercionFn(context, `value`) : undefined; + const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` + ? [] : undefined; + if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions }))) + return false; + const reverts = []; + if (typeof subCoercions !== `undefined`) + for (const [, coercion] of subCoercions) + reverts.push(coercion()); + try { + if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { + if (context.value !== value) { + if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) + return pushError(state, `Unbound coercion result`); + state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]); + } + (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions); + } + return resolvedFollowups.every(spec => { + return spec(context.value, state); + }); + } + finally { + for (const revert of reverts) { + revert(); + } + } + }, + }); +} +function applyCascade(spec, ...followups) { + const resolvedFollowups = Array.isArray(followups[0]) + ? followups[0] + : followups; + return cascade(spec, resolvedFollowups); +} +/** + * Wraps the given spec to also allow `undefined`. + */ +function isOptional(spec) { + return makeValidator({ + test: (value, state) => { + if (typeof value === `undefined`) + return true; + return spec(value, state); + }, + }); +} +/** + * Wraps the given spec to also allow `null`. + */ +function isNullable(spec) { + return makeValidator({ + test: (value, state) => { + if (value === null) + return true; + return spec(value, state); + }, + }); +} +/** + * Create a validator that checks that the tested object contains the specified + * keys. + */ +function hasRequiredKeys(requiredKeys) { + const requiredSet = new Set(requiredKeys); + return makeValidator({ + test: (value, state) => { + const keys = new Set(Object.keys(value)); + const problems = []; + for (const key of requiredSet) + if (!keys.has(key)) + problems.push(key); + if (problems.length > 0) + return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested object contains none of the + * specified keys. + */ +function hasForbiddenKeys(forbiddenKeys) { + const forbiddenSet = new Set(forbiddenKeys); + return makeValidator({ + test: (value, state) => { + const keys = new Set(Object.keys(value)); + const problems = []; + for (const key of forbiddenSet) + if (keys.has(key)) + problems.push(key); + if (problems.length > 0) + return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`); + return true; + }, + }); +} +/** + * Create a validator that checks that the tested object contains at most one + * of the specified keys. + */ +function hasMutuallyExclusiveKeys(exclusiveKeys) { + const exclusiveSet = new Set(exclusiveKeys); + return makeValidator({ + test: (value, state) => { + const keys = new Set(Object.keys(value)); + const used = []; + for (const key of exclusiveSet) + if (keys.has(key)) + used.push(key); + if (used.length > 1) + return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`); + return true; + }, + }); +} +(function (KeyRelationship) { + KeyRelationship["Forbids"] = "Forbids"; + KeyRelationship["Requires"] = "Requires"; +})(exports.KeyRelationship || (exports.KeyRelationship = {})); +const keyRelationships = { + [exports.KeyRelationship.Forbids]: { + expect: false, + message: `forbids using`, + }, + [exports.KeyRelationship.Requires]: { + expect: true, + message: `requires using`, + }, +}; +/** + * Create a validator that checks that, when the specified subject property is + * set, the relationship is satisfied. + */ +function hasKeyRelationship(subject, relationship, others, { ignore = [], } = {}) { + const skipped = new Set(ignore); + const otherSet = new Set(others); + const spec = keyRelationships[relationship]; + const conjunction = relationship === exports.KeyRelationship.Forbids + ? `or` + : `and`; + return makeValidator({ + test: (value, state) => { + const keys = new Set(Object.keys(value)); + if (!keys.has(subject) || skipped.has(value[subject])) + return true; + const problems = []; + for (const key of otherSet) + if ((keys.has(key) && !skipped.has(value[key])) !== spec.expect) + problems.push(key); + if (problems.length >= 1) + return pushError(state, `Property "${subject}" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`); + return true; + }, + }); +} + +exports.TypeAssertionError = TypeAssertionError; +exports.applyCascade = applyCascade; +exports.as = as; +exports.assert = assert; +exports.assertWithErrors = assertWithErrors; +exports.cascade = cascade; +exports.fn = fn; +exports.hasExactLength = hasExactLength; +exports.hasForbiddenKeys = hasForbiddenKeys; +exports.hasKeyRelationship = hasKeyRelationship; +exports.hasMaxLength = hasMaxLength; +exports.hasMinLength = hasMinLength; +exports.hasMutuallyExclusiveKeys = hasMutuallyExclusiveKeys; +exports.hasRequiredKeys = hasRequiredKeys; +exports.hasUniqueItems = hasUniqueItems; +exports.isArray = isArray; +exports.isAtLeast = isAtLeast; +exports.isAtMost = isAtMost; +exports.isBase64 = isBase64; +exports.isBoolean = isBoolean; +exports.isDate = isDate; +exports.isDict = isDict; +exports.isEnum = isEnum; +exports.isHexColor = isHexColor; +exports.isISO8601 = isISO8601; +exports.isInExclusiveRange = isInExclusiveRange; +exports.isInInclusiveRange = isInInclusiveRange; +exports.isInstanceOf = isInstanceOf; +exports.isInteger = isInteger; +exports.isJSON = isJSON; +exports.isLiteral = isLiteral; +exports.isLowerCase = isLowerCase; +exports.isMap = isMap; +exports.isNegative = isNegative; +exports.isNullable = isNullable; +exports.isNumber = isNumber; +exports.isObject = isObject; +exports.isOneOf = isOneOf; +exports.isOptional = isOptional; +exports.isPartial = isPartial; +exports.isPositive = isPositive; +exports.isRecord = isRecord; +exports.isSet = isSet; +exports.isString = isString; +exports.isTuple = isTuple; +exports.isUUID4 = isUUID4; +exports.isUnknown = isUnknown; +exports.isUpperCase = isUpperCase; +exports.makeTrait = makeTrait; +exports.makeValidator = makeValidator; +exports.matchesRegExp = matchesRegExp; +exports.softAssert = softAssert; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/which-npm-2.0.2-320ddf72f7-9.zip/node_modules/which/which.js": +/*!***********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/which-npm-2.0.2-320ddf72f7-9.zip/node_modules/which/which.js ***! + \***********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' + +const path = __webpack_require__(/*! path */ "path") +const COLON = isWindows ? ';' : ':' +const isexe = __webpack_require__(/*! isexe */ "../../../.yarn/berry/cache/isexe-npm-2.0.0-b58870bd2e-9.zip/node_modules/isexe/index.js") + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ) + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : '' + const pathExt = isWindows ? pathExtExe.split(colon) : [''] + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +} + +const which = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + if (!opt) + opt = {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + resolve(subStep(p, i, 0)) + }) + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }) + }) + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +} + +const whichSync = (cmd, opt) => { + opt = opt || {} + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) + const found = [] + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i] + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw + + const pCmd = path.join(pathPart, cmd) + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j] + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +} + +module.exports = which +which.sync = whichSync + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/iterator.js": +/*!******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/iterator.js ***! + \******************************************************************************************************/ +/***/ ((module) => { + +"use strict"; + +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js": +/*!*****************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/yallist.js ***! + \*****************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + __webpack_require__(/*! ./iterator.js */ "../../../.yarn/berry/cache/yallist-npm-4.0.0-b493d9e907-9.zip/node_modules/yallist/iterator.js")(Yallist) +} catch (er) {} + + +/***/ }), + +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Cli.js": +/*!************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Cli.js ***! + \************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var constants = __webpack_require__(/*! ../constants.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/constants.js"); +var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); +var core = __webpack_require__(/*! ../core.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/core.js"); +var format = __webpack_require__(/*! ../format.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/format.js"); +var HelpCommand = __webpack_require__(/*! ./HelpCommand.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/HelpCommand.js"); + +const errorCommandSymbol = Symbol(`clipanion/errorCommand`); +function getDefaultColorSettings() { + if (process.env.FORCE_COLOR === `0`) + return false; + if (process.env.FORCE_COLOR === `1`) + return true; + if (typeof process.stdout !== `undefined` && process.stdout.isTTY) + return true; + return false; +} +/** + * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`. + */ +class Cli { + constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors = getDefaultColorSettings() } = {}) { + this.registrations = new Map(); + this.builder = new core.CliBuilder({ binaryName: binaryNameOpt }); + this.binaryLabel = binaryLabel; + this.binaryName = binaryNameOpt; + this.binaryVersion = binaryVersion; + this.enableCapture = enableCapture; + this.enableColors = enableColors; + } + /** + * Creates a new Cli and registers all commands passed as parameters. + * + * @param commandClasses The Commands to register + * @returns The created `Cli` instance + */ + static from(commandClasses, options = {}) { + const cli = new Cli(options); + for (const commandClass of commandClasses) + cli.register(commandClass); + return cli; + } + /** + * Registers a command inside the CLI. + */ + register(commandClass) { + var _a; + const specs = new Map(); + const command = new commandClass(); + for (const key in command) { + const value = command[key]; + if (typeof value === `object` && value !== null && value[Command.Command.isOption]) { + specs.set(key, value); + } + } + const builder = this.builder.command(); + const index = builder.cliIndex; + const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths; + if (typeof paths !== `undefined`) + for (const path of paths) + builder.addPath(path); + this.registrations.set(commandClass, { specs, builder, index }); + for (const [key, { definition }] of specs.entries()) + definition(builder, key); + builder.setContext({ + commandClass, + }); + } + process(input) { + const { contexts, process } = this.builder.compile(); + const state = process(input); + switch (state.selectedIndex) { + case constants.HELP_COMMAND_INDEX: + { + return HelpCommand.HelpCommand.from(state, contexts); + } + default: + { + const { commandClass } = contexts[state.selectedIndex]; + const record = this.registrations.get(commandClass); + if (typeof record === `undefined`) + throw new Error(`Assertion failed: Expected the command class to have been registered.`); + const command = new commandClass(); + command.path = state.path; + try { + for (const [key, { transformer }] of record.specs.entries()) + command[key] = transformer(record.builder, key, state); + return command; + } + catch (error) { + error[errorCommandSymbol] = command; + throw error; + } + } + break; + } + } + async run(input, userContext) { + let command; + const context = { + ...Cli.defaultContext, + ...userContext, + }; + if (!Array.isArray(input)) { + command = input; + } + else { + try { + command = this.process(input); + } + catch (error) { + context.stdout.write(this.error(error)); + return 1; + } + } + if (command.help) { + context.stdout.write(this.usage(command, { detailed: true })); + return 0; + } + command.context = context; + command.cli = { + binaryLabel: this.binaryLabel, + binaryName: this.binaryName, + binaryVersion: this.binaryVersion, + enableCapture: this.enableCapture, + enableColors: this.enableColors, + definitions: () => this.definitions(), + error: (error, opts) => this.error(error, opts), + process: input => this.process(input), + run: (input, subContext) => this.run(input, { ...context, ...subContext }), + usage: (command, opts) => this.usage(command, opts), + }; + const activate = this.enableCapture + ? getCaptureActivator(context) + : noopCaptureActivator; + let exitCode; + try { + exitCode = await activate(() => command.validateAndExecute().catch(error => command.catch(error).then(() => 0))); + } + catch (error) { + context.stdout.write(this.error(error, { command })); + return 1; + } + return exitCode; + } + /** + * Runs a command and exits the current `process` with the exit code returned by the command. + * + * @param input An array containing the name of the command and its arguments. + * + * @example + * cli.runExit(process.argv.slice(2)) + */ + async runExit(input, context) { + process.exitCode = await this.run(input, context); + } + suggest(input, partial) { + const { suggest } = this.builder.compile(); + return suggest(input, partial); + } + definitions({ colored = false } = {}) { + const data = []; + for (const [commandClass, { index }] of this.registrations) { + if (typeof commandClass.usage === `undefined`) + continue; + const { usage: path } = this.getUsageByIndex(index, { detailed: false }); + const { usage, options } = this.getUsageByIndex(index, { detailed: true, inlineOptions: false }); + const category = typeof commandClass.usage.category !== `undefined` + ? format.formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) + : undefined; + const description = typeof commandClass.usage.description !== `undefined` + ? format.formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false }) + : undefined; + const details = typeof commandClass.usage.details !== `undefined` + ? format.formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true }) + : undefined; + const examples = typeof commandClass.usage.examples !== `undefined` + ? commandClass.usage.examples.map(([label, cli]) => [format.formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\$0/g, this.binaryName)]) + : undefined; + data.push({ path, usage, category, description, details, examples, options }); + } + return data; + } + usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) { + var _a; + // In case the default command is the only one, we can just show the command help rather than the general one + if (command === null) { + for (const commandClass of this.registrations.keys()) { + const paths = commandClass.paths; + const isDocumented = typeof commandClass.usage !== `undefined`; + const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0); + const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false); + if (isDefault) { + if (command) { + command = null; + break; + } + else { + command = commandClass; + } + } + else { + if (isDocumented) { + command = null; + continue; + } + } + } + if (command) { + detailed = true; + } + } + // @ts-ignore + const commandClass = command !== null && command instanceof Command.Command + ? command.constructor + : command; + let result = ``; + if (!commandClass) { + const commandsByCategories = new Map(); + for (const [commandClass, { index }] of this.registrations.entries()) { + if (typeof commandClass.usage === `undefined`) + continue; + const category = typeof commandClass.usage.category !== `undefined` + ? format.formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false }) + : null; + let categoryCommands = commandsByCategories.get(category); + if (typeof categoryCommands === `undefined`) + commandsByCategories.set(category, categoryCommands = []); + const { usage } = this.getUsageByIndex(index); + categoryCommands.push({ commandClass, usage }); + } + const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => { + if (a === null) + return -1; + if (b === null) + return +1; + return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` }); + }); + const hasLabel = typeof this.binaryLabel !== `undefined`; + const hasVersion = typeof this.binaryVersion !== `undefined`; + if (hasLabel || hasVersion) { + if (hasLabel && hasVersion) + result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\n\n`; + else if (hasLabel) + result += `${this.format(colored).header(`${this.binaryLabel}`)}\n`; + else + result += `${this.format(colored).header(`${this.binaryVersion}`)}\n`; + result += ` ${this.format(colored).bold(prefix)}${this.binaryName} \n`; + } + else { + result += `${this.format(colored).bold(prefix)}${this.binaryName} \n`; + } + for (const categoryName of categoryNames) { + const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => { + return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` }); + }); + const header = categoryName !== null + ? categoryName.trim() + : `General commands`; + result += `\n`; + result += `${this.format(colored).header(`${header}`)}\n`; + for (const { commandClass, usage } of commands) { + const doc = commandClass.usage.description || `undocumented`; + result += `\n`; + result += ` ${this.format(colored).bold(usage)}\n`; + result += ` ${format.formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`; + } + } + result += `\n`; + result += format.formatMarkdownish(`You can also print more details about any of these commands by calling them with the \`-h,--help\` flag right after the command name.`, { format: this.format(colored), paragraphs: true }); + } + else { + if (!detailed) { + const { usage } = this.getUsageByRegistration(commandClass); + result += `${this.format(colored).bold(prefix)}${usage}\n`; + } + else { + const { description = ``, details = ``, examples = [], } = commandClass.usage || {}; + if (description !== ``) { + result += format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase()); + result += `\n`; + } + if (details !== `` || examples.length > 0) { + result += `${this.format(colored).header(`Usage`)}\n`; + result += `\n`; + } + const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false }); + result += `${this.format(colored).bold(prefix)}${usage}\n`; + if (options.length > 0) { + result += `\n`; + result += `${format.richFormat.header(`Options`)}\n`; + const maxDefinitionLength = options.reduce((length, option) => { + return Math.max(length, option.definition.length); + }, 0); + result += `\n`; + for (const { definition, description } of options) { + result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`; + } + } + if (details !== ``) { + result += `\n`; + result += `${this.format(colored).header(`Details`)}\n`; + result += `\n`; + result += format.formatMarkdownish(details, { format: this.format(colored), paragraphs: true }); + } + if (examples.length > 0) { + result += `\n`; + result += `${this.format(colored).header(`Examples`)}\n`; + for (const [description, example] of examples) { + result += `\n`; + result += format.formatMarkdownish(description, { format: this.format(colored), paragraphs: false }); + result += `${example + .replace(/^/m, ` ${this.format(colored).bold(prefix)}`) + .replace(/\$0/g, this.binaryName)}\n`; + } + } + } + } + return result; + } + error(error, _a) { + var _b; + var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a; + if (!(error instanceof Error)) + error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`); + let result = ``; + let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`); + if (name === `Error`) + name = `Internal Error`; + result += `${this.format(colored).error(name)}: ${error.message}\n`; + const meta = error.clipanion; + if (typeof meta !== `undefined`) { + if (meta.type === `usage`) { + result += `\n`; + result += this.usage(command); + } + } + else { + if (error.stack) { + result += `${error.stack.replace(/^.*\n/, ``)}\n`; + } + } + return result; } - threw = false - } finally { - if (threw && fd) - try { fs.closeSync(fd) } catch (er) {} - } -} - -const listFile = (opt, cb) => { - const parse = new Parser(opt) - const readSize = opt.maxReadSize || 16*1024*1024 - - const file = opt.file - const p = new Promise((resolve, reject) => { - parse.on('error', reject) - parse.on('end', resolve) - - fs.stat(file, (er, stat) => { - if (er) - reject(er) - else { - const stream = new fsm.ReadStream(file, { - readSize: readSize, - size: stat.size - }) - stream.on('error', reject) - stream.pipe(parse) - } - }) - }) - return cb ? p.then(cb, cb) : p -} - -const list = opt => new Parser(opt) - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mkdir.js": -/*!*******************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mkdir.js ***! - \*******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -// wrapper around mkdirp for tar's needs. - -// TODO: This should probably be a class, not functionally -// passing around state in a gazillion args. - -const mkdirp = __webpack_require__(/*! mkdirp */ "./.yarn/cache/mkdirp-npm-1.0.3-02fc91ac70-c5c46ae417.zip/node_modules/mkdirp/index.js") -const fs = __webpack_require__(/*! fs */ "fs") -const path = __webpack_require__(/*! path */ "path") -const chownr = __webpack_require__(/*! chownr */ "./.yarn/cache/chownr-npm-1.1.4-5bd400ab08-115648f8eb.zip/node_modules/chownr/chownr.js") - -class SymlinkError extends Error { - constructor (symlink, path) { - super('Cannot extract through symbolic link') - this.path = path - this.symlink = symlink - } - - get name () { - return 'SylinkError' - } -} - -class CwdError extends Error { - constructor (path, code) { - super(code + ': Cannot cd into \'' + path + '\'') - this.path = path - this.code = code - } - - get name () { - return 'CwdError' - } -} - -const mkdir = module.exports = (dir, opt, cb) => { - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - const mode = opt.mode | 0o0700 - const needChmod = (mode & umask) !== 0 - - const uid = opt.uid - const gid = opt.gid - const doChown = typeof uid === 'number' && - typeof gid === 'number' && - ( uid !== opt.processUid || gid !== opt.processGid ) - - const preserve = opt.preserve - const unlink = opt.unlink - const cache = opt.cache - const cwd = opt.cwd - - const done = (er, created) => { - if (er) - cb(er) - else { - cache.set(dir, true) - if (created && doChown) - chownr(created, uid, gid, er => done(er)) - else if (needChmod) - fs.chmod(dir, mode, cb) - else - cb() + getUsageByRegistration(klass, opts) { + const record = this.registrations.get(klass); + if (typeof record === `undefined`) + throw new Error(`Assertion failed: Unregistered command`); + return this.getUsageByIndex(record.index, opts); } - } - - if (cache && cache.get(dir) === true) - return done() - - if (dir === cwd) - return fs.stat(dir, (er, st) => { - if (er || !st.isDirectory()) - er = new CwdError(dir, er && er.code || 'ENOTDIR') - done(er) - }) - - if (preserve) - return mkdirp(dir, {mode}).then(made => done(null, made), done) - - const sub = path.relative(cwd, dir) - const parts = sub.split(/\/|\\/) - mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) -} - -const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { - if (!parts.length) - return cb(null, created) - const p = parts.shift() - const part = base + '/' + p - if (cache.get(part)) - return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) -} - -const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { - if (er) { - if (er.path && path.dirname(er.path) === cwd && - (er.code === 'ENOTDIR' || er.code === 'ENOENT')) - return cb(new CwdError(cwd, er.code)) - - fs.lstat(part, (statEr, st) => { - if (statEr) - cb(statEr) - else if (st.isDirectory()) - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - else if (unlink) - fs.unlink(part, er => { - if (er) - return cb(er) - fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) - }) - else if (st.isSymbolicLink()) - return cb(new SymlinkError(part, part + '/' + parts.join('/'))) - else - cb(er) - }) - } else { - created = created || part - mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) - } -} - -const mkdirSync = module.exports.sync = (dir, opt) => { - // if there's any overlap between mask and mode, - // then we'll need an explicit chmod - const umask = opt.umask - const mode = opt.mode | 0o0700 - const needChmod = (mode & umask) !== 0 - - const uid = opt.uid - const gid = opt.gid - const doChown = typeof uid === 'number' && - typeof gid === 'number' && - ( uid !== opt.processUid || gid !== opt.processGid ) - - const preserve = opt.preserve - const unlink = opt.unlink - const cache = opt.cache - const cwd = opt.cwd - - const done = (created) => { - cache.set(dir, true) - if (created && doChown) - chownr.sync(created, uid, gid) - if (needChmod) - fs.chmodSync(dir, mode) - } - - if (cache && cache.get(dir) === true) - return done() - - if (dir === cwd) { - let ok = false - let code = 'ENOTDIR' - try { - ok = fs.statSync(dir).isDirectory() - } catch (er) { - code = er.code - } finally { - if (!ok) - throw new CwdError(dir, code) + getUsageByIndex(n, opts) { + return this.builder.getBuilderByIndex(n).usage(opts); } - done() - return - } - - if (preserve) - return done(mkdirp.sync(dir, mode)) - - const sub = path.relative(cwd, dir) - const parts = sub.split(/\/|\\/) - let created = null - for (let p = parts.shift(), part = cwd; - p && (part += '/' + p); - p = parts.shift()) { - - if (cache.get(part)) - continue - - try { - fs.mkdirSync(part, mode) - created = created || part - cache.set(part, true) - } catch (er) { - if (er.path && path.dirname(er.path) === cwd && - (er.code === 'ENOTDIR' || er.code === 'ENOENT')) - return new CwdError(cwd, er.code) - - const st = fs.lstatSync(part) - if (st.isDirectory()) { - cache.set(part, true) - continue - } else if (unlink) { - fs.unlinkSync(part) - fs.mkdirSync(part, mode) - created = created || part - cache.set(part, true) - continue - } else if (st.isSymbolicLink()) - return new SymlinkError(part, part + '/' + parts.join('/')) + format(colored = this.enableColors) { + return colored ? format.richFormat : format.textFormat; } - } - - return done(created) } - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mode-fix.js": -/*!**********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mode-fix.js ***! - \**********************************************************************************************/ -/***/ ((module) => { - -"use strict"; - -module.exports = (mode, isDir, portable) => { - mode &= 0o7777 - - // in portable mode, use the minimum reasonable umask - // if this system creates files with 0o664 by default - // (as some linux distros do), then we'll write the - // archive with 0o644 instead. Also, don't ever create - // a file that is not readable/writable by the owner. - if (portable) { - mode = (mode | 0o600) &~0o22 - } - - // if dirs are readable, then they should be listable - if (isDir) { - if (mode & 0o400) - mode |= 0o100 - if (mode & 0o40) - mode |= 0o10 - if (mode & 0o4) - mode |= 0o1 - } - return mode +/** + * The default context of the CLI. + * + * Contains the stdio of the current `process`. + */ +Cli.defaultContext = { + stdin: process.stdin, + stdout: process.stdout, + stderr: process.stderr, +}; +let gContextStorage; +function getCaptureActivator(context) { + let contextStorage = gContextStorage; + if (typeof contextStorage === `undefined`) { + if (context.stdout === process.stdout && context.stderr === process.stderr) + return noopCaptureActivator; + const { AsyncLocalStorage: LazyAsyncLocalStorage } = __webpack_require__(/*! async_hooks */ "async_hooks"); + contextStorage = gContextStorage = new LazyAsyncLocalStorage(); + const origStdoutWrite = process.stdout._write; + process.stdout._write = function (chunk, encoding, cb) { + const context = contextStorage.getStore(); + if (typeof context === `undefined`) + return origStdoutWrite.call(this, chunk, encoding, cb); + return context.stdout.write(chunk, encoding, cb); + }; + const origStderrWrite = process.stderr._write; + process.stderr._write = function (chunk, encoding, cb) { + const context = contextStorage.getStore(); + if (typeof context === `undefined`) + return origStderrWrite.call(this, chunk, encoding, cb); + return context.stderr.write(chunk, encoding, cb); + }; + } + return (fn) => { + return contextStorage.run(context, fn); + }; } +function noopCaptureActivator(fn) { + return fn(); +} + +exports.Cli = Cli; /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pack.js": -/*!******************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pack.js ***! - \******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js": +/*!****************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js ***! + \****************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// A readable tar stream creator -// Technically, this is a transform stream that you write paths into, -// and tar format comes out of. -// The `add()` method is like `write()` but returns this, -// and end() return `this` as well, so you can -// do `new Pack(opt).add('files').add('dir').end().pipe(output) -// You could also do something like: -// streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) - -class PackJob { - constructor (path, absolute) { - this.path = path || './' - this.absolute = absolute - this.entry = null - this.stat = null - this.readdir = null - this.pending = false - this.ignore = false - this.piped = false - } -} - -const MiniPass = __webpack_require__(/*! minipass */ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js") -const zlib = __webpack_require__(/*! minizlib */ "./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/index.js") -const ReadEntry = __webpack_require__(/*! ./read-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js") -const WriteEntry = __webpack_require__(/*! ./write-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/write-entry.js") -const WriteEntrySync = WriteEntry.Sync -const WriteEntryTar = WriteEntry.Tar -const Yallist = __webpack_require__(/*! yallist */ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/yallist.js") -const EOF = Buffer.alloc(1024) -const ONSTAT = Symbol('onStat') -const ENDED = Symbol('ended') -const QUEUE = Symbol('queue') -const CURRENT = Symbol('current') -const PROCESS = Symbol('process') -const PROCESSING = Symbol('processing') -const PROCESSJOB = Symbol('processJob') -const JOBS = Symbol('jobs') -const JOBDONE = Symbol('jobDone') -const ADDFSENTRY = Symbol('addFSEntry') -const ADDTARENTRY = Symbol('addTarEntry') -const STAT = Symbol('stat') -const READDIR = Symbol('readdir') -const ONREADDIR = Symbol('onreaddir') -const PIPE = Symbol('pipe') -const ENTRY = Symbol('entry') -const ENTRYOPT = Symbol('entryOpt') -const WRITEENTRYCLASS = Symbol('writeEntryClass') -const WRITE = Symbol('write') -const ONDRAIN = Symbol('ondrain') - -const fs = __webpack_require__(/*! fs */ "fs") -const path = __webpack_require__(/*! path */ "path") -const warner = __webpack_require__(/*! ./warn-mixin.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/warn-mixin.js") - -const Pack = warner(class Pack extends MiniPass { - constructor (opt) { - super(opt) - opt = opt || Object.create(null) - this.opt = opt - this.file = opt.file || '' - this.cwd = opt.cwd || process.cwd() - this.maxReadSize = opt.maxReadSize - this.preservePaths = !!opt.preservePaths - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.prefix = (opt.prefix || '').replace(/(\\|\/)+$/, '') - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.readdirCache = opt.readdirCache || new Map() +Object.defineProperty(exports, "__esModule", ({ value: true })); - this[WRITEENTRYCLASS] = WriteEntry - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) +var utils = __webpack_require__(/*! ./options/utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); - this.portable = !!opt.portable - this.zip = null - if (opt.gzip) { - if (typeof opt.gzip !== 'object') - opt.gzip = {} - if (this.portable) - opt.gzip.portable = true - this.zip = new zlib.Gzip(opt.gzip) - this.zip.on('data', chunk => super.write(chunk)) - this.zip.on('end', _ => super.end()) - this.zip.on('drain', _ => this[ONDRAIN]()) - this.on('resume', _ => this.zip.resume()) - } else - this.on('drain', this[ONDRAIN]) +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { + return e[k]; + } + }); + } + }); + } + n['default'] = e; + return Object.freeze(n); +} - this.noDirRecurse = !!opt.noDirRecurse - this.follow = !!opt.follow - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null +class Command { + constructor() { + /** + * Predefined that will be set to true if `-h,--help` has been used, in + * which case `Command#execute` won't be called. + */ + this.help = false; + } + /** + * Defines the usage information for the given command. + */ + static Usage(usage) { + return usage; + } + /** + * Standard error handler which will simply rethrow the error. Can be used + * to add custom logic to handle errors from the command or simply return + * the parent class error handling. + */ + async catch(error) { + throw error; + } + async validateAndExecute() { + const commandClass = this.constructor; + const cascade = commandClass.schema; + if (Array.isArray(cascade)) { + const { isDict, isUnknown, applyCascade } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(__webpack_require__(/*! typanion */ "../../../.yarn/berry/cache/typanion-npm-3.9.0-ef0bfe7e8b-9.zip/node_modules/typanion/lib/index.js")); }); + const schema = applyCascade(isDict(isUnknown()), cascade); + const errors = []; + const coercions = []; + const check = schema(this, { errors, coercions }); + if (!check) + throw utils.formatError(`Invalid option schema`, errors); + for (const [, op] of coercions) { + op(); + } + } + else if (cascade != null) { + throw new Error(`Invalid command schema`); + } + const exitCode = await this.execute(); + if (typeof exitCode !== `undefined`) { + return exitCode; + } + else { + return 0; + } + } +} +/** + * Used to detect option definitions. + */ +Command.isOption = utils.isOptionSymbol; +/** + * Just an helper to use along with the `paths` fields, to make it + * clearer that a command is the default one. + * + * @example + * class MyCommand extends Command { + * static paths = [Command.Default]; + * } + */ +Command.Default = []; - this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true +exports.Command = Command; - this[QUEUE] = new Yallist - this[JOBS] = 0 - this.jobs = +opt.jobs || 4 - this[PROCESSING] = false - this[ENDED] = false - } - [WRITE] (chunk) { - return super.write(chunk) - } +/***/ }), - add (path) { - this.write(path) - return this - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/HelpCommand.js": +/*!********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/HelpCommand.js ***! + \********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - end (path) { - if (path) - this.write(path) - this[ENDED] = true - this[PROCESS]() - return this - } +"use strict"; - write (path) { - if (this[ENDED]) - throw new Error('write after end') - if (path instanceof ReadEntry) - this[ADDTARENTRY](path) - else - this[ADDFSENTRY](path) - return this.flowing - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - [ADDTARENTRY] (p) { - const absolute = path.resolve(this.cwd, p.path) - if (this.prefix) - p.path = this.prefix + '/' + p.path.replace(/^\.(\/+|$)/, '') +var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); - // in this case, we don't have to wait for the stat - if (!this.filter(p.path, p)) - p.resume() - else { - const job = new PackJob(p.path, absolute, false) - job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) - job.entry.on('end', _ => this[JOBDONE](job)) - this[JOBS] += 1 - this[QUEUE].push(job) +class HelpCommand extends Command.Command { + constructor(contexts) { + super(); + this.contexts = contexts; + this.commands = []; + } + static from(state, contexts) { + const command = new HelpCommand(contexts); + command.path = state.path; + for (const opt of state.options) { + switch (opt.name) { + case `-c`: + { + command.commands.push(Number(opt.value)); + } + break; + case `-i`: + { + command.index = Number(opt.value); + } + break; + } + } + return command; + } + async execute() { + let commands = this.commands; + if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length) + commands = [commands[this.index]]; + if (commands.length === 0) { + this.context.stdout.write(this.cli.usage()); + } + else if (commands.length === 1) { + this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true })); + } + else if (commands.length > 1) { + this.context.stdout.write(`Multiple commands match your selection:\n`); + this.context.stdout.write(`\n`); + let index = 0; + for (const command of this.commands) + this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) })); + this.context.stdout.write(`\n`); + this.context.stdout.write(`Run again with -h= to see the longer details of any of those commands.\n`); + } } +} - this[PROCESS]() - } - - [ADDFSENTRY] (p) { - const absolute = path.resolve(this.cwd, p) - if (this.prefix) - p = this.prefix + '/' + p.replace(/^\.(\/+|$)/, '') - - this[QUEUE].push(new PackJob(p, absolute)) - this[PROCESS]() - } +exports.HelpCommand = HelpCommand; - [STAT] (job) { - job.pending = true - this[JOBS] += 1 - const stat = this.follow ? 'stat' : 'lstat' - fs[stat](job.absolute, (er, stat) => { - job.pending = false - this[JOBS] -= 1 - if (er) - this.emit('error', er) - else - this[ONSTAT](job, stat) - }) - } - [ONSTAT] (job, stat) { - this.statCache.set(job.absolute, stat) - job.stat = stat +/***/ }), - // now we have the stat, we can filter it. - if (!this.filter(job.path, stat)) - job.ignore = true +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js": +/*!*****************************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js ***! + \*****************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - this[PROCESS]() - } +"use strict"; - [READDIR] (job) { - job.pending = true - this[JOBS] += 1 - fs.readdir(job.absolute, (er, entries) => { - job.pending = false - this[JOBS] -= 1 - if (er) - return this.emit('error', er) - this[ONREADDIR](job, entries) - }) - } - [ONREADDIR] (job, entries) { - this.readdirCache.set(job.absolute, entries) - job.readdir = entries - this[PROCESS]() - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - [PROCESS] () { - if (this[PROCESSING]) - return +var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); - this[PROCESSING] = true - for (let w = this[QUEUE].head; - w !== null && this[JOBS] < this.jobs; - w = w.next) { - this[PROCESSJOB](w.value) - if (w.value.ignore) { - const p = w.next - this[QUEUE].removeNode(w) - w.next = p - } +/** + * A command that prints the clipanion definitions. + */ +class DefinitionsCommand extends Command.Command { + async execute() { + this.context.stdout.write(`${JSON.stringify(this.cli.definitions(), null, 2)}\n`); } +} +DefinitionsCommand.paths = [[`--clipanion=definitions`]]; - this[PROCESSING] = false +exports.DefinitionsCommand = DefinitionsCommand; - if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { - if (this.zip) - this.zip.end(EOF) - else { - super.write(EOF) - super.end() - } - } - } - get [CURRENT] () { - return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value - } +/***/ }), - [JOBDONE] (job) { - this[QUEUE].shift() - this[JOBS] -= 1 - this[PROCESS]() - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/help.js": +/*!**********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/help.js ***! + \**********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - [PROCESSJOB] (job) { - if (job.pending) - return +"use strict"; - if (job.entry) { - if (job === this[CURRENT] && !job.piped) - this[PIPE](job) - return - } - if (!job.stat) { - if (this.statCache.has(job.absolute)) - this[ONSTAT](job, this.statCache.get(job.absolute)) - else - this[STAT](job) - } - if (!job.stat) - return +Object.defineProperty(exports, "__esModule", ({ value: true })); - // filtered out! - if (job.ignore) - return +var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); - if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { - if (this.readdirCache.has(job.absolute)) - this[ONREADDIR](job, this.readdirCache.get(job.absolute)) - else - this[READDIR](job) - if (!job.readdir) - return +/** + * A command that prints the usage of all commands. + * + * Paths: `-h`, `--help` + */ +class HelpCommand extends Command.Command { + async execute() { + this.context.stdout.write(this.cli.usage()); } +} +HelpCommand.paths = [[`-h`], [`--help`]]; - // we know it doesn't have an entry, because that got checked above - job.entry = this[ENTRY](job) - if (!job.entry) { - job.ignore = true - return - } +exports.HelpCommand = HelpCommand; - if (job === this[CURRENT] && !job.piped) - this[PIPE](job) - } - [ENTRYOPT] (job) { - return { - onwarn: (code, msg, data) => this.warn(code, msg, data), - noPax: this.noPax, - cwd: this.cwd, - absolute: job.absolute, - preservePaths: this.preservePaths, - maxReadSize: this.maxReadSize, - strict: this.strict, - portable: this.portable, - linkCache: this.linkCache, - statCache: this.statCache, - noMtime: this.noMtime, - mtime: this.mtime - } - } +/***/ }), - [ENTRY] (job) { - this[JOBS] += 1 - try { - return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) - .on('end', () => this[JOBDONE](job)) - .on('error', er => this.emit('error', er)) - } catch (er) { - this.emit('error', er) - } - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/index.js": +/*!***********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/index.js ***! + \***********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - [ONDRAIN] () { - if (this[CURRENT] && this[CURRENT].entry) - this[CURRENT].entry.resume() - } +"use strict"; - // like .pipe() but using super, because our write() is special - [PIPE] (job) { - job.piped = true - if (job.readdir) - job.readdir.forEach(entry => { - const p = this.prefix ? - job.path.slice(this.prefix.length + 1) || './' - : job.path +Object.defineProperty(exports, "__esModule", ({ value: true })); - const base = p === './' ? '' : p.replace(/\/*$/, '/') - this[ADDFSENTRY](base + entry) - }) +var definitions = __webpack_require__(/*! ./definitions.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/definitions.js"); +var help = __webpack_require__(/*! ./help.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/help.js"); +var version = __webpack_require__(/*! ./version.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/version.js"); - const source = job.entry - const zip = this.zip - if (zip) - source.on('data', chunk => { - if (!zip.write(chunk)) - source.pause() - }) - else - source.on('data', chunk => { - if (!super.write(chunk)) - source.pause() - }) - } - pause () { - if (this.zip) - this.zip.pause() - return super.pause() - } -}) +exports.DefinitionsCommand = definitions.DefinitionsCommand; +exports.HelpCommand = help.HelpCommand; +exports.VersionCommand = version.VersionCommand; -class PackSync extends Pack { - constructor (opt) { - super(opt) - this[WRITEENTRYCLASS] = WriteEntrySync - } - // pause/resume are no-ops in sync streams. - pause () {} - resume () {} +/***/ }), - [STAT] (job) { - const stat = this.follow ? 'statSync' : 'lstatSync' - this[ONSTAT](job, fs[stat](job.absolute)) - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/version.js": +/*!*************************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/version.js ***! + \*************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - [READDIR] (job, stat) { - this[ONREADDIR](job, fs.readdirSync(job.absolute)) - } +"use strict"; - // gotta get it all in this tick - [PIPE] (job) { - const source = job.entry - const zip = this.zip - if (job.readdir) - job.readdir.forEach(entry => { - const p = this.prefix ? - job.path.slice(this.prefix.length + 1) || './' - : job.path +Object.defineProperty(exports, "__esModule", ({ value: true })); - const base = p === './' ? '' : p.replace(/\/*$/, '/') - this[ADDFSENTRY](base + entry) - }) +var Command = __webpack_require__(/*! ../Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); - if (zip) - source.on('data', chunk => { - zip.write(chunk) - }) - else - source.on('data', chunk => { - super[WRITE](chunk) - }) - } +/** + * A command that prints the version of the binary (`cli.binaryVersion`). + * + * Paths: `-v`, `--version` + */ +class VersionCommand extends Command.Command { + async execute() { + var _a; + this.context.stdout.write(`${(_a = this.cli.binaryVersion) !== null && _a !== void 0 ? _a : ``}\n`); + } } +VersionCommand.paths = [[`-v`], [`--version`]]; -Pack.Sync = PackSync - -module.exports = Pack +exports.VersionCommand = VersionCommand; /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js": -/*!*******************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js ***! - \*******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js": +/*!**************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js ***! + \**************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -// this[BUFFER] is the remainder of a chunk if we're waiting for -// the full 512 bytes of a header to come in. We will Buffer.concat() -// it to the next write(), which is a mem copy, but a small one. -// -// this[QUEUE] is a Yallist of entries that haven't been emitted -// yet this can only get filled up if the user keeps write()ing after -// a write() returns false, or does a write() with more than one entry -// -// We don't buffer chunks, we always parse them and either create an -// entry, or push it into the active entry. The ReadEntry class knows -// to throw data away if .ignore=true -// -// Shift entry off the buffer when it emits 'end', and emit 'entry' for -// the next one in the list. -// -// At any time, we're pushing body chunks into the entry at WRITEENTRY, -// and waiting for 'end' on the entry at READENTRY -// -// ignored entries get .resume() called on them straight away +Object.defineProperty(exports, "__esModule", ({ value: true })); -const warner = __webpack_require__(/*! ./warn-mixin.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/warn-mixin.js") -const path = __webpack_require__(/*! path */ "path") -const Header = __webpack_require__(/*! ./header.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js") -const EE = __webpack_require__(/*! events */ "events") -const Yallist = __webpack_require__(/*! yallist */ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/yallist.js") -const maxMetaEntrySize = 1024 * 1024 -const Entry = __webpack_require__(/*! ./read-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js") -const Pax = __webpack_require__(/*! ./pax.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pax.js") -const zlib = __webpack_require__(/*! minizlib */ "./.yarn/cache/minizlib-npm-2.1.0-9531be52b3-6a811aaa3a.zip/node_modules/minizlib/index.js") +var errors = __webpack_require__(/*! ../errors.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/errors.js"); +var Command = __webpack_require__(/*! ./Command.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Command.js"); +var Cli = __webpack_require__(/*! ./Cli.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/Cli.js"); +var index = __webpack_require__(/*! ./builtins/index.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/builtins/index.js"); +var index$1 = __webpack_require__(/*! ./options/index.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/index.js"); -const gzipHeader = Buffer.from([0x1f, 0x8b]) -const STATE = Symbol('state') -const WRITEENTRY = Symbol('writeEntry') -const READENTRY = Symbol('readEntry') -const NEXTENTRY = Symbol('nextEntry') -const PROCESSENTRY = Symbol('processEntry') -const EX = Symbol('extendedHeader') -const GEX = Symbol('globalExtendedHeader') -const META = Symbol('meta') -const EMITMETA = Symbol('emitMeta') -const BUFFER = Symbol('buffer') -const QUEUE = Symbol('queue') -const ENDED = Symbol('ended') -const EMITTEDEND = Symbol('emittedEnd') -const EMIT = Symbol('emit') -const UNZIP = Symbol('unzip') -const CONSUMECHUNK = Symbol('consumeChunk') -const CONSUMECHUNKSUB = Symbol('consumeChunkSub') -const CONSUMEBODY = Symbol('consumeBody') -const CONSUMEMETA = Symbol('consumeMeta') -const CONSUMEHEADER = Symbol('consumeHeader') -const CONSUMING = Symbol('consuming') -const BUFFERCONCAT = Symbol('bufferConcat') -const MAYBEEND = Symbol('maybeEnd') -const WRITING = Symbol('writing') -const ABORTED = Symbol('aborted') -const DONE = Symbol('onDone') -const SAW_VALID_ENTRY = Symbol('sawValidEntry') -const SAW_NULL_BLOCK = Symbol('sawNullBlock') -const SAW_EOF = Symbol('sawEOF') -const noop = _ => true -module.exports = warner(class Parser extends EE { - constructor (opt) { - opt = opt || {} - super(opt) +exports.UsageError = errors.UsageError; +exports.Command = Command.Command; +exports.Cli = Cli.Cli; +exports.Builtins = index; +exports.Option = index$1; - this.file = opt.file || '' - // set to boolean false when an entry starts. 1024 bytes of \0 - // is technically a valid tarball, albeit a boring one. - this[SAW_VALID_ENTRY] = null +/***/ }), - // these BADARCHIVE errors can't be detected early. listen on DONE. - this.on(DONE, _ => { - if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { - // either less than 1 block of data, or all entries were invalid. - // Either way, probably not even a tarball. - this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') - } - }) +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Array.js": +/*!**********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Array.js ***! + \**********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (opt.ondone) - this.on(DONE, opt.ondone) - else - this.on(DONE, _ => { - this.emit('prefinish') - this.emit('finish') - this.emit('end') - this.emit('close') - }) +"use strict"; - this.strict = !!opt.strict - this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize - this.filter = typeof opt.filter === 'function' ? opt.filter : noop - // have to set this so that streams are ok piping into it - this.writable = true - this.readable = false +Object.defineProperty(exports, "__esModule", ({ value: true })); - this[QUEUE] = new Yallist() - this[BUFFER] = null - this[READENTRY] = null - this[WRITEENTRY] = null - this[STATE] = 'begin' - this[META] = '' - this[EX] = null - this[GEX] = null - this[ENDED] = false - this[UNZIP] = null - this[ABORTED] = false - this[SAW_NULL_BLOCK] = false - this[SAW_EOF] = false - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - if (typeof opt.onentry === 'function') - this.on('entry', opt.onentry) - } +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); - [CONSUMEHEADER] (chunk, position) { - if (this[SAW_VALID_ENTRY] === null) - this[SAW_VALID_ENTRY] = false - let header - try { - header = new Header(chunk, position, this[EX], this[GEX]) - } catch (er) { - return this.warn('TAR_ENTRY_INVALID', er) - } +function Array(descriptor, initialValueBase, optsBase) { + const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); + const { arity = 1 } = opts; + const optNames = descriptor.split(`,`); + const nameSet = new Set(optNames); + return utils.makeCommandOption({ + definition(builder) { + builder.addOption({ + names: optNames, + arity, + hidden: opts === null || opts === void 0 ? void 0 : opts.hidden, + description: opts === null || opts === void 0 ? void 0 : opts.description, + required: opts.required, + }); + }, + transformer(builder, key, state) { + let currentValue = typeof initialValue !== `undefined` + ? [...initialValue] + : undefined; + for (const { name, value } of state.options) { + if (!nameSet.has(name)) + continue; + currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : []; + currentValue.push(value); + } + return currentValue; + }, + }); +} - if (header.nullBlock) { - if (this[SAW_NULL_BLOCK]) { - this[SAW_EOF] = true - // ending an archive with no entries. pointless, but legal. - if (this[STATE] === 'begin') - this[STATE] = 'header' - this[EMIT]('eof') - } else { - this[SAW_NULL_BLOCK] = true - this[EMIT]('nullBlock') - } - } else { - this[SAW_NULL_BLOCK] = false - if (!header.cksumValid) - this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header}) - else if (!header.path) - this.warn('TAR_ENTRY_INVALID', 'path is required', {header}) - else { - const type = header.type - if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) - this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header}) - else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) - this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header}) - else { - const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) +exports.Array = Array; - // we do this for meta & ignored entries as well, because they - // are still valid tar, or else we wouldn't know to ignore them - if (!this[SAW_VALID_ENTRY]) { - if (entry.remain) { - // this might be the one! - const onend = () => { - if (!entry.invalid) - this[SAW_VALID_ENTRY] = true - } - entry.on('end', onend) - } else { - this[SAW_VALID_ENTRY] = true - } - } - if (entry.meta) { - if (entry.size > this.maxMetaEntrySize) { - entry.ignore = true - this[EMIT]('ignoredEntry', entry) - this[STATE] = 'ignore' - entry.resume() - } else if (entry.size > 0) { - this[META] = '' - entry.on('data', c => this[META] += c) - this[STATE] = 'meta' - } - } else { - this[EX] = null - entry.ignore = entry.ignore || !this.filter(entry.path, entry) +/***/ }), - if (entry.ignore) { - // probably valid, just not something we care about - this[EMIT]('ignoredEntry', entry) - this[STATE] = entry.remain ? 'ignore' : 'header' - entry.resume() - } else { - if (entry.remain) - this[STATE] = 'body' - else { - this[STATE] = 'header' - entry.end() - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Boolean.js": +/*!************************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Boolean.js ***! + \************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (!this[READENTRY]) { - this[QUEUE].push(entry) - this[NEXTENTRY]() - } else - this[QUEUE].push(entry) +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); + +function Boolean(descriptor, initialValueBase, optsBase) { + const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); + const optNames = descriptor.split(`,`); + const nameSet = new Set(optNames); + return utils.makeCommandOption({ + definition(builder) { + builder.addOption({ + names: optNames, + allowBinding: false, + arity: 0, + hidden: opts.hidden, + description: opts.description, + required: opts.required, + }); + }, + transformer(builer, key, state) { + let currentValue = initialValue; + for (const { name, value } of state.options) { + if (!nameSet.has(name)) + continue; + currentValue = value; } - } - } - } - } - } + return currentValue; + }, + }); +} - [PROCESSENTRY] (entry) { - let go = true +exports.Boolean = Boolean; - if (!entry) { - this[READENTRY] = null - go = false - } else if (Array.isArray(entry)) - this.emit.apply(this, entry) - else { - this[READENTRY] = entry - this.emit('entry', entry) - if (!entry.emittedEnd) { - entry.on('end', _ => this[NEXTENTRY]()) - go = false - } - } - return go - } +/***/ }), - [NEXTENTRY] () { - do {} while (this[PROCESSENTRY](this[QUEUE].shift())) +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Counter.js": +/*!************************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Counter.js ***! + \************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (!this[QUEUE].length) { - // At this point, there's nothing in the queue, but we may have an - // entry which is being consumed (readEntry). - // If we don't, then we definitely can handle more data. - // If we do, and either it's flowing, or it has never had any data - // written to it, then it needs more. - // The only other possibility is that it has returned false from a - // write() call, so we wait for the next drain to continue. - const re = this[READENTRY] - const drainNow = !re || re.flowing || re.size === re.remain - if (drainNow) { - if (!this[WRITING]) - this.emit('drain') - } else - re.once('drain', _ => this.emit('drain')) - } - } +"use strict"; - [CONSUMEBODY] (chunk, position) { - // write up to but no more than writeEntry.blockRemain - const entry = this[WRITEENTRY] - const br = entry.blockRemain - const c = (br >= chunk.length && position === 0) ? chunk - : chunk.slice(position, position + br) - entry.write(c) +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (!entry.blockRemain) { - this[STATE] = 'header' - this[WRITEENTRY] = null - entry.end() - } +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); - return c.length - } +function Counter(descriptor, initialValueBase, optsBase) { + const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); + const optNames = descriptor.split(`,`); + const nameSet = new Set(optNames); + return utils.makeCommandOption({ + definition(builder) { + builder.addOption({ + names: optNames, + allowBinding: false, + arity: 0, + hidden: opts.hidden, + description: opts.description, + required: opts.required, + }); + }, + transformer(builder, key, state) { + let currentValue = initialValue; + for (const { name, value } of state.options) { + if (!nameSet.has(name)) + continue; + currentValue !== null && currentValue !== void 0 ? currentValue : (currentValue = 0); + // Negated options reset the counter + if (!value) { + currentValue = 0; + } + else { + currentValue += 1; + } + } + return currentValue; + }, + }); +} - [CONSUMEMETA] (chunk, position) { - const entry = this[WRITEENTRY] - const ret = this[CONSUMEBODY](chunk, position) +exports.Counter = Counter; - // if we finished, then the entry is reset - if (!this[WRITEENTRY]) - this[EMITMETA](entry) - return ret - } +/***/ }), - [EMIT] (ev, data, extra) { - if (!this[QUEUE].length && !this[READENTRY]) - this.emit(ev, data, extra) - else - this[QUEUE].push([ev, data, extra]) - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Proxy.js": +/*!**********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Proxy.js ***! + \**********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - [EMITMETA] (entry) { - this[EMIT]('meta', this[META]) - switch (entry.type) { - case 'ExtendedHeader': - case 'OldExtendedHeader': - this[EX] = Pax.parse(this[META], this[EX], false) - break +"use strict"; - case 'GlobalExtendedHeader': - this[GEX] = Pax.parse(this[META], this[GEX], true) - break - case 'NextFileHasLongPath': - case 'OldGnuLongPath': - this[EX] = this[EX] || Object.create(null) - this[EX].path = this[META].replace(/\0.*/, '') - break +Object.defineProperty(exports, "__esModule", ({ value: true })); - case 'NextFileHasLongLinkpath': - this[EX] = this[EX] || Object.create(null) - this[EX].linkpath = this[META].replace(/\0.*/, '') - break +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); - /* istanbul ignore next */ - default: throw new Error('unknown meta: ' + entry.type) - } - } +/** + * Used to annotate that the command wants to retrieve all trailing + * arguments that cannot be tied to a declared option. + * + * Be careful: this function is order-dependent! Make sure to define it + * after any positional argument you want to declare. + * + * This function is mutually exclusive with Option.Rest. + * + * @example + * yarn run foo hello --foo=bar world + * ► proxy = ["hello", "--foo=bar", "world"] + */ +function Proxy(opts = {}) { + return utils.makeCommandOption({ + definition(builder, key) { + var _a; + builder.addProxy({ + name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, + required: opts.required, + }); + }, + transformer(builder, key, state) { + return state.positionals.map(({ value }) => value); + }, + }); +} - abort (error) { - this[ABORTED] = true - this.emit('abort', error) - // always throws, even in non-strict mode - this.warn('TAR_ABORT', error, { recoverable: false }) - } +exports.Proxy = Proxy; - write (chunk) { - if (this[ABORTED]) - return - // first write, might be gzipped - if (this[UNZIP] === null && chunk) { - if (this[BUFFER]) { - chunk = Buffer.concat([this[BUFFER], chunk]) - this[BUFFER] = null - } - if (chunk.length < gzipHeader.length) { - this[BUFFER] = chunk - return true - } - for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { - if (chunk[i] !== gzipHeader[i]) - this[UNZIP] = false - } - if (this[UNZIP] === null) { - const ended = this[ENDED] - this[ENDED] = false - this[UNZIP] = new zlib.Unzip() - this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) - this[UNZIP].on('error', er => this.abort(er)) - this[UNZIP].on('end', _ => { - this[ENDED] = true - this[CONSUMECHUNK]() - }) - this[WRITING] = true - const ret = this[UNZIP][ended ? 'end' : 'write' ](chunk) - this[WRITING] = false - return ret - } - } +/***/ }), - this[WRITING] = true - if (this[UNZIP]) - this[UNZIP].write(chunk) - else - this[CONSUMECHUNK](chunk) - this[WRITING] = false +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Rest.js": +/*!*********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Rest.js ***! + \*********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - // return false if there's a queue, or if the current entry isn't flowing - const ret = - this[QUEUE].length ? false : - this[READENTRY] ? this[READENTRY].flowing : - true +"use strict"; - // if we have no queue, then that means a clogged READENTRY - if (!ret && !this[QUEUE].length) - this[READENTRY].once('drain', _ => this.emit('drain')) - return ret - } +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); +var core = __webpack_require__(/*! ../../core.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/core.js"); + +/** + * Used to annotate that the command supports any number of positional + * arguments. + * + * Be careful: this function is order-dependent! Make sure to define it + * after any positional argument you want to declare. + * + * This function is mutually exclusive with Option.Proxy. + * + * @example + * yarn add hello world + * ► rest = ["hello", "world"] + */ +function Rest(opts = {}) { + return utils.makeCommandOption({ + definition(builder, key) { + var _a; + builder.addRest({ + name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, + required: opts.required, + }); + }, + transformer(builder, key, state) { + // The builder's arity.extra will always be NoLimits, + // because it is set when we call registerDefinition + const isRestPositional = (index) => { + const positional = state.positionals[index]; + // A NoLimits extra (i.e. an optional rest argument) + if (positional.extra === core.NoLimits) + return true; + // A leading positional (i.e. a required rest argument) + if (positional.extra === false && index < builder.arity.leading.length) + return true; + return false; + }; + let count = 0; + while (count < state.positionals.length && isRestPositional(count)) + count += 1; + return state.positionals.splice(0, count).map(({ value }) => value); + }, + }); +} - [BUFFERCONCAT] (c) { - if (c && !this[ABORTED]) - this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c - } +exports.Rest = Rest; - [MAYBEEND] () { - if (this[ENDED] && - !this[EMITTEDEND] && - !this[ABORTED] && - !this[CONSUMING]) { - this[EMITTEDEND] = true - const entry = this[WRITEENTRY] - if (entry && entry.blockRemain) { - // truncated, likely a damaged file - const have = this[BUFFER] ? this[BUFFER].length : 0 - this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ - entry.blockRemain} more bytes, only ${have} available)`, {entry}) - if (this[BUFFER]) - entry.write(this[BUFFER]) - entry.end() - } - this[EMIT](DONE) - } - } - [CONSUMECHUNK] (chunk) { - if (this[CONSUMING]) - this[BUFFERCONCAT](chunk) - else if (!chunk && !this[BUFFER]) - this[MAYBEEND]() - else { - this[CONSUMING] = true - if (this[BUFFER]) { - this[BUFFERCONCAT](chunk) - const c = this[BUFFER] - this[BUFFER] = null - this[CONSUMECHUNKSUB](c) - } else { - this[CONSUMECHUNKSUB](chunk) - } +/***/ }), - while (this[BUFFER] && - this[BUFFER].length >= 512 && - !this[ABORTED] && - !this[SAW_EOF]) { - const c = this[BUFFER] - this[BUFFER] = null - this[CONSUMECHUNKSUB](c) - } - this[CONSUMING] = false - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/String.js": +/*!***********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/String.js ***! + \***********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (!this[BUFFER] || this[ENDED]) - this[MAYBEEND]() - } +"use strict"; - [CONSUMECHUNKSUB] (chunk) { - // we know that we are in CONSUMING mode, so anything written goes into - // the buffer. Advance the position and put any remainder in the buffer. - let position = 0 - let length = chunk.length - while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { - switch (this[STATE]) { - case 'begin': - case 'header': - this[CONSUMEHEADER](chunk, position) - position += 512 - break - case 'ignore': - case 'body': - position += this[CONSUMEBODY](chunk, position) - break +Object.defineProperty(exports, "__esModule", ({ value: true })); - case 'meta': - position += this[CONSUMEMETA](chunk, position) - break +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); +var core = __webpack_require__(/*! ../../core.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/core.js"); - /* istanbul ignore next */ - default: - throw new Error('invalid state: ' + this[STATE]) - } +function StringOption(descriptor, initialValueBase, optsBase) { + const [initialValue, opts] = utils.rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {}); + const { arity = 1 } = opts; + const optNames = descriptor.split(`,`); + const nameSet = new Set(optNames); + return utils.makeCommandOption({ + definition(builder) { + builder.addOption({ + names: optNames, + arity: opts.tolerateBoolean ? 0 : arity, + hidden: opts.hidden, + description: opts.description, + required: opts.required, + }); + }, + transformer(builder, key, state) { + let usedName; + let currentValue = initialValue; + for (const { name, value } of state.options) { + if (!nameSet.has(name)) + continue; + usedName = name; + currentValue = value; + } + if (typeof currentValue === `string`) { + return utils.applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator); + } + else { + return currentValue; + } + }, + }); +} +function StringPositional(opts = {}) { + const { required = true } = opts; + return utils.makeCommandOption({ + definition(builder, key) { + var _a; + builder.addPositional({ + name: (_a = opts.name) !== null && _a !== void 0 ? _a : key, + required: opts.required, + }); + }, + transformer(builder, key, state) { + var _a; + for (let i = 0; i < state.positionals.length; ++i) { + // We skip NoLimits extras. We only care about + // required and optional finite positionals. + if (state.positionals[i].extra === core.NoLimits) + continue; + // We skip optional positionals when we only + // care about required positionals. + if (required && state.positionals[i].extra === true) + continue; + // We skip required positionals when we only + // care about optional positionals. + if (!required && state.positionals[i].extra === false) + continue; + // We remove the positional from the list + const [positional] = state.positionals.splice(i, 1); + return utils.applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator); + } + return undefined; + }, + }); +} +// This function is badly typed, but it doesn't matter because the overloads provide the true public typings +function String(descriptor, ...args) { + if (typeof descriptor === `string`) { + return StringOption(descriptor, ...args); } - - if (position < length) { - if (this[BUFFER]) - this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) - else - this[BUFFER] = chunk.slice(position) + else { + return StringPositional(descriptor); } - } +} - end (chunk) { - if (!this[ABORTED]) { - if (this[UNZIP]) - this[UNZIP].end(chunk) - else { - this[ENDED] = true - this.write(chunk) - } - } - } -}) +exports.String = String; /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/path-reservations.js": -/*!*******************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/path-reservations.js ***! - \*******************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// A path exclusive reservation system -// reserve([list, of, paths], fn) -// When the fn is first in line for all its paths, it -// is called with a cb that clears the reservation. -// -// Used by async unpack to avoid clobbering paths in use, -// while still allowing maximal safe parallelization. - -const assert = __webpack_require__(/*! assert */ "assert") - -module.exports = () => { - // path => [function or Set] - // A Set object means a directory reservation - // A fn is a direct reservation on that path - const queues = new Map() +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/index.js": +/*!**********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/index.js ***! + \**********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - // fn => {paths:[path,...], dirs:[path, ...]} - const reservations = new Map() +"use strict"; - // return a set of parent dirs for a given path - const { join } = __webpack_require__(/*! path */ "path") - const getDirs = path => - join(path).split(/[\\\/]/).slice(0, -1).reduce((set, path) => - set.length ? set.concat(join(set[set.length-1], path)) : [path], []) - // functions currently running - const running = new Set() +Object.defineProperty(exports, "__esModule", ({ value: true })); - // return the queues for each path the function cares about - // fn => {paths, dirs} - const getQueues = fn => { - const res = reservations.get(fn) - /* istanbul ignore if - unpossible */ - if (!res) - throw new Error('function does not have any path reservations') - return { - paths: res.paths.map(path => queues.get(path)), - dirs: [...res.dirs].map(path => queues.get(path)), - } - } +var utils = __webpack_require__(/*! ./utils.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js"); +var _Array = __webpack_require__(/*! ./Array.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Array.js"); +var _Boolean = __webpack_require__(/*! ./Boolean.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Boolean.js"); +var Counter = __webpack_require__(/*! ./Counter.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Counter.js"); +var _Proxy = __webpack_require__(/*! ./Proxy.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Proxy.js"); +var Rest = __webpack_require__(/*! ./Rest.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/Rest.js"); +var _String = __webpack_require__(/*! ./String.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/String.js"); - // check if fn is first in line for all its paths, and is - // included in the first set for all its dir queues - const check = fn => { - const {paths, dirs} = getQueues(fn) - return paths.every(q => q[0] === fn) && - dirs.every(q => q[0] instanceof Set && q[0].has(fn)) - } - // run the function if it's first in line and not already running - const run = fn => { - if (running.has(fn) || !check(fn)) - return false - running.add(fn) - fn(() => clear(fn)) - return true - } - const clear = fn => { - if (!running.has(fn)) - return false +exports.applyValidator = utils.applyValidator; +exports.cleanValidationError = utils.cleanValidationError; +exports.formatError = utils.formatError; +exports.isOptionSymbol = utils.isOptionSymbol; +exports.makeCommandOption = utils.makeCommandOption; +exports.rerouteArguments = utils.rerouteArguments; +exports.Array = _Array.Array; +exports.Boolean = _Boolean.Boolean; +exports.Counter = Counter.Counter; +exports.Proxy = _Proxy.Proxy; +exports.Rest = Rest.Rest; +exports.String = _String.String; - const { paths, dirs } = reservations.get(fn) - const next = new Set() - paths.forEach(path => { - const q = queues.get(path) - assert.equal(q[0], fn) - if (q.length === 1) - queues.delete(path) - else { - q.shift() - if (typeof q[0] === 'function') - next.add(q[0]) - else - q[0].forEach(fn => next.add(fn)) - } - }) +/***/ }), - dirs.forEach(dir => { - const q = queues.get(dir) - assert(q[0] instanceof Set) - if (q[0].size === 1 && q.length === 1) { - queues.delete(dir) - } else if (q[0].size === 1) { - q.shift() +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js": +/*!**********************************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/options/utils.js ***! + \**********************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - // must be a function or else the Set would've been reused - next.add(q[0]) - } else - q[0].delete(fn) - }) - running.delete(fn) +"use strict"; - next.forEach(fn => run(fn)) - return true - } - const reserve = (paths, fn) => { - const dirs = new Set( - paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) - ) - reservations.set(fn, {dirs, paths}) - paths.forEach(path => { - const q = queues.get(path) - if (!q) - queues.set(path, [fn]) - else - q.push(fn) - }) - dirs.forEach(dir => { - const q = queues.get(dir) - if (!q) - queues.set(dir, [new Set([fn])]) - else if (q[q.length-1] instanceof Set) - q[q.length-1].add(fn) - else - q.push(new Set([fn])) - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); - return run(fn) - } +var errors = __webpack_require__(/*! ../../errors.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/errors.js"); - return { check, reserve } +const isOptionSymbol = Symbol(`clipanion/isOption`); +function makeCommandOption(spec) { + // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation. + return { ...spec, [isOptionSymbol]: true }; +} +function rerouteArguments(a, b) { + if (typeof a === `undefined`) + return [a, b]; + if (typeof a === `object` && a !== null && !Array.isArray(a)) { + return [undefined, a]; + } + else { + return [a, b]; + } +} +function cleanValidationError(message, lowerCase = false) { + let cleaned = message.replace(/^\.: /, ``); + if (lowerCase) + cleaned = cleaned[0].toLowerCase() + cleaned.slice(1); + return cleaned; +} +function formatError(message, errors$1) { + if (errors$1.length === 1) { + return new errors.UsageError(`${message}: ${cleanValidationError(errors$1[0], true)}`); + } + else { + return new errors.UsageError(`${message}:\n${errors$1.map(error => `\n- ${cleanValidationError(error)}`).join(``)}`); + } +} +function applyValidator(name, value, validator) { + if (typeof validator === `undefined`) + return value; + const errors = []; + const coercions = []; + const coercion = (v) => { + const orig = value; + value = v; + return coercion.bind(null, orig); + }; + const check = validator(value, { errors, coercions, coercion }); + if (!check) + throw formatError(`Invalid value for ${name}`, errors); + for (const [, op] of coercions) + op(); + return value; } +exports.applyValidator = applyValidator; +exports.cleanValidationError = cleanValidationError; +exports.formatError = formatError; +exports.isOptionSymbol = isOptionSymbol; +exports.makeCommandOption = makeCommandOption; +exports.rerouteArguments = rerouteArguments; + /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pax.js": -/*!*****************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pax.js ***! - \*****************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/constants.js": +/*!*********************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/constants.js ***! + \*********************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const Header = __webpack_require__(/*! ./header.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js") -const path = __webpack_require__(/*! path */ "path") -class Pax { - constructor (obj, global) { - this.atime = obj.atime || null - this.charset = obj.charset || null - this.comment = obj.comment || null - this.ctime = obj.ctime || null - this.gid = obj.gid || null - this.gname = obj.gname || null - this.linkpath = obj.linkpath || null - this.mtime = obj.mtime || null - this.path = obj.path || null - this.size = obj.size || null - this.uid = obj.uid || null - this.uname = obj.uname || null - this.dev = obj.dev || null - this.ino = obj.ino || null - this.nlink = obj.nlink || null - this.global = global || false - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - encode () { - const body = this.encodeBody() - if (body === '') - return null +const NODE_INITIAL = 0; +const NODE_SUCCESS = 1; +const NODE_ERRORED = 2; +const START_OF_INPUT = `\u0001`; +const END_OF_INPUT = `\u0000`; +const HELP_COMMAND_INDEX = -1; +const HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/; +const OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/; +const BATCH_REGEX = /^-[a-zA-Z]{2,}$/; +const BINDING_REGEX = /^([^=]+)=([\s\S]*)$/; +const DEBUG = process.env.DEBUG_CLI === `1`; - const bodyLen = Buffer.byteLength(body) - // round up to 512 bytes - // add 512 for header - const bufLen = 512 * Math.ceil(1 + bodyLen / 512) - const buf = Buffer.allocUnsafe(bufLen) +exports.BATCH_REGEX = BATCH_REGEX; +exports.BINDING_REGEX = BINDING_REGEX; +exports.DEBUG = DEBUG; +exports.END_OF_INPUT = END_OF_INPUT; +exports.HELP_COMMAND_INDEX = HELP_COMMAND_INDEX; +exports.HELP_REGEX = HELP_REGEX; +exports.NODE_ERRORED = NODE_ERRORED; +exports.NODE_INITIAL = NODE_INITIAL; +exports.NODE_SUCCESS = NODE_SUCCESS; +exports.OPTION_REGEX = OPTION_REGEX; +exports.START_OF_INPUT = START_OF_INPUT; - // 0-fill the header section, it might not hit every field - for (let i = 0; i < 512; i++) { - buf[i] = 0 + +/***/ }), + +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/core.js": +/*!****************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/core.js ***! + \****************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var constants = __webpack_require__(/*! ./constants.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/constants.js"); +var errors = __webpack_require__(/*! ./errors.js */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/errors.js"); + +// ------------------------------------------------------------------------ +function debug(str) { + if (constants.DEBUG) { + console.log(str); + } +} +const basicHelpState = { + candidateUsage: null, + requiredOptions: [], + errorMessage: null, + ignoreOptions: false, + path: [], + positionals: [], + options: [], + remainder: null, + selectedIndex: constants.HELP_COMMAND_INDEX, +}; +function makeStateMachine() { + return { + nodes: [makeNode(), makeNode(), makeNode()], + }; +} +function makeAnyOfMachine(inputs) { + const output = makeStateMachine(); + const heads = []; + let offset = output.nodes.length; + for (const input of inputs) { + heads.push(offset); + for (let t = 0; t < input.nodes.length; ++t) + if (!isTerminalNode(t)) + output.nodes.push(cloneNode(input.nodes[t], offset)); + offset += input.nodes.length - 2; + } + for (const head of heads) + registerShortcut(output, constants.NODE_INITIAL, head); + return output; +} +function injectNode(machine, node) { + machine.nodes.push(node); + return machine.nodes.length - 1; +} +function simplifyMachine(input) { + const visited = new Set(); + const process = (node) => { + if (visited.has(node)) + return; + visited.add(node); + const nodeDef = input.nodes[node]; + for (const transitions of Object.values(nodeDef.statics)) + for (const { to } of transitions) + process(to); + for (const [, { to }] of nodeDef.dynamics) + process(to); + for (const { to } of nodeDef.shortcuts) + process(to); + const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to)); + while (nodeDef.shortcuts.length > 0) { + const { to } = nodeDef.shortcuts.shift(); + const toDef = input.nodes[to]; + for (const [segment, transitions] of Object.entries(toDef.statics)) { + const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment) + ? nodeDef.statics[segment] = [] + : nodeDef.statics[segment]; + for (const transition of transitions) { + if (!store.some(({ to }) => transition.to === to)) { + store.push(transition); + } + } + } + for (const [test, transition] of toDef.dynamics) + if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to)) + nodeDef.dynamics.push([test, transition]); + for (const transition of toDef.shortcuts) { + if (!shortcuts.has(transition.to)) { + nodeDef.shortcuts.push(transition); + shortcuts.add(transition.to); + } + } + } + }; + process(constants.NODE_INITIAL); +} +function debugMachine(machine, { prefix = `` } = {}) { + // Don't iterate unless it's needed + if (constants.DEBUG) { + debug(`${prefix}Nodes are:`); + for (let t = 0; t < machine.nodes.length; ++t) { + debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`); + } } - - new Header({ - // XXX split the path - // then the path should be PaxHeader + basename, but less than 99, - // prepend with the dirname - path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), - mode: this.mode || 0o644, - uid: this.uid || null, - gid: this.gid || null, - size: bodyLen, - mtime: this.mtime || null, - type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', - linkpath: '', - uname: this.uname || '', - gname: this.gname || '', - devmaj: 0, - devmin: 0, - atime: this.atime || null, - ctime: this.ctime || null - }).encode(buf) - - buf.write(body, 512, bodyLen, 'utf8') - - // null pad after the body - for (let i = bodyLen + 512; i < buf.length; i++) { - buf[i] = 0 +} +function runMachineInternal(machine, input, partial = false) { + debug(`Running a vm on ${JSON.stringify(input)}`); + let branches = [{ node: constants.NODE_INITIAL, state: { + candidateUsage: null, + requiredOptions: [], + errorMessage: null, + ignoreOptions: false, + options: [], + path: [], + positionals: [], + remainder: null, + selectedIndex: null, + } }]; + debugMachine(machine, { prefix: ` ` }); + const tokens = [constants.START_OF_INPUT, ...input]; + for (let t = 0; t < tokens.length; ++t) { + const segment = tokens[t]; + debug(` Processing ${JSON.stringify(segment)}`); + const nextBranches = []; + for (const { node, state } of branches) { + debug(` Current node is ${node}`); + const nodeDef = machine.nodes[node]; + if (node === constants.NODE_ERRORED) { + nextBranches.push({ node, state }); + continue; + } + console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`); + const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment); + if (!partial || t < tokens.length - 1 || hasExactMatch) { + if (hasExactMatch) { + const transitions = nodeDef.statics[segment]; + for (const { to, reducer } of transitions) { + nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); + debug(` Static transition to ${to} found`); + } + } + else { + debug(` No static transition found`); + } + } + else { + let hasMatches = false; + for (const candidate of Object.keys(nodeDef.statics)) { + if (!candidate.startsWith(segment)) + continue; + if (segment === candidate) { + for (const { to, reducer } of nodeDef.statics[candidate]) { + nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); + debug(` Static transition to ${to} found`); + } + } + else { + for (const { to } of nodeDef.statics[candidate]) { + nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } }); + debug(` Static transition to ${to} found (partial match)`); + } + } + hasMatches = true; + } + if (!hasMatches) { + debug(` No partial static transition found`); + } + } + if (segment !== constants.END_OF_INPUT) { + for (const [test, { to, reducer }] of nodeDef.dynamics) { + if (execute(tests, test, state, segment)) { + nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment) : state }); + debug(` Dynamic transition to ${to} found (via ${test})`); + } + } + } + } + if (nextBranches.length === 0 && segment === constants.END_OF_INPUT && input.length === 1) { + return [{ + node: constants.NODE_INITIAL, + state: basicHelpState, + }]; + } + if (nextBranches.length === 0) { + throw new errors.UnknownSyntaxError(input, branches.filter(({ node }) => { + return node !== constants.NODE_ERRORED; + }).map(({ state }) => { + return { usage: state.candidateUsage, reason: null }; + })); + } + if (nextBranches.every(({ node }) => node === constants.NODE_ERRORED)) { + throw new errors.UnknownSyntaxError(input, nextBranches.map(({ state }) => { + return { usage: state.candidateUsage, reason: state.errorMessage }; + })); + } + branches = trimSmallerBranches(nextBranches); } - - return buf - } - - encodeBody () { - return ( - this.encodeField('path') + - this.encodeField('ctime') + - this.encodeField('atime') + - this.encodeField('dev') + - this.encodeField('ino') + - this.encodeField('nlink') + - this.encodeField('charset') + - this.encodeField('comment') + - this.encodeField('gid') + - this.encodeField('gname') + - this.encodeField('linkpath') + - this.encodeField('mtime') + - this.encodeField('size') + - this.encodeField('uid') + - this.encodeField('uname') - ) - } - - encodeField (field) { - if (this[field] === null || this[field] === undefined) - return '' - const v = this[field] instanceof Date ? this[field].getTime() / 1000 - : this[field] - const s = ' ' + - (field === 'dev' || field === 'ino' || field === 'nlink' - ? 'SCHILY.' : '') + - field + '=' + v + '\n' - const byteLen = Buffer.byteLength(s) - // the digits includes the length of the digits in ascii base-10 - // so if it's 9 characters, then adding 1 for the 9 makes it 10 - // which makes it 11 chars. - let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 - if (byteLen + digits >= Math.pow(10, digits)) - digits += 1 - const len = digits + byteLen - return len + s - } + if (branches.length > 0) { + debug(` Results:`); + for (const branch of branches) { + debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`); + } + } + else { + debug(` No results`); + } + return branches; +} +function checkIfNodeIsFinished(node, state) { + if (state.selectedIndex !== null) + return true; + if (Object.prototype.hasOwnProperty.call(node.statics, constants.END_OF_INPUT)) + for (const { to } of node.statics[constants.END_OF_INPUT]) + if (to === constants.NODE_SUCCESS) + return true; + return false; +} +function suggestMachine(machine, input, partial) { + // If we're accepting partial matches, then exact matches need to be + // prefixed with an extra space. + const prefix = partial && input.length > 0 ? [``] : []; + const branches = runMachineInternal(machine, input, partial); + const suggestions = []; + const suggestionsJson = new Set(); + const traverseSuggestion = (suggestion, node, skipFirst = true) => { + let nextNodes = [node]; + while (nextNodes.length > 0) { + const currentNodes = nextNodes; + nextNodes = []; + for (const node of currentNodes) { + const nodeDef = machine.nodes[node]; + const keys = Object.keys(nodeDef.statics); + // The fact that `key` is unused is likely a bug, but no one has investigated it yet. + // TODO: Investigate it. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const key of Object.keys(nodeDef.statics)) { + const segment = keys[0]; + for (const { to, reducer } of nodeDef.statics[segment]) { + if (reducer !== `pushPath`) + continue; + if (!skipFirst) + suggestion.push(segment); + nextNodes.push(to); + } + } + } + skipFirst = false; + } + const json = JSON.stringify(suggestion); + if (suggestionsJson.has(json)) + return; + suggestions.push(suggestion); + suggestionsJson.add(json); + }; + for (const { node, state } of branches) { + if (state.remainder !== null) { + traverseSuggestion([state.remainder], node); + continue; + } + const nodeDef = machine.nodes[node]; + const isFinished = checkIfNodeIsFinished(nodeDef, state); + for (const [candidate, transitions] of Object.entries(nodeDef.statics)) + if ((isFinished && candidate !== constants.END_OF_INPUT) || (!candidate.startsWith(`-`) && transitions.some(({ reducer }) => reducer === `pushPath`))) + traverseSuggestion([...prefix, candidate], node); + if (!isFinished) + continue; + for (const [test, { to }] of nodeDef.dynamics) { + if (to === constants.NODE_ERRORED) + continue; + const tokens = suggest(test, state); + if (tokens === null) + continue; + for (const token of tokens) { + traverseSuggestion([...prefix, token], node); + } + } + } + return [...suggestions].sort(); +} +function runMachine(machine, input) { + const branches = runMachineInternal(machine, [...input, constants.END_OF_INPUT]); + return selectBestState(input, branches.map(({ state }) => { + return state; + })); } - -Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) - -const merge = (a, b) => - b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a - -const parseKV = string => - string - .replace(/\n$/, '') - .split('\n') - .reduce(parseKVLine, Object.create(null)) - -const parseKVLine = (set, line) => { - const n = parseInt(line, 10) - - // XXX Values with \n in them will fail this. - // Refactor to not be a naive line-by-line parse. - if (n !== Buffer.byteLength(line) + 1) - return set - - line = line.substr((n + ' ').length) - const kv = line.split('=') - const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') - if (!k) - return set - - const v = kv.join('=') - set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) - ? new Date(v * 1000) - : /^[0-9]+$/.test(v) ? +v - : v - return set +function trimSmallerBranches(branches) { + let maxPathSize = 0; + for (const { state } of branches) + if (state.path.length > maxPathSize) + maxPathSize = state.path.length; + return branches.filter(({ state }) => { + return state.path.length === maxPathSize; + }); } - -module.exports = Pax - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js": -/*!************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js ***! - \************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -const types = __webpack_require__(/*! ./types.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js") -const MiniPass = __webpack_require__(/*! minipass */ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js") - -const SLURP = Symbol('slurp') -module.exports = class ReadEntry extends MiniPass { - constructor (header, ex, gex) { - super() - // read entries always start life paused. this is to avoid the - // situation where Minipass's auto-ending empty streams results - // in an entry ending before we're ready for it. - this.pause() - this.extended = ex - this.globalExtended = gex - this.header = header - this.startBlockSize = 512 * Math.ceil(header.size / 512) - this.blockRemain = this.startBlockSize - this.remain = header.size - this.type = header.type - this.meta = false - this.ignore = false - switch (this.type) { - case 'File': - case 'OldFile': - case 'Link': - case 'SymbolicLink': - case 'CharacterDevice': - case 'BlockDevice': - case 'Directory': - case 'FIFO': - case 'ContiguousFile': - case 'GNUDumpDir': - break - - case 'NextFileHasLongLinkpath': - case 'NextFileHasLongPath': - case 'OldGnuLongPath': - case 'GlobalExtendedHeader': - case 'ExtendedHeader': - case 'OldExtendedHeader': - this.meta = true - break - - // NOTE: gnutar and bsdtar treat unrecognized types as 'File' - // it may be worth doing the same, but with a warning. - default: - this.ignore = true +function selectBestState(input, states) { + const terminalStates = states.filter(state => { + return state.selectedIndex !== null; + }); + if (terminalStates.length === 0) + throw new Error(); + const requiredOptionsSetStates = terminalStates.filter(state => state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name)))); + if (requiredOptionsSetStates.length === 0) { + throw new errors.UnknownSyntaxError(input, terminalStates.map(state => ({ + usage: state.candidateUsage, + reason: null, + }))); } - - this.path = header.path - this.mode = header.mode - if (this.mode) - this.mode = this.mode & 0o7777 - this.uid = header.uid - this.gid = header.gid - this.uname = header.uname - this.gname = header.gname - this.size = header.size - this.mtime = header.mtime - this.atime = header.atime - this.ctime = header.ctime - this.linkpath = header.linkpath - this.uname = header.uname - this.gname = header.gname - - if (ex) this[SLURP](ex) - if (gex) this[SLURP](gex, true) - } - - write (data) { - const writeLen = data.length - if (writeLen > this.blockRemain) - throw new Error('writing more to entry than is appropriate') - - const r = this.remain - const br = this.blockRemain - this.remain = Math.max(0, r - writeLen) - this.blockRemain = Math.max(0, br - writeLen) - if (this.ignore) - return true - - if (r >= writeLen) - return super.write(data) - - // r < writeLen - return super.write(data.slice(0, r)) - } - - [SLURP] (ex, global) { - for (let k in ex) { - // we slurp in everything except for the path attribute in - // a global extended header, because that's weird. - if (ex[k] !== null && ex[k] !== undefined && - !(global && k === 'path')) - this[k] = ex[k] + let maxPathSize = 0; + for (const state of requiredOptionsSetStates) + if (state.path.length > maxPathSize) + maxPathSize = state.path.length; + const bestPathBranches = requiredOptionsSetStates.filter(state => { + return state.path.length === maxPathSize; + }); + const getPositionalCount = (state) => state.positionals.filter(({ extra }) => { + return !extra; + }).length + state.options.length; + const statesWithPositionalCount = bestPathBranches.map(state => { + return { state, positionalCount: getPositionalCount(state) }; + }); + let maxPositionalCount = 0; + for (const { positionalCount } of statesWithPositionalCount) + if (positionalCount > maxPositionalCount) + maxPositionalCount = positionalCount; + const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => { + return positionalCount === maxPositionalCount; + }).map(({ state }) => { + return state; + }); + const fixedStates = aggregateHelpStates(bestPositionalStates); + if (fixedStates.length > 1) + throw new errors.AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage)); + return fixedStates[0]; +} +function aggregateHelpStates(states) { + const notHelps = []; + const helps = []; + for (const state of states) { + if (state.selectedIndex === constants.HELP_COMMAND_INDEX) { + helps.push(state); + } + else { + notHelps.push(state); + } } - } + if (helps.length > 0) { + notHelps.push({ + ...basicHelpState, + path: findCommonPrefix(...helps.map(state => state.path)), + options: helps.reduce((options, state) => options.concat(state.options), []), + }); + } + return notHelps; } - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/replace.js": -/*!*********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/replace.js ***! - \*********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -// tar -r -const hlo = __webpack_require__(/*! ./high-level-opt.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js") -const Pack = __webpack_require__(/*! ./pack.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pack.js") -const Parse = __webpack_require__(/*! ./parse.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js") -const fs = __webpack_require__(/*! fs */ "fs") -const fsm = __webpack_require__(/*! fs-minipass */ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js") -const t = __webpack_require__(/*! ./list.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/list.js") -const path = __webpack_require__(/*! path */ "path") - -// starting at the head of the file, read a Header -// If the checksum is invalid, that's our position to start writing -// If it is, jump forward by the specified size (round up to 512) -// and try again. -// Write the new Pack stream starting there. - -const Header = __webpack_require__(/*! ./header.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js") - -const r = module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) - - if (!opt.file) - throw new TypeError('file is required') - - if (opt.gzip) - throw new TypeError('cannot append to compressed archives') - - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') - - files = Array.from(files) - - return opt.sync ? replaceSync(opt, files) - : replace(opt, files, cb) +function findCommonPrefix(firstPath, secondPath, ...rest) { + if (secondPath === undefined) + return Array.from(firstPath); + return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest); +} +function makeNode() { + return { + dynamics: [], + shortcuts: [], + statics: {}, + }; +} +function isTerminalNode(node) { + return node === constants.NODE_SUCCESS || node === constants.NODE_ERRORED; +} +function cloneTransition(input, offset = 0) { + return { + to: !isTerminalNode(input.to) ? input.to > 2 ? input.to + offset - 2 : input.to + offset : input.to, + reducer: input.reducer, + }; +} +function cloneNode(input, offset = 0) { + const output = makeNode(); + for (const [test, transition] of input.dynamics) + output.dynamics.push([test, cloneTransition(transition, offset)]); + for (const transition of input.shortcuts) + output.shortcuts.push(cloneTransition(transition, offset)); + for (const [segment, transitions] of Object.entries(input.statics)) + output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset)); + return output; } - -const replaceSync = (opt, files) => { - const p = new Pack.Sync(opt) - - let threw = true - let fd - let position - - try { - try { - fd = fs.openSync(opt.file, 'r+') - } catch (er) { - if (er.code === 'ENOENT') - fd = fs.openSync(opt.file, 'w+') - else - throw er +function registerDynamic(machine, from, test, to, reducer) { + machine.nodes[from].dynamics.push([ + test, + { to, reducer: reducer }, + ]); +} +function registerShortcut(machine, from, to, reducer) { + machine.nodes[from].shortcuts.push({ to, reducer: reducer }); +} +function registerStatic(machine, from, test, to, reducer) { + const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test) + ? machine.nodes[from].statics[test] = [] + : machine.nodes[from].statics[test]; + store.push({ to, reducer: reducer }); +} +function execute(store, callback, state, segment) { + // TypeScript's control flow can't properly narrow + // generic conditionals for some mysterious reason + if (Array.isArray(callback)) { + const [name, ...args] = callback; + return store[name](state, segment, ...args); } - - const st = fs.fstatSync(fd) - const headBuf = Buffer.alloc(512) - - POSITION: for (position = 0; position < st.size; position += 512) { - for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { - bytes = fs.readSync( - fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos - ) - - if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) - throw new Error('cannot append to compressed archives') - - if (!bytes) - break POSITION - } - - let h = new Header(headBuf) - if (!h.cksumValid) - break - let entryBlockSize = 512 * Math.ceil(h.size / 512) - if (position + entryBlockSize + 512 > st.size) - break - // the 512 for the header we just parsed will be added as well - // also jump ahead all the blocks for the body - position += entryBlockSize - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime) + else { + return store[callback](state, segment); } - threw = false - - streamSync(opt, p, position, fd, files) - } finally { - if (threw) - try { fs.closeSync(fd) } catch (er) {} - } } - -const streamSync = (opt, p, position, fd, files) => { - const stream = new fsm.WriteStreamSync(opt.file, { - fd: fd, - start: position - }) - p.pipe(stream) - addFilesSync(p, files) +function suggest(callback, state) { + const fn = Array.isArray(callback) + ? tests[callback[0]] + : tests[callback]; + // @ts-ignore + if (typeof fn.suggest === `undefined`) + return null; + const args = Array.isArray(callback) + ? callback.slice(1) + : []; + // @ts-ignore + return fn.suggest(state, ...args); } - -const replace = (opt, files, cb) => { - files = Array.from(files) - const p = new Pack(opt) - - const getPos = (fd, size, cb_) => { - const cb = (er, pos) => { - if (er) - fs.close(fd, _ => cb_(er)) - else - cb_(null, pos) +const tests = { + always: () => { + return true; + }, + isOptionLike: (state, segment) => { + return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`)); + }, + isNotOptionLike: (state, segment) => { + return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`); + }, + isOption: (state, segment, name, hidden) => { + return !state.ignoreOptions && segment === name; + }, + isBatchOption: (state, segment, names) => { + return !state.ignoreOptions && constants.BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.includes(`-${name}`)); + }, + isBoundOption: (state, segment, names, options) => { + const optionParsing = segment.match(constants.BINDING_REGEX); + return !state.ignoreOptions && !!optionParsing && constants.OPTION_REGEX.test(optionParsing[1]) && names.includes(optionParsing[1]) + // Disallow bound options with no arguments (i.e. booleans) + && options.filter(opt => opt.names.includes(optionParsing[1])).every(opt => opt.allowBinding); + }, + isNegatedOption: (state, segment, name) => { + return !state.ignoreOptions && segment === `--no-${name.slice(2)}`; + }, + isHelp: (state, segment) => { + return !state.ignoreOptions && constants.HELP_REGEX.test(segment); + }, + isUnsupportedOption: (state, segment, names) => { + return !state.ignoreOptions && segment.startsWith(`-`) && constants.OPTION_REGEX.test(segment) && !names.includes(segment); + }, + isInvalidOption: (state, segment) => { + return !state.ignoreOptions && segment.startsWith(`-`) && !constants.OPTION_REGEX.test(segment); + }, +}; +// @ts-ignore +tests.isOption.suggest = (state, name, hidden = true) => { + return !hidden ? [name] : null; +}; +const reducers = { + setCandidateState: (state, segment, candidateState) => { + return { ...state, ...candidateState }; + }, + setSelectedIndex: (state, segment, index) => { + return { ...state, selectedIndex: index }; + }, + pushBatch: (state, segment) => { + return { ...state, options: state.options.concat([...segment.slice(1)].map(name => ({ name: `-${name}`, value: true }))) }; + }, + pushBound: (state, segment) => { + const [, name, value] = segment.match(constants.BINDING_REGEX); + return { ...state, options: state.options.concat({ name, value }) }; + }, + pushPath: (state, segment) => { + return { ...state, path: state.path.concat(segment) }; + }, + pushPositional: (state, segment) => { + return { ...state, positionals: state.positionals.concat({ value: segment, extra: false }) }; + }, + pushExtra: (state, segment) => { + return { ...state, positionals: state.positionals.concat({ value: segment, extra: true }) }; + }, + pushExtraNoLimits: (state, segment) => { + return { ...state, positionals: state.positionals.concat({ value: segment, extra: NoLimits }) }; + }, + pushTrue: (state, segment, name = segment) => { + return { ...state, options: state.options.concat({ name: segment, value: true }) }; + }, + pushFalse: (state, segment, name = segment) => { + return { ...state, options: state.options.concat({ name, value: false }) }; + }, + pushUndefined: (state, segment) => { + return { ...state, options: state.options.concat({ name: segment, value: undefined }) }; + }, + pushStringValue: (state, segment) => { + var _a; + const copy = { ...state, options: [...state.options] }; + const lastOption = state.options[state.options.length - 1]; + lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]); + return copy; + }, + setStringValue: (state, segment) => { + const copy = { ...state, options: [...state.options] }; + const lastOption = state.options[state.options.length - 1]; + lastOption.value = segment; + return copy; + }, + inhibateOptions: (state) => { + return { ...state, ignoreOptions: true }; + }, + useHelp: (state, segment, command) => { + const [, /* name */ , index] = segment.match(constants.HELP_REGEX); + if (typeof index !== `undefined`) { + return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] }; + } + else { + return { ...state, options: [{ name: `-c`, value: String(command) }] }; + } + }, + setError: (state, segment, errorMessage) => { + if (segment === constants.END_OF_INPUT) { + return { ...state, errorMessage: `${errorMessage}.` }; + } + else { + return { ...state, errorMessage: `${errorMessage} ("${segment}").` }; + } + }, + setOptionArityError: (state, segment) => { + const lastOption = state.options[state.options.length - 1]; + return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` }; + }, +}; +// ------------------------------------------------------------------------ +const NoLimits = Symbol(); +class CommandBuilder { + constructor(cliIndex, cliOpts) { + this.allOptionNames = []; + this.arity = { leading: [], trailing: [], extra: [], proxy: false }; + this.options = []; + this.paths = []; + this.cliIndex = cliIndex; + this.cliOpts = cliOpts; + } + addPath(path) { + this.paths.push(path); + } + setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) { + Object.assign(this.arity, { leading, trailing, extra, proxy }); + } + addPositional({ name = `arg`, required = true } = {}) { + if (!required && this.arity.extra === NoLimits) + throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`); + if (!required && this.arity.trailing.length > 0) + throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`); + if (!required && this.arity.extra !== NoLimits) { + this.arity.extra.push(name); + } + else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) { + this.arity.leading.push(name); + } + else { + this.arity.trailing.push(name); + } + } + addRest({ name = `arg`, required = 0 } = {}) { + if (this.arity.extra === NoLimits) + throw new Error(`Infinite lists cannot be declared multiple times in the same command`); + if (this.arity.trailing.length > 0) + throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`); + for (let t = 0; t < required; ++t) + this.addPositional({ name }); + this.arity.extra = NoLimits; } - - let position = 0 - if (size === 0) - return cb(null, 0) - - let bufPos = 0 - const headBuf = Buffer.alloc(512) - const onread = (er, bytes) => { - if (er) - return cb(er) - bufPos += bytes - if (bufPos < 512 && bytes) - return fs.read( - fd, headBuf, bufPos, headBuf.length - bufPos, - position + bufPos, onread - ) - - if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) - return cb(new Error('cannot append to compressed archives')) - - // truncated header - if (bufPos < 512) - return cb(null, position) - - const h = new Header(headBuf) - if (!h.cksumValid) - return cb(null, position) - - const entryBlockSize = 512 * Math.ceil(h.size / 512) - if (position + entryBlockSize + 512 > size) - return cb(null, position) - - position += entryBlockSize + 512 - if (position >= size) - return cb(null, position) - - if (opt.mtimeCache) - opt.mtimeCache.set(h.path, h.mtime) - bufPos = 0 - fs.read(fd, headBuf, 0, 512, position, onread) + addProxy({ required = 0 } = {}) { + this.addRest({ required }); + this.arity.proxy = true; } - fs.read(fd, headBuf, 0, 512, position, onread) - } - - const promise = new Promise((resolve, reject) => { - p.on('error', reject) - let flag = 'r+' - const onopen = (er, fd) => { - if (er && er.code === 'ENOENT' && flag === 'r+') { - flag = 'w+' - return fs.open(opt.file, flag, onopen) - } - - if (er) - return reject(er) - - fs.fstat(fd, (er, st) => { - if (er) - return reject(er) - getPos(fd, st.size, (er, position) => { - if (er) - return reject(er) - const stream = new fsm.WriteStream(opt.file, { - fd: fd, - start: position - }) - p.pipe(stream) - stream.on('error', reject) - stream.on('close', resolve) - addFilesAsync(p, files) - }) - }) + addOption({ names, description, arity = 0, hidden = false, required = false, allowBinding = true }) { + if (!allowBinding && arity > 1) + throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`); + if (!Number.isInteger(arity)) + throw new Error(`The arity must be an integer, got ${arity}`); + if (arity < 0) + throw new Error(`The arity must be positive, got ${arity}`); + this.allOptionNames.push(...names); + this.options.push({ names, description, arity, hidden, required, allowBinding }); + } + setContext(context) { + this.context = context; + } + usage({ detailed = true, inlineOptions = true } = {}) { + const segments = [this.cliOpts.binaryName]; + const detailedOptionList = []; + if (this.paths.length > 0) + segments.push(...this.paths[0]); + if (detailed) { + for (const { names, arity, hidden, description, required } of this.options) { + if (hidden) + continue; + const args = []; + for (let t = 0; t < arity; ++t) + args.push(` #${t}`); + const definition = `${names.join(`,`)}${args.join(``)}`; + if (!inlineOptions && description) { + detailedOptionList.push({ definition, description, required }); + } + else { + segments.push(required ? `<${definition}>` : `[${definition}]`); + } + } + segments.push(...this.arity.leading.map(name => `<${name}>`)); + if (this.arity.extra === NoLimits) + segments.push(`...`); + else + segments.push(...this.arity.extra.map(name => `[${name}]`)); + segments.push(...this.arity.trailing.map(name => `<${name}>`)); + } + const usage = segments.join(` `); + return { usage, options: detailedOptionList }; + } + compile() { + if (typeof this.context === `undefined`) + throw new Error(`Assertion failed: No context attached`); + const machine = makeStateMachine(); + let firstNode = constants.NODE_INITIAL; + const candidateUsage = this.usage().usage; + const requiredOptions = this.options + .filter(opt => opt.required) + .map(opt => opt.names); + firstNode = injectNode(machine, makeNode()); + registerStatic(machine, constants.NODE_INITIAL, constants.START_OF_INPUT, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]); + const positionalArgument = this.arity.proxy + ? `always` + : `isNotOptionLike`; + const paths = this.paths.length > 0 + ? this.paths + : [[]]; + for (const path of paths) { + let lastPathNode = firstNode; + // We allow options to be specified before the path. Note that we + // only do this when there is a path, otherwise there would be + // some redundancy with the options attached later. + if (path.length > 0) { + const optionPathNode = injectNode(machine, makeNode()); + registerShortcut(machine, lastPathNode, optionPathNode); + this.registerOptions(machine, optionPathNode); + lastPathNode = optionPathNode; + } + for (let t = 0; t < path.length; ++t) { + const nextPathNode = injectNode(machine, makeNode()); + registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`); + lastPathNode = nextPathNode; + } + if (this.arity.leading.length > 0 || !this.arity.proxy) { + const helpNode = injectNode(machine, makeNode()); + registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]); + registerStatic(machine, helpNode, constants.END_OF_INPUT, constants.NODE_SUCCESS, [`setSelectedIndex`, constants.HELP_COMMAND_INDEX]); + this.registerOptions(machine, lastPathNode); + } + if (this.arity.leading.length > 0) + registerStatic(machine, lastPathNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); + let lastLeadingNode = lastPathNode; + for (let t = 0; t < this.arity.leading.length; ++t) { + const nextLeadingNode = injectNode(machine, makeNode()); + if (!this.arity.proxy) + this.registerOptions(machine, nextLeadingNode); + if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) + registerStatic(machine, nextLeadingNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); + registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`); + lastLeadingNode = nextLeadingNode; + } + let lastExtraNode = lastLeadingNode; + if (this.arity.extra === NoLimits || this.arity.extra.length > 0) { + const extraShortcutNode = injectNode(machine, makeNode()); + registerShortcut(machine, lastLeadingNode, extraShortcutNode); + if (this.arity.extra === NoLimits) { + const extraNode = injectNode(machine, makeNode()); + if (!this.arity.proxy) + this.registerOptions(machine, extraNode); + registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`); + registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`); + registerShortcut(machine, extraNode, extraShortcutNode); + } + else { + for (let t = 0; t < this.arity.extra.length; ++t) { + const nextExtraNode = injectNode(machine, makeNode()); + if (!this.arity.proxy) + this.registerOptions(machine, nextExtraNode); + registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`); + registerShortcut(machine, nextExtraNode, extraShortcutNode); + lastExtraNode = nextExtraNode; + } + } + lastExtraNode = extraShortcutNode; + } + if (this.arity.trailing.length > 0) + registerStatic(machine, lastExtraNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); + let lastTrailingNode = lastExtraNode; + for (let t = 0; t < this.arity.trailing.length; ++t) { + const nextTrailingNode = injectNode(machine, makeNode()); + if (!this.arity.proxy) + this.registerOptions(machine, nextTrailingNode); + if (t + 1 < this.arity.trailing.length) + registerStatic(machine, nextTrailingNode, constants.END_OF_INPUT, constants.NODE_ERRORED, [`setError`, `Not enough positional arguments`]); + registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`); + lastTrailingNode = nextTrailingNode; + } + registerDynamic(machine, lastTrailingNode, positionalArgument, constants.NODE_ERRORED, [`setError`, `Extraneous positional argument`]); + registerStatic(machine, lastTrailingNode, constants.END_OF_INPUT, constants.NODE_SUCCESS, [`setSelectedIndex`, this.cliIndex]); + } + return { + machine, + context: this.context, + }; + } + registerOptions(machine, node) { + registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`); + registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, `pushBatch`); + registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`); + registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], constants.NODE_ERRORED, [`setError`, `Unsupported option name`]); + registerDynamic(machine, node, [`isInvalidOption`], constants.NODE_ERRORED, [`setError`, `Invalid option name`]); + for (const option of this.options) { + const longestName = option.names.reduce((longestName, name) => { + return name.length > longestName.length ? name : longestName; + }, ``); + if (option.arity === 0) { + for (const name of option.names) { + registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], node, `pushTrue`); + if (name.startsWith(`--`) && !name.startsWith(`--no-`)) { + registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, name]); + } + } + } + else { + // We inject a new node at the end of the state machine + let lastNode = injectNode(machine, makeNode()); + // We register transitions from the starting node to this new node + for (const name of option.names) + registerDynamic(machine, node, [`isOption`, name, option.hidden || name !== longestName], lastNode, `pushUndefined`); + // For each argument, we inject a new node at the end and we + // register a transition from the current node to this new node + for (let t = 0; t < option.arity; ++t) { + const nextNode = injectNode(machine, makeNode()); + // We can provide better errors when another option or END_OF_INPUT is encountered + registerStatic(machine, lastNode, constants.END_OF_INPUT, constants.NODE_ERRORED, `setOptionArityError`); + registerDynamic(machine, lastNode, `isOptionLike`, constants.NODE_ERRORED, `setOptionArityError`); + // If the option has a single argument, no need to store it in an array + const action = option.arity === 1 + ? `setStringValue` + : `pushStringValue`; + registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action); + lastNode = nextNode; + } + // In the end, we register a shortcut from + // the last node back to the starting node + registerShortcut(machine, lastNode, node); + } + } } - fs.open(opt.file, flag, onopen) - }) - - return cb ? promise.then(cb, cb) : promise -} - -const addFilesSync = (p, files) => { - files.forEach(file => { - if (file.charAt(0) === '@') - t({ - file: path.resolve(p.cwd, file.substr(1)), - sync: true, - noResume: true, - onentry: entry => p.add(entry) - }) - else - p.add(file) - }) - p.end() -} - -const addFilesAsync = (p, files) => { - while (files.length) { - const file = files.shift() - if (file.charAt(0) === '@') - return t({ - file: path.resolve(p.cwd, file.substr(1)), - noResume: true, - onentry: entry => p.add(entry) - }).then(_ => addFilesAsync(p, files)) - else - p.add(file) - } - p.end() -} - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js": -/*!*******************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js ***! - \*******************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// map types from key to human-friendly name -exports.name = new Map([ - ['0', 'File'], - // same as File - ['', 'OldFile'], - ['1', 'Link'], - ['2', 'SymbolicLink'], - // Devices and FIFOs aren't fully supported - // they are parsed, but skipped when unpacking - ['3', 'CharacterDevice'], - ['4', 'BlockDevice'], - ['5', 'Directory'], - ['6', 'FIFO'], - // same as File - ['7', 'ContiguousFile'], - // pax headers - ['g', 'GlobalExtendedHeader'], - ['x', 'ExtendedHeader'], - // vendor-specific stuff - // skip - ['A', 'SolarisACL'], - // like 5, but with data, which should be skipped - ['D', 'GNUDumpDir'], - // metadata only, skip - ['I', 'Inode'], - // data = link path of next file - ['K', 'NextFileHasLongLinkpath'], - // data = path of next file - ['L', 'NextFileHasLongPath'], - // skip - ['M', 'ContinuationFile'], - // like L - ['N', 'OldGnuLongPath'], - // skip - ['S', 'SparseFile'], - // skip - ['V', 'TapeVolumeHeader'], - // like x - ['X', 'OldExtendedHeader'] -]) - -// map the other direction -exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) - - -/***/ }), - -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/unpack.js": -/*!********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/unpack.js ***! - \********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -// the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. -// but the path reservations are required to avoid race conditions where -// parallelized unpack ops may mess with one another, due to dependencies -// (like a Link depending on its target) or destructive operations (like -// clobbering an fs object to create one of a different type.) - -const assert = __webpack_require__(/*! assert */ "assert") -const EE = __webpack_require__(/*! events */ "events").EventEmitter -const Parser = __webpack_require__(/*! ./parse.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/parse.js") -const fs = __webpack_require__(/*! fs */ "fs") -const fsm = __webpack_require__(/*! fs-minipass */ "./.yarn/cache/fs-minipass-npm-2.1.0-501ef87306-1b8d128dae.zip/node_modules/fs-minipass/index.js") -const path = __webpack_require__(/*! path */ "path") -const mkdir = __webpack_require__(/*! ./mkdir.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mkdir.js") -const mkdirSync = mkdir.sync -const wc = __webpack_require__(/*! ./winchars.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/winchars.js") -const pathReservations = __webpack_require__(/*! ./path-reservations.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/path-reservations.js") - -const ONENTRY = Symbol('onEntry') -const CHECKFS = Symbol('checkFs') -const CHECKFS2 = Symbol('checkFs2') -const ISREUSABLE = Symbol('isReusable') -const MAKEFS = Symbol('makeFs') -const FILE = Symbol('file') -const DIRECTORY = Symbol('directory') -const LINK = Symbol('link') -const SYMLINK = Symbol('symlink') -const HARDLINK = Symbol('hardlink') -const UNSUPPORTED = Symbol('unsupported') -const UNKNOWN = Symbol('unknown') -const CHECKPATH = Symbol('checkPath') -const MKDIR = Symbol('mkdir') -const ONERROR = Symbol('onError') -const PENDING = Symbol('pending') -const PEND = Symbol('pend') -const UNPEND = Symbol('unpend') -const ENDED = Symbol('ended') -const MAYBECLOSE = Symbol('maybeClose') -const SKIP = Symbol('skip') -const DOCHOWN = Symbol('doChown') -const UID = Symbol('uid') -const GID = Symbol('gid') -const crypto = __webpack_require__(/*! crypto */ "crypto") -const getFlag = __webpack_require__(/*! ./get-write-flag.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/get-write-flag.js") - -/* istanbul ignore next */ -const neverCalled = () => { - throw new Error('sync function called cb somehow?!?') -} - -// Unlinks on Windows are not atomic. -// -// This means that if you have a file entry, followed by another -// file entry with an identical name, and you cannot re-use the file -// (because it's a hardlink, or because unlink:true is set, or it's -// Windows, which does not have useful nlink values), then the unlink -// will be committed to the disk AFTER the new file has been written -// over the old one, deleting the new file. -// -// To work around this, on Windows systems, we rename the file and then -// delete the renamed file. It's a sloppy kludge, but frankly, I do not -// know of a better way to do this, given windows' non-atomic unlink -// semantics. -// -// See: https://github.com/npm/node-tar/issues/183 -/* istanbul ignore next */ -const unlinkFile = (path, cb) => { - if (process.platform !== 'win32') - return fs.unlink(path, cb) - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.rename(path, name, er => { - if (er) - return cb(er) - fs.unlink(name, cb) - }) -} - -/* istanbul ignore next */ -const unlinkFileSync = path => { - if (process.platform !== 'win32') - return fs.unlinkSync(path) - - const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') - fs.renameSync(path, name) - fs.unlinkSync(name) } - -// this.gid, entry.gid, this.processUid -const uint32 = (a, b, c) => - a === a >>> 0 ? a - : b === b >>> 0 ? b - : c - -class Unpack extends Parser { - constructor (opt) { - if (!opt) - opt = {} - - opt.ondone = _ => { - this[ENDED] = true - this[MAYBECLOSE]() +class CliBuilder { + constructor({ binaryName = `...` } = {}) { + this.builders = []; + this.opts = { binaryName }; } + static build(cbs, opts = {}) { + return new CliBuilder(opts).commands(cbs).compile(); + } + getBuilderByIndex(n) { + if (!(n >= 0 && n < this.builders.length)) + throw new Error(`Assertion failed: Out-of-bound command index (${n})`); + return this.builders[n]; + } + commands(cbs) { + for (const cb of cbs) + cb(this.command()); + return this; + } + command() { + const builder = new CommandBuilder(this.builders.length, this.opts); + this.builders.push(builder); + return builder; + } + compile() { + const machines = []; + const contexts = []; + for (const builder of this.builders) { + const { machine, context } = builder.compile(); + machines.push(machine); + contexts.push(context); + } + const machine = makeAnyOfMachine(machines); + simplifyMachine(machine); + return { + machine, + contexts, + process: (input) => { + return runMachine(machine, input); + }, + suggest: (input, partial) => { + return suggestMachine(machine, input, partial); + }, + }; + } +} - super(opt) - - this.reservations = pathReservations() - - this.transform = typeof opt.transform === 'function' ? opt.transform : null - - this.writable = true - this.readable = false +exports.CliBuilder = CliBuilder; +exports.CommandBuilder = CommandBuilder; +exports.NoLimits = NoLimits; +exports.aggregateHelpStates = aggregateHelpStates; +exports.cloneNode = cloneNode; +exports.cloneTransition = cloneTransition; +exports.debug = debug; +exports.debugMachine = debugMachine; +exports.execute = execute; +exports.injectNode = injectNode; +exports.isTerminalNode = isTerminalNode; +exports.makeAnyOfMachine = makeAnyOfMachine; +exports.makeNode = makeNode; +exports.makeStateMachine = makeStateMachine; +exports.reducers = reducers; +exports.registerDynamic = registerDynamic; +exports.registerShortcut = registerShortcut; +exports.registerStatic = registerStatic; +exports.runMachineInternal = runMachineInternal; +exports.selectBestState = selectBestState; +exports.simplifyMachine = simplifyMachine; +exports.suggest = suggest; +exports.tests = tests; +exports.trimSmallerBranches = trimSmallerBranches; - this[PENDING] = 0 - this[ENDED] = false - this.dirCache = opt.dirCache || new Map() +/***/ }), - if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { - // need both or neither - if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') - throw new TypeError('cannot set owner without number uid and gid') - if (opt.preserveOwner) - throw new TypeError( - 'cannot preserve owner in archive and also set owner explicitly') - this.uid = opt.uid - this.gid = opt.gid - this.setOwner = true - } else { - this.uid = null - this.gid = null - this.setOwner = false - } +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/errors.js": +/*!******************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/errors.js ***! + \******************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - // default true for root - if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') - this.preserveOwner = process.getuid && process.getuid() === 0 - else - this.preserveOwner = !!opt.preserveOwner +"use strict"; - this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? - process.getuid() : null - this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? - process.getgid() : null - // mostly just for testing, but useful in some cases. - // Forcibly trigger a chown on every entry, no matter what - this.forceChown = opt.forceChown === true +Object.defineProperty(exports, "__esModule", ({ value: true })); - // turn > candidate.reason !== null && candidate.reason === candidates[0].reason)) { + const [{ reason }] = this.candidates; + this.message = `${reason}\n\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\n`)}`; + } + else if (this.candidates.length === 1) { + const [{ usage }] = this.candidates; + this.message = `Command not found; did you mean:\n\n$ ${usage}\n${whileRunning(input)}`; + } + else { + this.message = `Command not found; did you mean one of:\n\n${this.candidates.map(({ usage }, index) => { + return `${`${index}.`.padStart(4)} ${usage}`; + }).join(`\n`)}\n\n${whileRunning(input)}`; + } + } +} +class AmbiguousSyntaxError extends Error { + constructor(input, usages) { + super(); + this.input = input; + this.usages = usages; + this.clipanion = { type: `none` }; + this.name = `AmbiguousSyntaxError`; + this.message = `Cannot find which to pick amongst the following alternatives:\n\n${this.usages.map((usage, index) => { + return `${`${index}.`.padStart(4)} ${usage}`; + }).join(`\n`)}\n\n${whileRunning(input)}`; + } +} +const whileRunning = (input) => `While running ${input.filter(token => { + return token !== constants.END_OF_INPUT; +}).map(token => { + const json = JSON.stringify(token); + if (token.match(/\s/) || token.length === 0 || json !== `"${token}"`) { + return json; + } + else { + return token; + } +}).join(` `)}`; - // do not unpack over ANY files - this.keep = !!opt.keep +exports.AmbiguousSyntaxError = AmbiguousSyntaxError; +exports.UnknownSyntaxError = UnknownSyntaxError; +exports.UsageError = UsageError; - // do not set mtime/atime of extracted entries - this.noMtime = !!opt.noMtime - // allow .., absolute path entries, and unpacking through symlinks - // without this, warn and skip .., relativize absolutes, and error - // on symlinks in extraction path - this.preservePaths = !!opt.preservePaths +/***/ }), - // unlink files and links before writing. This breaks existing hard - // links, and removes symlink directories rather than erroring - this.unlink = !!opt.unlink +/***/ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/format.js": +/*!******************************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/format.js ***! + \******************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { - this.cwd = path.resolve(opt.cwd || process.cwd()) - this.strip = +opt.strip || 0 - this.processUmask = process.umask() - this.umask = typeof opt.umask === 'number' ? opt.umask : this.processUmask - // default mode for dirs created as parents - this.dmode = opt.dmode || (0o0777 & (~this.umask)) - this.fmode = opt.fmode || (0o0666 & (~this.umask)) - this.on('entry', entry => this[ONENTRY](entry)) - } +"use strict"; - // a bad or damaged archive is a warning for Parser, but an error - // when extracting. Mark those errors as unrecoverable, because - // the Unpack contract cannot be met. - warn (code, msg, data = {}) { - if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') - data.recoverable = false - return super.warn(code, msg, data) - } - [MAYBECLOSE] () { - if (this[ENDED] && this[PENDING] === 0) { - this.emit('prefinish') - this.emit('finish') - this.emit('end') - this.emit('close') +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const MAX_LINE_LENGTH = 80; +const richLine = Array(MAX_LINE_LENGTH).fill(`━`); +for (let t = 0; t <= 24; ++t) + richLine[richLine.length - t] = `\x1b[38;5;${232 + t}m━`; +const richFormat = { + header: str => `\x1b[1m━━━ ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\x1b[0m`, + bold: str => `\x1b[1m${str}\x1b[22m`, + error: str => `\x1b[31m\x1b[1m${str}\x1b[22m\x1b[39m`, + code: str => `\x1b[36m${str}\x1b[39m`, +}; +const textFormat = { + header: str => str, + bold: str => str, + error: str => str, + code: str => str, +}; +function dedent(text) { + const lines = text.split(`\n`); + const nonEmptyLines = lines.filter(line => line.match(/\S/)); + const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0; + return lines + .map(line => line.slice(indent).trimRight()) + .join(`\n`); +} +function formatMarkdownish(text, { format, paragraphs }) { + // Enforce \n as newline character + text = text.replace(/\r\n?/g, `\n`); + // Remove the indentation, since it got messed up with the JS indentation + text = dedent(text); + // Remove surrounding newlines, since they got added for JS formatting + text = text.replace(/^\n+|\n+$/g, ``); + // List items always end with at least two newlines (in order to not be collapsed) + text = text.replace(/^(\s*)-([^\n]*?)\n+/gm, `$1-$2\n\n`); + // Single newlines are removed; larger than that are collapsed into one + text = text.replace(/\n(\n)?\n*/g, `$1`); + if (paragraphs) { + text = text.split(/\n/).map(paragraph => { + // Does the paragraph starts with a list? + const bulletMatch = paragraph.match(/^\s*[*-][\t ]+(.*)/); + if (!bulletMatch) + // No, cut the paragraphs into segments of 80 characters + return paragraph.match(/(.{1,80})(?: |$)/g).join(`\n`); + const indent = paragraph.length - paragraph.trimStart().length; + // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix) + return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => { + return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line; + }).join(`\n`); + }).join(`\n\n`); } - } + // Highlight the code segments + text = text.replace(/(`+)((?:.|[\n])*?)\1/g, ($0, $1, $2) => { + return format.code($1 + $2 + $1); + }); + // Highlight the code segments + text = text.replace(/(\*\*)((?:.|[\n])*?)\1/g, ($0, $1, $2) => { + return format.bold($1 + $2 + $1); + }); + return text ? `${text}\n` : ``; +} - [CHECKPATH] (entry) { - if (this.strip) { - const parts = entry.path.split(/\/|\\/) - if (parts.length < this.strip) - return false - entry.path = parts.slice(this.strip).join('/') +exports.formatMarkdownish = formatMarkdownish; +exports.richFormat = richFormat; +exports.textFormat = textFormat; - if (entry.type === 'Link') { - const linkparts = entry.linkpath.split(/\/|\\/) - if (linkparts.length >= this.strip) - entry.linkpath = linkparts.slice(this.strip).join('/') - } - } - if (!this.preservePaths) { - const p = entry.path - if (p.match(/(^|\/|\\)\.\.(\\|\/|$)/)) { - this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { - entry, - path: p, - }) - return false - } +/***/ }), - // absolutes on posix are also absolutes on win32 - // so we only need to test this one to get both - if (path.win32.isAbsolute(p)) { - const parsed = path.win32.parse(p) - entry.path = p.substr(parsed.root.length) - const r = parsed.root - this.warn('TAR_ENTRY_INFO', `stripping ${r} from absolute path`, { - entry, - path: p, - }) - } - } +/***/ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/browser.js": +/*!*******************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/browser.js ***! + \*******************************************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { - // only encode : chars that aren't drive letter indicators - if (this.win32) { - const parsed = path.win32.parse(entry.path) - entry.path = parsed.root === '' ? wc.encode(entry.path) - : parsed.root + wc.encode(entry.path.substr(parsed.root.length)) - } +/* eslint-env browser */ - if (path.isAbsolute(entry.path)) - entry.absolute = entry.path - else - entry.absolute = path.resolve(this.cwd, entry.path) +/** + * This is the web browser implementation of `debug()`. + */ - return true - } +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - [ONENTRY] (entry) { - if (!this[CHECKPATH](entry)) - return entry.resume() + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); - assert.equal(typeof entry.absolute, 'string') +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; - switch (entry.type) { - case 'Directory': - case 'GNUDumpDir': - if (entry.mode) - entry.mode = entry.mode | 0o700 +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - case 'File': - case 'OldFile': - case 'ContiguousFile': - case 'Link': - case 'SymbolicLink': - return this[CHECKFS](entry) +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } - case 'CharacterDevice': - case 'BlockDevice': - case 'FIFO': - return this[UNSUPPORTED](entry) - } - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - [ONERROR] (er, entry) { - // Cwd has to exist, or else nothing works. That's serious. - // Other errors are warnings, which raise the error in strict - // mode, but otherwise continue on. - if (er.name === 'CwdError') - this.emit('error', er) - else { - this.warn('TAR_ENTRY_ERROR', er, {entry}) - this[UNPEND]() - entry.resume() - } - } + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} - [MKDIR] (dir, mode, cb) { - mkdir(dir, { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode: mode - }, cb) - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - [DOCHOWN] (entry) { - // in preserve owner mode, chown if the entry doesn't match process - // in set owner mode, chown if setting doesn't match process - return this.forceChown || - this.preserveOwner && - ( typeof entry.uid === 'number' && entry.uid !== this.processUid || - typeof entry.gid === 'number' && entry.gid !== this.processGid ) - || - ( typeof this.uid === 'number' && this.uid !== this.processUid || - typeof this.gid === 'number' && this.gid !== this.processGid ) - } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - [UID] (entry) { - return uint32(this.uid, entry.uid, this.processUid) - } + if (!this.useColors) { + return; + } - [GID] (entry) { - return uint32(this.gid, entry.gid, this.processGid) - } + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - [FILE] (entry, fullyDone) { - const mode = entry.mode & 0o7777 || this.fmode - const stream = new fsm.WriteStream(entry.absolute, { - flags: getFlag(entry.size), - mode: mode, - autoClose: false - }) - stream.on('error', er => this[ONERROR](er, entry)) + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - let actions = 1 - const done = er => { - if (er) - return this[ONERROR](er, entry) + args.splice(lastC, 0, c); +} - if (--actions === 0) { - fs.close(stream.fd, er => { - fullyDone() - er ? this[ONERROR](er, entry) : this[UNPEND]() - }) - } - } +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - stream.on('finish', _ => { - // if futimes fails, try utimes - // if utimes fails, fail with the original error - // same for fchown/chown - const abs = entry.absolute - const fd = stream.fd +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - if (entry.mtime && !this.noMtime) { - actions++ - const atime = entry.atime || new Date() - const mtime = entry.mtime - fs.futimes(fd, atime, mtime, er => - er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) - : done()) - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - if (this[DOCHOWN](entry)) { - actions++ - const uid = this[UID](entry) - const gid = this[GID](entry) - fs.fchown(fd, uid, gid, er => - er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) - : done()) - } + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - done() - }) + return r; +} - const tx = this.transform ? this.transform(entry) || entry : entry - if (tx !== entry) { - tx.on('error', er => this[ONERROR](er, entry)) - entry.pipe(tx) - } - tx.pipe(stream) - } +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - [DIRECTORY] (entry, fullyDone) { - const mode = entry.mode & 0o7777 || this.dmode - this[MKDIR](entry.absolute, mode, er => { - if (er) { - fullyDone() - return this[ONERROR](er, entry) - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - let actions = 1 - const done = _ => { - if (--actions === 0) { - fullyDone() - this[UNPEND]() - entry.resume() - } - } +module.exports = __webpack_require__(/*! ./common */ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/common.js")(exports); - if (entry.mtime && !this.noMtime) { - actions++ - fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) - } +const {formatters} = module.exports; - if (this[DOCHOWN](entry)) { - actions++ - fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - done() - }) - } +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - [UNSUPPORTED] (entry) { - entry.unsupported = true - this.warn('TAR_ENTRY_UNSUPPORTED', - `unsupported entry type: ${entry.type}`, {entry}) - entry.resume() - } - [SYMLINK] (entry, done) { - this[LINK](entry, entry.linkpath, 'symlink', done) - } +/***/ }), - [HARDLINK] (entry, done) { - this[LINK](entry, path.resolve(this.cwd, entry.linkpath), 'link', done) - } +/***/ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/common.js": +/*!******************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/common.js ***! + \******************************************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - [PEND] () { - this[PENDING]++ - } - [UNPEND] () { - this[PENDING]-- - this[MAYBECLOSE]() - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - [SKIP] (entry) { - this[UNPEND]() - entry.resume() - } +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(/*! ms */ "../../../.yarn/berry/cache/ms-npm-2.1.2-ec0c1512ff-9.zip/node_modules/ms/index.js"); + createDebug.destroy = destroy; - // Check if we can reuse an existing filesystem entry safely and - // overwrite it, rather than unlinking and recreating - // Windows doesn't report a useful nlink, so we just never reuse entries - [ISREUSABLE] (entry, st) { - return entry.type === 'File' && - !this.unlink && - st.isFile() && - st.nlink <= 1 && - process.platform !== 'win32' - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - // check if a thing is there, and if so, try to clobber it - [CHECKFS] (entry) { - this[PEND]() - const paths = [entry.path] - if (entry.linkpath) - paths.push(entry.linkpath) - this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) - } - [CHECKFS2] (entry, done) { - this[MKDIR](path.dirname(entry.absolute), this.dmode, er => { - if (er) { - done() - return this[ONERROR](er, entry) - } - fs.lstat(entry.absolute, (er, st) => { - if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { - this[SKIP](entry) - done() - } else if (er || this[ISREUSABLE](entry, st)) { - this[MAKEFS](null, entry, done) - } - else if (st.isDirectory()) { - if (entry.type === 'Directory') { - if (!entry.mode || (st.mode & 0o7777) === entry.mode) - this[MAKEFS](null, entry, done) - else - fs.chmod(entry.absolute, entry.mode, - er => this[MAKEFS](er, entry, done)) - } else - fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) - } else - unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) - }) - }) - } + /** + * The currently active debug mode names, and names to skip. + */ - [MAKEFS] (er, entry, done) { - if (er) - return this[ONERROR](er, entry) + createDebug.names = []; + createDebug.skips = []; - switch (entry.type) { - case 'File': - case 'OldFile': - case 'ContiguousFile': - return this[FILE](entry, done) + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - case 'Link': - return this[HARDLINK](entry, done) + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - case 'SymbolicLink': - return this[SYMLINK](entry, done) + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - case 'Directory': - case 'GNUDumpDir': - return this[DIRECTORY](entry, done) - } - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - [LINK] (entry, linkpath, link, done) { - // XXX: get the type ('file' or 'dir') for windows - fs[link](linkpath, entry.absolute, er => { - if (er) - return this[ONERROR](er, entry) - done() - this[UNPEND]() - entry.resume() - }) - } -} + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; -class UnpackSync extends Unpack { - constructor (opt) { - super(opt) - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - [CHECKFS] (entry) { - const er = this[MKDIR](path.dirname(entry.absolute), this.dmode, neverCalled) - if (er) - return this[ONERROR](er, entry) - try { - const st = fs.lstatSync(entry.absolute) - if (this.keep || this.newer && st.mtime > entry.mtime) - return this[SKIP](entry) - else if (this[ISREUSABLE](entry, st)) - return this[MAKEFS](null, entry, neverCalled) - else { - try { - if (st.isDirectory()) { - if (entry.type === 'Directory') { - if (entry.mode && (st.mode & 0o7777) !== entry.mode) - fs.chmodSync(entry.absolute, entry.mode) - } else - fs.rmdirSync(entry.absolute) - } else - unlinkFileSync(entry.absolute) - return this[MAKEFS](null, entry, neverCalled) - } catch (er) { - return this[ONERROR](er, entry) - } - } - } catch (er) { - return this[MAKEFS](null, entry, neverCalled) - } - } + const self = debug; - [FILE] (entry, _) { - const mode = entry.mode & 0o7777 || this.fmode + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - const oner = er => { - let closeError - try { - fs.closeSync(fd) - } catch (e) { - closeError = e - } - if (er || closeError) - this[ONERROR](er || closeError, entry) - } + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - let stream - let fd - try { - fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) - } catch (er) { - return oner(er) - } - const tx = this.transform ? this.transform(entry) || entry : entry - if (tx !== entry) { - tx.on('error', er => this[ONERROR](er, entry)) - entry.pipe(tx) - } + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - tx.on('data', chunk => { - try { - fs.writeSync(fd, chunk, 0, chunk.length) - } catch (er) { - oner(er) - } - }) + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - tx.on('end', _ => { - let er = null - // try both, falling futimes back to utimes - // if either fails, handle the first error - if (entry.mtime && !this.noMtime) { - const atime = entry.atime || new Date() - const mtime = entry.mtime - try { - fs.futimesSync(fd, atime, mtime) - } catch (futimeser) { - try { - fs.utimesSync(entry.absolute, atime, mtime) - } catch (utimeser) { - er = futimeser - } - } - } + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - if (this[DOCHOWN](entry)) { - const uid = this[UID](entry) - const gid = this[GID](entry) + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - try { - fs.fchownSync(fd, uid, gid) - } catch (fchowner) { - try { - fs.chownSync(entry.absolute, uid, gid) - } catch (chowner) { - er = er || fchowner - } - } - } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - oner(er) - }) - } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - [DIRECTORY] (entry, _) { - const mode = entry.mode & 0o7777 || this.dmode - const er = this[MKDIR](entry.absolute, mode) - if (er) - return this[ONERROR](er, entry) - if (entry.mtime && !this.noMtime) { - try { - fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) - } catch (er) {} - } - if (this[DOCHOWN](entry)) { - try { - fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) - } catch (er) {} - } - entry.resume() - } + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - [MKDIR] (dir, mode) { - try { - return mkdir.sync(dir, { - uid: this.uid, - gid: this.gid, - processUid: this.processUid, - processGid: this.processGid, - umask: this.processUmask, - preserve: this.preservePaths, - unlink: this.unlink, - cache: this.dirCache, - cwd: this.cwd, - mode: mode - }) - } catch (er) { - return er - } - } + return debug; + } - [LINK] (entry, linkpath, link, _) { - try { - fs[link + 'Sync'](linkpath, entry.absolute) - entry.resume() - } catch (er) { - return this[ONERROR](er, entry) - } - } -} + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -Unpack.Sync = UnpackSync -module.exports = Unpack + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; -/***/ }), + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/update.js": -/*!********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/update.js ***! - \********************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -"use strict"; + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -// tar -u + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -const hlo = __webpack_require__(/*! ./high-level-opt.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/high-level-opt.js") -const r = __webpack_require__(/*! ./replace.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/replace.js") -// just call tar.r with the filter and mtimeCache + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -const u = module.exports = (opt_, files, cb) => { - const opt = hlo(opt_) + let i; + let len; - if (!opt.file) - throw new TypeError('file is required') + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - if (opt.gzip) - throw new TypeError('cannot append to compressed archives') + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - if (!files || !Array.isArray(files) || !files.length) - throw new TypeError('no files or directories specified') + return false; + } - files = Array.from(files) + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - mtimeFilter(opt) - return r(opt, files, cb) -} + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -const mtimeFilter = opt => { - const filter = opt.filter + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - if (!opt.mtimeCache) - opt.mtimeCache = new Map() + createDebug.enable(createDebug.load()); - opt.filter = filter ? (path, stat) => - filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) - : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) + return createDebug; } +module.exports = setup; + /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/warn-mixin.js": -/*!************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/warn-mixin.js ***! - \************************************************************************************************/ -/***/ ((module) => { +/***/ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/index.js": +/*!*****************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/index.js ***! + \*****************************************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -module.exports = Base => class extends Base { - warn (code, message, data = {}) { - if (this.file) - data.file = this.file - if (this.cwd) - data.cwd = this.cwd - data.code = message instanceof Error && message.code || code - data.tarCode = code - if (!this.strict && data.recoverable !== false) { - if (message instanceof Error) { - data = Object.assign(message, data) - message = message.message - } - this.emit('warn', data.tarCode, message, data) - } else if (message instanceof Error) { - this.emit('error', Object.assign(message, data)) - } else - this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) - } +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __webpack_require__(/*! ./browser.js */ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/browser.js"); +} else { + module.exports = __webpack_require__(/*! ./node.js */ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/node.js"); } /***/ }), -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/winchars.js": -/*!**********************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/winchars.js ***! - \**********************************************************************************************/ -/***/ ((module) => { +/***/ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/node.js": +/*!****************************************************************************************************************************************!*\ + !*** ./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/node.js ***! + \****************************************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { -"use strict"; +/** + * Module dependencies. + */ +const tty = __webpack_require__(/*! tty */ "tty"); +const util = __webpack_require__(/*! util */ "util"); -// When writing files on Windows, translate the characters to their -// 0xf000 higher-encoded versions. +/** + * This is the Node.js implementation of `debug()`. + */ -const raw = [ - '|', - '<', - '>', - '?', - ':' -] +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); -const win = raw.map(char => - String.fromCharCode(0xf000 + char.charCodeAt(0))) +/** + * Colors. + */ -const toWin = new Map(raw.map((char, i) => [char, win[i]])) -const toRaw = new Map(win.map((char, i) => [char, raw[i]])) +exports.colors = [6, 2, 3, 4, 5, 1]; -module.exports = { - encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), - decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s) +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __webpack_require__(/*! supports-color */ "../../../.yarn/berry/cache/supports-color-npm-9.2.2-d003069e84-9.zip/node_modules/supports-color/index.js"); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -/***/ }), +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); -/***/ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/write-entry.js": -/*!*************************************************************************************************!*\ - !*** ./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/write-entry.js ***! - \*************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } -"use strict"; + obj[prop] = val; + return obj; +}, {}); -const MiniPass = __webpack_require__(/*! minipass */ "./.yarn/cache/minipass-npm-3.1.1-b51d7e264d-cfcfd86adc.zip/node_modules/minipass/index.js") -const Pax = __webpack_require__(/*! ./pax.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/pax.js") -const Header = __webpack_require__(/*! ./header.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/header.js") -const ReadEntry = __webpack_require__(/*! ./read-entry.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/read-entry.js") -const fs = __webpack_require__(/*! fs */ "fs") -const path = __webpack_require__(/*! path */ "path") +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ -const types = __webpack_require__(/*! ./types.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/types.js") -const maxReadSize = 16 * 1024 * 1024 -const PROCESS = Symbol('process') -const FILE = Symbol('file') -const DIRECTORY = Symbol('directory') -const SYMLINK = Symbol('symlink') -const HARDLINK = Symbol('hardlink') -const HEADER = Symbol('header') -const READ = Symbol('read') -const LSTAT = Symbol('lstat') -const ONLSTAT = Symbol('onlstat') -const ONREAD = Symbol('onread') -const ONREADLINK = Symbol('onreadlink') -const OPENFILE = Symbol('openfile') -const ONOPENFILE = Symbol('onopenfile') -const CLOSE = Symbol('close') -const MODE = Symbol('mode') -const warner = __webpack_require__(/*! ./warn-mixin.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/warn-mixin.js") -const winchars = __webpack_require__(/*! ./winchars.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/winchars.js") +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} -const modeFix = __webpack_require__(/*! ./mode-fix.js */ "./.yarn/cache/tar-npm-6.0.1-aedef672fb-498c4a5671.zip/node_modules/tar/lib/mode-fix.js") +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -const WriteEntry = warner(class WriteEntry extends MiniPass { - constructor (p, opt) { - opt = opt || {} - super(opt) - if (typeof p !== 'string') - throw new TypeError('path is required') - this.path = p - // suppress atime, ctime, uid, gid, uname, gname - this.portable = !!opt.portable - // until node has builtin pwnam functions, this'll have to do - this.myuid = process.getuid && process.getuid() - this.myuser = process.env.USER || '' - this.maxReadSize = opt.maxReadSize || maxReadSize - this.linkCache = opt.linkCache || new Map() - this.statCache = opt.statCache || new Map() - this.preservePaths = !!opt.preservePaths - this.cwd = opt.cwd || process.cwd() - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - this.mtime = opt.mtime || null +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - let pathWarn = false - if (!this.preservePaths && path.win32.isAbsolute(p)) { - // absolutes on posix are also absolutes on win32 - // so we only need to test this one to get both - const parsed = path.win32.parse(p) - this.path = p.substr(parsed.root.length) - pathWarn = parsed.root - } +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} - this.win32 = !!opt.win32 || process.platform === 'win32' - if (this.win32) { - this.path = winchars.decode(this.path.replace(/\\/g, '/')) - p = p.replace(/\\/g, '/') - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} - this.absolute = opt.absolute || path.resolve(this.cwd, p) +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - if (this.path === '') - this.path = './' +function load() { + return process.env.DEBUG; +} - if (pathWarn) { - this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path, - }) - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - if (this.statCache.has(this.absolute)) - this[ONLSTAT](this.statCache.get(this.absolute)) - else - this[LSTAT]() - } +function init(debug) { + debug.inspectOpts = {}; - [LSTAT] () { - fs.lstat(this.absolute, (er, stat) => { - if (er) - return this.emit('error', er) - this[ONLSTAT](stat) - }) - } + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - [ONLSTAT] (stat) { - this.statCache.set(this.absolute, stat) - this.stat = stat - if (!stat.isFile()) - stat.size = 0 - this.type = getType(stat) - this.emit('stat', stat) - this[PROCESS]() - } +module.exports = __webpack_require__(/*! ./common */ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/common.js")(exports); - [PROCESS] () { - switch (this.type) { - case 'File': return this[FILE]() - case 'Directory': return this[DIRECTORY]() - case 'SymbolicLink': return this[SYMLINK]() - // unsupported types are ignored. - default: return this.end() - } - } +const {formatters} = module.exports; - [MODE] (mode) { - return modeFix(mode, this.type === 'Directory', this.portable) - } +/** + * Map %o to `util.inspect()`, all on a single line. + */ - [HEADER] () { - if (this.type === 'Directory' && this.portable) - this.noMtime = true +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; - this.header = new Header({ - path: this.path, - linkpath: this.linkpath, - // only the permissions and setuid/setgid/sticky bitflags - // not the higher-order bits that specify file type - mode: this[MODE](this.stat.mode), - uid: this.portable ? null : this.stat.uid, - gid: this.portable ? null : this.stat.gid, - size: this.stat.size, - mtime: this.noMtime ? null : this.mtime || this.stat.mtime, - type: this.type, - uname: this.portable ? null : - this.stat.uid === this.myuid ? this.myuser : '', - atime: this.portable ? null : this.stat.atime, - ctime: this.portable ? null : this.stat.ctime - }) +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - if (this.header.encode() && !this.noPax) - this.write(new Pax({ - atime: this.portable ? null : this.header.atime, - ctime: this.portable ? null : this.header.ctime, - gid: this.portable ? null : this.header.gid, - mtime: this.noMtime ? null : this.mtime || this.header.mtime, - path: this.path, - linkpath: this.linkpath, - size: this.header.size, - uid: this.portable ? null : this.header.uid, - uname: this.portable ? null : this.header.uname, - dev: this.portable ? null : this.stat.dev, - ino: this.portable ? null : this.stat.ino, - nlink: this.portable ? null : this.stat.nlink - }).encode()) - this.write(this.header.block) - } +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - [DIRECTORY] () { - if (this.path.substr(-1) !== '/') - this.path += '/' - this.stat.size = 0 - this[HEADER]() - this.end() - } - [SYMLINK] () { - fs.readlink(this.absolute, (er, linkpath) => { - if (er) - return this.emit('error', er) - this[ONREADLINK](linkpath) - }) - } +/***/ }), - [ONREADLINK] (linkpath) { - this.linkpath = linkpath.replace(/\\/g, '/') - this[HEADER]() - this.end() - } +/***/ "./sources/Engine.ts": +/*!***************************!*\ + !*** ./sources/Engine.ts ***! + \***************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - [HARDLINK] (linkpath) { - this.type = 'Link' - this.linkpath = path.relative(this.cwd, linkpath).replace(/\\/g, '/') - this.stat.size = 0 - this[HEADER]() - this.end() - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Engine": () => (/* binding */ Engine) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js"); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _config_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../config.json */ "./config.json"); +/* harmony import */ var _corepackUtils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./corepackUtils */ "./sources/corepackUtils.ts"); +/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./folderUtils */ "./sources/folderUtils.ts"); +/* harmony import */ var _semverUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./semverUtils */ "./sources/semverUtils.ts"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./sources/types.ts"); - [FILE] () { - if (this.stat.nlink > 1) { - const linkKey = this.stat.dev + ':' + this.stat.ino - if (this.linkCache.has(linkKey)) { - const linkpath = this.linkCache.get(linkKey) - if (linkpath.indexOf(this.cwd) === 0) - return this[HARDLINK](linkpath) - } - this.linkCache.set(linkKey, this.absolute) - } - this[HEADER]() - if (this.stat.size === 0) - return this.end() - this[OPENFILE]() - } - [OPENFILE] () { - fs.open(this.absolute, 'r', (er, fd) => { - if (er) - return this.emit('error', er) - this[ONOPENFILE](fd) - }) - } - [ONOPENFILE] (fd) { - const blockLen = 512 * Math.ceil(this.stat.size / 512) - const bufLen = Math.min(blockLen, this.maxReadSize) - const buf = Buffer.allocUnsafe(bufLen) - this[READ](fd, buf, 0, buf.length, 0, this.stat.size, blockLen) - } - [READ] (fd, buf, offset, length, pos, remain, blockRemain) { - fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { - if (er) { - // ignoring the error from close(2) is a bad practice, but at - // this point we already have an error, don't need another one - return this[CLOSE](fd, () => this.emit('error', er)) - } - this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead) - }) - } - [CLOSE] (fd, cb) { - fs.close(fd, cb) - } - [ONREAD] (fd, buf, offset, length, pos, remain, blockRemain, bytesRead) { - if (bytesRead <= 0 && remain > 0) { - const er = new Error('encountered unexpected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](fd, () => this.emit('error', er)) + +class Engine { + constructor(config = _config_json__WEBPACK_IMPORTED_MODULE_3__) { + this.config = config; + } + getPackageManagerFor(binaryName) { + for (const packageManager of _types__WEBPACK_IMPORTED_MODULE_7__.SupportedPackageManagerSet) { + for (const rangeDefinition of Object.values(this.config.definitions[packageManager].ranges)) { + const bins = Array.isArray(rangeDefinition.bin) + ? rangeDefinition.bin + : Object.keys(rangeDefinition.bin); + if (bins.includes(binaryName)) { + return packageManager; + } + } + } + return null; + } + getBinariesFor(name) { + const binNames = new Set(); + for (const rangeDefinition of Object.values(this.config.definitions[name].ranges)) { + const bins = Array.isArray(rangeDefinition.bin) + ? rangeDefinition.bin + : Object.keys(rangeDefinition.bin); + for (const name of bins) { + binNames.add(name); + } + } + return binNames; + } + async getDefaultDescriptors() { + const locators = []; + for (const name of _types__WEBPACK_IMPORTED_MODULE_7__.SupportedPackageManagerSet) + locators.push({ name, range: await this.getDefaultVersion(name) }); + return locators; + } + async getDefaultVersion(packageManager) { + const definition = this.config.definitions[packageManager]; + if (typeof definition === `undefined`) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${packageManager}) isn't supported by this corepack build`); + let lastKnownGood; + try { + lastKnownGood = JSON.parse(await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(this.getLastKnownGoodFile(), `utf8`)); + } + catch (_a) { + // Ignore errors; too bad + } + if (typeof lastKnownGood !== `object` || lastKnownGood === null) + return definition.default; + if (!Object.prototype.hasOwnProperty.call(lastKnownGood, packageManager)) + return definition.default; + const override = lastKnownGood[packageManager]; + if (typeof override !== `string`) + return definition.default; + return override; } - - if (bytesRead > remain) { - const er = new Error('did not encounter expected EOF') - er.path = this.absolute - er.syscall = 'read' - er.code = 'EOF' - return this[CLOSE](fd, () => this.emit('error', er)) + async activatePackageManager(locator) { + const lastKnownGoodFile = this.getLastKnownGoodFile(); + let lastKnownGood; + try { + lastKnownGood = JSON.parse(await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(lastKnownGoodFile, `utf8`)); + } + catch (_a) { + // Ignore errors; too bad + } + if (typeof lastKnownGood !== `object` || lastKnownGood === null) + lastKnownGood = {}; + lastKnownGood[locator.name] = locator.reference; + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.mkdir(path__WEBPACK_IMPORTED_MODULE_1___default().dirname(lastKnownGoodFile), { recursive: true }); + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.writeFile(lastKnownGoodFile, `${JSON.stringify(lastKnownGood, null, 2)}\n`); } - - // null out the rest of the buffer, if we could fit the block padding - if (bytesRead === remain) { - for (let i = bytesRead; i < length && bytesRead < blockRemain; i++) { - buf[i + offset] = 0 - bytesRead ++ - remain ++ - } + async ensurePackageManager(locator) { + const definition = this.config.definitions[locator.name]; + if (typeof definition === `undefined`) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${locator.name}) isn't supported by this corepack build`); + const ranges = Object.keys(definition.ranges).reverse(); + const range = ranges.find(range => _semverUtils__WEBPACK_IMPORTED_MODULE_6__.satisfiesWithPrereleases(locator.reference, range)); + if (typeof range === `undefined`) + throw new Error(`Assertion failed: Specified resolution (${locator.reference}) isn't supported by any of ${ranges.join(`, `)}`); + const installedLocation = await _corepackUtils__WEBPACK_IMPORTED_MODULE_4__.installVersion(_folderUtils__WEBPACK_IMPORTED_MODULE_5__.getInstallFolder(), locator, { + spec: definition.ranges[range], + }); + return { + location: installedLocation, + spec: definition.ranges[range], + }; } - - const writeBuf = offset === 0 && bytesRead === buf.length ? - buf : buf.slice(offset, offset + bytesRead) - remain -= bytesRead - blockRemain -= bytesRead - pos += bytesRead - offset += bytesRead - - this.write(writeBuf) - - if (!remain) { - if (blockRemain) - this.write(Buffer.alloc(blockRemain)) - return this[CLOSE](fd, er => er ? this.emit('error', er) : this.end()) + async resolveDescriptor(descriptor, { allowTags = false, useCache = true } = {}) { + const definition = this.config.definitions[descriptor.name]; + if (typeof definition === `undefined`) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`This package manager (${descriptor.name}) isn't supported by this corepack build`); + let finalDescriptor = descriptor; + if (descriptor.range.match(/^[a-z-]+$/)) { + if (!allowTags) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Packages managers can't be referended via tags in this context`); + // We only resolve tags from the latest registry entry + const ranges = Object.keys(definition.ranges); + const tagRange = ranges[ranges.length - 1]; + const tags = await _corepackUtils__WEBPACK_IMPORTED_MODULE_4__.fetchAvailableTags(definition.ranges[tagRange].registry); + if (!Object.prototype.hasOwnProperty.call(tags, descriptor.range)) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Tag not found (${descriptor.range})`); + finalDescriptor = { + name: descriptor.name, + range: tags[descriptor.range], + }; + } + // If a compatible version is already installed, no need to query one + // from the remote listings + const cachedVersion = await _corepackUtils__WEBPACK_IMPORTED_MODULE_4__.findInstalledVersion(_folderUtils__WEBPACK_IMPORTED_MODULE_5__.getInstallFolder(), finalDescriptor); + if (cachedVersion !== null && useCache) + return { name: finalDescriptor.name, reference: cachedVersion }; + const candidateRangeDefinitions = Object.keys(definition.ranges).filter(range => { + return _semverUtils__WEBPACK_IMPORTED_MODULE_6__.satisfiesWithPrereleases(finalDescriptor.range, range); + }); + const tagResolutions = await Promise.all(candidateRangeDefinitions.map(async (range) => { + return [range, await _corepackUtils__WEBPACK_IMPORTED_MODULE_4__.fetchAvailableVersions(definition.ranges[range].registry)]; + })); + // If a version is available under multiple strategies (for example if + // Yarn is published to both the v1 package and git), we only care + // about the latest one + const resolutionMap = new Map(); + for (const [range, resolutions] of tagResolutions) + for (const entry of resolutions) + resolutionMap.set(entry, range); + const candidates = [...resolutionMap.keys()]; + const maxSatisfying = semver__WEBPACK_IMPORTED_MODULE_2___default().maxSatisfying(candidates, finalDescriptor.range); + if (maxSatisfying === null) + return null; + return { name: finalDescriptor.name, reference: maxSatisfying }; } - - if (offset >= length) { - buf = Buffer.allocUnsafe(length) - offset = 0 + getLastKnownGoodFile() { + return path__WEBPACK_IMPORTED_MODULE_1___default().join(_folderUtils__WEBPACK_IMPORTED_MODULE_5__.getInstallFolder(), `lastKnownGood.json`); } - length = buf.length - offset - this[READ](fd, buf, offset, length, pos, remain, blockRemain) - } -}) - -class WriteEntrySync extends WriteEntry { - constructor (path, opt) { - super(path, opt) - } - - [LSTAT] () { - this[ONLSTAT](fs.lstatSync(this.absolute)) - } +} - [SYMLINK] () { - this[ONREADLINK](fs.readlinkSync(this.absolute)) - } - [OPENFILE] () { - this[ONOPENFILE](fs.openSync(this.absolute, 'r')) - } +/***/ }), - [READ] (fd, buf, offset, length, pos, remain, blockRemain) { - let threw = true - try { - const bytesRead = fs.readSync(fd, buf, offset, length, pos) - this[ONREAD](fd, buf, offset, length, pos, remain, blockRemain, bytesRead) - threw = false - } finally { - // ignoring the error from close(2) is a bad practice, but at - // this point we already have an error, don't need another one - if (threw) - try { this[CLOSE](fd, () => {}) } catch (er) {} - } - } +/***/ "./sources/commands/Disable.ts": +/*!*************************************!*\ + !*** ./sources/commands/Disable.ts ***! + \*************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - [CLOSE] (fd, cb) { - fs.closeSync(fd) - cb() - } -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DisableCommand": () => (/* binding */ DisableCommand) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! which */ "../../../.yarn/berry/cache/which-npm-2.0.2-320ddf72f7-9.zip/node_modules/which/which.js"); +/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(which__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); -const WriteEntryTar = warner(class WriteEntryTar extends MiniPass { - constructor (readEntry, opt) { - opt = opt || {} - super(opt) - this.preservePaths = !!opt.preservePaths - this.portable = !!opt.portable - this.strict = !!opt.strict - this.noPax = !!opt.noPax - this.noMtime = !!opt.noMtime - this.readEntry = readEntry - this.type = readEntry.type - if (this.type === 'Directory' && this.portable) - this.noMtime = true - this.path = readEntry.path - this.mode = this[MODE](readEntry.mode) - this.uid = this.portable ? null : readEntry.uid - this.gid = this.portable ? null : readEntry.gid - this.uname = this.portable ? null : readEntry.uname - this.gname = this.portable ? null : readEntry.gname - this.size = readEntry.size - this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime - this.atime = this.portable ? null : readEntry.atime - this.ctime = this.portable ? null : readEntry.ctime - this.linkpath = readEntry.linkpath - if (typeof opt.onwarn === 'function') - this.on('warn', opt.onwarn) - let pathWarn = false - if (path.isAbsolute(this.path) && !this.preservePaths) { - const parsed = path.parse(this.path) - pathWarn = parsed.root - this.path = this.path.substr(parsed.root.length) +class DisableCommand extends clipanion__WEBPACK_IMPORTED_MODULE_4__.Command { + constructor() { + super(...arguments); + this.installDirectory = clipanion__WEBPACK_IMPORTED_MODULE_4__.Option.String(`--install-directory`, { + description: `Where the shims are located`, + }); + this.names = clipanion__WEBPACK_IMPORTED_MODULE_4__.Option.Rest(); } - - this.remain = readEntry.size - this.blockRemain = readEntry.startBlockSize - - this.header = new Header({ - path: this.path, - linkpath: this.linkpath, - // only the permissions and setuid/setgid/sticky bitflags - // not the higher-order bits that specify file type - mode: this.mode, - uid: this.portable ? null : this.uid, - gid: this.portable ? null : this.gid, - size: this.size, - mtime: this.noMtime ? null : this.mtime, - type: this.type, - uname: this.portable ? null : this.uname, - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime - }) - - if (pathWarn) { - this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { - entry: this, - path: pathWarn + this.path, - }) + async execute() { + let installDirectory = this.installDirectory; + // Node always call realpath on the module it executes, so we already + // lost track of how the binary got called. To find it back, we need to + // iterate over the PATH variable. + if (typeof installDirectory === `undefined`) + installDirectory = path__WEBPACK_IMPORTED_MODULE_1___default().dirname(await which__WEBPACK_IMPORTED_MODULE_2___default()(`corepack`)); + const names = this.names.length === 0 + ? _types__WEBPACK_IMPORTED_MODULE_3__.SupportedPackageManagerSetWithoutNpm + : this.names; + for (const name of new Set(names)) { + if (!(0,_types__WEBPACK_IMPORTED_MODULE_3__.isSupportedPackageManager)(name)) + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager name '${name}'`); + for (const binName of this.context.engine.getBinariesFor(name)) { + if (process.platform === `win32`) { + await this.removeWin32Link(installDirectory, binName); + } + else { + await this.removePosixLink(installDirectory, binName); + } + } + } } + async removePosixLink(installDirectory, binName) { + const file = path__WEBPACK_IMPORTED_MODULE_1___default().join(installDirectory, binName); + try { + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.unlink(file); + } + catch (err) { + if (err.code !== `ENOENT`) { + throw err; + } + } + } + async removeWin32Link(installDirectory, binName) { + for (const ext of [``, `.ps1`, `.cmd`]) { + const file = path__WEBPACK_IMPORTED_MODULE_1___default().join(installDirectory, `${binName}${ext}`); + try { + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.unlink(file); + } + catch (err) { + if (err.code !== `ENOENT`) { + throw err; + } + } + } + } +} +DisableCommand.paths = [ + [`disable`], +]; +DisableCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_4__.Command.Usage({ + description: `Remove the Corepack shims from the install directory`, + details: ` + When run, this command will remove the shims for the specified package managers from the install directory, or all shims if no parameters are passed. - if (this.header.encode() && !this.noPax) - super.write(new Pax({ - atime: this.portable ? null : this.atime, - ctime: this.portable ? null : this.ctime, - gid: this.portable ? null : this.gid, - mtime: this.noMtime ? null : this.mtime, - path: this.path, - linkpath: this.linkpath, - size: this.size, - uid: this.portable ? null : this.uid, - uname: this.portable ? null : this.uname, - dev: this.portable ? null : this.readEntry.dev, - ino: this.portable ? null : this.readEntry.ino, - nlink: this.portable ? null : this.readEntry.nlink - }).encode()) - - super.write(this.header.block) - readEntry.pipe(this) - } - - [MODE] (mode) { - return modeFix(mode, this.type === 'Directory', this.portable) - } - - write (data) { - const writeLen = data.length - if (writeLen > this.blockRemain) - throw new Error('writing more to entry than is appropriate') - this.blockRemain -= writeLen - return super.write(data) - } + By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--install-directory\` flag. + `, + examples: [[ + `Disable all shims, removing them if they're next to the \`coreshim\` binary`, + `$0 disable`, + ], [ + `Disable all shims, removing them from the specified directory`, + `$0 disable --install-directory /path/to/bin`, + ], [ + `Disable the Yarn shim only`, + `$0 disable yarn`, + ]], +}); - end () { - if (this.blockRemain) - this.write(Buffer.alloc(this.blockRemain)) - return super.end() - } -}) -WriteEntry.Sync = WriteEntrySync -WriteEntry.Tar = WriteEntryTar +/***/ }), -const getType = stat => - stat.isFile() ? 'File' - : stat.isDirectory() ? 'Directory' - : stat.isSymbolicLink() ? 'SymbolicLink' - : 'Unsupported' +/***/ "./sources/commands/Enable.ts": +/*!************************************!*\ + !*** ./sources/commands/Enable.ts ***! + \************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -module.exports = WriteEntry +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "EnableCommand": () => (/* binding */ EnableCommand) +/* harmony export */ }); +/* harmony import */ var _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @zkochan/cmd-shim */ "../../../.yarn/berry/cache/@zkochan-cmd-shim-npm-5.2.2-ae7b6d5b86-9.zip/node_modules/@zkochan/cmd-shim/index.js"); +/* harmony import */ var _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! which */ "../../../.yarn/berry/cache/which-npm-2.0.2-320ddf72f7-9.zip/node_modules/which/which.js"); +/* harmony import */ var which__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(which__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _nodeUtils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../nodeUtils */ "./sources/nodeUtils.ts"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); -/***/ }), -/***/ "./.yarn/cache/typanion-npm-3.3.1-ee9997c7cf-212d2beb55.zip/node_modules/typanion/lib/index.js": -/*!*****************************************************************************************************!*\ - !*** ./.yarn/cache/typanion-npm-3.3.1-ee9997c7cf-212d2beb55.zip/node_modules/typanion/lib/index.js ***! - \*****************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/; -const colorStringRegExp = /^#[0-9a-f]{6}$/i; -const colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i; -// https://stackoverflow.com/a/475217/880703 -const base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -// https://stackoverflow.com/a/14166194/880703 -const uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i; -// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_ -const iso8601RegExp = /^(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))T(?:[01]\d|2[0-3])(:?)[0-5]\d(?:\3[0-5]\d)?(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$/; -const makeTrait = (value) => () => { - return value; -}; -function makeValidator({ test }) { - return makeTrait(test)(); -} -function getPrintable(value) { - if (value === null) - return `null`; - if (value === undefined) - return `undefined`; - if (value === ``) - return `an empty string`; - return JSON.stringify(value); -} -function computeKey(state, key) { - var _a, _b, _c; - if (typeof key === `number`) { - return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`; - } - else if (simpleKeyRegExp.test(key)) { - return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`; - } - else { - return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`; +class EnableCommand extends clipanion__WEBPACK_IMPORTED_MODULE_6__.Command { + constructor() { + super(...arguments); + this.installDirectory = clipanion__WEBPACK_IMPORTED_MODULE_6__.Option.String(`--install-directory`, { + description: `Where the shims are to be installed`, + }); + this.names = clipanion__WEBPACK_IMPORTED_MODULE_6__.Option.Rest(); } -} -function makeCoercionFn(target, key) { - return (v) => { - const previous = target[key]; - target[key] = v; - return makeCoercionFn(target, key).bind(null, previous); - }; -} -function makeSetter(target, key) { - return (v) => { - target[key] = v; - }; -} -function plural(n, singular, plural) { - return n === 1 ? singular : plural; -} -function pushError({ errors, p } = {}, message) { - errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`); - return false; -} -const isUnknown = () => makeValidator({ - test: (value, state) => { - return true; - }, -}); -function isLiteral(expected) { - return makeValidator({ - test: (value, state) => { - if (value !== expected) - return pushError(state, `Expected a literal (got ${getPrintable(expected)})`); - return true; - }, - }); -} -const isString = () => makeValidator({ - test: (value, state) => { - if (typeof value !== `string`) - return pushError(state, `Expected a string (got ${getPrintable(value)})`); - return true; - }, -}); -function isEnum(enumSpec) { - const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec); - const values = new Set(valuesArray); - return makeValidator({ - test: (value, state) => { - if (!values.has(value)) - return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`); - return true; - }, - }); -} -const BOOLEAN_COERCIONS = new Map([ - [`true`, true], - [`True`, true], - [`1`, true], - [1, true], - [`false`, false], - [`False`, false], - [`0`, false], - [0, false], -]); -const isBoolean = () => makeValidator({ - test: (value, state) => { - var _a; - if (typeof value !== `boolean`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - const coercion = BOOLEAN_COERCIONS.get(value); - if (typeof coercion !== `undefined`) { - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); - return true; - } - } - return pushError(state, `Expected a boolean (got ${getPrintable(value)})`); - } - return true; - }, -}); -const isNumber = () => makeValidator({ - test: (value, state) => { - var _a; - if (typeof value !== `number`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - let coercion; - if (typeof value === `string`) { - let val; - try { - val = JSON.parse(value); - } - catch (_b) { } - // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS - if (typeof val === `number`) { - if (JSON.stringify(val) === value) { - coercion = val; - } - else { - return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`); - } - } - } - if (typeof coercion !== `undefined`) { - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); - return true; - } - } - return pushError(state, `Expected a number (got ${getPrintable(value)})`); - } - return true; - }, -}); -const isDate = () => makeValidator({ - test: (value, state) => { - var _a; - if (!(value instanceof Date)) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - let coercion; - if (typeof value === `string` && iso8601RegExp.test(value)) { - coercion = new Date(value); - } - else { - let timestamp; - if (typeof value === `string`) { - let val; - try { - val = JSON.parse(value); - } - catch (_b) { } - if (typeof val === `number`) { - timestamp = val; - } - } - else if (typeof value === `number`) { - timestamp = value; - } - if (typeof timestamp !== `undefined`) { - if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) { - coercion = new Date(timestamp * 1000); - } - else { - return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`); - } - } - } - if (typeof coercion !== `undefined`) { - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]); - return true; - } - } - return pushError(state, `Expected a date (got ${getPrintable(value)})`); - } - return true; - }, -}); -const isArray = (spec, { delimiter } = {}) => makeValidator({ - test: (value, state) => { - var _a; - if (typeof value === `string` && typeof delimiter !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - value = value.split(delimiter); - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]); - } - } - if (!Array.isArray(value)) - return pushError(state, `Expected an array (got ${getPrintable(value)})`); - let valid = true; - for (let t = 0, T = value.length; t < T; ++t) { - valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid; - if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { - break; - } - } - return valid; - }, -}); -const isTuple = (spec, { delimiter } = {}) => { - const lengthValidator = hasExactLength(spec.length); - return makeValidator({ - test: (value, state) => { - var _a; - if (typeof value === `string` && typeof delimiter !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - value = value.split(delimiter); - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]); + async execute() { + let installDirectory = this.installDirectory; + // Node always call realpath on the module it executes, so we already + // lost track of how the binary got called. To find it back, we need to + // iterate over the PATH variable. + if (typeof installDirectory === `undefined`) + installDirectory = path__WEBPACK_IMPORTED_MODULE_2___default().dirname(await which__WEBPACK_IMPORTED_MODULE_3___default()(`corepack`)); + // Otherwise the relative symlink we'll compute will be incorrect, if the + // install directory is within a symlink + installDirectory = fs__WEBPACK_IMPORTED_MODULE_1___default().realpathSync(installDirectory); + // We use `eval` so that Webpack doesn't statically transform it. + const manifestPath = _nodeUtils__WEBPACK_IMPORTED_MODULE_4__.dynamicRequire.resolve(`corepack/package.json`); + const distFolder = path__WEBPACK_IMPORTED_MODULE_2___default().join(path__WEBPACK_IMPORTED_MODULE_2___default().dirname(manifestPath), `dist`); + if (!fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(distFolder)) + throw new Error(`Assertion failed: The stub folder doesn't exist`); + const names = this.names.length === 0 + ? _types__WEBPACK_IMPORTED_MODULE_5__.SupportedPackageManagerSetWithoutNpm + : this.names; + for (const name of new Set(names)) { + if (!(0,_types__WEBPACK_IMPORTED_MODULE_5__.isSupportedPackageManager)(name)) + throw new clipanion__WEBPACK_IMPORTED_MODULE_6__.UsageError(`Invalid package manager name '${name}'`); + for (const binName of this.context.engine.getBinariesFor(name)) { + if (process.platform === `win32`) { + await this.generateWin32Link(installDirectory, distFolder, binName); } - } - if (!Array.isArray(value)) - return pushError(state, `Expected a tuple (got ${getPrintable(value)})`); - let valid = lengthValidator(value, Object.assign({}, state)); - for (let t = 0, T = value.length; t < T && t < spec.length; ++t) { - valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid; - if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { - break; + else { + await this.generatePosixLink(installDirectory, distFolder, binName); } } - return valid; - }, - }); -}; -const isDict = (spec, { keys: keySpec = null, } = {}) => makeValidator({ - test: (value, state) => { - if (typeof value !== `object` || value === null) - return pushError(state, `Expected an object (got ${getPrintable(value)})`); - const keys = Object.keys(value); - let valid = true; - for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) { - const key = keys[t]; - const sub = value[key]; - if (key === `__proto__` || key === `constructor`) { - valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`); - continue; - } - if (keySpec !== null && !keySpec(key, state)) { - valid = false; - continue; + } + } + async generatePosixLink(installDirectory, distFolder, binName) { + const file = path__WEBPACK_IMPORTED_MODULE_2___default().join(installDirectory, binName); + const symlink = path__WEBPACK_IMPORTED_MODULE_2___default().relative(installDirectory, path__WEBPACK_IMPORTED_MODULE_2___default().join(distFolder, `${binName}.js`)); + if (fs__WEBPACK_IMPORTED_MODULE_1___default().existsSync(file)) { + const currentSymlink = await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.readlink(file); + if (currentSymlink !== symlink) { + await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.unlink(file); } - if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) { - valid = false; - continue; + else { + return; } } - return valid; - }, + await fs__WEBPACK_IMPORTED_MODULE_1___default().promises.symlink(symlink, file); + } + async generateWin32Link(installDirectory, distFolder, binName) { + const file = path__WEBPACK_IMPORTED_MODULE_2___default().join(installDirectory, binName); + await _zkochan_cmd_shim__WEBPACK_IMPORTED_MODULE_0___default()(path__WEBPACK_IMPORTED_MODULE_2___default().join(distFolder, `${binName}.js`), file, { + createCmdFile: true, + }); + } +} +EnableCommand.paths = [ + [`enable`], +]; +EnableCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_6__.Command.Usage({ + description: `Add the Corepack shims to the install directories`, + details: ` + When run, this commmand will check whether the shims for the specified package managers can be found with the correct values inside the install directory. If not, or if they don't exist, they will be created. + + By default it will locate the install directory by running the equivalent of \`which corepack\`, but this can be tweaked by explicitly passing the install directory via the \`--install-directory\` flag. + `, + examples: [[ + `Enable all shims, putting them next to the \`corepath\` binary`, + `$0 enable`, + ], [ + `Enable all shims, putting them in the specified directory`, + `$0 enable --install-directory /path/to/folder`, + ], [ + `Enable the Yarn shim only`, + `$0 enable yarn`, + ]], }); -const isObject = (props, { extra: extraSpec = null, } = {}) => { - const specKeys = Object.keys(props); - return makeValidator({ - test: (value, state) => { - if (typeof value !== `object` || value === null) - return pushError(state, `Expected an object (got ${getPrintable(value)})`); - const keys = new Set([...specKeys, ...Object.keys(value)]); - const extra = {}; - let valid = true; - for (const key of keys) { - if (key === `constructor` || key === `__proto__`) { - valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`); + + +/***/ }), + +/***/ "./sources/commands/Hydrate.ts": +/*!*************************************!*\ + !*** ./sources/commands/Hydrate.ts ***! + \*************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "HydrateCommand": () => (/* binding */ HydrateCommand) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../folderUtils */ "./sources/folderUtils.ts"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types */ "./sources/types.ts"); + + + + +class HydrateCommand extends clipanion__WEBPACK_IMPORTED_MODULE_3__.Command { + constructor() { + super(...arguments); + this.activate = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--activate`, false, { + description: `If true, this release will become the default one for this package manager`, + }); + this.fileName = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.String(); + } + async execute() { + const installFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_1__.getInstallFolder(); + const fileName = path__WEBPACK_IMPORTED_MODULE_0___default().resolve(this.context.cwd, this.fileName); + const archiveEntries = new Map(); + let hasShortEntries = false; + const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/index.js", 19)); + await tar.t({ file: fileName, onentry: entry => { + const segments = entry.header.path.split(/\//g); + if (segments.length < 3) { + hasShortEntries = true; } else { - const spec = Object.prototype.hasOwnProperty.call(props, key) - ? props[key] - : undefined; - const sub = Object.prototype.hasOwnProperty.call(value, key) - ? value[key] - : undefined; - if (typeof spec !== `undefined`) { - valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid; - } - else if (extraSpec === null) { - valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`); - } - else { - Object.defineProperty(extra, key, { - enumerable: true, - get: () => sub, - set: makeSetter(value, key) - }); - } + let references = archiveEntries.get(segments[0]); + if (typeof references === `undefined`) + archiveEntries.set(segments[0], references = new Set()); + references.add(segments[1]); } - if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) { - break; + } }); + if (hasShortEntries || archiveEntries.size < 1) + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Invalid archive format; did it get generated by 'corepack prepare'?`); + for (const [name, references] of archiveEntries) { + for (const reference of references) { + if (!(0,_types__WEBPACK_IMPORTED_MODULE_2__.isSupportedPackageManager)(name)) + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Unsupported package manager '${name}'`); + if (this.activate) + this.context.stdout.write(`Hydrating ${name}@${reference} for immediate activation...\n`); + else + this.context.stdout.write(`Hydrating ${name}@${reference}...\n`); + await tar.x({ file: fileName, cwd: installFolder }, [`${name}/${reference}`]); + if (this.activate) { + await this.context.engine.activatePackageManager({ name, reference }); } } - if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null)) - valid = extraSpec(extra, state) && valid; - return valid; - }, - }); -}; -const isInstanceOf = (constructor) => makeValidator({ - test: (value, state) => { - if (!(value instanceof constructor)) - return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`); - return true; - }, + } + this.context.stdout.write(`All done!\n`); + } +} +HydrateCommand.paths = [ + [`hydrate`], +]; +HydrateCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_3__.Command.Usage({ + description: `Import a package manager into the cache`, + details: ` + This command unpacks a package manager archive into the cache. The archive must have been generated by the \`corepack prepare\` command - no other will work. + `, + examples: [[ + `Import a package manager in the cache`, + `$0 hydrate corepack.tgz`, + ]], }); -const isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({ - test: (value, state) => { - var _a, _b, _c; - const matches = []; - const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` - ? [] : undefined; - for (let t = 0, T = specs.length; t < T; ++t) { - const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined` - ? [] : undefined; - const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` - ? [] : undefined; - if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) { - matches.push([`#${t + 1}`, subCoercions]); - if (!exclusive) { - break; + + +/***/ }), + +/***/ "./sources/commands/Prepare.ts": +/*!*************************************!*\ + !*** ./sources/commands/Prepare.ts ***! + \*************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "PrepareCommand": () => (/* binding */ PrepareCommand) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../folderUtils */ "./sources/folderUtils.ts"); +/* harmony import */ var _specUtils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../specUtils */ "./sources/specUtils.ts"); + + + + +class PrepareCommand extends clipanion__WEBPACK_IMPORTED_MODULE_3__.Command { + constructor() { + super(...arguments); + this.activate = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--activate`, false, { + description: `If true, this release will become the default one for this package manager`, + }); + this.all = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--all`, false, { + description: `If true, all available default package managers will be installed`, + }); + this.json = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Boolean(`--json`, false, { + description: `If true, the output will be the path of the generated tarball`, + }); + this.output = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.String(`-o,--output`, { + description: `If true, the installed package managers will also be stored in a tarball`, + tolerateBoolean: true, + }); + this.specs = clipanion__WEBPACK_IMPORTED_MODULE_3__.Option.Rest(); + } + async execute() { + if (this.all && this.specs.length > 0) + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`The --all option cannot be used along with an explicit package manager specification`); + const specs = this.all + ? await this.context.engine.getDefaultDescriptors() + : this.specs; + const installLocations = []; + if (specs.length === 0) { + const lookup = await _specUtils__WEBPACK_IMPORTED_MODULE_2__.loadSpec(this.context.cwd); + switch (lookup.type) { + case `NoProject`: + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Couldn't find a project in the local directory - please explicit the package manager to pack, or run this command from a valid project`); + case `NoSpec`: + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`The local project doesn't feature a 'packageManager' field - please explicit the package manager to pack, or update the manifest to reference it`); + default: { + specs.push(lookup.spec); + } + } + } + for (const request of specs) { + const spec = typeof request === `string` + ? _specUtils__WEBPACK_IMPORTED_MODULE_2__.parseSpec(request, `CLI arguments`) + : request; + const resolved = await this.context.engine.resolveDescriptor(spec); + if (resolved === null) + throw new clipanion__WEBPACK_IMPORTED_MODULE_3__.UsageError(`Failed to successfully resolve '${spec.range}' to a valid ${spec.name} release`); + if (!this.json) { + if (this.activate) { + this.context.stdout.write(`Preparing ${spec.name}@${spec.range} for immediate activation...\n`); + } + else { + this.context.stdout.write(`Preparing ${spec.name}@${spec.range}...\n`); } } - else { - errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]); + const installSpec = await this.context.engine.ensurePackageManager(resolved); + installLocations.push(installSpec.location); + if (this.activate) { + await this.context.engine.activatePackageManager(resolved); } } - if (matches.length === 1) { - const [, subCoercions] = matches[0]; - if (typeof subCoercions !== `undefined`) - (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions); - return true; + if (this.output) { + const outputName = typeof this.output === `string` + ? this.output + : `corepack.tgz`; + const baseInstallFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_1__.getInstallFolder(); + const outputPath = path__WEBPACK_IMPORTED_MODULE_0___default().resolve(this.context.cwd, outputName); + if (!this.json) + this.context.stdout.write(`Packing the selected tools in ${path__WEBPACK_IMPORTED_MODULE_0___default().basename(outputPath)}...\n`); + const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/index.js", 19)); + await tar.c({ gzip: true, cwd: baseInstallFolder, file: path__WEBPACK_IMPORTED_MODULE_0___default().resolve(outputPath) }, installLocations.map(location => { + return path__WEBPACK_IMPORTED_MODULE_0___default().relative(baseInstallFolder, location); + })); + if (this.json) { + this.context.stdout.write(`${JSON.stringify(outputPath)}\n`); + } + else { + this.context.stdout.write(`All done!\n`); + } } - if (matches.length > 1) - pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`); - else - (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer); - return false; - }, + } +} +PrepareCommand.paths = [ + [`prepare`], +]; +PrepareCommand.usage = clipanion__WEBPACK_IMPORTED_MODULE_3__.Command.Usage({ + description: `Generate a package manager archive`, + details: ` + This command makes sure that the specified package managers are installed in the local cache. Calling this command explicitly unless you operate in an environment without network access (in which case you'd have to call \`prepare\` while building your image, to make sure all tools are available for later use). + + When the \`-o,--output\` flag is set, Corepack will also compress the resulting package manager into a format suitable for \`corepack hydrate\`, and will store it at the specified location on the disk. + `, + examples: [[ + `Prepare the package manager from the active project`, + `$0 prepare`, + ], [ + `Prepare a specific Yarn version`, + `$0 prepare yarn@2.2.2`, + ], [ + `Generate an archive for a specific Yarn version`, + `$0 prepare yarn@2.2.2 -o`, + ], [ + `Generate a named archive`, + `$0 prepare yarn@2.2.2 --output=yarn.tgz`, + ]], }); -const applyCascade = (spec, followups) => makeValidator({ - test: (value, state) => { - var _a, _b; - const context = { value: value }; - const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` - ? makeCoercionFn(context, `value`) : undefined; - const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined` - ? [] : undefined; - if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions }))) - return false; - const reverts = []; - if (typeof subCoercions !== `undefined`) - for (const [, coercion] of subCoercions) - reverts.push(coercion()); - try { - if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) { - if (context.value !== value) { - if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`) - return pushError(state, `Unbound coercion result`); - state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]); - } - (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions); + + +/***/ }), + +/***/ "./sources/corepackUtils.ts": +/*!**********************************!*\ + !*** ./sources/corepackUtils.ts ***! + \**********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "fetchAvailableTags": () => (/* binding */ fetchAvailableTags), +/* harmony export */ "fetchAvailableVersions": () => (/* binding */ fetchAvailableVersions), +/* harmony export */ "findInstalledVersion": () => (/* binding */ findInstalledVersion), +/* harmony export */ "installVersion": () => (/* binding */ installVersion), +/* harmony export */ "runVersion": () => (/* binding */ runVersion) +/* harmony export */ }); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js"); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _debugUtils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./debugUtils */ "./sources/debugUtils.ts"); +/* harmony import */ var _folderUtils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./folderUtils */ "./sources/folderUtils.ts"); +/* harmony import */ var _fsUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fsUtils */ "./sources/fsUtils.ts"); +/* harmony import */ var _httpUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./httpUtils */ "./sources/httpUtils.ts"); +/* harmony import */ var _nodeUtils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./nodeUtils */ "./sources/nodeUtils.ts"); + + + + + + + + +async function fetchAvailableTags(spec) { + switch (spec.type) { + case `npm`: { + const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_6__.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, { headers: { [`Accept`]: `application/vnd.npm.install-v1+json` } }); + return data[`dist-tags`]; + } + case `url`: { + const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_6__.fetchAsJson(spec.url); + return data[spec.fields.tags]; + } + default: { + throw new Error(`Unsupported specification ${JSON.stringify(spec)}`); + } + } +} +async function fetchAvailableVersions(spec) { + switch (spec.type) { + case `npm`: { + const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_6__.fetchAsJson(`https://registry.npmjs.org/${spec.package}`, { headers: { [`Accept`]: `application/vnd.npm.install-v1+json` } }); + return Object.keys(data.versions); + } + case `url`: { + const data = await _httpUtils__WEBPACK_IMPORTED_MODULE_6__.fetchAsJson(spec.url); + const field = data[spec.fields.versions]; + return Array.isArray(field) ? field : Object.keys(field); + } + default: { + throw new Error(`Unsupported specification ${JSON.stringify(spec)}`); + } + } +} +async function findInstalledVersion(installTarget, descriptor) { + const installFolder = path__WEBPACK_IMPORTED_MODULE_1___default().join(installTarget, descriptor.name); + let folderContent; + try { + folderContent = await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readdir(installFolder); + } + catch (error) { + if (error.code === `ENOENT`) { + folderContent = []; + } + else { + throw error; + } + } + const candidateVersions = []; + for (const entry of folderContent) { + // Some dot-folders tend to pop inside directories, especially on OSX + if (entry.startsWith(`.`)) + continue; + candidateVersions.push(entry); + } + const bestMatch = semver__WEBPACK_IMPORTED_MODULE_2___default().maxSatisfying(candidateVersions, descriptor.range); + if (bestMatch === null) + return null; + return bestMatch; +} +async function installVersion(installTarget, locator, { spec }) { + const { default: tar } = await Promise.resolve(/*! import() eager */).then(__webpack_require__.t.bind(__webpack_require__, /*! tar */ "../../../.yarn/berry/cache/tar-npm-6.1.11-e6ac3cba9c-9.zip/node_modules/tar/index.js", 19)); + const installFolder = path__WEBPACK_IMPORTED_MODULE_1___default().join(installTarget, locator.name, locator.reference); + if (fs__WEBPACK_IMPORTED_MODULE_0___default().existsSync(installFolder)) { + _debugUtils__WEBPACK_IMPORTED_MODULE_3__.log(`Reusing ${locator.name}@${locator.reference}`); + return installFolder; + } + const url = spec.url.replace(`{}`, locator.reference); + // Creating a temporary folder inside the install folder means that we + // are sure it'll be in the same drive as the destination, so we can + // just move it there atomically once we are done + const tmpFolder = _folderUtils__WEBPACK_IMPORTED_MODULE_4__.getTemporaryFolder(installTarget); + _debugUtils__WEBPACK_IMPORTED_MODULE_3__.log(`Installing ${locator.name}@${locator.reference} from ${url} to ${tmpFolder}`); + const stream = await _httpUtils__WEBPACK_IMPORTED_MODULE_6__.fetchUrlStream(url); + const parsedUrl = new URL(url); + const ext = path__WEBPACK_IMPORTED_MODULE_1___default().posix.extname(parsedUrl.pathname); + let outputFile = null; + let sendTo; + if (ext === `.tgz`) { + sendTo = tar.x({ strip: 1, cwd: tmpFolder }); + } + else if (ext === `.js`) { + outputFile = path__WEBPACK_IMPORTED_MODULE_1___default().join(tmpFolder, path__WEBPACK_IMPORTED_MODULE_1___default().posix.basename(parsedUrl.pathname)); + sendTo = fs__WEBPACK_IMPORTED_MODULE_0___default().createWriteStream(outputFile); + } + stream.pipe(sendTo); + await new Promise(resolve => { + sendTo.on(`finish`, resolve); + }); + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.mkdir(path__WEBPACK_IMPORTED_MODULE_1___default().dirname(installFolder), { recursive: true }); + try { + await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.rename(tmpFolder, installFolder); + } + catch (err) { + if (err.code === `ENOTEMPTY` || + // On Windows the error code is EPERM so we check if it is a directory + (err.code === `EPERM` && (await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.stat(installFolder)).isDirectory())) { + _debugUtils__WEBPACK_IMPORTED_MODULE_3__.log(`Another instance of corepack installed ${locator.name}@${locator.reference}`); + await _fsUtils__WEBPACK_IMPORTED_MODULE_5__.rimraf(tmpFolder); + } + else { + throw err; + } + } + _debugUtils__WEBPACK_IMPORTED_MODULE_3__.log(`Install finished`); + return installFolder; +} +/** + * Loads the binary, taking control of the current process. + */ +async function runVersion(installSpec, binName, args) { + let binPath = null; + if (Array.isArray(installSpec.spec.bin)) { + if (installSpec.spec.bin.some(bin => bin === binName)) { + const parsedUrl = new URL(installSpec.spec.url); + const ext = path__WEBPACK_IMPORTED_MODULE_1___default().posix.extname(parsedUrl.pathname); + if (ext === `.js`) { + binPath = path__WEBPACK_IMPORTED_MODULE_1___default().join(installSpec.location, path__WEBPACK_IMPORTED_MODULE_1___default().posix.basename(parsedUrl.pathname)); } - return followups.every(spec => { - return spec(context.value, state); - }); } - finally { - for (const revert of reverts) { - revert(); + } + else { + for (const [name, dest] of Object.entries(installSpec.spec.bin)) { + if (name === binName) { + binPath = path__WEBPACK_IMPORTED_MODULE_1___default().join(installSpec.location, dest); + break; } } - }, -}); -const isOptional = (spec) => makeValidator({ - test: (value, state) => { - if (typeof value === `undefined`) - return true; - return spec(value, state); - }, -}); -const isNullable = (spec) => makeValidator({ - test: (value, state) => { - if (value === null) - return true; - return spec(value, state); - }, -}); -const hasMinLength = (length) => makeValidator({ - test: (value, state) => { - if (!(value.length >= length)) - return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`); - return true; - }, -}); -const hasMaxLength = (length) => makeValidator({ - test: (value, state) => { - if (!(value.length <= length)) - return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`); - return true; - }, -}); -const hasExactLength = (length) => makeValidator({ - test: (value, state) => { - if (!(value.length === length)) - return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`); - return true; - }, -}); -const hasUniqueItems = ({ map, } = {}) => makeValidator({ - test: (value, state) => { - const set = new Set(); - const dup = new Set(); - for (let t = 0, T = value.length; t < T; ++t) { - const sub = value[t]; - const key = typeof map !== `undefined` - ? map(sub) - : sub; - if (set.has(key)) { - if (dup.has(key)) - continue; - pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`); - dup.add(key); + } + if (!binPath) + throw new Error(`Assertion failed: Unable to locate path for bin '${binName}'`); + _nodeUtils__WEBPACK_IMPORTED_MODULE_7__.registerV8CompileCache(); + // We load the binary into the current process, + // while making it think it was spawned. + // Non-exhaustive list of requirements: + // - Yarn uses process.argv[1] to determine its own path: https://github.com/yarnpkg/berry/blob/0da258120fc266b06f42aed67e4227e81a2a900f/packages/yarnpkg-cli/sources/main.ts#L80 + // - pnpm uses `require.main == null` to determine its own version: https://github.com/pnpm/pnpm/blob/e2866dee92991e979b2b0e960ddf5a74f6845d90/packages/cli-meta/src/index.ts#L14 + process.env.COREPACK_ROOT = path__WEBPACK_IMPORTED_MODULE_1___default().dirname(eval(`__dirname`)); + process.argv = [ + process.execPath, + binPath, + ...args, + ]; + process.execArgv = []; + return _nodeUtils__WEBPACK_IMPORTED_MODULE_7__.loadMainModule(binPath); +} + + +/***/ }), + +/***/ "./sources/debugUtils.ts": +/*!*******************************!*\ + !*** ./sources/debugUtils.ts ***! + \*******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "log": () => (/* binding */ log) +/* harmony export */ }); +/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! debug */ "./.yarn/__virtual__/debug-virtual-80c19f725b/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/index.js"); +/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(debug__WEBPACK_IMPORTED_MODULE_0__); + +const log = debug__WEBPACK_IMPORTED_MODULE_0___default()(`corepack`); + + +/***/ }), + +/***/ "./sources/folderUtils.ts": +/*!********************************!*\ + !*** ./sources/folderUtils.ts ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getInstallFolder": () => (/* binding */ getInstallFolder), +/* harmony export */ "getTemporaryFolder": () => (/* binding */ getTemporaryFolder) +/* harmony export */ }); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! os */ "os"); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__); + + + +function getInstallFolder() { + var _a; + return (_a = process.env.COREPACK_HOME) !== null && _a !== void 0 ? _a : (0,path__WEBPACK_IMPORTED_MODULE_2__.join)((0,os__WEBPACK_IMPORTED_MODULE_1__.homedir)(), `.node/corepack`); +} +function getTemporaryFolder(target = (0,os__WEBPACK_IMPORTED_MODULE_1__.tmpdir)()) { + (0,fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync)(target, { recursive: true }); + while (true) { + const rnd = Math.random() * 0x100000000; + const hex = rnd.toString(16).padStart(8, `0`); + const path = (0,path__WEBPACK_IMPORTED_MODULE_2__.join)(target, `corepack-${process.pid}-${hex}`); + try { + (0,fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync)(path); + return path; + } + catch (error) { + if (error.code === `EEXIST`) { + continue; } else { - set.add(key); + throw error; } } - return dup.size === 0; - }, -}); -const isNegative = () => makeValidator({ - test: (value, state) => { - if (!(value <= 0)) - return pushError(state, `Expected to be negative (got ${value})`); - return true; - }, -}); -const isPositive = () => makeValidator({ - test: (value, state) => { - if (!(value >= 0)) - return pushError(state, `Expected to be positive (got ${value})`); - return true; - }, -}); -const isAtLeast = (n) => makeValidator({ - test: (value, state) => { - if (!(value >= n)) - return pushError(state, `Expected to be at least ${n} (got ${value})`); - return true; - }, -}); -const isAtMost = (n) => makeValidator({ - test: (value, state) => { - if (!(value <= n)) - return pushError(state, `Expected to be at most ${n} (got ${value})`); - return true; - }, -}); -const isInInclusiveRange = (a, b) => makeValidator({ - test: (value, state) => { - if (!(value >= a && value <= b)) - return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`); - return true; - }, -}); -const isInExclusiveRange = (a, b) => makeValidator({ - test: (value, state) => { - if (!(value >= a && value < b)) - return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`); - return true; - }, -}); -const isInteger = ({ unsafe = false, } = {}) => makeValidator({ - test: (value, state) => { - if (value !== Math.round(value)) - return pushError(state, `Expected to be an integer (got ${value})`); - if (!Number.isSafeInteger(value)) - return pushError(state, `Expected to be a safe integer (got ${value})`); - return true; - }, -}); -const matchesRegExp = (regExp) => makeValidator({ - test: (value, state) => { - if (!regExp.test(value)) - return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`); - return true; - }, -}); -const isLowerCase = () => makeValidator({ - test: (value, state) => { - if (value !== value.toLowerCase()) - return pushError(state, `Expected to be all-lowercase (got ${value})`); - return true; - }, -}); -const isUpperCase = () => makeValidator({ - test: (value, state) => { - if (value !== value.toUpperCase()) - return pushError(state, `Expected to be all-uppercase (got ${value})`); - return true; - }, -}); -const isUUID4 = () => makeValidator({ - test: (value, state) => { - if (!uuid4RegExp.test(value)) - return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`); - return true; - }, -}); -const isISO8601 = () => makeValidator({ - test: (value, state) => { - if (!iso8601RegExp.test(value)) - return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`); - return false; - }, -}); -const isHexColor = ({ alpha = false, }) => makeValidator({ - test: (value, state) => { - const res = alpha - ? colorStringRegExp.test(value) - : colorStringAlphaRegExp.test(value); - if (!res) - return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`); - return true; - }, -}); -const isBase64 = () => makeValidator({ - test: (value, state) => { - if (!base64RegExp.test(value)) - return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`); - return true; - }, -}); -const isJSON = (spec = isUnknown()) => makeValidator({ - test: (value, state) => { - let data; - try { - data = JSON.parse(value); - } - catch (_a) { - return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`); - } - return spec(data, state); - }, -}); -const hasRequiredKeys = (requiredKeys) => { - const requiredSet = new Set(requiredKeys); - return makeValidator({ - test: (value, state) => { - const keys = new Set(Object.keys(value)); - const problems = []; - for (const key of requiredSet) - if (!keys.has(key)) - problems.push(key); - if (problems.length > 0) - return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${problems.map(name => `"${name}"`).join(`, `)}`); - return true; - }, - }); -}; -const hasForbiddenKeys = (forbiddenKeys) => { - const forbiddenSet = new Set(forbiddenKeys); - return makeValidator({ - test: (value, state) => { - const keys = new Set(Object.keys(value)); - const problems = []; - for (const key of forbiddenSet) - if (keys.has(key)) - problems.push(key); - if (problems.length > 0) - return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${problems.map(name => `"${name}"`).join(`, `)}`); - return true; - }, - }); -}; -const hasMutuallyExclusiveKeys = (exclusiveKeys) => { - const exclusiveSet = new Set(exclusiveKeys); - return makeValidator({ - test: (value, state) => { - const keys = new Set(Object.keys(value)); - const used = []; - for (const key of exclusiveSet) - if (keys.has(key)) - used.push(key); - if (used.length > 1) - return pushError(state, `Mutually exclusive properties ${used.map(name => `"${name}"`).join(`, `)}`); - return true; - }, - }); -}; -(function (KeyRelationship) { - KeyRelationship["Forbids"] = "Forbids"; - KeyRelationship["Requires"] = "Requires"; -})(exports.KeyRelationship || (exports.KeyRelationship = {})); -const keyRelationships = { - [exports.KeyRelationship.Forbids]: { - expect: false, - message: `forbids using`, - }, - [exports.KeyRelationship.Requires]: { - expect: true, - message: `requires using`, - }, -}; -const hasKeyRelationship = (subject, relationship, others, { ignore = [], } = {}) => { - const skipped = new Set(ignore); - const otherSet = new Set(others); - const spec = keyRelationships[relationship]; - return makeValidator({ - test: (value, state) => { - const keys = new Set(Object.keys(value)); - if (!keys.has(subject) || skipped.has(value[subject])) - return true; - const problems = []; - for (const key of otherSet) - if ((keys.has(key) && !skipped.has(value[key])) !== spec.expect) - problems.push(key); - if (problems.length >= 1) - return pushError(state, `Property "${subject}" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${problems.map(name => `"${name}"`).join(`, `)}`); - return true; - }, - }); -}; - -exports.applyCascade = applyCascade; -exports.base64RegExp = base64RegExp; -exports.colorStringAlphaRegExp = colorStringAlphaRegExp; -exports.colorStringRegExp = colorStringRegExp; -exports.computeKey = computeKey; -exports.getPrintable = getPrintable; -exports.hasExactLength = hasExactLength; -exports.hasForbiddenKeys = hasForbiddenKeys; -exports.hasKeyRelationship = hasKeyRelationship; -exports.hasMaxLength = hasMaxLength; -exports.hasMinLength = hasMinLength; -exports.hasMutuallyExclusiveKeys = hasMutuallyExclusiveKeys; -exports.hasRequiredKeys = hasRequiredKeys; -exports.hasUniqueItems = hasUniqueItems; -exports.isArray = isArray; -exports.isAtLeast = isAtLeast; -exports.isAtMost = isAtMost; -exports.isBase64 = isBase64; -exports.isBoolean = isBoolean; -exports.isDate = isDate; -exports.isDict = isDict; -exports.isEnum = isEnum; -exports.isHexColor = isHexColor; -exports.isISO8601 = isISO8601; -exports.isInExclusiveRange = isInExclusiveRange; -exports.isInInclusiveRange = isInInclusiveRange; -exports.isInstanceOf = isInstanceOf; -exports.isInteger = isInteger; -exports.isJSON = isJSON; -exports.isLiteral = isLiteral; -exports.isLowerCase = isLowerCase; -exports.isNegative = isNegative; -exports.isNullable = isNullable; -exports.isNumber = isNumber; -exports.isObject = isObject; -exports.isOneOf = isOneOf; -exports.isOptional = isOptional; -exports.isPositive = isPositive; -exports.isString = isString; -exports.isTuple = isTuple; -exports.isUUID4 = isUUID4; -exports.isUnknown = isUnknown; -exports.isUpperCase = isUpperCase; -exports.iso8601RegExp = iso8601RegExp; -exports.makeCoercionFn = makeCoercionFn; -exports.makeSetter = makeSetter; -exports.makeTrait = makeTrait; -exports.makeValidator = makeValidator; -exports.matchesRegExp = matchesRegExp; -exports.plural = plural; -exports.pushError = pushError; -exports.simpleKeyRegExp = simpleKeyRegExp; -exports.uuid4RegExp = uuid4RegExp; + } +} /***/ }), -/***/ "./.yarn/cache/which-npm-2.0.2-320ddf72f7-1a5c563d3c.zip/node_modules/which/which.js": -/*!*******************************************************************************************!*\ - !*** ./.yarn/cache/which-npm-2.0.2-320ddf72f7-1a5c563d3c.zip/node_modules/which/which.js ***! - \*******************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./sources/fsUtils.ts": +/*!****************************!*\ + !*** ./sources/fsUtils.ts ***! + \****************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "rimraf": () => (/* binding */ rimraf) +/* harmony export */ }); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs/promises */ "fs/promises"); +/* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__); -const path = __webpack_require__(/*! path */ "path") -const COLON = isWindows ? ';' : ':' -const isexe = __webpack_require__(/*! isexe */ "./.yarn/cache/isexe-npm-2.0.0-b58870bd2e-26bf6c5480.zip/node_modules/isexe/index.js") +async function rimraf(path) { + return (0,fs_promises__WEBPACK_IMPORTED_MODULE_0__.rm)(path, { recursive: true, force: true }); +} -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON +/***/ }), - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ) - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : '' - const pathExt = isWindows ? pathExtExe.split(colon) : [''] +/***/ "./sources/httpUtils.ts": +/*!******************************!*\ + !*** ./sources/httpUtils.ts ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "fetchAsBuffer": () => (/* binding */ fetchAsBuffer), +/* harmony export */ "fetchAsJson": () => (/* binding */ fetchAsJson), +/* harmony export */ "fetchUrlStream": () => (/* binding */ fetchUrlStream) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); - return { - pathEnv, - pathExt, - pathExtExe, - } +async function fetchUrlStream(url, options = {}) { + if (process.env.COREPACK_ENABLE_NETWORK === `0`) + throw new clipanion__WEBPACK_IMPORTED_MODULE_0__.UsageError(`Network access disabled by the environment; can't reach ${url}`); + const { default: https } = await Promise.resolve(/*! import() */).then(__webpack_require__.t.bind(__webpack_require__, /*! https */ "https", 23)); + const { default: ProxyAgent } = await __webpack_require__.e(/*! import() */ "vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js").then(__webpack_require__.t.bind(__webpack_require__, /*! proxy-agent */ "../../../.yarn/berry/cache/proxy-agent-npm-5.0.0-41772f4b01-9.zip/node_modules/proxy-agent/index.js", 23)); + const proxyAgent = new ProxyAgent(); + return new Promise((resolve, reject) => { + const request = https.get(url, Object.assign(Object.assign({}, options), { agent: proxyAgent }), response => { + var _a; + const statusCode = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 500; + if (!(statusCode >= 200 && statusCode < 300)) + return reject(new Error(`Server answered with HTTP ${statusCode}`)); + return resolve(response); + }); + request.on(`error`, err => { + reject(new Error(`Error when performing the request`)); + }); + }); +} +async function fetchAsBuffer(url, options) { + const response = await fetchUrlStream(url, options); + return new Promise((resolve, reject) => { + const chunks = []; + response.on(`data`, chunk => { + chunks.push(chunk); + }); + response.on(`error`, error => { + reject(error); + }); + response.on(`end`, () => { + resolve(Buffer.concat(chunks)); + }); + }); +} +async function fetchAsJson(url, options) { + const buffer = await fetchAsBuffer(url, options); + const asText = buffer.toString(); + try { + return JSON.parse(asText); + } + catch (error) { + const truncated = asText.length > 30 + ? `${asText.slice(0, 30)}...` + : asText; + throw new Error(`Couldn't parse JSON data: ${JSON.stringify(truncated)}`); + } } -const which = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt - opt = {} - } - if (!opt) - opt = {} - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] +/***/ }), - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) +/***/ "./sources/main.ts": +/*!*************************!*\ + !*** ./sources/main.ts ***! + \*************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "runMain": () => (/* binding */ runMain) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var _Engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Engine */ "./sources/Engine.ts"); +/* harmony import */ var _commands_Disable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./commands/Disable */ "./sources/commands/Disable.ts"); +/* harmony import */ var _commands_Enable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./commands/Enable */ "./sources/commands/Enable.ts"); +/* harmony import */ var _commands_Hydrate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./commands/Hydrate */ "./sources/commands/Hydrate.ts"); +/* harmony import */ var _commands_Prepare__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./commands/Prepare */ "./sources/commands/Prepare.ts"); +/* harmony import */ var _corepackUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./corepackUtils */ "./sources/corepackUtils.ts"); +/* harmony import */ var _miscUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./miscUtils */ "./sources/miscUtils.ts"); +/* harmony import */ var _specUtils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./specUtils */ "./sources/specUtils.ts"); - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - resolve(subStep(p, i, 0)) - }) - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }) - }) - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -} -const whichSync = (cmd, opt) => { - opt = opt || {} - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) - const found = [] - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i] - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw - const pCmd = path.join(pathPart, cmd) - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j] - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur +function getPackageManagerRequestFromCli(parameter, context) { + if (!parameter) + return null; + const match = parameter.match(/^([^@]*)(?:@(.*))?$/); + if (!match) + return null; + const [, binaryName, binaryVersion] = match; + const packageManager = context.engine.getPackageManagerFor(binaryName); + if (!packageManager) + return null; + return { + packageManager, + binaryName, + binaryVersion: binaryVersion || null, + }; +} +async function executePackageManagerRequest({ packageManager, binaryName, binaryVersion }, args, context) { + var _a; + const defaultVersion = await context.engine.getDefaultVersion(packageManager); + const definition = context.engine.config.definitions[packageManager]; + // If all leading segments match one of the patterns defined in the `transparent` + // key, we tolerate calling this binary even if the local project isn't explicitly + // configured for it, and we use the special default version if requested. + let isTransparentCommand = false; + for (const transparentPath of definition.transparent.commands) { + if (transparentPath[0] === binaryName && transparentPath.slice(1).every((segment, index) => segment === args[index])) { + isTransparentCommand = true; + break; } - } catch (ex) {} } - } + const fallbackReference = isTransparentCommand + ? (_a = definition.transparent.default) !== null && _a !== void 0 ? _a : defaultVersion + : defaultVersion; + const fallbackLocator = { + name: packageManager, + reference: fallbackReference, + }; + let descriptor; + try { + descriptor = await _specUtils__WEBPACK_IMPORTED_MODULE_7__.findProjectSpec(context.cwd, fallbackLocator, { transparent: isTransparentCommand }); + } + catch (err) { + if (err instanceof _miscUtils__WEBPACK_IMPORTED_MODULE_6__.Cancellation) { + return 1; + } + else { + throw err; + } + } + if (binaryVersion) + descriptor.range = binaryVersion; + const resolved = await context.engine.resolveDescriptor(descriptor, { allowTags: true }); + if (resolved === null) + throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Failed to successfully resolve '${descriptor.range}' to a valid ${descriptor.name} release`); + const installSpec = await context.engine.ensurePackageManager(resolved); + return await _corepackUtils__WEBPACK_IMPORTED_MODULE_5__.runVersion(installSpec, binaryName, args); +} +async function main(argv) { + const corepackVersion = (__webpack_require__(/*! ../package.json */ "./package.json").version); + // Because we load the binaries in the same process, we don't support custom contexts. + const context = Object.assign(Object.assign({}, clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli.defaultContext), { cwd: process.cwd(), engine: new _Engine__WEBPACK_IMPORTED_MODULE_0__.Engine() }); + const [firstArg, ...restArgs] = argv; + const request = getPackageManagerRequestFromCli(firstArg, context); + let cli; + if (!request) { + // If the first argument doesn't match any supported package manager, we fallback to the standard Corepack CLI + cli = new clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli({ + binaryLabel: `Corepack`, + binaryName: `corepack`, + binaryVersion: corepackVersion, + }); + cli.register(clipanion__WEBPACK_IMPORTED_MODULE_8__.Builtins.HelpCommand); + cli.register(clipanion__WEBPACK_IMPORTED_MODULE_8__.Builtins.VersionCommand); + cli.register(_commands_Enable__WEBPACK_IMPORTED_MODULE_2__.EnableCommand); + cli.register(_commands_Disable__WEBPACK_IMPORTED_MODULE_1__.DisableCommand); + cli.register(_commands_Hydrate__WEBPACK_IMPORTED_MODULE_3__.HydrateCommand); + cli.register(_commands_Prepare__WEBPACK_IMPORTED_MODULE_4__.PrepareCommand); + return await cli.run(argv, context); + } + else { + // Otherwise, we create a single-command CLI to run the specified package manager (we still use Clipanion in order to pretty-print usage errors). + const cli = new clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli({ + binaryLabel: `'${request.binaryName}', via Corepack`, + binaryName: request.binaryName, + binaryVersion: `corepack/${corepackVersion}`, + }); + cli.register(class BinaryCommand extends clipanion__WEBPACK_IMPORTED_MODULE_8__.Command { + constructor() { + super(...arguments); + this.proxy = clipanion__WEBPACK_IMPORTED_MODULE_8__.Option.Proxy(); + } + async execute() { + return executePackageManagerRequest(request, this.proxy, this.context); + } + }); + return await cli.run(restArgs, context); + } +} +// Important: this is the only function that the corepack binary exports. +function runMain(argv) { + main(argv).then(exitCode => { + process.exitCode = exitCode; + }, err => { + console.error(err.stack); + process.exitCode = 1; + }); +} - if (opt.all && found.length) - return found - if (opt.nothrow) - return null +/***/ }), - throw getNotFoundError(cmd) -} +/***/ "./sources/miscUtils.ts": +/*!******************************!*\ + !*** ./sources/miscUtils.ts ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -module.exports = which -which.sync = whichSync +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Cancellation": () => (/* binding */ Cancellation) +/* harmony export */ }); +class Cancellation extends Error { + constructor() { + super(`Cancelled operation`); + } +} /***/ }), -/***/ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/iterator.js": -/*!**************************************************************************************************!*\ - !*** ./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/iterator.js ***! - \**************************************************************************************************/ -/***/ ((module) => { +/***/ "./sources/nodeUtils.ts": +/*!******************************!*\ + !*** ./sources/nodeUtils.ts ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), +/* harmony export */ "loadMainModule": () => (/* binding */ loadMainModule), +/* harmony export */ "registerV8CompileCache": () => (/* binding */ registerV8CompileCache) +/* harmony export */ }); +/* harmony import */ var module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! module */ "module"); +/* harmony import */ var module__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(module__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -module.exports = function (Yallist) { - Yallist.prototype[Symbol.iterator] = function* () { - for (let walker = this.head; walker; walker = walker.next) { - yield walker.value + +const dynamicRequire = typeof require !== `undefined` + ? require + : __webpack_require__("./sources sync recursive"); +function getV8CompileCachePath() { + return typeof require !== `undefined` + ? `./vcc.js` + : `corepack/dist/vcc.js`; +} +function registerV8CompileCache() { + const vccPath = getV8CompileCachePath(); + dynamicRequire(vccPath); +} +/** + * Loads a module as a main module, enabling the `require.main === module` pattern. + */ +function loadMainModule(id) { + const modulePath = module__WEBPACK_IMPORTED_MODULE_0___default()._resolveFilename(id, null, true); + const module = new (module__WEBPACK_IMPORTED_MODULE_0___default())(modulePath, undefined); + module.filename = modulePath; + module.paths = module__WEBPACK_IMPORTED_MODULE_0___default()._nodeModulePaths(path__WEBPACK_IMPORTED_MODULE_1___default().dirname(modulePath)); + (module__WEBPACK_IMPORTED_MODULE_0___default()._cache)[modulePath] = module; + process.mainModule = module; + module.id = `.`; + try { + return module.load(modulePath); + } + catch (error) { + delete (module__WEBPACK_IMPORTED_MODULE_0___default()._cache)[modulePath]; + throw error; } - } } /***/ }), -/***/ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/yallist.js": -/*!*************************************************************************************************!*\ - !*** ./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/yallist.js ***! - \*************************************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./sources/semverUtils.ts": +/*!********************************!*\ + !*** ./sources/semverUtils.ts ***! + \********************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "satisfiesWithPrereleases": () => (/* binding */ satisfiesWithPrereleases) +/* harmony export */ }); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js"); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_0__); -module.exports = Yallist - -Yallist.Node = Node -Yallist.create = Yallist - -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } - - self.tail = null - self.head = null - self.length = 0 - - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) +/** + * Returns whether the given semver version satisfies the given range. Notably + * this supports prerelease versions so that "2.0.0-rc.0" satisfies the range + * ">=1.0.0", for example. + * + * This function exists because the semver.satisfies method does not include + * pre releases. This means ranges such as * would not satisfy 1.0.0-rc. The + * includePrerelease flag has a weird behavior and cannot be used (if you want + * to try it out, just run the `semverUtils` testsuite using this flag instead + * of our own implementation, and you'll see the failing cases). + * + * See https://github.com/yarnpkg/berry/issues/575 for more context. + */ +function satisfiesWithPrereleases(version, range, loose = false) { + let semverRange; + try { + semverRange = new (semver__WEBPACK_IMPORTED_MODULE_0___default().Range)(range, loose); } - } - - return self + catch (err) { + return false; + } + if (!version) + return false; + let semverVersion; + try { + semverVersion = new (semver__WEBPACK_IMPORTED_MODULE_0___default().SemVer)(version, semverRange.loose); + if (semverVersion.prerelease) { + semverVersion.prerelease = []; + } + } + catch (err) { + return false; + } + // A range has multiple sets of comparators. A version must satisfy all + // comparators in a set and at least one set to satisfy the range. + return semverRange.set.some(comparatorSet => { + for (const comparator of comparatorSet) + if (comparator.semver.prerelease) + comparator.semver.prerelease = []; + return comparatorSet.every(comparator => { + return comparator.test(semverVersion); + }); + }); } -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } - var next = node.next - var prev = node.prev +/***/ }), - if (next) { - next.prev = prev - } +/***/ "./sources/specUtils.ts": +/*!******************************!*\ + !*** ./sources/specUtils.ts ***! + \******************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (prev) { - prev.next = next - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "findProjectSpec": () => (/* binding */ findProjectSpec), +/* harmony export */ "loadSpec": () => (/* binding */ loadSpec), +/* harmony export */ "parseSpec": () => (/* binding */ parseSpec) +/* harmony export */ }); +/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-72ec1bc418/4/.yarn/berry/cache/clipanion-npm-3.1.0-ced87dbbea-9.zip/node_modules/clipanion/lib/advanced/index.js"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! fs */ "fs"); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! path */ "path"); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ "../../../.yarn/berry/cache/semver-npm-7.3.7-3bfe704194-9.zip/node_modules/semver/index.js"); +/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types */ "./sources/types.ts"); - if (node === this.head) { - this.head = next - } - if (node === this.tail) { - this.tail = prev - } - node.list.length-- - node.next = null - node.prev = null - node.list = null - return next + + +const nodeModulesRegExp = /[\\/]node_modules[\\/](@[^\\/]*[\\/])?([^@\\/][^\\/]*)$/; +function parseSpec(raw, source) { + if (typeof raw !== `string`) + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager specification in ${source}; expected a string`); + const match = raw.match(/^(?!_)(.+)@(.+)$/); + if (match === null || !semver__WEBPACK_IMPORTED_MODULE_2___default().valid(match[2])) + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package manager specification in ${source}; expected a semver version`); + if (!(0,_types__WEBPACK_IMPORTED_MODULE_3__.isSupportedPackageManager)(match[1])) + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Unsupported package manager specification (${match})`); + return { + name: match[1], + range: match[2], + }; +} +/** + * Locates the active project's package manager specification. + * + * If the specification exists but doesn't match the active package manager, + * an error is thrown to prevent users from using the wrong package manager, + * which would lead to inconsistent project layouts. + * + * If the project doesn't include a specification file, we just assume that + * whatever the user uses is exactly what they want to use. Since the version + * isn't explicited, we fallback on known good versions. + * + * Finally, if the project doesn't exist at all, we ask the user whether they + * want to create one in the current project. If they do, we initialize a new + * project using the default package managers, and configure it so that we + * don't need to ask again in the future. + */ +async function findProjectSpec(initialCwd, locator, { transparent = false } = {}) { + // A locator is a valid descriptor (but not the other way around) + const fallbackLocator = { name: locator.name, range: locator.reference }; + while (true) { + const result = await loadSpec(initialCwd); + switch (result.type) { + case `NoProject`: + case `NoSpec`: + { + return fallbackLocator; + } + break; + case `Found`: + { + if (result.spec.name !== locator.name) { + if (transparent) { + return fallbackLocator; + } + else { + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`This project is configured to use ${result.spec.name}`); + } + } + else { + return result.spec; + } + } + break; + } + } +} +async function loadSpec(initialCwd) { + let nextCwd = initialCwd; + let currCwd = ``; + let selection = null; + while (nextCwd !== currCwd && (!selection || !selection.data.packageManager)) { + currCwd = nextCwd; + nextCwd = path__WEBPACK_IMPORTED_MODULE_1___default().dirname(currCwd); + if (nodeModulesRegExp.test(currCwd)) + continue; + const manifestPath = path__WEBPACK_IMPORTED_MODULE_1___default().join(currCwd, `package.json`); + if (!fs__WEBPACK_IMPORTED_MODULE_0___default().existsSync(manifestPath)) + continue; + const content = await fs__WEBPACK_IMPORTED_MODULE_0___default().promises.readFile(manifestPath, `utf8`); + let data; + try { + data = JSON.parse(content); + } + catch (_a) { } + if (typeof data !== `object` || data === null) + throw new clipanion__WEBPACK_IMPORTED_MODULE_4__.UsageError(`Invalid package.json in ${path__WEBPACK_IMPORTED_MODULE_1___default().relative(initialCwd, manifestPath)}`); + selection = { data, manifestPath }; + } + if (selection === null) + return { type: `NoProject`, target: path__WEBPACK_IMPORTED_MODULE_1___default().join(initialCwd, `package.json`) }; + const rawPmSpec = selection.data.packageManager; + if (typeof rawPmSpec === `undefined`) + return { type: `NoSpec`, target: selection.manifestPath }; + return { + type: `Found`, + spec: parseSpec(rawPmSpec, path__WEBPACK_IMPORTED_MODULE_1___default().relative(initialCwd, selection.manifestPath)), + }; } -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - if (node.list) { - node.list.removeNode(node) - } +/***/ }), - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node - } +/***/ "./sources/types.ts": +/*!**************************!*\ + !*** ./sources/types.ts ***! + \**************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - this.head = node - if (!this.tail) { - this.tail = node - } - this.length++ +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SupportedPackageManagerSet": () => (/* binding */ SupportedPackageManagerSet), +/* harmony export */ "SupportedPackageManagerSetWithoutNpm": () => (/* binding */ SupportedPackageManagerSetWithoutNpm), +/* harmony export */ "SupportedPackageManagers": () => (/* binding */ SupportedPackageManagers), +/* harmony export */ "isSupportedPackageManager": () => (/* binding */ isSupportedPackageManager) +/* harmony export */ }); +var SupportedPackageManagers; +(function (SupportedPackageManagers) { + SupportedPackageManagers["Npm"] = "npm"; + SupportedPackageManagers["Pnpm"] = "pnpm"; + SupportedPackageManagers["Yarn"] = "yarn"; +})(SupportedPackageManagers || (SupportedPackageManagers = {})); +const SupportedPackageManagerSet = new Set(Object.values(SupportedPackageManagers)); +const SupportedPackageManagerSetWithoutNpm = new Set(Object.values(SupportedPackageManagers)); +// npm is distributed with Node as a builtin; we don't want Corepack to override it unless the npm team is on board +SupportedPackageManagerSetWithoutNpm.delete(SupportedPackageManagers.Npm); +function isSupportedPackageManager(value) { + return SupportedPackageManagerSet.has(value); } -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return - } - if (node.list) { - node.list.removeNode(node) - } +/***/ }), - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node - } +/***/ "./sources sync recursive": +/*!***********************!*\ + !*** ./sources/ sync ***! + \***********************/ +/***/ ((module) => { - this.tail = node - if (!this.head) { - this.head = node - } - this.length++ +function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } +webpackEmptyContext.keys = () => ([]); +webpackEmptyContext.resolve = webpackEmptyContext; +webpackEmptyContext.id = "./sources sync recursive"; +module.exports = webpackEmptyContext; -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) - } - return this.length -} +/***/ }), -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) - } - return this.length -} +/***/ "assert": +/*!*************************!*\ + !*** external "assert" ***! + \*************************/ +/***/ ((module) => { -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined - } +"use strict"; +module.exports = require("assert"); - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null - } - this.length-- - return res -} +/***/ }), -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined - } +/***/ "async_hooks": +/*!******************************!*\ + !*** external "async_hooks" ***! + \******************************/ +/***/ ((module) => { - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null - } else { - this.tail = null - } - this.length-- - return res -} +"use strict"; +module.exports = require("async_hooks"); -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next - } -} +/***/ }), -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev - } -} +/***/ "buffer": +/*!*************************!*\ + !*** external "buffer" ***! + \*************************/ +/***/ ((module) => { -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next - } - if (i === n && walker !== null) { - return walker.value - } -} +"use strict"; +module.exports = require("buffer"); -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev - } - if (i === n && walker !== null) { - return walker.value - } -} +/***/ }), -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next - } - return res -} +/***/ "constants": +/*!****************************!*\ + !*** external "constants" ***! + \****************************/ +/***/ ((module) => { -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev - } - return res -} +"use strict"; +module.exports = require("constants"); -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } +/***/ }), - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next - } +/***/ "crypto": +/*!*************************!*\ + !*** external "crypto" ***! + \*************************/ +/***/ ((module) => { - return acc -} +"use strict"; +module.exports = require("crypto"); -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } +/***/ }), - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev - } +/***/ "dns": +/*!**********************!*\ + !*** external "dns" ***! + \**********************/ +/***/ ((module) => { - return acc -} +"use strict"; +module.exports = require("dns"); -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next - } - return arr -} +/***/ }), -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev - } - return arr -} +/***/ "events": +/*!*************************!*\ + !*** external "events" ***! + \*************************/ +/***/ ((module) => { -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) - } - return ret -} +"use strict"; +module.exports = require("events"); + +/***/ }), + +/***/ "fs": +/*!*********************!*\ + !*** external "fs" ***! + \*********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("fs"); + +/***/ }), + +/***/ "fs/promises": +/*!******************************!*\ + !*** external "fs/promises" ***! + \******************************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("fs/promises"); + +/***/ }), + +/***/ "http": +/*!***********************!*\ + !*** external "http" ***! + \***********************/ +/***/ ((module) => { -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) - } - return ret -} +"use strict"; +module.exports = require("http"); -Yallist.prototype.splice = function (start, deleteCount, ...nodes) { - if (start > this.length) { - start = this.length - 1 - } - if (start < 0) { - start = this.length + start; - } +/***/ }), - for (var i = 0, walker = this.head; walker !== null && i < start; i++) { - walker = walker.next - } +/***/ "https": +/*!************************!*\ + !*** external "https" ***! + \************************/ +/***/ ((module) => { - var ret = [] - for (var i = 0; walker && i < deleteCount; i++) { - ret.push(walker.value) - walker = this.removeNode(walker) - } - if (walker === null) { - walker = this.tail - } +"use strict"; +module.exports = require("https"); - if (walker !== this.head && walker !== this.tail) { - walker = walker.prev - } +/***/ }), - for (var i = 0; i < nodes.length; i++) { - walker = insert(this, walker, nodes[i]) - } - return ret; -} +/***/ "module": +/*!*************************!*\ + !*** external "module" ***! + \*************************/ +/***/ ((module) => { -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p - } - this.head = tail - this.tail = head - return this -} +"use strict"; +module.exports = require("module"); -function insert (self, node, value) { - var inserted = node === self.head ? - new Node(value, null, node, self) : - new Node(value, node, node.next, self) +/***/ }), - if (inserted.next === null) { - self.tail = inserted - } - if (inserted.prev === null) { - self.head = inserted - } +/***/ "net": +/*!**********************!*\ + !*** external "net" ***! + \**********************/ +/***/ ((module) => { - self.length++ +"use strict"; +module.exports = require("net"); - return inserted -} +/***/ }), -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail - } - self.length++ -} +/***/ "node:os": +/*!**************************!*\ + !*** external "node:os" ***! + \**************************/ +/***/ ((module) => { -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ -} +"use strict"; +module.exports = require("node:os"); -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } +/***/ }), - this.list = list - this.value = value +/***/ "node:process": +/*!*******************************!*\ + !*** external "node:process" ***! + \*******************************/ +/***/ ((module) => { - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null - } +"use strict"; +module.exports = require("node:process"); - if (next) { - next.prev = this - this.next = next - } else { - this.next = null - } -} +/***/ }), -try { - // add if support for Symbol.iterator is present - __webpack_require__(/*! ./iterator.js */ "./.yarn/cache/yallist-npm-4.0.0-b493d9e907-343617202a.zip/node_modules/yallist/iterator.js")(Yallist) -} catch (er) {} +/***/ "node:tty": +/*!***************************!*\ + !*** external "node:tty" ***! + \***************************/ +/***/ ((module) => { +"use strict"; +module.exports = require("node:tty"); /***/ }), -/***/ "./config.json": +/***/ "os": /*!*********************!*\ - !*** ./config.json ***! + !*** external "os" ***! \*********************/ /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"definitions":{"npm":{"default":"7.20.1","transparent":{"commands":[["npm","init"],["npx"]]},"ranges":{"*":{"url":"https://registry.npmjs.org/npm/-/npm-{}.tgz","bin":{"npm":"./bin/npm-cli.js","npx":"./bin/npx-cli.js"},"registry":{"type":"npm","package":"npm"}}}},"pnpm":{"default":"6.11.0","transparent":{"commands":[["pnpm","init"],["pnpx"]]},"ranges":{"<6.0.0":{"url":"https://registry.npmjs.org/pnpm/-/pnpm-{}.tgz","bin":{"pnpm":"./bin/pnpm.js","pnpx":"./bin/pnpx.js"},"registry":{"type":"npm","package":"pnpm"}},">=6.0.0":{"url":"https://registry.npmjs.org/pnpm/-/pnpm-{}.tgz","bin":{"pnpm":"./bin/pnpm.cjs","pnpx":"./bin/pnpx.cjs"},"registry":{"type":"npm","package":"pnpm"}}}},"yarn":{"default":"1.22.15","transparent":{"default":"3.0.0","commands":[["yarn","dlx"]]},"ranges":{"<2.0.0":{"url":"https://registry.yarnpkg.com/yarn/-/yarn-{}.tgz","bin":{"yarn":"./bin/yarn.js","yarnpkg":"./bin/yarn.js"},"registry":{"type":"npm","package":"yarn"}},">=2.0.0":{"name":"yarn","url":"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js","bin":["yarn","yarnpkg"],"registry":{"type":"url","url":"https://repo.yarnpkg.com/tags","fields":{"tags":"latest","versions":"tags"}}}}}}}'); +module.exports = require("os"); /***/ }), -/***/ "./package.json": -/*!**********************!*\ - !*** ./package.json ***! - \**********************/ +/***/ "path": +/*!***********************!*\ + !*** external "path" ***! + \***********************/ /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"name":"corepack","version":"0.10.0","homepage":"https://github.com/nodejs/corepack#readme","bugs":{"url":"https://github.com/nodejs/corepack/issues"},"repository":{"type":"git","url":"https://github.com/nodejs/corepack.git"},"license":"MIT","bin":{"corepack":"./dist/corepack.js","pnpm":"./dist/pnpm.js","pnpx":"./dist/pnpx.js","yarn":"./dist/yarn.js","yarnpkg":"./dist/yarnpkg.js"},"packageManager":"yarn@3.0.0","devDependencies":{"@babel/core":"^7.14.3","@babel/plugin-proposal-class-properties":"^7.13.0","@babel/plugin-proposal-decorators":"^7.14.2","@babel/plugin-proposal-nullish-coalescing-operator":"^7.10.4","@babel/plugin-transform-modules-commonjs":"^7.14.0","@babel/preset-typescript":"^7.13.0","@types/debug":"^4.1.5","@types/jest":"^26.0.23","@types/node":"^13.9.2","@types/semver":"^7.1.0","@types/tar":"^4.0.3","@types/which":"^1.3.2","@typescript-eslint/eslint-plugin":"^2.0.0","@typescript-eslint/parser":"^4.2.0","@yarnpkg/eslint-config":"^0.1.0","@yarnpkg/fslib":"^2.1.0","@zkochan/cmd-shim":"^5.0.0","babel-plugin-dynamic-import-node":"^2.3.3","clipanion":"^3.0.1","debug":"^4.1.1","eslint":"^7.10.0","eslint-plugin-arca":"^0.9.5","jest":"^26.0.0","nock":"^13.0.4","semver":"^7.1.3","supports-color":"^7.1.0","tar":"^6.0.1","terser-webpack-plugin":"^5.1.2","ts-loader":"^8.0.2","ts-node":"^8.10.2","typescript":"^4.3.2","v8-compile-cache":"^2.3.0","webpack":"^5.38.1","webpack-cli":"^3.3.11","which":"^2.0.2"},"scripts":{"build":"rm -rf dist && webpack && ts-node ./mkshims.ts","corepack":"ts-node ./sources/main.ts","prepack":"node ./.yarn/releases/*.*js build","postpack":"rm -rf dist shims","test":"yarn jest"},"files":["dist","shims","LICENSE.md"],"publishConfig":{"executableFiles":["./dist/npm.js","./dist/npx.js","./dist/pnpm.js","./dist/pnpx.js","./dist/yarn.js","./dist/yarnpkg.js","./dist/corepack.js","./shims/npm","./shims/npm.ps1","./shims/npx","./shims/npx.ps1","./shims/pnpm","./shims/pnpm.ps1","./shims/pnpx","./shims/pnpx.ps1","./shims/yarn","./shims/yarn.ps1","./shims/yarnpkg","./shims/yarnpkg.ps1"]}}'); +module.exports = require("path"); /***/ }), -/***/ "assert": +/***/ "stream": /*!*************************!*\ - !*** external "assert" ***! + !*** external "stream" ***! \*************************/ /***/ ((module) => { "use strict"; -module.exports = require("assert");; +module.exports = require("stream"); /***/ }), -/***/ "buffer": -/*!*************************!*\ - !*** external "buffer" ***! - \*************************/ +/***/ "string_decoder": +/*!*********************************!*\ + !*** external "string_decoder" ***! + \*********************************/ /***/ ((module) => { "use strict"; -module.exports = require("buffer");; +module.exports = require("string_decoder"); /***/ }), -/***/ "child_process": -/*!********************************!*\ - !*** external "child_process" ***! - \********************************/ +/***/ "tls": +/*!**********************!*\ + !*** external "tls" ***! + \**********************/ /***/ ((module) => { "use strict"; -module.exports = require("child_process");; +module.exports = require("tls"); /***/ }), -/***/ "crypto": -/*!*************************!*\ - !*** external "crypto" ***! - \*************************/ +/***/ "tty": +/*!**********************!*\ + !*** external "tty" ***! + \**********************/ /***/ ((module) => { "use strict"; -module.exports = require("crypto");; +module.exports = require("tty"); /***/ }), -/***/ "events": -/*!*************************!*\ - !*** external "events" ***! - \*************************/ +/***/ "url": +/*!**********************!*\ + !*** external "url" ***! + \**********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("url"); + +/***/ }), + +/***/ "util": +/*!***********************!*\ + !*** external "util" ***! + \***********************/ +/***/ ((module) => { + +"use strict"; +module.exports = require("util"); + +/***/ }), + +/***/ "zlib": +/*!***********************!*\ + !*** external "zlib" ***! + \***********************/ /***/ ((module) => { -"use strict"; -module.exports = require("events");; +"use strict"; +module.exports = require("zlib"); + +/***/ }), + +/***/ "../../../.yarn/berry/cache/supports-color-npm-9.2.2-d003069e84-9.zip/node_modules/supports-color/index.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/supports-color-npm-9.2.2-d003069e84-9.zip/node_modules/supports-color/index.js ***! + \*****************************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createSupportsColor": () => (/* binding */ createSupportsColor), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var node_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! node:process */ "node:process"); +/* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! node:os */ "node:os"); +/* harmony import */ var node_tty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! node:tty */ "node:tty"); + + + + +// From: https://github.com/sindresorhus/has-flag/blob/main/index.js +function hasFlag(flag, argv = node_process__WEBPACK_IMPORTED_MODULE_0__.argv) { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +} + +const {env} = node_process__WEBPACK_IMPORTED_MODULE_0__; + +let flagForceColor; +if ( + hasFlag('no-color') + || hasFlag('no-colors') + || hasFlag('color=false') + || hasFlag('color=never') +) { + flagForceColor = 0; +} else if ( + hasFlag('color') + || hasFlag('colors') + || hasFlag('color=true') + || hasFlag('color=always') +) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') + || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } -/***/ }), + if (hasFlag('color=256')) { + return 2; + } + } -/***/ "fs": -/*!*********************!*\ - !*** external "fs" ***! - \*********************/ -/***/ ((module) => { + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } -"use strict"; -module.exports = require("fs");; + const min = forceColor || 0; -/***/ }), + if (env.TERM === 'dumb') { + return min; + } -/***/ "https": -/*!************************!*\ - !*** external "https" ***! - \************************/ -/***/ ((module) => { + if (node_process__WEBPACK_IMPORTED_MODULE_0__.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = node_os__WEBPACK_IMPORTED_MODULE_1__.release().split('.'); + if ( + Number(osRelease[0]) >= 10 + && Number(osRelease[2]) >= 10_586 + ) { + return Number(osRelease[2]) >= 14_931 ? 3 : 2; + } -"use strict"; -module.exports = require("https");; + return 1; + } -/***/ }), + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } -/***/ "os": -/*!*********************!*\ - !*** external "os" ***! - \*********************/ -/***/ ((module) => { + return min; + } -"use strict"; -module.exports = require("os");; + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -/***/ }), + // Check for Azure DevOps pipelines + if ('TF_BUILD' in env && 'AGENT_NAME' in env) { + return 1; + } -/***/ "path": -/*!***********************!*\ - !*** external "path" ***! - \***********************/ -/***/ ((module) => { + if (env.COLORTERM === 'truecolor') { + return 3; + } -"use strict"; -module.exports = require("path");; + if ('TERM_PROGRAM' in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); -/***/ }), + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } -/***/ "stream": -/*!*************************!*\ - !*** external "stream" ***! - \*************************/ -/***/ ((module) => { + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -"use strict"; -module.exports = require("stream");; + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -/***/ }), + if ('COLORTERM' in env) { + return 1; + } -/***/ "string_decoder": -/*!*********************************!*\ - !*** external "string_decoder" ***! - \*********************************/ -/***/ ((module) => { + return min; +} -"use strict"; -module.exports = require("string_decoder");; +function createSupportsColor(stream, options = {}) { + const level = _supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options, + }); -/***/ }), + return translateLevel(level); +} -/***/ "tty": -/*!**********************!*\ - !*** external "tty" ***! - \**********************/ -/***/ ((module) => { +const supportsColor = { + stdout: createSupportsColor({isTTY: node_tty__WEBPACK_IMPORTED_MODULE_2__.isatty(1)}), + stderr: createSupportsColor({isTTY: node_tty__WEBPACK_IMPORTED_MODULE_2__.isatty(2)}), +}; + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (supportsColor); -"use strict"; -module.exports = require("tty");; /***/ }), -/***/ "util": -/*!***********************!*\ - !*** external "util" ***! - \***********************/ +/***/ "./config.json": +/*!*********************!*\ + !*** ./config.json ***! + \*********************/ /***/ ((module) => { "use strict"; -module.exports = require("util");; +module.exports = JSON.parse('{"definitions":{"npm":{"default":"8.12.1","transparent":{"commands":[["npm","init"],["npx"]]},"ranges":{"*":{"url":"https://registry.npmjs.org/npm/-/npm-{}.tgz","bin":{"npm":"./bin/npm-cli.js","npx":"./bin/npx-cli.js"},"registry":{"type":"npm","package":"npm"}}}},"pnpm":{"default":"7.2.1","transparent":{"commands":[["pnpm","init"],["pnpx"],["pnpm","dlx"]]},"ranges":{"<6.0.0":{"url":"https://registry.npmjs.org/pnpm/-/pnpm-{}.tgz","bin":{"pnpm":"./bin/pnpm.js","pnpx":"./bin/pnpx.js"},"registry":{"type":"npm","package":"pnpm"}},">=6.0.0":{"url":"https://registry.npmjs.org/pnpm/-/pnpm-{}.tgz","bin":{"pnpm":"./bin/pnpm.cjs","pnpx":"./bin/pnpx.cjs"},"registry":{"type":"npm","package":"pnpm"}}}},"yarn":{"default":"1.22.19","transparent":{"default":"3.2.1","commands":[["yarn","dlx"]]},"ranges":{"<2.0.0":{"url":"https://registry.yarnpkg.com/yarn/-/yarn-{}.tgz","bin":{"yarn":"./bin/yarn.js","yarnpkg":"./bin/yarn.js"},"registry":{"type":"npm","package":"yarn"}},">=2.0.0":{"name":"yarn","url":"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js","bin":["yarn","yarnpkg"],"registry":{"type":"url","url":"https://repo.yarnpkg.com/tags","fields":{"tags":"latest","versions":"tags"}}}}}}}'); /***/ }), -/***/ "zlib": -/*!***********************!*\ - !*** external "zlib" ***! - \***********************/ +/***/ "./package.json": +/*!**********************!*\ + !*** ./package.json ***! + \**********************/ /***/ ((module) => { "use strict"; -module.exports = require("zlib");; +module.exports = JSON.parse('{"name":"corepack","version":"0.11.2","homepage":"https://github.com/nodejs/corepack#readme","bugs":{"url":"https://github.com/nodejs/corepack/issues"},"repository":{"type":"git","url":"https://github.com/nodejs/corepack.git"},"license":"MIT","packageManager":"yarn@4.0.0-rc.6","devDependencies":{"@babel/core":"^7.14.3","@babel/plugin-transform-modules-commonjs":"^7.14.0","@babel/preset-typescript":"^7.13.0","@types/debug":"^4.1.5","@types/jest":"^27.0.0","@types/node":"^17.0.10","@types/semver":"^7.1.0","@types/tar":"^6.0.0","@types/which":"^2.0.0","@typescript-eslint/eslint-plugin":"^5.0.0","@typescript-eslint/parser":"^5.0.0","@yarnpkg/eslint-config":"^1.0.0-rc.5","@yarnpkg/fslib":"^2.1.0","@zkochan/cmd-shim":"^5.0.0","babel-plugin-dynamic-import-node":"^2.3.3","clipanion":"^3.0.1","debug":"^4.1.1","eslint":"^8.0.0","eslint-plugin-arca":"^0.15.0","jest":"^28.0.0","nock":"^13.0.4","proxy-agent":"^5.0.0","semver":"^7.1.3","supports-color":"^9.0.0","tar":"^6.0.1","terser-webpack-plugin":"^5.1.2","ts-loader":"^9.0.0","ts-node":"^10.0.0","typescript":"^4.3.2","v8-compile-cache":"^2.3.0","webpack":"^5.38.1","webpack-cli":"^4.0.0","which":"^2.0.2"},"scripts":{"build":"rm -rf dist shims && webpack && ts-node ./mkshims.ts","corepack":"ts-node ./sources/_entryPoint.ts","lint":"yarn eslint","prepack":"yarn build","postpack":"rm -rf dist shims","typecheck":"tsc --noEmit","test":"yarn jest"},"files":["dist","shims","LICENSE.md"],"publishConfig":{"bin":{"corepack":"./dist/corepack.js","pnpm":"./dist/pnpm.js","pnpx":"./dist/pnpx.js","yarn":"./dist/yarn.js","yarnpkg":"./dist/yarnpkg.js"},"executableFiles":["./dist/npm.js","./dist/npx.js","./dist/pnpm.js","./dist/pnpx.js","./dist/yarn.js","./dist/yarnpkg.js","./dist/corepack.js","./shims/npm","./shims/npm.ps1","./shims/npx","./shims/npx.ps1","./shims/pnpm","./shims/pnpm.ps1","./shims/pnpx","./shims/pnpx.ps1","./shims/yarn","./shims/yarn.ps1","./shims/yarnpkg","./shims/yarnpkg.ps1"]},"resolutions":{"vm2":"patch:vm2@npm:3.9.9#.yarn/patches/vm2-npm-3.9.9-03fd1f4dc5.patch"}}'); /***/ }) @@ -14636,12 +16830,15 @@ module.exports = require("zlib");; /******/ }; /******/ /******/ // Execute the module function -/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = __webpack_modules__; +/******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { @@ -14697,6 +16894,28 @@ module.exports = require("zlib");; /******/ }; /******/ })(); /******/ +/******/ /* webpack/runtime/ensure chunk */ +/******/ (() => { +/******/ __webpack_require__.f = {}; +/******/ // This file contains only the entry chunk. +/******/ // The chunk loading function for additional chunks +/******/ __webpack_require__.e = (chunkId) => { +/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => { +/******/ __webpack_require__.f[key](chunkId, promises); +/******/ return promises; +/******/ }, [])); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/get javascript chunk filename */ +/******/ (() => { +/******/ // This function allow to reference async chunks +/******/ __webpack_require__.u = (chunkId) => { +/******/ // return url for filenames based on template +/******/ return "" + chunkId + ".js"; +/******/ }; +/******/ })(); +/******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) @@ -14713,148 +16932,67 @@ module.exports = require("zlib");; /******/ }; /******/ })(); /******/ +/******/ /* webpack/runtime/require chunk loading */ +/******/ (() => { +/******/ // no baseURI +/******/ +/******/ // object to store loaded chunks +/******/ // "1" means "loaded", otherwise not loaded yet +/******/ var installedChunks = { +/******/ "corepack": 1 +/******/ }; +/******/ +/******/ // no on chunks loaded +/******/ +/******/ var installChunk = (chunk) => { +/******/ var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime; +/******/ for(var moduleId in moreModules) { +/******/ if(__webpack_require__.o(moreModules, moduleId)) { +/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; +/******/ } +/******/ } +/******/ if(runtime) runtime(__webpack_require__); +/******/ for(var i = 0; i < chunkIds.length; i++) +/******/ installedChunks[chunkIds[i]] = 1; +/******/ +/******/ }; +/******/ +/******/ // require() chunk loading for javascript +/******/ __webpack_require__.f.require = (chunkId, promises) => { +/******/ // "1" is the signal for "already loaded" +/******/ if(!installedChunks[chunkId]) { +/******/ if(true) { // all chunks have JS +/******/ installChunk(require("./" + __webpack_require__.u(chunkId))); +/******/ } else installedChunks[chunkId] = 1; +/******/ } +/******/ }; +/******/ +/******/ // no external install chunk +/******/ +/******/ // no HMR +/******/ +/******/ // no HMR manifest +/******/ })(); +/******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be in strict mode. (() => { "use strict"; -/*!*************************!*\ - !*** ./sources/main.ts ***! - \*************************/ +/*!********************************!*\ + !*** ./sources/_entryPoint.ts ***! + \********************************/ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "main": () => (/* binding */ main), -/* harmony export */ "runMain": () => (/* binding */ runMain) +/* harmony export */ "runMain": () => (/* reexport safe */ _main__WEBPACK_IMPORTED_MODULE_0__.runMain) /* harmony export */ }); -/* harmony import */ var clipanion__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! clipanion */ "./.yarn/__virtual__/clipanion-virtual-119dc92083/0/cache/clipanion-npm-3.0.1-901533eeed-3a4b0c1e7d.zip/node_modules/clipanion/lib/advanced/index.js"); -/* harmony import */ var _Engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Engine */ "./sources/Engine.ts"); -/* harmony import */ var _commands_Disable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./commands/Disable */ "./sources/commands/Disable.ts"); -/* harmony import */ var _commands_Enable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./commands/Enable */ "./sources/commands/Enable.ts"); -/* harmony import */ var _commands_Hydrate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./commands/Hydrate */ "./sources/commands/Hydrate.ts"); -/* harmony import */ var _commands_Prepare__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./commands/Prepare */ "./sources/commands/Prepare.ts"); -/* harmony import */ var _miscUtils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./miscUtils */ "./sources/miscUtils.ts"); -/* harmony import */ var _corepackUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./corepackUtils */ "./sources/corepackUtils.ts"); -/* harmony import */ var _specUtils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./specUtils */ "./sources/specUtils.ts"); +/* harmony import */ var _main__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./main */ "./sources/main.ts"); +// Used by the generated shims - - - - - - - -function getPackageManagerRequestFromCli(parameter, context) { - if (!parameter) - return null; - const match = parameter.match(/^([^@]*)(?:@(.*))?$/); - if (!match) - return null; - const [, binaryName, binaryVersion] = match; - const packageManager = context.engine.getPackageManagerFor(binaryName); - if (!packageManager) - return null; - return { - packageManager, - binaryName, - binaryVersion: binaryVersion || null, - }; -} -async function executePackageManagerRequest({ packageManager, binaryName, binaryVersion }, args, context) { - var _a; - const defaultVersion = await context.engine.getDefaultVersion(packageManager); - const definition = context.engine.config.definitions[packageManager]; - // If all leading segments match one of the patterns defined in the `transparent` - // key, we tolerate calling this binary even if the local project isn't explicitly - // configured for it, and we use the special default version if requested. - let isTransparentCommand = false; - for (const transparentPath of definition.transparent.commands) { - if (transparentPath[0] === binaryName && transparentPath.slice(1).every((segment, index) => segment === args[index])) { - isTransparentCommand = true; - break; - } - } - const fallbackReference = isTransparentCommand - ? (_a = definition.transparent.default) !== null && _a !== void 0 ? _a : defaultVersion - : defaultVersion; - const fallbackLocator = { - name: packageManager, - reference: fallbackReference, - }; - let descriptor; - try { - descriptor = await _specUtils__WEBPACK_IMPORTED_MODULE_7__.findProjectSpec(context.cwd, fallbackLocator, { transparent: isTransparentCommand }); - } - catch (err) { - if (err instanceof _miscUtils__WEBPACK_IMPORTED_MODULE_5__.Cancellation) { - return 1; - } - else { - throw err; - } - } - if (binaryVersion) - descriptor.range = binaryVersion; - const resolved = await context.engine.resolveDescriptor(descriptor, { allowTags: true }); - if (resolved === null) - throw new clipanion__WEBPACK_IMPORTED_MODULE_8__.UsageError(`Failed to successfully resolve '${descriptor.range}' to a valid ${descriptor.name} release`); - const installSpec = await context.engine.ensurePackageManager(resolved); - const exitCode = await _corepackUtils__WEBPACK_IMPORTED_MODULE_6__.runVersion(installSpec, resolved, binaryName, args, context); - return exitCode; -} -async function main(argv, context) { - const corepackVersion = __webpack_require__(/*! ../package.json */ "./package.json").version; - const [firstArg, ...restArgs] = argv; - const request = getPackageManagerRequestFromCli(firstArg, context); - let cli; - if (!request) { - // If the first argument doesn't match any supported package manager, we fallback to the standard Corepack CLI - cli = new clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli({ - binaryLabel: `Corepack`, - binaryName: `corepack`, - binaryVersion: corepackVersion, - }); - cli.register(clipanion__WEBPACK_IMPORTED_MODULE_8__.Builtins.HelpCommand); - cli.register(clipanion__WEBPACK_IMPORTED_MODULE_8__.Builtins.VersionCommand); - cli.register(_commands_Enable__WEBPACK_IMPORTED_MODULE_2__.EnableCommand); - cli.register(_commands_Disable__WEBPACK_IMPORTED_MODULE_1__.DisableCommand); - cli.register(_commands_Hydrate__WEBPACK_IMPORTED_MODULE_3__.HydrateCommand); - cli.register(_commands_Prepare__WEBPACK_IMPORTED_MODULE_4__.PrepareCommand); - return await cli.run(argv, Object.assign(Object.assign({}, clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli.defaultContext), context)); - } - else { - // Otherwise, we create a single-command CLI to run the specified package manager (we still use Clipanion in order to pretty-print usage errors). - const cli = new clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli({ - binaryLabel: `'${request.binaryName}', via Corepack`, - binaryName: request.binaryName, - binaryVersion: `corepack/${corepackVersion}`, - }); - cli.register(class BinaryCommand extends clipanion__WEBPACK_IMPORTED_MODULE_8__.Command { - constructor() { - super(...arguments); - this.proxy = clipanion__WEBPACK_IMPORTED_MODULE_8__.Option.Proxy(); - } - async execute() { - return executePackageManagerRequest(request, this.proxy, this.context); - } - }); - return await cli.run(restArgs, Object.assign(Object.assign({}, clipanion__WEBPACK_IMPORTED_MODULE_8__.Cli.defaultContext), context)); - } -} -function runMain(argv) { - main(argv, { - cwd: process.cwd(), - engine: new _Engine__WEBPACK_IMPORTED_MODULE_0__.Engine(), - }).then(exitCode => { - process.exitCode = exitCode; - }, err => { - console.error(err.stack); - process.exitCode = 1; - }); -} // Using `eval` to be sure that Webpack doesn't transform it if (process.mainModule === eval(`module`)) - runMain(process.argv.slice(2)); + (0,_main__WEBPACK_IMPORTED_MODULE_0__.runMain)(process.argv.slice(2)); })(); diff --git a/deps/corepack/dist/vcc.js b/deps/corepack/dist/vcc.js index 69558e7cdd55a4..2a8c9014b546d1 100644 --- a/deps/corepack/dist/vcc.js +++ b/deps/corepack/dist/vcc.js @@ -3,10 +3,10 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ "./.yarn/cache/v8-compile-cache-npm-2.3.0-961375f150-adb0a271ea.zip/node_modules/v8-compile-cache/v8-compile-cache.js": -/*!****************************************************************************************************************************!*\ - !*** ./.yarn/cache/v8-compile-cache-npm-2.3.0-961375f150-adb0a271ea.zip/node_modules/v8-compile-cache/v8-compile-cache.js ***! - \****************************************************************************************************************************/ +/***/ "../../../.yarn/berry/cache/v8-compile-cache-npm-2.3.0-961375f150-9.zip/node_modules/v8-compile-cache/v8-compile-cache.js": +/*!********************************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/v8-compile-cache-npm-2.3.0-961375f150-9.zip/node_modules/v8-compile-cache/v8-compile-cache.js ***! + \********************************************************************************************************************************/ /***/ (function(module, exports) { 'use strict'; @@ -415,7 +415,7 @@ module.exports.__TEST__ = { /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module doesn't tell about it's top-level declarations so it can't be inlined -/******/ var __webpack_exports__ = __webpack_require__("./.yarn/cache/v8-compile-cache-npm-2.3.0-961375f150-adb0a271ea.zip/node_modules/v8-compile-cache/v8-compile-cache.js"); +/******/ var __webpack_exports__ = __webpack_require__("../../../.yarn/berry/cache/v8-compile-cache-npm-2.3.0-961375f150-9.zip/node_modules/v8-compile-cache/v8-compile-cache.js"); /******/ var __webpack_export_target__ = exports; /******/ for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i]; /******/ if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true }); diff --git a/deps/corepack/dist/vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js.js b/deps/corepack/dist/vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js.js new file mode 100644 index 00000000000000..4406f4966a4d0c --- /dev/null +++ b/deps/corepack/dist/vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js.js @@ -0,0 +1,40843 @@ +exports.id = "vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js"; +exports.ids = ["vendors-_yarn_berry_cache_proxy-agent-npm-5_0_0-41772f4b01-9_zip_node_modules_proxy-agent_index_js"]; +exports.modules = { + +/***/ "../../../.yarn/berry/cache/@tootallnate-once-npm-1.1.2-0517220057-9.zip/node_modules/@tootallnate/once/dist/index.js": +/*!****************************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/@tootallnate-once-npm-1.1.2-0517220057-9.zip/node_modules/@tootallnate/once/dist/index.js ***! + \****************************************************************************************************************************/ +/***/ ((module) => { + +"use strict"; + +function noop() { } +function once(emitter, name) { + const o = once.spread(emitter, name); + const r = o.then((args) => args[0]); + r.cancel = o.cancel; + return r; +} +(function (once) { + function spread(emitter, name) { + let c = null; + const p = new Promise((resolve, reject) => { + function cancel() { + emitter.removeListener(name, onEvent); + emitter.removeListener('error', onError); + p.cancel = noop; + } + function onEvent(...args) { + cancel(); + resolve(args); + } + function onError(err) { + cancel(); + reject(err); + } + c = cancel; + emitter.on(name, onEvent); + emitter.on('error', onError); + }); + if (!c) { + throw new TypeError('Could not get `cancel()` function'); + } + p.cancel = c; + return p; + } + once.spread = spread; +})(once || (once = {})); +module.exports = once; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "../../../.yarn/berry/cache/agent-base-npm-6.0.2-428f325a93-9.zip/node_modules/agent-base/dist/src/index.js": +/*!******************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/agent-base-npm-6.0.2-428f325a93-9.zip/node_modules/agent-base/dist/src/index.js ***! + \******************************************************************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __webpack_require__(/*! events */ "events"); +const debug_1 = __importDefault(__webpack_require__(/*! debug */ "./.yarn/__virtual__/debug-virtual-a35d5f160d/4/.yarn/berry/cache/debug-npm-4.3.4-4513954577-9.zip/node_modules/debug/src/index.js")); +const promisify_1 = __importDefault(__webpack_require__(/*! ./promisify */ "../../../.yarn/berry/cache/agent-base-npm-6.0.2-428f325a93-9.zip/node_modules/agent-base/dist/src/promisify.js")); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "../../../.yarn/berry/cache/agent-base-npm-6.0.2-428f325a93-9.zip/node_modules/agent-base/dist/src/promisify.js": +/*!**********************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/agent-base-npm-6.0.2-428f325a93-9.zip/node_modules/agent-base/dist/src/promisify.js ***! + \**********************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports["default"] = promisify; +//# sourceMappingURL=promisify.js.map + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel-core.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel-core.js ***! + \*****************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +function default_1(fork) { + fork.use(es7_1.default); + var types = fork.use(types_1.default); + var defaults = fork.use(shared_1.default).defaults; + var def = types.Type.def; + var or = types.Type.or; + def("Noop") + .bases("Statement") + .build(); + def("DoExpression") + .bases("Expression") + .build("body") + .field("body", [def("Statement")]); + def("Super") + .bases("Expression") + .build(); + def("BindExpression") + .bases("Expression") + .build("object", "callee") + .field("object", or(def("Expression"), null)) + .field("callee", def("Expression")); + def("Decorator") + .bases("Node") + .build("expression") + .field("expression", def("Expression")); + def("Property") + .field("decorators", or([def("Decorator")], null), defaults["null"]); + def("MethodDefinition") + .field("decorators", or([def("Decorator")], null), defaults["null"]); + def("MetaProperty") + .bases("Expression") + .build("meta", "property") + .field("meta", def("Identifier")) + .field("property", def("Identifier")); + def("ParenthesizedExpression") + .bases("Expression") + .build("expression") + .field("expression", def("Expression")); + def("ImportSpecifier") + .bases("ModuleSpecifier") + .build("imported", "local") + .field("imported", def("Identifier")); + def("ImportDefaultSpecifier") + .bases("ModuleSpecifier") + .build("local"); + def("ImportNamespaceSpecifier") + .bases("ModuleSpecifier") + .build("local"); + def("ExportDefaultDeclaration") + .bases("Declaration") + .build("declaration") + .field("declaration", or(def("Declaration"), def("Expression"))); + def("ExportNamedDeclaration") + .bases("Declaration") + .build("declaration", "specifiers", "source") + .field("declaration", or(def("Declaration"), null)) + .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray) + .field("source", or(def("Literal"), null), defaults["null"]); + def("ExportSpecifier") + .bases("ModuleSpecifier") + .build("local", "exported") + .field("exported", def("Identifier")); + def("ExportNamespaceSpecifier") + .bases("Specifier") + .build("exported") + .field("exported", def("Identifier")); + def("ExportDefaultSpecifier") + .bases("Specifier") + .build("exported") + .field("exported", def("Identifier")); + def("ExportAllDeclaration") + .bases("Declaration") + .build("exported", "source") + .field("exported", or(def("Identifier"), null)) + .field("source", def("Literal")); + def("CommentBlock") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); + def("CommentLine") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); + def("Directive") + .bases("Node") + .build("value") + .field("value", def("DirectiveLiteral")); + def("DirectiveLiteral") + .bases("Node", "Expression") + .build("value") + .field("value", String, defaults["use strict"]); + def("InterpreterDirective") + .bases("Node") + .build("value") + .field("value", String); + def("BlockStatement") + .bases("Statement") + .build("body") + .field("body", [def("Statement")]) + .field("directives", [def("Directive")], defaults.emptyArray); + def("Program") + .bases("Node") + .build("body") + .field("body", [def("Statement")]) + .field("directives", [def("Directive")], defaults.emptyArray) + .field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]); + // Split Literal + def("StringLiteral") + .bases("Literal") + .build("value") + .field("value", String); + def("NumericLiteral") + .bases("Literal") + .build("value") + .field("value", Number) + .field("raw", or(String, null), defaults["null"]) + .field("extra", { + rawValue: Number, + raw: String + }, function getDefault() { + return { + rawValue: this.value, + raw: this.value + "" + }; + }); + def("BigIntLiteral") + .bases("Literal") + .build("value") + // Only String really seems appropriate here, since BigInt values + // often exceed the limits of JS numbers. + .field("value", or(String, Number)) + .field("extra", { + rawValue: String, + raw: String + }, function getDefault() { + return { + rawValue: String(this.value), + raw: this.value + "n" + }; + }); + def("NullLiteral") + .bases("Literal") + .build() + .field("value", null, defaults["null"]); + def("BooleanLiteral") + .bases("Literal") + .build("value") + .field("value", Boolean); + def("RegExpLiteral") + .bases("Literal") + .build("pattern", "flags") + .field("pattern", String) + .field("flags", String) + .field("value", RegExp, function () { + return new RegExp(this.pattern, this.flags); + }); + var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement")); + // Split Property -> ObjectProperty and ObjectMethod + def("ObjectExpression") + .bases("Expression") + .build("properties") + .field("properties", [ObjectExpressionProperty]); + // ObjectMethod hoist .value properties to own properties + def("ObjectMethod") + .bases("Node", "Function") + .build("kind", "key", "params", "body", "computed") + .field("kind", or("method", "get", "set")) + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("params", [def("Pattern")]) + .field("body", def("BlockStatement")) + .field("computed", Boolean, defaults["false"]) + .field("generator", Boolean, defaults["false"]) + .field("async", Boolean, defaults["false"]) + .field("accessibility", // TypeScript + or(def("Literal"), null), defaults["null"]) + .field("decorators", or([def("Decorator")], null), defaults["null"]); + def("ObjectProperty") + .bases("Node") + .build("key", "value") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("value", or(def("Expression"), def("Pattern"))) + .field("accessibility", // TypeScript + or(def("Literal"), null), defaults["null"]) + .field("computed", Boolean, defaults["false"]); + var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod")); + // MethodDefinition -> ClassMethod + def("ClassBody") + .bases("Declaration") + .build("body") + .field("body", [ClassBodyElement]); + def("ClassMethod") + .bases("Declaration", "Function") + .build("kind", "key", "params", "body", "computed", "static") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))); + def("ClassPrivateMethod") + .bases("Declaration", "Function") + .build("key", "params", "body", "kind", "computed", "static") + .field("key", def("PrivateName")); + ["ClassMethod", + "ClassPrivateMethod", + ].forEach(function (typeName) { + def(typeName) + .field("kind", or("get", "set", "method", "constructor"), function () { return "method"; }) + .field("body", def("BlockStatement")) + .field("computed", Boolean, defaults["false"]) + .field("static", or(Boolean, null), defaults["null"]) + .field("abstract", or(Boolean, null), defaults["null"]) + .field("access", or("public", "private", "protected", null), defaults["null"]) + .field("accessibility", or("public", "private", "protected", null), defaults["null"]) + .field("decorators", or([def("Decorator")], null), defaults["null"]) + .field("optional", or(Boolean, null), defaults["null"]); + }); + def("ClassPrivateProperty") + .bases("ClassProperty") + .build("key", "value") + .field("key", def("PrivateName")) + .field("value", or(def("Expression"), null), defaults["null"]); + def("PrivateName") + .bases("Expression", "Pattern") + .build("id") + .field("id", def("Identifier")); + var ObjectPatternProperty = or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty"), // Used by Esprima + def("ObjectProperty"), // Babel 6 + def("RestProperty") // Babel 6 + ); + // Split into RestProperty and SpreadProperty + def("ObjectPattern") + .bases("Pattern") + .build("properties") + .field("properties", [ObjectPatternProperty]) + .field("decorators", or([def("Decorator")], null), defaults["null"]); + def("SpreadProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); + def("RestProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); + def("ForAwaitStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or(def("VariableDeclaration"), def("Expression"))) + .field("right", def("Expression")) + .field("body", def("Statement")); + // The callee node of a dynamic import(...) expression. + def("Import") + .bases("Expression") + .build(); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel.js ***! + \************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var babel_core_1 = tslib_1.__importDefault(__webpack_require__(/*! ./babel-core */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel-core.js")); +var flow_1 = tslib_1.__importDefault(__webpack_require__(/*! ./flow */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/flow.js")); +function default_1(fork) { + fork.use(babel_core_1.default); + fork.use(flow_1.default); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/core.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/core.js ***! + \***********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + var types = fork.use(types_1.default); + var Type = types.Type; + var def = Type.def; + var or = Type.or; + var shared = fork.use(shared_1.default); + var defaults = shared.defaults; + var geq = shared.geq; + // Abstract supertype of all syntactic entities that are allowed to have a + // .loc field. + def("Printable") + .field("loc", or(def("SourceLocation"), null), defaults["null"], true); + def("Node") + .bases("Printable") + .field("type", String) + .field("comments", or([def("Comment")], null), defaults["null"], true); + def("SourceLocation") + .field("start", def("Position")) + .field("end", def("Position")) + .field("source", or(String, null), defaults["null"]); + def("Position") + .field("line", geq(1)) + .field("column", geq(0)); + def("File") + .bases("Node") + .build("program", "name") + .field("program", def("Program")) + .field("name", or(String, null), defaults["null"]); + def("Program") + .bases("Node") + .build("body") + .field("body", [def("Statement")]); + def("Function") + .bases("Node") + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("params", [def("Pattern")]) + .field("body", def("BlockStatement")) + .field("generator", Boolean, defaults["false"]) + .field("async", Boolean, defaults["false"]); + def("Statement").bases("Node"); + // The empty .build() here means that an EmptyStatement can be constructed + // (i.e. it's not abstract) but that it needs no arguments. + def("EmptyStatement").bases("Statement").build(); + def("BlockStatement") + .bases("Statement") + .build("body") + .field("body", [def("Statement")]); + // TODO Figure out how to silently coerce Expressions to + // ExpressionStatements where a Statement was expected. + def("ExpressionStatement") + .bases("Statement") + .build("expression") + .field("expression", def("Expression")); + def("IfStatement") + .bases("Statement") + .build("test", "consequent", "alternate") + .field("test", def("Expression")) + .field("consequent", def("Statement")) + .field("alternate", or(def("Statement"), null), defaults["null"]); + def("LabeledStatement") + .bases("Statement") + .build("label", "body") + .field("label", def("Identifier")) + .field("body", def("Statement")); + def("BreakStatement") + .bases("Statement") + .build("label") + .field("label", or(def("Identifier"), null), defaults["null"]); + def("ContinueStatement") + .bases("Statement") + .build("label") + .field("label", or(def("Identifier"), null), defaults["null"]); + def("WithStatement") + .bases("Statement") + .build("object", "body") + .field("object", def("Expression")) + .field("body", def("Statement")); + def("SwitchStatement") + .bases("Statement") + .build("discriminant", "cases", "lexical") + .field("discriminant", def("Expression")) + .field("cases", [def("SwitchCase")]) + .field("lexical", Boolean, defaults["false"]); + def("ReturnStatement") + .bases("Statement") + .build("argument") + .field("argument", or(def("Expression"), null)); + def("ThrowStatement") + .bases("Statement") + .build("argument") + .field("argument", def("Expression")); + def("TryStatement") + .bases("Statement") + .build("block", "handler", "finalizer") + .field("block", def("BlockStatement")) + .field("handler", or(def("CatchClause"), null), function () { + return this.handlers && this.handlers[0] || null; + }) + .field("handlers", [def("CatchClause")], function () { + return this.handler ? [this.handler] : []; + }, true) // Indicates this field is hidden from eachField iteration. + .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) + .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); + def("CatchClause") + .bases("Node") + .build("param", "guard", "body") + // https://github.com/tc39/proposal-optional-catch-binding + .field("param", or(def("Pattern"), null), defaults["null"]) + .field("guard", or(def("Expression"), null), defaults["null"]) + .field("body", def("BlockStatement")); + def("WhileStatement") + .bases("Statement") + .build("test", "body") + .field("test", def("Expression")) + .field("body", def("Statement")); + def("DoWhileStatement") + .bases("Statement") + .build("body", "test") + .field("body", def("Statement")) + .field("test", def("Expression")); + def("ForStatement") + .bases("Statement") + .build("init", "test", "update", "body") + .field("init", or(def("VariableDeclaration"), def("Expression"), null)) + .field("test", or(def("Expression"), null)) + .field("update", or(def("Expression"), null)) + .field("body", def("Statement")); + def("ForInStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or(def("VariableDeclaration"), def("Expression"))) + .field("right", def("Expression")) + .field("body", def("Statement")); + def("DebuggerStatement").bases("Statement").build(); + def("Declaration").bases("Statement"); + def("FunctionDeclaration") + .bases("Function", "Declaration") + .build("id", "params", "body") + .field("id", def("Identifier")); + def("FunctionExpression") + .bases("Function", "Expression") + .build("id", "params", "body"); + def("VariableDeclaration") + .bases("Declaration") + .build("kind", "declarations") + .field("kind", or("var", "let", "const")) + .field("declarations", [def("VariableDeclarator")]); + def("VariableDeclarator") + .bases("Node") + .build("id", "init") + .field("id", def("Pattern")) + .field("init", or(def("Expression"), null), defaults["null"]); + def("Expression").bases("Node"); + def("ThisExpression").bases("Expression").build(); + def("ArrayExpression") + .bases("Expression") + .build("elements") + .field("elements", [or(def("Expression"), null)]); + def("ObjectExpression") + .bases("Expression") + .build("properties") + .field("properties", [def("Property")]); + // TODO Not in the Mozilla Parser API, but used by Esprima. + def("Property") + .bases("Node") // Want to be able to visit Property Nodes. + .build("kind", "key", "value") + .field("kind", or("init", "get", "set")) + .field("key", or(def("Literal"), def("Identifier"))) + .field("value", def("Expression")); + def("SequenceExpression") + .bases("Expression") + .build("expressions") + .field("expressions", [def("Expression")]); + var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete"); + def("UnaryExpression") + .bases("Expression") + .build("operator", "argument", "prefix") + .field("operator", UnaryOperator) + .field("argument", def("Expression")) + // Esprima doesn't bother with this field, presumably because it's + // always true for unary operators. + .field("prefix", Boolean, defaults["true"]); + var BinaryOperator = or("==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "**", "&", // TODO Missing from the Parser API. + "|", "^", "in", "instanceof"); + def("BinaryExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", BinaryOperator) + .field("left", def("Expression")) + .field("right", def("Expression")); + var AssignmentOperator = or("=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="); + def("AssignmentExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", AssignmentOperator) + .field("left", or(def("Pattern"), def("MemberExpression"))) + .field("right", def("Expression")); + var UpdateOperator = or("++", "--"); + def("UpdateExpression") + .bases("Expression") + .build("operator", "argument", "prefix") + .field("operator", UpdateOperator) + .field("argument", def("Expression")) + .field("prefix", Boolean); + var LogicalOperator = or("||", "&&"); + def("LogicalExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", LogicalOperator) + .field("left", def("Expression")) + .field("right", def("Expression")); + def("ConditionalExpression") + .bases("Expression") + .build("test", "consequent", "alternate") + .field("test", def("Expression")) + .field("consequent", def("Expression")) + .field("alternate", def("Expression")); + def("NewExpression") + .bases("Expression") + .build("callee", "arguments") + .field("callee", def("Expression")) + // The Mozilla Parser API gives this type as [or(def("Expression"), + // null)], but null values don't really make sense at the call site. + // TODO Report this nonsense. + .field("arguments", [def("Expression")]); + def("CallExpression") + .bases("Expression") + .build("callee", "arguments") + .field("callee", def("Expression")) + // See comment for NewExpression above. + .field("arguments", [def("Expression")]); + def("MemberExpression") + .bases("Expression") + .build("object", "property", "computed") + .field("object", def("Expression")) + .field("property", or(def("Identifier"), def("Expression"))) + .field("computed", Boolean, function () { + var type = this.property.type; + if (type === 'Literal' || + type === 'MemberExpression' || + type === 'BinaryExpression') { + return true; + } + return false; + }); + def("Pattern").bases("Node"); + def("SwitchCase") + .bases("Node") + .build("test", "consequent") + .field("test", or(def("Expression"), null)) + .field("consequent", [def("Statement")]); + def("Identifier") + .bases("Expression", "Pattern") + .build("name") + .field("name", String) + .field("optional", Boolean, defaults["false"]); + def("Literal") + .bases("Expression") + .build("value") + .field("value", or(String, Boolean, null, Number, RegExp)) + .field("regex", or({ + pattern: String, + flags: String + }, null), function () { + if (this.value instanceof RegExp) { + var flags = ""; + if (this.value.ignoreCase) + flags += "i"; + if (this.value.multiline) + flags += "m"; + if (this.value.global) + flags += "g"; + return { + pattern: this.value.source, + flags: flags + }; + } + return null; + }); + // Abstract (non-buildable) comment supertype. Not a Node. + def("Comment") + .bases("Printable") + .field("value", String) + // A .leading comment comes before the node, whereas a .trailing + // comment comes after it. These two fields should not both be true, + // but they might both be false when the comment falls inside a node + // and the node has no children for the comment to lead or trail, + // e.g. { /*dangling*/ }. + .field("leading", Boolean, defaults["true"]) + .field("trailing", Boolean, defaults["false"]); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es-proposals.js": +/*!*******************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es-proposals.js ***! + \*******************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +var core_1 = tslib_1.__importDefault(__webpack_require__(/*! ./core */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/core.js")); +function default_1(fork) { + fork.use(core_1.default); + var types = fork.use(types_1.default); + var Type = types.Type; + var def = types.Type.def; + var or = Type.or; + var shared = fork.use(shared_1.default); + var defaults = shared.defaults; + // https://github.com/tc39/proposal-optional-chaining + // `a?.b` as per https://github.com/estree/estree/issues/146 + def("OptionalMemberExpression") + .bases("MemberExpression") + .build("object", "property", "computed", "optional") + .field("optional", Boolean, defaults["true"]); + // a?.b() + def("OptionalCallExpression") + .bases("CallExpression") + .build("callee", "arguments", "optional") + .field("optional", Boolean, defaults["true"]); + // https://github.com/tc39/proposal-nullish-coalescing + // `a ?? b` as per https://github.com/babel/babylon/pull/761/files + var LogicalOperator = or("||", "&&", "??"); + def("LogicalExpression") + .field("operator", LogicalOperator); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es2020.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es2020.js ***! + \*************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +function default_1(fork) { + fork.use(es7_1.default); + var types = fork.use(types_1.default); + var def = types.Type.def; + def("ImportExpression") + .bases("Expression") + .build("source") + .field("source", def("Expression")); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es6.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es6.js ***! + \**********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var core_1 = tslib_1.__importDefault(__webpack_require__(/*! ./core */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/core.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + fork.use(core_1.default); + var types = fork.use(types_1.default); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + def("Function") + .field("generator", Boolean, defaults["false"]) + .field("expression", Boolean, defaults["false"]) + .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) + // TODO This could be represented as a RestElement in .params. + .field("rest", or(def("Identifier"), null), defaults["null"]); + // The ESTree way of representing a ...rest parameter. + def("RestElement") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")) + .field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier + or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]); + def("SpreadElementPattern") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")); + def("FunctionDeclaration") + .build("id", "params", "body", "generator", "expression"); + def("FunctionExpression") + .build("id", "params", "body", "generator", "expression"); + // The Parser API calls this ArrowExpression, but Esprima and all other + // actual parsers use ArrowFunctionExpression. + def("ArrowFunctionExpression") + .bases("Function", "Expression") + .build("params", "body", "expression") + // The forced null value here is compatible with the overridden + // definition of the "id" field in the Function interface. + .field("id", null, defaults["null"]) + // Arrow function bodies are allowed to be expressions. + .field("body", or(def("BlockStatement"), def("Expression"))) + // The current spec forbids arrow generators, so I have taken the + // liberty of enforcing that. TODO Report this. + .field("generator", false, defaults["false"]); + def("ForOfStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or(def("VariableDeclaration"), def("Pattern"))) + .field("right", def("Expression")) + .field("body", def("Statement")); + def("YieldExpression") + .bases("Expression") + .build("argument", "delegate") + .field("argument", or(def("Expression"), null)) + .field("delegate", Boolean, defaults["false"]); + def("GeneratorExpression") + .bases("Expression") + .build("body", "blocks", "filter") + .field("body", def("Expression")) + .field("blocks", [def("ComprehensionBlock")]) + .field("filter", or(def("Expression"), null)); + def("ComprehensionExpression") + .bases("Expression") + .build("body", "blocks", "filter") + .field("body", def("Expression")) + .field("blocks", [def("ComprehensionBlock")]) + .field("filter", or(def("Expression"), null)); + def("ComprehensionBlock") + .bases("Node") + .build("left", "right", "each") + .field("left", def("Pattern")) + .field("right", def("Expression")) + .field("each", Boolean); + def("Property") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("value", or(def("Expression"), def("Pattern"))) + .field("method", Boolean, defaults["false"]) + .field("shorthand", Boolean, defaults["false"]) + .field("computed", Boolean, defaults["false"]); + def("ObjectProperty") + .field("shorthand", Boolean, defaults["false"]); + def("PropertyPattern") + .bases("Pattern") + .build("key", "pattern") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("pattern", def("Pattern")) + .field("computed", Boolean, defaults["false"]); + def("ObjectPattern") + .bases("Pattern") + .build("properties") + .field("properties", [or(def("PropertyPattern"), def("Property"))]); + def("ArrayPattern") + .bases("Pattern") + .build("elements") + .field("elements", [or(def("Pattern"), null)]); + def("MethodDefinition") + .bases("Declaration") + .build("kind", "key", "value", "static") + .field("kind", or("constructor", "method", "get", "set")) + .field("key", def("Expression")) + .field("value", def("Function")) + .field("computed", Boolean, defaults["false"]) + .field("static", Boolean, defaults["false"]); + def("SpreadElement") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); + def("ArrayExpression") + .field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]); + def("NewExpression") + .field("arguments", [or(def("Expression"), def("SpreadElement"))]); + def("CallExpression") + .field("arguments", [or(def("Expression"), def("SpreadElement"))]); + // Note: this node type is *not* an AssignmentExpression with a Pattern on + // the left-hand side! The existing AssignmentExpression type already + // supports destructuring assignments. AssignmentPattern nodes may appear + // wherever a Pattern is allowed, and the right-hand side represents a + // default value to be destructured against the left-hand side, if no + // value is otherwise provided. For example: default parameter values. + def("AssignmentPattern") + .bases("Pattern") + .build("left", "right") + .field("left", def("Pattern")) + .field("right", def("Expression")); + var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty")); + def("ClassProperty") + .bases("Declaration") + .build("key") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("computed", Boolean, defaults["false"]); + def("ClassPropertyDefinition") // static property + .bases("Declaration") + .build("definition") + // Yes, Virginia, circular definitions are permitted. + .field("definition", ClassBodyElement); + def("ClassBody") + .bases("Declaration") + .build("body") + .field("body", [ClassBodyElement]); + def("ClassDeclaration") + .bases("Declaration") + .build("id", "body", "superClass") + .field("id", or(def("Identifier"), null)) + .field("body", def("ClassBody")) + .field("superClass", or(def("Expression"), null), defaults["null"]); + def("ClassExpression") + .bases("Expression") + .build("id", "body", "superClass") + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("body", def("ClassBody")) + .field("superClass", or(def("Expression"), null), defaults["null"]); + // Specifier and ModuleSpecifier are abstract non-standard types + // introduced for definitional convenience. + def("Specifier").bases("Node"); + // This supertype is shared/abused by both def/babel.js and + // def/esprima.js. In the future, it will be possible to load only one set + // of definitions appropriate for a given parser, but until then we must + // rely on default functions to reconcile the conflicting AST formats. + def("ModuleSpecifier") + .bases("Specifier") + // This local field is used by Babel/Acorn. It should not technically + // be optional in the Babel/Acorn AST format, but it must be optional + // in the Esprima AST format. + .field("local", or(def("Identifier"), null), defaults["null"]) + // The id and name fields are used by Esprima. The id field should not + // technically be optional in the Esprima AST format, but it must be + // optional in the Babel/Acorn AST format. + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("name", or(def("Identifier"), null), defaults["null"]); + // Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. + // import {} from ...; + def("ImportSpecifier") + .bases("ModuleSpecifier") + .build("id", "name"); + // import <* as id> from ...; + def("ImportNamespaceSpecifier") + .bases("ModuleSpecifier") + .build("id"); + // import from ...; + def("ImportDefaultSpecifier") + .bases("ModuleSpecifier") + .build("id"); + def("ImportDeclaration") + .bases("Declaration") + .build("specifiers", "source", "importKind") + .field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray) + .field("source", def("Literal")) + .field("importKind", or("value", "type"), function () { + return "value"; + }); + def("TaggedTemplateExpression") + .bases("Expression") + .build("tag", "quasi") + .field("tag", def("Expression")) + .field("quasi", def("TemplateLiteral")); + def("TemplateLiteral") + .bases("Expression") + .build("quasis", "expressions") + .field("quasis", [def("TemplateElement")]) + .field("expressions", [def("Expression")]); + def("TemplateElement") + .bases("Node") + .build("value", "tail") + .field("value", { "cooked": String, "raw": String }) + .field("tail", Boolean); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js ***! + \**********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var es6_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es6 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es6.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + fork.use(es6_1.default); + var types = fork.use(types_1.default); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + def("Function") + .field("async", Boolean, defaults["false"]); + def("SpreadProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); + def("ObjectExpression") + .field("properties", [or(def("Property"), def("SpreadProperty"), def("SpreadElement"))]); + def("SpreadPropertyPattern") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")); + def("ObjectPattern") + .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"))]); + def("AwaitExpression") + .bases("Expression") + .build("argument", "all") + .field("argument", or(def("Expression"), null)) + .field("all", Boolean, defaults["false"]); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/esprima.js": +/*!**************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/esprima.js ***! + \**************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + fork.use(es7_1.default); + var types = fork.use(types_1.default); + var defaults = fork.use(shared_1.default).defaults; + var def = types.Type.def; + var or = types.Type.or; + def("VariableDeclaration") + .field("declarations", [or(def("VariableDeclarator"), def("Identifier") // Esprima deviation. + )]); + def("Property") + .field("value", or(def("Expression"), def("Pattern") // Esprima deviation. + )); + def("ArrayPattern") + .field("elements", [or(def("Pattern"), def("SpreadElement"), null)]); + def("ObjectPattern") + .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty") // Used by Esprima. + )]); + // Like ModuleSpecifier, except type:"ExportSpecifier" and buildable. + // export {} [from ...]; + def("ExportSpecifier") + .bases("ModuleSpecifier") + .build("id", "name"); + // export <*> from ...; + def("ExportBatchSpecifier") + .bases("Specifier") + .build(); + def("ExportDeclaration") + .bases("Declaration") + .build("default", "declaration", "specifiers", "source") + .field("default", Boolean) + .field("declaration", or(def("Declaration"), def("Expression"), // Implies default. + null)) + .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray) + .field("source", or(def("Literal"), null), defaults["null"]); + def("Block") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); + def("Line") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/flow.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/flow.js ***! + \***********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +var type_annotations_1 = tslib_1.__importDefault(__webpack_require__(/*! ./type-annotations */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/type-annotations.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + fork.use(es7_1.default); + fork.use(type_annotations_1.default); + var types = fork.use(types_1.default); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + // Base types + def("Flow").bases("Node"); + def("FlowType").bases("Flow"); + // Type annotations + def("AnyTypeAnnotation") + .bases("FlowType") + .build(); + def("EmptyTypeAnnotation") + .bases("FlowType") + .build(); + def("MixedTypeAnnotation") + .bases("FlowType") + .build(); + def("VoidTypeAnnotation") + .bases("FlowType") + .build(); + def("NumberTypeAnnotation") + .bases("FlowType") + .build(); + def("NumberLiteralTypeAnnotation") + .bases("FlowType") + .build("value", "raw") + .field("value", Number) + .field("raw", String); + // Babylon 6 differs in AST from Flow + // same as NumberLiteralTypeAnnotation + def("NumericLiteralTypeAnnotation") + .bases("FlowType") + .build("value", "raw") + .field("value", Number) + .field("raw", String); + def("StringTypeAnnotation") + .bases("FlowType") + .build(); + def("StringLiteralTypeAnnotation") + .bases("FlowType") + .build("value", "raw") + .field("value", String) + .field("raw", String); + def("BooleanTypeAnnotation") + .bases("FlowType") + .build(); + def("BooleanLiteralTypeAnnotation") + .bases("FlowType") + .build("value", "raw") + .field("value", Boolean) + .field("raw", String); + def("TypeAnnotation") + .bases("Node") + .build("typeAnnotation") + .field("typeAnnotation", def("FlowType")); + def("NullableTypeAnnotation") + .bases("FlowType") + .build("typeAnnotation") + .field("typeAnnotation", def("FlowType")); + def("NullLiteralTypeAnnotation") + .bases("FlowType") + .build(); + def("NullTypeAnnotation") + .bases("FlowType") + .build(); + def("ThisTypeAnnotation") + .bases("FlowType") + .build(); + def("ExistsTypeAnnotation") + .bases("FlowType") + .build(); + def("ExistentialTypeParam") + .bases("FlowType") + .build(); + def("FunctionTypeAnnotation") + .bases("FlowType") + .build("params", "returnType", "rest", "typeParameters") + .field("params", [def("FunctionTypeParam")]) + .field("returnType", def("FlowType")) + .field("rest", or(def("FunctionTypeParam"), null)) + .field("typeParameters", or(def("TypeParameterDeclaration"), null)); + def("FunctionTypeParam") + .bases("Node") + .build("name", "typeAnnotation", "optional") + .field("name", def("Identifier")) + .field("typeAnnotation", def("FlowType")) + .field("optional", Boolean); + def("ArrayTypeAnnotation") + .bases("FlowType") + .build("elementType") + .field("elementType", def("FlowType")); + def("ObjectTypeAnnotation") + .bases("FlowType") + .build("properties", "indexers", "callProperties") + .field("properties", [ + or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty")) + ]) + .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray) + .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray) + .field("inexact", or(Boolean, void 0), defaults["undefined"]) + .field("exact", Boolean, defaults["false"]) + .field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray); + def("Variance") + .bases("Node") + .build("kind") + .field("kind", or("plus", "minus")); + var LegacyVariance = or(def("Variance"), "plus", "minus", null); + def("ObjectTypeProperty") + .bases("Node") + .build("key", "value", "optional") + .field("key", or(def("Literal"), def("Identifier"))) + .field("value", def("FlowType")) + .field("optional", Boolean) + .field("variance", LegacyVariance, defaults["null"]); + def("ObjectTypeIndexer") + .bases("Node") + .build("id", "key", "value") + .field("id", def("Identifier")) + .field("key", def("FlowType")) + .field("value", def("FlowType")) + .field("variance", LegacyVariance, defaults["null"]); + def("ObjectTypeCallProperty") + .bases("Node") + .build("value") + .field("value", def("FunctionTypeAnnotation")) + .field("static", Boolean, defaults["false"]); + def("QualifiedTypeIdentifier") + .bases("Node") + .build("qualification", "id") + .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier"))) + .field("id", def("Identifier")); + def("GenericTypeAnnotation") + .bases("FlowType") + .build("id", "typeParameters") + .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))) + .field("typeParameters", or(def("TypeParameterInstantiation"), null)); + def("MemberTypeAnnotation") + .bases("FlowType") + .build("object", "property") + .field("object", def("Identifier")) + .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation"))); + def("UnionTypeAnnotation") + .bases("FlowType") + .build("types") + .field("types", [def("FlowType")]); + def("IntersectionTypeAnnotation") + .bases("FlowType") + .build("types") + .field("types", [def("FlowType")]); + def("TypeofTypeAnnotation") + .bases("FlowType") + .build("argument") + .field("argument", def("FlowType")); + def("ObjectTypeSpreadProperty") + .bases("Node") + .build("argument") + .field("argument", def("FlowType")); + def("ObjectTypeInternalSlot") + .bases("Node") + .build("id", "value", "optional", "static", "method") + .field("id", def("Identifier")) + .field("value", def("FlowType")) + .field("optional", Boolean) + .field("static", Boolean) + .field("method", Boolean); + def("TypeParameterDeclaration") + .bases("Node") + .build("params") + .field("params", [def("TypeParameter")]); + def("TypeParameterInstantiation") + .bases("Node") + .build("params") + .field("params", [def("FlowType")]); + def("TypeParameter") + .bases("FlowType") + .build("name", "variance", "bound") + .field("name", String) + .field("variance", LegacyVariance, defaults["null"]) + .field("bound", or(def("TypeAnnotation"), null), defaults["null"]); + def("ClassProperty") + .field("variance", LegacyVariance, defaults["null"]); + def("ClassImplements") + .bases("Node") + .build("id") + .field("id", def("Identifier")) + .field("superClass", or(def("Expression"), null), defaults["null"]) + .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); + def("InterfaceTypeAnnotation") + .bases("FlowType") + .build("body", "extends") + .field("body", def("ObjectTypeAnnotation")) + .field("extends", or([def("InterfaceExtends")], null), defaults["null"]); + def("InterfaceDeclaration") + .bases("Declaration") + .build("id", "body", "extends") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]) + .field("body", def("ObjectTypeAnnotation")) + .field("extends", [def("InterfaceExtends")]); + def("DeclareInterface") + .bases("InterfaceDeclaration") + .build("id", "body", "extends"); + def("InterfaceExtends") + .bases("Node") + .build("id") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); + def("TypeAlias") + .bases("Declaration") + .build("id", "typeParameters", "right") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterDeclaration"), null)) + .field("right", def("FlowType")); + def("OpaqueType") + .bases("Declaration") + .build("id", "typeParameters", "impltype", "supertype") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterDeclaration"), null)) + .field("impltype", def("FlowType")) + .field("supertype", def("FlowType")); + def("DeclareTypeAlias") + .bases("TypeAlias") + .build("id", "typeParameters", "right"); + def("DeclareOpaqueType") + .bases("TypeAlias") + .build("id", "typeParameters", "supertype"); + def("TypeCastExpression") + .bases("Expression") + .build("expression", "typeAnnotation") + .field("expression", def("Expression")) + .field("typeAnnotation", def("TypeAnnotation")); + def("TupleTypeAnnotation") + .bases("FlowType") + .build("types") + .field("types", [def("FlowType")]); + def("DeclareVariable") + .bases("Statement") + .build("id") + .field("id", def("Identifier")); + def("DeclareFunction") + .bases("Statement") + .build("id") + .field("id", def("Identifier")); + def("DeclareClass") + .bases("InterfaceDeclaration") + .build("id"); + def("DeclareModule") + .bases("Statement") + .build("id", "body") + .field("id", or(def("Identifier"), def("Literal"))) + .field("body", def("BlockStatement")); + def("DeclareModuleExports") + .bases("Statement") + .build("typeAnnotation") + .field("typeAnnotation", def("TypeAnnotation")); + def("DeclareExportDeclaration") + .bases("Declaration") + .build("default", "declaration", "specifiers", "source") + .field("default", Boolean) + .field("declaration", or(def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("FlowType"), // Implies default. + null)) + .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray) + .field("source", or(def("Literal"), null), defaults["null"]); + def("DeclareExportAllDeclaration") + .bases("Declaration") + .build("source") + .field("source", or(def("Literal"), null), defaults["null"]); + def("FlowPredicate").bases("Flow"); + def("InferredPredicate") + .bases("FlowPredicate") + .build(); + def("DeclaredPredicate") + .bases("FlowPredicate") + .build("value") + .field("value", def("Expression")); + def("CallExpression") + .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); + def("NewExpression") + .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/jsx.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/jsx.js ***! + \**********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + fork.use(es7_1.default); + var types = fork.use(types_1.default); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + def("JSXAttribute") + .bases("Node") + .build("name", "value") + .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))) + .field("value", or(def("Literal"), // attr="value" + def("JSXExpressionContainer"), // attr={value} + null // attr= or just attr + ), defaults["null"]); + def("JSXIdentifier") + .bases("Identifier") + .build("name") + .field("name", String); + def("JSXNamespacedName") + .bases("Node") + .build("namespace", "name") + .field("namespace", def("JSXIdentifier")) + .field("name", def("JSXIdentifier")); + def("JSXMemberExpression") + .bases("MemberExpression") + .build("object", "property") + .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))) + .field("property", def("JSXIdentifier")) + .field("computed", Boolean, defaults.false); + var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression")); + def("JSXSpreadAttribute") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); + var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))]; + def("JSXExpressionContainer") + .bases("Expression") + .build("expression") + .field("expression", def("Expression")); + def("JSXElement") + .bases("Expression") + .build("openingElement", "closingElement", "children") + .field("openingElement", def("JSXOpeningElement")) + .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]) + .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead. + )], defaults.emptyArray) + .field("name", JSXElementName, function () { + // Little-known fact: the `this` object inside a default function + // is none other than the partially-built object itself, and any + // fields initialized directly from builder function arguments + // (like openingElement, closingElement, and children) are + // guaranteed to be available. + return this.openingElement.name; + }, true) // hidden from traversal + .field("selfClosing", Boolean, function () { + return this.openingElement.selfClosing; + }, true) // hidden from traversal + .field("attributes", JSXAttributes, function () { + return this.openingElement.attributes; + }, true); // hidden from traversal + def("JSXOpeningElement") + .bases("Node") // TODO Does this make sense? Can't really be an JSXElement. + .build("name", "attributes", "selfClosing") + .field("name", JSXElementName) + .field("attributes", JSXAttributes, defaults.emptyArray) + .field("selfClosing", Boolean, defaults["false"]); + def("JSXClosingElement") + .bases("Node") // TODO Same concern. + .build("name") + .field("name", JSXElementName); + def("JSXFragment") + .bases("Expression") + .build("openingElement", "closingElement", "children") + .field("openingElement", def("JSXOpeningFragment")) + .field("closingElement", def("JSXClosingFragment")) + .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead. + )], defaults.emptyArray); + def("JSXOpeningFragment") + .bases("Node") // TODO Same concern. + .build(); + def("JSXClosingFragment") + .bases("Node") // TODO Same concern. + .build(); + def("JSXText") + .bases("Literal") + .build("value") + .field("value", String); + def("JSXEmptyExpression").bases("Expression").build(); + // This PR has caused many people issues, but supporting it seems like a + // good idea anyway: https://github.com/babel/babel/pull/4988 + def("JSXSpreadChild") + .bases("Expression") + .build("expression") + .field("expression", def("Expression")); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/type-annotations.js": +/*!***********************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/type-annotations.js ***! + \***********************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +/** + * Type annotation defs shared between Flow and TypeScript. + * These defs could not be defined in ./flow.ts or ./typescript.ts directly + * because they use the same name. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + var types = fork.use(types_1.default); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null); + var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null); + def("Identifier") + .field("typeAnnotation", TypeAnnotation, defaults["null"]); + def("ObjectPattern") + .field("typeAnnotation", TypeAnnotation, defaults["null"]); + def("Function") + .field("returnType", TypeAnnotation, defaults["null"]) + .field("typeParameters", TypeParamDecl, defaults["null"]); + def("ClassProperty") + .build("key", "value", "typeAnnotation", "static") + .field("value", or(def("Expression"), null)) + .field("static", Boolean, defaults["false"]) + .field("typeAnnotation", TypeAnnotation, defaults["null"]); + ["ClassDeclaration", + "ClassExpression", + ].forEach(function (typeName) { + def(typeName) + .field("typeParameters", TypeParamDecl, defaults["null"]) + .field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"]) + .field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray); + }); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/typescript.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/typescript.js ***! + \*****************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var babel_core_1 = tslib_1.__importDefault(__webpack_require__(/*! ./babel-core */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel-core.js")); +var type_annotations_1 = tslib_1.__importDefault(__webpack_require__(/*! ./type-annotations */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/type-annotations.js")); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var shared_1 = tslib_1.__importDefault(__webpack_require__(/*! ../lib/shared */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js")); +function default_1(fork) { + // Since TypeScript is parsed by Babylon, include the core Babylon types + // but omit the Flow-related types. + fork.use(babel_core_1.default); + fork.use(type_annotations_1.default); + var types = fork.use(types_1.default); + var n = types.namedTypes; + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(shared_1.default).defaults; + var StringLiteral = types.Type.from(function (value, deep) { + if (n.StringLiteral && + n.StringLiteral.check(value, deep)) { + return true; + } + if (n.Literal && + n.Literal.check(value, deep) && + typeof value.value === "string") { + return true; + } + return false; + }, "StringLiteral"); + def("TSType") + .bases("Node"); + var TSEntityName = or(def("Identifier"), def("TSQualifiedName")); + def("TSTypeReference") + .bases("TSType", "TSHasOptionalTypeParameterInstantiation") + .build("typeName", "typeParameters") + .field("typeName", TSEntityName); + // An abstract (non-buildable) base type that provide a commonly-needed + // optional .typeParameters field. + def("TSHasOptionalTypeParameterInstantiation") + .field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]); + // An abstract (non-buildable) base type that provide a commonly-needed + // optional .typeParameters field. + def("TSHasOptionalTypeParameters") + .field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]); + // An abstract (non-buildable) base type that provide a commonly-needed + // optional .typeAnnotation field. + def("TSHasOptionalTypeAnnotation") + .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]); + def("TSQualifiedName") + .bases("Node") + .build("left", "right") + .field("left", TSEntityName) + .field("right", TSEntityName); + def("TSAsExpression") + .bases("Expression", "Pattern") + .build("expression", "typeAnnotation") + .field("expression", def("Expression")) + .field("typeAnnotation", def("TSType")) + .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); + def("TSNonNullExpression") + .bases("Expression", "Pattern") + .build("expression") + .field("expression", def("Expression")); + [ + "TSAnyKeyword", + "TSBigIntKeyword", + "TSBooleanKeyword", + "TSNeverKeyword", + "TSNullKeyword", + "TSNumberKeyword", + "TSObjectKeyword", + "TSStringKeyword", + "TSSymbolKeyword", + "TSUndefinedKeyword", + "TSUnknownKeyword", + "TSVoidKeyword", + "TSThisType", + ].forEach(function (keywordType) { + def(keywordType) + .bases("TSType") + .build(); + }); + def("TSArrayType") + .bases("TSType") + .build("elementType") + .field("elementType", def("TSType")); + def("TSLiteralType") + .bases("TSType") + .build("literal") + .field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression"))); + ["TSUnionType", + "TSIntersectionType", + ].forEach(function (typeName) { + def(typeName) + .bases("TSType") + .build("types") + .field("types", [def("TSType")]); + }); + def("TSConditionalType") + .bases("TSType") + .build("checkType", "extendsType", "trueType", "falseType") + .field("checkType", def("TSType")) + .field("extendsType", def("TSType")) + .field("trueType", def("TSType")) + .field("falseType", def("TSType")); + def("TSInferType") + .bases("TSType") + .build("typeParameter") + .field("typeParameter", def("TSTypeParameter")); + def("TSParenthesizedType") + .bases("TSType") + .build("typeAnnotation") + .field("typeAnnotation", def("TSType")); + var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))]; + ["TSFunctionType", + "TSConstructorType", + ].forEach(function (typeName) { + def(typeName) + .bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") + .build("parameters") + .field("parameters", ParametersType); + }); + def("TSDeclareFunction") + .bases("Declaration", "TSHasOptionalTypeParameters") + .build("id", "params", "returnType") + .field("declare", Boolean, defaults["false"]) + .field("async", Boolean, defaults["false"]) + .field("generator", Boolean, defaults["false"]) + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("params", [def("Pattern")]) + // tSFunctionTypeAnnotationCommon + .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used? + null), defaults["null"]); + def("TSDeclareMethod") + .bases("Declaration", "TSHasOptionalTypeParameters") + .build("key", "params", "returnType") + .field("async", Boolean, defaults["false"]) + .field("generator", Boolean, defaults["false"]) + .field("params", [def("Pattern")]) + // classMethodOrPropertyCommon + .field("abstract", Boolean, defaults["false"]) + .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]) + .field("static", Boolean, defaults["false"]) + .field("computed", Boolean, defaults["false"]) + .field("optional", Boolean, defaults["false"]) + .field("key", or(def("Identifier"), def("StringLiteral"), def("NumericLiteral"), + // Only allowed if .computed is true. + def("Expression"))) + // classMethodOrDeclareMethodCommon + .field("kind", or("get", "set", "method", "constructor"), function getDefault() { return "method"; }) + .field("access", // Not "accessibility"? + or("public", "private", "protected", void 0), defaults["undefined"]) + .field("decorators", or([def("Decorator")], null), defaults["null"]) + // tSFunctionTypeAnnotationCommon + .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used? + null), defaults["null"]); + def("TSMappedType") + .bases("TSType") + .build("typeParameter", "typeAnnotation") + .field("readonly", or(Boolean, "+", "-"), defaults["false"]) + .field("typeParameter", def("TSTypeParameter")) + .field("optional", or(Boolean, "+", "-"), defaults["false"]) + .field("typeAnnotation", or(def("TSType"), null), defaults["null"]); + def("TSTupleType") + .bases("TSType") + .build("elementTypes") + .field("elementTypes", [or(def("TSType"), def("TSNamedTupleMember"))]); + def("TSNamedTupleMember") + .bases("TSType") + .build("label", "elementType", "optional") + .field("label", def("Identifier")) + .field("optional", Boolean, defaults["false"]) + .field("elementType", def("TSType")); + def("TSRestType") + .bases("TSType") + .build("typeAnnotation") + .field("typeAnnotation", def("TSType")); + def("TSOptionalType") + .bases("TSType") + .build("typeAnnotation") + .field("typeAnnotation", def("TSType")); + def("TSIndexedAccessType") + .bases("TSType") + .build("objectType", "indexType") + .field("objectType", def("TSType")) + .field("indexType", def("TSType")); + def("TSTypeOperator") + .bases("TSType") + .build("operator") + .field("operator", String) + .field("typeAnnotation", def("TSType")); + def("TSTypeAnnotation") + .bases("Node") + .build("typeAnnotation") + .field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation"))); + def("TSIndexSignature") + .bases("Declaration", "TSHasOptionalTypeAnnotation") + .build("parameters", "typeAnnotation") + .field("parameters", [def("Identifier")]) // Length === 1 + .field("readonly", Boolean, defaults["false"]); + def("TSPropertySignature") + .bases("Declaration", "TSHasOptionalTypeAnnotation") + .build("key", "typeAnnotation", "optional") + .field("key", def("Expression")) + .field("computed", Boolean, defaults["false"]) + .field("readonly", Boolean, defaults["false"]) + .field("optional", Boolean, defaults["false"]) + .field("initializer", or(def("Expression"), null), defaults["null"]); + def("TSMethodSignature") + .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") + .build("key", "parameters", "typeAnnotation") + .field("key", def("Expression")) + .field("computed", Boolean, defaults["false"]) + .field("optional", Boolean, defaults["false"]) + .field("parameters", ParametersType); + def("TSTypePredicate") + .bases("TSTypeAnnotation", "TSType") + .build("parameterName", "typeAnnotation", "asserts") + .field("parameterName", or(def("Identifier"), def("TSThisType"))) + .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]) + .field("asserts", Boolean, defaults["false"]); + ["TSCallSignatureDeclaration", + "TSConstructSignatureDeclaration", + ].forEach(function (typeName) { + def(typeName) + .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") + .build("parameters", "typeAnnotation") + .field("parameters", ParametersType); + }); + def("TSEnumMember") + .bases("Node") + .build("id", "initializer") + .field("id", or(def("Identifier"), StringLiteral)) + .field("initializer", or(def("Expression"), null), defaults["null"]); + def("TSTypeQuery") + .bases("TSType") + .build("exprName") + .field("exprName", or(TSEntityName, def("TSImportType"))); + // Inferred from Babylon's tsParseTypeMember method. + var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature")); + def("TSTypeLiteral") + .bases("TSType") + .build("members") + .field("members", [TSTypeMember]); + def("TSTypeParameter") + .bases("Identifier") + .build("name", "constraint", "default") + .field("name", String) + .field("constraint", or(def("TSType"), void 0), defaults["undefined"]) + .field("default", or(def("TSType"), void 0), defaults["undefined"]); + def("TSTypeAssertion") + .bases("Expression", "Pattern") + .build("typeAnnotation", "expression") + .field("typeAnnotation", def("TSType")) + .field("expression", def("Expression")) + .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); + def("TSTypeParameterDeclaration") + .bases("Declaration") + .build("params") + .field("params", [def("TSTypeParameter")]); + def("TSTypeParameterInstantiation") + .bases("Node") + .build("params") + .field("params", [def("TSType")]); + def("TSEnumDeclaration") + .bases("Declaration") + .build("id", "members") + .field("id", def("Identifier")) + .field("const", Boolean, defaults["false"]) + .field("declare", Boolean, defaults["false"]) + .field("members", [def("TSEnumMember")]) + .field("initializer", or(def("Expression"), null), defaults["null"]); + def("TSTypeAliasDeclaration") + .bases("Declaration", "TSHasOptionalTypeParameters") + .build("id", "typeAnnotation") + .field("id", def("Identifier")) + .field("declare", Boolean, defaults["false"]) + .field("typeAnnotation", def("TSType")); + def("TSModuleBlock") + .bases("Node") + .build("body") + .field("body", [def("Statement")]); + def("TSModuleDeclaration") + .bases("Declaration") + .build("id", "body") + .field("id", or(StringLiteral, TSEntityName)) + .field("declare", Boolean, defaults["false"]) + .field("global", Boolean, defaults["false"]) + .field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]); + def("TSImportType") + .bases("TSType", "TSHasOptionalTypeParameterInstantiation") + .build("argument", "qualifier", "typeParameters") + .field("argument", StringLiteral) + .field("qualifier", or(TSEntityName, void 0), defaults["undefined"]); + def("TSImportEqualsDeclaration") + .bases("Declaration") + .build("id", "moduleReference") + .field("id", def("Identifier")) + .field("isExport", Boolean, defaults["false"]) + .field("moduleReference", or(TSEntityName, def("TSExternalModuleReference"))); + def("TSExternalModuleReference") + .bases("Declaration") + .build("expression") + .field("expression", StringLiteral); + def("TSExportAssignment") + .bases("Statement") + .build("expression") + .field("expression", def("Expression")); + def("TSNamespaceExportDeclaration") + .bases("Declaration") + .build("id") + .field("id", def("Identifier")); + def("TSInterfaceBody") + .bases("Node") + .build("body") + .field("body", [TSTypeMember]); + def("TSExpressionWithTypeArguments") + .bases("TSType", "TSHasOptionalTypeParameterInstantiation") + .build("expression", "typeParameters") + .field("expression", TSEntityName); + def("TSInterfaceDeclaration") + .bases("Declaration", "TSHasOptionalTypeParameters") + .build("id", "body") + .field("id", TSEntityName) + .field("declare", Boolean, defaults["false"]) + .field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"]) + .field("body", def("TSInterfaceBody")); + def("TSParameterProperty") + .bases("Pattern") + .build("parameter") + .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]) + .field("readonly", Boolean, defaults["false"]) + .field("parameter", or(def("Identifier"), def("AssignmentPattern"))); + def("ClassProperty") + .field("access", // Not "accessibility"? + or("public", "private", "protected", void 0), defaults["undefined"]); + // Defined already in es6 and babel-core. + def("ClassBody") + .field("body", [or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"), + // Just need to add these types: + def("TSDeclareMethod"), TSTypeMember)]); +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/fork.js": +/*!*******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/fork.js ***! + \*******************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./lib/types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var path_visitor_1 = tslib_1.__importDefault(__webpack_require__(/*! ./lib/path-visitor */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path-visitor.js")); +var equiv_1 = tslib_1.__importDefault(__webpack_require__(/*! ./lib/equiv */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/equiv.js")); +var path_1 = tslib_1.__importDefault(__webpack_require__(/*! ./lib/path */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path.js")); +var node_path_1 = tslib_1.__importDefault(__webpack_require__(/*! ./lib/node-path */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/node-path.js")); +function default_1(defs) { + var fork = createFork(); + var types = fork.use(types_1.default); + defs.forEach(fork.use); + types.finalize(); + var PathVisitor = fork.use(path_visitor_1.default); + return { + Type: types.Type, + builtInTypes: types.builtInTypes, + namedTypes: types.namedTypes, + builders: types.builders, + defineMethod: types.defineMethod, + getFieldNames: types.getFieldNames, + getFieldValue: types.getFieldValue, + eachField: types.eachField, + someField: types.someField, + getSupertypeNames: types.getSupertypeNames, + getBuilderName: types.getBuilderName, + astNodesAreEquivalent: fork.use(equiv_1.default), + finalize: types.finalize, + Path: fork.use(path_1.default), + NodePath: fork.use(node_path_1.default), + PathVisitor: PathVisitor, + use: fork.use, + visit: PathVisitor.visit, + }; +} +exports["default"] = default_1; +function createFork() { + var used = []; + var usedResult = []; + function use(plugin) { + var idx = used.indexOf(plugin); + if (idx === -1) { + idx = used.length; + used.push(plugin); + usedResult[idx] = plugin(fork); + } + return usedResult[idx]; + } + var fork = { use: use }; + return fork; +} +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/gen/namedTypes.js": +/*!*****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/gen/namedTypes.js ***! + \*****************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.namedTypes = void 0; +var namedTypes; +(function (namedTypes) { +})(namedTypes = exports.namedTypes || (exports.namedTypes = {})); + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/equiv.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/equiv.js ***! + \************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +function default_1(fork) { + var types = fork.use(types_1.default); + var getFieldNames = types.getFieldNames; + var getFieldValue = types.getFieldValue; + var isArray = types.builtInTypes.array; + var isObject = types.builtInTypes.object; + var isDate = types.builtInTypes.Date; + var isRegExp = types.builtInTypes.RegExp; + var hasOwn = Object.prototype.hasOwnProperty; + function astNodesAreEquivalent(a, b, problemPath) { + if (isArray.check(problemPath)) { + problemPath.length = 0; + } + else { + problemPath = null; + } + return areEquivalent(a, b, problemPath); + } + astNodesAreEquivalent.assert = function (a, b) { + var problemPath = []; + if (!astNodesAreEquivalent(a, b, problemPath)) { + if (problemPath.length === 0) { + if (a !== b) { + throw new Error("Nodes must be equal"); + } + } + else { + throw new Error("Nodes differ in the following path: " + + problemPath.map(subscriptForProperty).join("")); + } + } + }; + function subscriptForProperty(property) { + if (/[_$a-z][_$a-z0-9]*/i.test(property)) { + return "." + property; + } + return "[" + JSON.stringify(property) + "]"; + } + function areEquivalent(a, b, problemPath) { + if (a === b) { + return true; + } + if (isArray.check(a)) { + return arraysAreEquivalent(a, b, problemPath); + } + if (isObject.check(a)) { + return objectsAreEquivalent(a, b, problemPath); + } + if (isDate.check(a)) { + return isDate.check(b) && (+a === +b); + } + if (isRegExp.check(a)) { + return isRegExp.check(b) && (a.source === b.source && + a.global === b.global && + a.multiline === b.multiline && + a.ignoreCase === b.ignoreCase); + } + return a == b; + } + function arraysAreEquivalent(a, b, problemPath) { + isArray.assert(a); + var aLength = a.length; + if (!isArray.check(b) || b.length !== aLength) { + if (problemPath) { + problemPath.push("length"); + } + return false; + } + for (var i = 0; i < aLength; ++i) { + if (problemPath) { + problemPath.push(i); + } + if (i in a !== i in b) { + return false; + } + if (!areEquivalent(a[i], b[i], problemPath)) { + return false; + } + if (problemPath) { + var problemPathTail = problemPath.pop(); + if (problemPathTail !== i) { + throw new Error("" + problemPathTail); + } + } + } + return true; + } + function objectsAreEquivalent(a, b, problemPath) { + isObject.assert(a); + if (!isObject.check(b)) { + return false; + } + // Fast path for a common property of AST nodes. + if (a.type !== b.type) { + if (problemPath) { + problemPath.push("type"); + } + return false; + } + var aNames = getFieldNames(a); + var aNameCount = aNames.length; + var bNames = getFieldNames(b); + var bNameCount = bNames.length; + if (aNameCount === bNameCount) { + for (var i = 0; i < aNameCount; ++i) { + var name = aNames[i]; + var aChild = getFieldValue(a, name); + var bChild = getFieldValue(b, name); + if (problemPath) { + problemPath.push(name); + } + if (!areEquivalent(aChild, bChild, problemPath)) { + return false; + } + if (problemPath) { + var problemPathTail = problemPath.pop(); + if (problemPathTail !== name) { + throw new Error("" + problemPathTail); + } + } + } + return true; + } + if (!problemPath) { + return false; + } + // Since aNameCount !== bNameCount, we need to find some name that's + // missing in aNames but present in bNames, or vice-versa. + var seenNames = Object.create(null); + for (i = 0; i < aNameCount; ++i) { + seenNames[aNames[i]] = true; + } + for (i = 0; i < bNameCount; ++i) { + name = bNames[i]; + if (!hasOwn.call(seenNames, name)) { + problemPath.push(name); + return false; + } + delete seenNames[name]; + } + for (name in seenNames) { + problemPath.push(name); + break; + } + return false; + } + return astNodesAreEquivalent; +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/node-path.js": +/*!****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/node-path.js ***! + \****************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var path_1 = tslib_1.__importDefault(__webpack_require__(/*! ./path */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path.js")); +var scope_1 = tslib_1.__importDefault(__webpack_require__(/*! ./scope */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/scope.js")); +function nodePathPlugin(fork) { + var types = fork.use(types_1.default); + var n = types.namedTypes; + var b = types.builders; + var isNumber = types.builtInTypes.number; + var isArray = types.builtInTypes.array; + var Path = fork.use(path_1.default); + var Scope = fork.use(scope_1.default); + var NodePath = function NodePath(value, parentPath, name) { + if (!(this instanceof NodePath)) { + throw new Error("NodePath constructor cannot be invoked without 'new'"); + } + Path.call(this, value, parentPath, name); + }; + var NPp = NodePath.prototype = Object.create(Path.prototype, { + constructor: { + value: NodePath, + enumerable: false, + writable: true, + configurable: true + } + }); + Object.defineProperties(NPp, { + node: { + get: function () { + Object.defineProperty(this, "node", { + configurable: true, + value: this._computeNode() + }); + return this.node; + } + }, + parent: { + get: function () { + Object.defineProperty(this, "parent", { + configurable: true, + value: this._computeParent() + }); + return this.parent; + } + }, + scope: { + get: function () { + Object.defineProperty(this, "scope", { + configurable: true, + value: this._computeScope() + }); + return this.scope; + } + } + }); + NPp.replace = function () { + delete this.node; + delete this.parent; + delete this.scope; + return Path.prototype.replace.apply(this, arguments); + }; + NPp.prune = function () { + var remainingNodePath = this.parent; + this.replace(); + return cleanUpNodesAfterPrune(remainingNodePath); + }; + // The value of the first ancestor Path whose value is a Node. + NPp._computeNode = function () { + var value = this.value; + if (n.Node.check(value)) { + return value; + } + var pp = this.parentPath; + return pp && pp.node || null; + }; + // The first ancestor Path whose value is a Node distinct from this.node. + NPp._computeParent = function () { + var value = this.value; + var pp = this.parentPath; + if (!n.Node.check(value)) { + while (pp && !n.Node.check(pp.value)) { + pp = pp.parentPath; + } + if (pp) { + pp = pp.parentPath; + } + } + while (pp && !n.Node.check(pp.value)) { + pp = pp.parentPath; + } + return pp || null; + }; + // The closest enclosing scope that governs this node. + NPp._computeScope = function () { + var value = this.value; + var pp = this.parentPath; + var scope = pp && pp.scope; + if (n.Node.check(value) && + Scope.isEstablishedBy(value)) { + scope = new Scope(this, scope); + } + return scope || null; + }; + NPp.getValueProperty = function (name) { + return types.getFieldValue(this.value, name); + }; + /** + * Determine whether this.node needs to be wrapped in parentheses in order + * for a parser to reproduce the same local AST structure. + * + * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression + * whose operator is "+" needs parentheses, because `1 + 2 * 3` would + * parse differently. + * + * If assumeExpressionContext === true, we don't worry about edge cases + * like an anonymous FunctionExpression appearing lexically first in its + * enclosing statement and thus needing parentheses to avoid being parsed + * as a FunctionDeclaration with a missing name. + */ + NPp.needsParens = function (assumeExpressionContext) { + var pp = this.parentPath; + if (!pp) { + return false; + } + var node = this.value; + // Only expressions need parentheses. + if (!n.Expression.check(node)) { + return false; + } + // Identifiers never need parentheses. + if (node.type === "Identifier") { + return false; + } + while (!n.Node.check(pp.value)) { + pp = pp.parentPath; + if (!pp) { + return false; + } + } + var parent = pp.value; + switch (node.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return parent.type === "MemberExpression" + && this.name === "object" + && parent.object === node; + case "BinaryExpression": + case "LogicalExpression": + switch (parent.type) { + case "CallExpression": + return this.name === "callee" + && parent.callee === node; + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return true; + case "MemberExpression": + return this.name === "object" + && parent.object === node; + case "BinaryExpression": + case "LogicalExpression": { + var n_1 = node; + var po = parent.operator; + var pp_1 = PRECEDENCE[po]; + var no = n_1.operator; + var np = PRECEDENCE[no]; + if (pp_1 > np) { + return true; + } + if (pp_1 === np && this.name === "right") { + if (parent.right !== n_1) { + throw new Error("Nodes must be equal"); + } + return true; + } + } + default: + return false; + } + case "SequenceExpression": + switch (parent.type) { + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; + case "ExpressionStatement": + return this.name !== "expression"; + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; + } + case "YieldExpression": + switch (parent.type) { + case "BinaryExpression": + case "LogicalExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "CallExpression": + case "MemberExpression": + case "NewExpression": + case "ConditionalExpression": + case "YieldExpression": + return true; + default: + return false; + } + case "Literal": + return parent.type === "MemberExpression" + && isNumber.check(node.value) + && this.name === "object" + && parent.object === node; + case "AssignmentExpression": + case "ConditionalExpression": + switch (parent.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + return true; + case "CallExpression": + return this.name === "callee" + && parent.callee === node; + case "ConditionalExpression": + return this.name === "test" + && parent.test === node; + case "MemberExpression": + return this.name === "object" + && parent.object === node; + default: + return false; + } + default: + if (parent.type === "NewExpression" && + this.name === "callee" && + parent.callee === node) { + return containsCallExpression(node); + } + } + if (assumeExpressionContext !== true && + !this.canBeFirstInStatement() && + this.firstInStatement()) + return true; + return false; + }; + function isBinary(node) { + return n.BinaryExpression.check(node) + || n.LogicalExpression.check(node); + } + // @ts-ignore 'isUnaryLike' is declared but its value is never read. [6133] + function isUnaryLike(node) { + return n.UnaryExpression.check(node) + // I considered making SpreadElement and SpreadProperty subtypes + // of UnaryExpression, but they're not really Expression nodes. + || (n.SpreadElement && n.SpreadElement.check(node)) + || (n.SpreadProperty && n.SpreadProperty.check(node)); + } + var PRECEDENCE = {}; + [["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ].forEach(function (tier, i) { + tier.forEach(function (op) { + PRECEDENCE[op] = i; + }); + }); + function containsCallExpression(node) { + if (n.CallExpression.check(node)) { + return true; + } + if (isArray.check(node)) { + return node.some(containsCallExpression); + } + if (n.Node.check(node)) { + return types.someField(node, function (_name, child) { + return containsCallExpression(child); + }); + } + return false; + } + NPp.canBeFirstInStatement = function () { + var node = this.node; + return !n.FunctionExpression.check(node) + && !n.ObjectExpression.check(node); + }; + NPp.firstInStatement = function () { + return firstInStatement(this); + }; + function firstInStatement(path) { + for (var node, parent; path.parent; path = path.parent) { + node = path.node; + parent = path.parent.node; + if (n.BlockStatement.check(parent) && + path.parent.name === "body" && + path.name === 0) { + if (parent.body[0] !== node) { + throw new Error("Nodes must be equal"); + } + return true; + } + if (n.ExpressionStatement.check(parent) && + path.name === "expression") { + if (parent.expression !== node) { + throw new Error("Nodes must be equal"); + } + return true; + } + if (n.SequenceExpression.check(parent) && + path.parent.name === "expressions" && + path.name === 0) { + if (parent.expressions[0] !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + if (n.CallExpression.check(parent) && + path.name === "callee") { + if (parent.callee !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + if (n.MemberExpression.check(parent) && + path.name === "object") { + if (parent.object !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + if (n.ConditionalExpression.check(parent) && + path.name === "test") { + if (parent.test !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + if (isBinary(parent) && + path.name === "left") { + if (parent.left !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + if (n.UnaryExpression.check(parent) && + !parent.prefix && + path.name === "argument") { + if (parent.argument !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } + return false; + } + return true; + } + /** + * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up. + */ + function cleanUpNodesAfterPrune(remainingNodePath) { + if (n.VariableDeclaration.check(remainingNodePath.node)) { + var declarations = remainingNodePath.get('declarations').value; + if (!declarations || declarations.length === 0) { + return remainingNodePath.prune(); + } + } + else if (n.ExpressionStatement.check(remainingNodePath.node)) { + if (!remainingNodePath.get('expression').value) { + return remainingNodePath.prune(); + } + } + else if (n.IfStatement.check(remainingNodePath.node)) { + cleanUpIfStatementAfterPrune(remainingNodePath); + } + return remainingNodePath; + } + function cleanUpIfStatementAfterPrune(ifStatement) { + var testExpression = ifStatement.get('test').value; + var alternate = ifStatement.get('alternate').value; + var consequent = ifStatement.get('consequent').value; + if (!consequent && !alternate) { + var testExpressionStatement = b.expressionStatement(testExpression); + ifStatement.replace(testExpressionStatement); + } + else if (!consequent && alternate) { + var negatedTestExpression = b.unaryExpression('!', testExpression, true); + if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') { + negatedTestExpression = testExpression.argument; + } + ifStatement.get("test").replace(negatedTestExpression); + ifStatement.get("consequent").replace(alternate); + ifStatement.get("alternate").replace(); + } + } + return NodePath; +} +exports["default"] = nodePathPlugin; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path-visitor.js": +/*!*******************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path-visitor.js ***! + \*******************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var node_path_1 = tslib_1.__importDefault(__webpack_require__(/*! ./node-path */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/node-path.js")); +var hasOwn = Object.prototype.hasOwnProperty; +function pathVisitorPlugin(fork) { + var types = fork.use(types_1.default); + var NodePath = fork.use(node_path_1.default); + var isArray = types.builtInTypes.array; + var isObject = types.builtInTypes.object; + var isFunction = types.builtInTypes.function; + var undefined; + var PathVisitor = function PathVisitor() { + if (!(this instanceof PathVisitor)) { + throw new Error("PathVisitor constructor cannot be invoked without 'new'"); + } + // Permanent state. + this._reusableContextStack = []; + this._methodNameTable = computeMethodNameTable(this); + this._shouldVisitComments = + hasOwn.call(this._methodNameTable, "Block") || + hasOwn.call(this._methodNameTable, "Line"); + this.Context = makeContextConstructor(this); + // State reset every time PathVisitor.prototype.visit is called. + this._visiting = false; + this._changeReported = false; + }; + function computeMethodNameTable(visitor) { + var typeNames = Object.create(null); + for (var methodName in visitor) { + if (/^visit[A-Z]/.test(methodName)) { + typeNames[methodName.slice("visit".length)] = true; + } + } + var supertypeTable = types.computeSupertypeLookupTable(typeNames); + var methodNameTable = Object.create(null); + var typeNameKeys = Object.keys(supertypeTable); + var typeNameCount = typeNameKeys.length; + for (var i = 0; i < typeNameCount; ++i) { + var typeName = typeNameKeys[i]; + methodName = "visit" + supertypeTable[typeName]; + if (isFunction.check(visitor[methodName])) { + methodNameTable[typeName] = methodName; + } + } + return methodNameTable; + } + PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { + if (methods instanceof PathVisitor) { + return methods; + } + if (!isObject.check(methods)) { + // An empty visitor? + return new PathVisitor; + } + var Visitor = function Visitor() { + if (!(this instanceof Visitor)) { + throw new Error("Visitor constructor cannot be invoked without 'new'"); + } + PathVisitor.call(this); + }; + var Vp = Visitor.prototype = Object.create(PVp); + Vp.constructor = Visitor; + extend(Vp, methods); + extend(Visitor, PathVisitor); + isFunction.assert(Visitor.fromMethodsObject); + isFunction.assert(Visitor.visit); + return new Visitor; + }; + function extend(target, source) { + for (var property in source) { + if (hasOwn.call(source, property)) { + target[property] = source[property]; + } + } + return target; + } + PathVisitor.visit = function visit(node, methods) { + return PathVisitor.fromMethodsObject(methods).visit(node); + }; + var PVp = PathVisitor.prototype; + PVp.visit = function () { + if (this._visiting) { + throw new Error("Recursively calling visitor.visit(path) resets visitor state. " + + "Try this.visit(path) or this.traverse(path) instead."); + } + // Private state that needs to be reset before every traversal. + this._visiting = true; + this._changeReported = false; + this._abortRequested = false; + var argc = arguments.length; + var args = new Array(argc); + for (var i = 0; i < argc; ++i) { + args[i] = arguments[i]; + } + if (!(args[0] instanceof NodePath)) { + args[0] = new NodePath({ root: args[0] }).get("root"); + } + // Called with the same arguments as .visit. + this.reset.apply(this, args); + var didNotThrow; + try { + var root = this.visitWithoutReset(args[0]); + didNotThrow = true; + } + finally { + this._visiting = false; + if (!didNotThrow && this._abortRequested) { + // If this.visitWithoutReset threw an exception and + // this._abortRequested was set to true, return the root of + // the AST instead of letting the exception propagate, so that + // client code does not have to provide a try-catch block to + // intercept the AbortRequest exception. Other kinds of + // exceptions will propagate without being intercepted and + // rethrown by a catch block, so their stacks will accurately + // reflect the original throwing context. + return args[0].value; + } + } + return root; + }; + PVp.AbortRequest = function AbortRequest() { }; + PVp.abort = function () { + var visitor = this; + visitor._abortRequested = true; + var request = new visitor.AbortRequest(); + // If you decide to catch this exception and stop it from propagating, + // make sure to call its cancel method to avoid silencing other + // exceptions that might be thrown later in the traversal. + request.cancel = function () { + visitor._abortRequested = false; + }; + throw request; + }; + PVp.reset = function (_path /*, additional arguments */) { + // Empty stub; may be reassigned or overridden by subclasses. + }; + PVp.visitWithoutReset = function (path) { + if (this instanceof this.Context) { + // Since this.Context.prototype === this, there's a chance we + // might accidentally call context.visitWithoutReset. If that + // happens, re-invoke the method against context.visitor. + return this.visitor.visitWithoutReset(path); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + var value = path.value; + var methodName = value && + typeof value === "object" && + typeof value.type === "string" && + this._methodNameTable[value.type]; + if (methodName) { + var context = this.acquireContext(path); + try { + return context.invokeVisitorMethod(methodName); + } + finally { + this.releaseContext(context); + } + } + else { + // If there was no visitor method to call, visit the children of + // this node generically. + return visitChildren(path, this); + } + }; + function visitChildren(path, visitor) { + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(visitor instanceof PathVisitor)) { + throw new Error(""); + } + var value = path.value; + if (isArray.check(value)) { + path.each(visitor.visitWithoutReset, visitor); + } + else if (!isObject.check(value)) { + // No children to visit. + } + else { + var childNames = types.getFieldNames(value); + // The .comments field of the Node type is hidden, so we only + // visit it if the visitor defines visitBlock or visitLine, and + // value.comments is defined. + if (visitor._shouldVisitComments && + value.comments && + childNames.indexOf("comments") < 0) { + childNames.push("comments"); + } + var childCount = childNames.length; + var childPaths = []; + for (var i = 0; i < childCount; ++i) { + var childName = childNames[i]; + if (!hasOwn.call(value, childName)) { + value[childName] = types.getFieldValue(value, childName); + } + childPaths.push(path.get(childName)); + } + for (var i = 0; i < childCount; ++i) { + visitor.visitWithoutReset(childPaths[i]); + } + } + return path.value; + } + PVp.acquireContext = function (path) { + if (this._reusableContextStack.length === 0) { + return new this.Context(path); + } + return this._reusableContextStack.pop().reset(path); + }; + PVp.releaseContext = function (context) { + if (!(context instanceof this.Context)) { + throw new Error(""); + } + this._reusableContextStack.push(context); + context.currentPath = null; + }; + PVp.reportChanged = function () { + this._changeReported = true; + }; + PVp.wasChangeReported = function () { + return this._changeReported; + }; + function makeContextConstructor(visitor) { + function Context(path) { + if (!(this instanceof Context)) { + throw new Error(""); + } + if (!(this instanceof PathVisitor)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + Object.defineProperty(this, "visitor", { + value: visitor, + writable: false, + enumerable: true, + configurable: false + }); + this.currentPath = path; + this.needToCallTraverse = true; + Object.seal(this); + } + if (!(visitor instanceof PathVisitor)) { + throw new Error(""); + } + // Note that the visitor object is the prototype of Context.prototype, + // so all visitor methods are inherited by context objects. + var Cp = Context.prototype = Object.create(visitor); + Cp.constructor = Context; + extend(Cp, sharedContextProtoMethods); + return Context; + } + // Every PathVisitor has a different this.Context constructor and + // this.Context.prototype object, but those prototypes can all use the + // same reset, invokeVisitorMethod, and traverse function objects. + var sharedContextProtoMethods = Object.create(null); + sharedContextProtoMethods.reset = + function reset(path) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + this.currentPath = path; + this.needToCallTraverse = true; + return this; + }; + sharedContextProtoMethods.invokeVisitorMethod = + function invokeVisitorMethod(methodName) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } + var result = this.visitor[methodName].call(this, this.currentPath); + if (result === false) { + // Visitor methods return false to indicate that they have handled + // their own traversal needs, and we should not complain if + // this.needToCallTraverse is still true. + this.needToCallTraverse = false; + } + else if (result !== undefined) { + // Any other non-undefined value returned from the visitor method + // is interpreted as a replacement value. + this.currentPath = this.currentPath.replace(result)[0]; + if (this.needToCallTraverse) { + // If this.traverse still hasn't been called, visit the + // children of the replacement node. + this.traverse(this.currentPath); + } + } + if (this.needToCallTraverse !== false) { + throw new Error("Must either call this.traverse or return false in " + methodName); + } + var path = this.currentPath; + return path && path.value; + }; + sharedContextProtoMethods.traverse = + function traverse(path, newVisitor) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } + this.needToCallTraverse = false; + return visitChildren(path, PathVisitor.fromMethodsObject(newVisitor || this.visitor)); + }; + sharedContextProtoMethods.visit = + function visit(path, newVisitor) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } + this.needToCallTraverse = false; + return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path); + }; + sharedContextProtoMethods.reportChanged = function reportChanged() { + this.visitor.reportChanged(); + }; + sharedContextProtoMethods.abort = function abort() { + this.needToCallTraverse = false; + this.visitor.abort(); + }; + return PathVisitor; +} +exports["default"] = pathVisitorPlugin; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path.js": +/*!***********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/path.js ***! + \***********************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var Op = Object.prototype; +var hasOwn = Op.hasOwnProperty; +function pathPlugin(fork) { + var types = fork.use(types_1.default); + var isArray = types.builtInTypes.array; + var isNumber = types.builtInTypes.number; + var Path = function Path(value, parentPath, name) { + if (!(this instanceof Path)) { + throw new Error("Path constructor cannot be invoked without 'new'"); + } + if (parentPath) { + if (!(parentPath instanceof Path)) { + throw new Error(""); + } + } + else { + parentPath = null; + name = null; + } + // The value encapsulated by this Path, generally equal to + // parentPath.value[name] if we have a parentPath. + this.value = value; + // The immediate parent Path of this Path. + this.parentPath = parentPath; + // The name of the property of parentPath.value through which this + // Path's value was reached. + this.name = name; + // Calling path.get("child") multiple times always returns the same + // child Path object, for both performance and consistency reasons. + this.__childCache = null; + }; + var Pp = Path.prototype; + function getChildCache(path) { + // Lazily create the child cache. This also cheapens cache + // invalidation, since you can just reset path.__childCache to null. + return path.__childCache || (path.__childCache = Object.create(null)); + } + function getChildPath(path, name) { + var cache = getChildCache(path); + var actualChildValue = path.getValueProperty(name); + var childPath = cache[name]; + if (!hasOwn.call(cache, name) || + // Ensure consistency between cache and reality. + childPath.value !== actualChildValue) { + childPath = cache[name] = new path.constructor(actualChildValue, path, name); + } + return childPath; + } + // This method is designed to be overridden by subclasses that need to + // handle missing properties, etc. + Pp.getValueProperty = function getValueProperty(name) { + return this.value[name]; + }; + Pp.get = function get() { + var names = []; + for (var _i = 0; _i < arguments.length; _i++) { + names[_i] = arguments[_i]; + } + var path = this; + var count = names.length; + for (var i = 0; i < count; ++i) { + path = getChildPath(path, names[i]); + } + return path; + }; + Pp.each = function each(callback, context) { + var childPaths = []; + var len = this.value.length; + var i = 0; + // Collect all the original child paths before invoking the callback. + for (var i = 0; i < len; ++i) { + if (hasOwn.call(this.value, i)) { + childPaths[i] = this.get(i); + } + } + // Invoke the callback on just the original child paths, regardless of + // any modifications made to the array by the callback. I chose these + // semantics over cleverly invoking the callback on new elements because + // this way is much easier to reason about. + context = context || this; + for (i = 0; i < len; ++i) { + if (hasOwn.call(childPaths, i)) { + callback.call(context, childPaths[i]); + } + } + }; + Pp.map = function map(callback, context) { + var result = []; + this.each(function (childPath) { + result.push(callback.call(this, childPath)); + }, context); + return result; + }; + Pp.filter = function filter(callback, context) { + var result = []; + this.each(function (childPath) { + if (callback.call(this, childPath)) { + result.push(childPath); + } + }, context); + return result; + }; + function emptyMoves() { } + function getMoves(path, offset, start, end) { + isArray.assert(path.value); + if (offset === 0) { + return emptyMoves; + } + var length = path.value.length; + if (length < 1) { + return emptyMoves; + } + var argc = arguments.length; + if (argc === 2) { + start = 0; + end = length; + } + else if (argc === 3) { + start = Math.max(start, 0); + end = length; + } + else { + start = Math.max(start, 0); + end = Math.min(end, length); + } + isNumber.assert(start); + isNumber.assert(end); + var moves = Object.create(null); + var cache = getChildCache(path); + for (var i = start; i < end; ++i) { + if (hasOwn.call(path.value, i)) { + var childPath = path.get(i); + if (childPath.name !== i) { + throw new Error(""); + } + var newIndex = i + offset; + childPath.name = newIndex; + moves[newIndex] = childPath; + delete cache[i]; + } + } + delete cache.length; + return function () { + for (var newIndex in moves) { + var childPath = moves[newIndex]; + if (childPath.name !== +newIndex) { + throw new Error(""); + } + cache[newIndex] = childPath; + path.value[newIndex] = childPath.value; + } + }; + } + Pp.shift = function shift() { + var move = getMoves(this, -1); + var result = this.value.shift(); + move(); + return result; + }; + Pp.unshift = function unshift() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var move = getMoves(this, args.length); + var result = this.value.unshift.apply(this.value, args); + move(); + return result; + }; + Pp.push = function push() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + isArray.assert(this.value); + delete getChildCache(this).length; + return this.value.push.apply(this.value, args); + }; + Pp.pop = function pop() { + isArray.assert(this.value); + var cache = getChildCache(this); + delete cache[this.value.length - 1]; + delete cache.length; + return this.value.pop(); + }; + Pp.insertAt = function insertAt(index) { + var argc = arguments.length; + var move = getMoves(this, argc - 1, index); + if (move === emptyMoves && argc <= 1) { + return this; + } + index = Math.max(index, 0); + for (var i = 1; i < argc; ++i) { + this.value[index + i - 1] = arguments[i]; + } + move(); + return this; + }; + Pp.insertBefore = function insertBefore() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var pp = this.parentPath; + var argc = args.length; + var insertAtArgs = [this.name]; + for (var i = 0; i < argc; ++i) { + insertAtArgs.push(args[i]); + } + return pp.insertAt.apply(pp, insertAtArgs); + }; + Pp.insertAfter = function insertAfter() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var pp = this.parentPath; + var argc = args.length; + var insertAtArgs = [this.name + 1]; + for (var i = 0; i < argc; ++i) { + insertAtArgs.push(args[i]); + } + return pp.insertAt.apply(pp, insertAtArgs); + }; + function repairRelationshipWithParent(path) { + if (!(path instanceof Path)) { + throw new Error(""); + } + var pp = path.parentPath; + if (!pp) { + // Orphan paths have no relationship to repair. + return path; + } + var parentValue = pp.value; + var parentCache = getChildCache(pp); + // Make sure parentCache[path.name] is populated. + if (parentValue[path.name] === path.value) { + parentCache[path.name] = path; + } + else if (isArray.check(parentValue)) { + // Something caused path.name to become out of date, so attempt to + // recover by searching for path.value in parentValue. + var i = parentValue.indexOf(path.value); + if (i >= 0) { + parentCache[path.name = i] = path; + } + } + else { + // If path.value disagrees with parentValue[path.name], and + // path.name is not an array index, let path.value become the new + // parentValue[path.name] and update parentCache accordingly. + parentValue[path.name] = path.value; + parentCache[path.name] = path; + } + if (parentValue[path.name] !== path.value) { + throw new Error(""); + } + if (path.parentPath.get(path.name) !== path) { + throw new Error(""); + } + return path; + } + Pp.replace = function replace(replacement) { + var results = []; + var parentValue = this.parentPath.value; + var parentCache = getChildCache(this.parentPath); + var count = arguments.length; + repairRelationshipWithParent(this); + if (isArray.check(parentValue)) { + var originalLength = parentValue.length; + var move = getMoves(this.parentPath, count - 1, this.name + 1); + var spliceArgs = [this.name, 1]; + for (var i = 0; i < count; ++i) { + spliceArgs.push(arguments[i]); + } + var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); + if (splicedOut[0] !== this.value) { + throw new Error(""); + } + if (parentValue.length !== (originalLength - 1 + count)) { + throw new Error(""); + } + move(); + if (count === 0) { + delete this.value; + delete parentCache[this.name]; + this.__childCache = null; + } + else { + if (parentValue[this.name] !== replacement) { + throw new Error(""); + } + if (this.value !== replacement) { + this.value = replacement; + this.__childCache = null; + } + for (i = 0; i < count; ++i) { + results.push(this.parentPath.get(this.name + i)); + } + if (results[0] !== this) { + throw new Error(""); + } + } + } + else if (count === 1) { + if (this.value !== replacement) { + this.__childCache = null; + } + this.value = parentValue[this.name] = replacement; + results.push(this); + } + else if (count === 0) { + delete parentValue[this.name]; + delete this.value; + this.__childCache = null; + // Leave this path cached as parentCache[this.name], even though + // it no longer has a value defined. + } + else { + throw new Error("Could not replace path"); + } + return results; + }; + return Path; +} +exports["default"] = pathPlugin; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/scope.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/scope.js ***! + \************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +var hasOwn = Object.prototype.hasOwnProperty; +function scopePlugin(fork) { + var types = fork.use(types_1.default); + var Type = types.Type; + var namedTypes = types.namedTypes; + var Node = namedTypes.Node; + var Expression = namedTypes.Expression; + var isArray = types.builtInTypes.array; + var b = types.builders; + var Scope = function Scope(path, parentScope) { + if (!(this instanceof Scope)) { + throw new Error("Scope constructor cannot be invoked without 'new'"); + } + ScopeType.assert(path.value); + var depth; + if (parentScope) { + if (!(parentScope instanceof Scope)) { + throw new Error(""); + } + depth = parentScope.depth + 1; + } + else { + parentScope = null; + depth = 0; + } + Object.defineProperties(this, { + path: { value: path }, + node: { value: path.value }, + isGlobal: { value: !parentScope, enumerable: true }, + depth: { value: depth }, + parent: { value: parentScope }, + bindings: { value: {} }, + types: { value: {} }, + }); + }; + var scopeTypes = [ + // Program nodes introduce global scopes. + namedTypes.Program, + // Function is the supertype of FunctionExpression, + // FunctionDeclaration, ArrowExpression, etc. + namedTypes.Function, + // In case you didn't know, the caught parameter shadows any variable + // of the same name in an outer scope. + namedTypes.CatchClause + ]; + var ScopeType = Type.or.apply(Type, scopeTypes); + Scope.isEstablishedBy = function (node) { + return ScopeType.check(node); + }; + var Sp = Scope.prototype; + // Will be overridden after an instance lazily calls scanScope. + Sp.didScan = false; + Sp.declares = function (name) { + this.scan(); + return hasOwn.call(this.bindings, name); + }; + Sp.declaresType = function (name) { + this.scan(); + return hasOwn.call(this.types, name); + }; + Sp.declareTemporary = function (prefix) { + if (prefix) { + if (!/^[a-z$_]/i.test(prefix)) { + throw new Error(""); + } + } + else { + prefix = "t$"; + } + // Include this.depth in the name to make sure the name does not + // collide with any variables in nested/enclosing scopes. + prefix += this.depth.toString(36) + "$"; + this.scan(); + var index = 0; + while (this.declares(prefix + index)) { + ++index; + } + var name = prefix + index; + return this.bindings[name] = types.builders.identifier(name); + }; + Sp.injectTemporary = function (identifier, init) { + identifier || (identifier = this.declareTemporary()); + var bodyPath = this.path.get("body"); + if (namedTypes.BlockStatement.check(bodyPath.value)) { + bodyPath = bodyPath.get("body"); + } + bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init || null)])); + return identifier; + }; + Sp.scan = function (force) { + if (force || !this.didScan) { + for (var name in this.bindings) { + // Empty out this.bindings, just in cases. + delete this.bindings[name]; + } + scanScope(this.path, this.bindings, this.types); + this.didScan = true; + } + }; + Sp.getBindings = function () { + this.scan(); + return this.bindings; + }; + Sp.getTypes = function () { + this.scan(); + return this.types; + }; + function scanScope(path, bindings, scopeTypes) { + var node = path.value; + ScopeType.assert(node); + if (namedTypes.CatchClause.check(node)) { + // A catch clause establishes a new scope but the only variable + // bound in that scope is the catch parameter. Any other + // declarations create bindings in the outer scope. + var param = path.get("param"); + if (param.value) { + addPattern(param, bindings); + } + } + else { + recursiveScanScope(path, bindings, scopeTypes); + } + } + function recursiveScanScope(path, bindings, scopeTypes) { + var node = path.value; + if (path.parent && + namedTypes.FunctionExpression.check(path.parent.node) && + path.parent.node.id) { + addPattern(path.parent.get("id"), bindings); + } + if (!node) { + // None of the remaining cases matter if node is falsy. + } + else if (isArray.check(node)) { + path.each(function (childPath) { + recursiveScanChild(childPath, bindings, scopeTypes); + }); + } + else if (namedTypes.Function.check(node)) { + path.get("params").each(function (paramPath) { + addPattern(paramPath, bindings); + }); + recursiveScanChild(path.get("body"), bindings, scopeTypes); + } + else if ((namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) || + (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) || + (namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) || + (namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))) { + addTypePattern(path.get("id"), scopeTypes); + } + else if (namedTypes.VariableDeclarator.check(node)) { + addPattern(path.get("id"), bindings); + recursiveScanChild(path.get("init"), bindings, scopeTypes); + } + else if (node.type === "ImportSpecifier" || + node.type === "ImportNamespaceSpecifier" || + node.type === "ImportDefaultSpecifier") { + addPattern( + // Esprima used to use the .name field to refer to the local + // binding identifier for ImportSpecifier nodes, but .id for + // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. + // ESTree/Acorn/ESpree use .local for all three node types. + path.get(node.local ? "local" : + node.name ? "name" : "id"), bindings); + } + else if (Node.check(node) && !Expression.check(node)) { + types.eachField(node, function (name, child) { + var childPath = path.get(name); + if (!pathHasValue(childPath, child)) { + throw new Error(""); + } + recursiveScanChild(childPath, bindings, scopeTypes); + }); + } + } + function pathHasValue(path, value) { + if (path.value === value) { + return true; + } + // Empty arrays are probably produced by defaults.emptyArray, in which + // case is makes sense to regard them as equivalent, if not ===. + if (Array.isArray(path.value) && + path.value.length === 0 && + Array.isArray(value) && + value.length === 0) { + return true; + } + return false; + } + function recursiveScanChild(path, bindings, scopeTypes) { + var node = path.value; + if (!node || Expression.check(node)) { + // Ignore falsy values and Expressions. + } + else if (namedTypes.FunctionDeclaration.check(node) && + node.id !== null) { + addPattern(path.get("id"), bindings); + } + else if (namedTypes.ClassDeclaration && + namedTypes.ClassDeclaration.check(node)) { + addPattern(path.get("id"), bindings); + } + else if (ScopeType.check(node)) { + if (namedTypes.CatchClause.check(node) && + // TODO Broaden this to accept any pattern. + namedTypes.Identifier.check(node.param)) { + var catchParamName = node.param.name; + var hadBinding = hasOwn.call(bindings, catchParamName); + // Any declarations that occur inside the catch body that do + // not have the same name as the catch parameter should count + // as bindings in the outer scope. + recursiveScanScope(path.get("body"), bindings, scopeTypes); + // If a new binding matching the catch parameter name was + // created while scanning the catch body, ignore it because it + // actually refers to the catch parameter and not the outer + // scope that we're currently scanning. + if (!hadBinding) { + delete bindings[catchParamName]; + } + } + } + else { + recursiveScanScope(path, bindings, scopeTypes); + } + } + function addPattern(patternPath, bindings) { + var pattern = patternPath.value; + namedTypes.Pattern.assert(pattern); + if (namedTypes.Identifier.check(pattern)) { + if (hasOwn.call(bindings, pattern.name)) { + bindings[pattern.name].push(patternPath); + } + else { + bindings[pattern.name] = [patternPath]; + } + } + else if (namedTypes.AssignmentPattern && + namedTypes.AssignmentPattern.check(pattern)) { + addPattern(patternPath.get('left'), bindings); + } + else if (namedTypes.ObjectPattern && + namedTypes.ObjectPattern.check(pattern)) { + patternPath.get('properties').each(function (propertyPath) { + var property = propertyPath.value; + if (namedTypes.Pattern.check(property)) { + addPattern(propertyPath, bindings); + } + else if (namedTypes.Property.check(property)) { + addPattern(propertyPath.get('value'), bindings); + } + else if (namedTypes.SpreadProperty && + namedTypes.SpreadProperty.check(property)) { + addPattern(propertyPath.get('argument'), bindings); + } + }); + } + else if (namedTypes.ArrayPattern && + namedTypes.ArrayPattern.check(pattern)) { + patternPath.get('elements').each(function (elementPath) { + var element = elementPath.value; + if (namedTypes.Pattern.check(element)) { + addPattern(elementPath, bindings); + } + else if (namedTypes.SpreadElement && + namedTypes.SpreadElement.check(element)) { + addPattern(elementPath.get("argument"), bindings); + } + }); + } + else if (namedTypes.PropertyPattern && + namedTypes.PropertyPattern.check(pattern)) { + addPattern(patternPath.get('pattern'), bindings); + } + else if ((namedTypes.SpreadElementPattern && + namedTypes.SpreadElementPattern.check(pattern)) || + (namedTypes.SpreadPropertyPattern && + namedTypes.SpreadPropertyPattern.check(pattern))) { + addPattern(patternPath.get('argument'), bindings); + } + } + function addTypePattern(patternPath, types) { + var pattern = patternPath.value; + namedTypes.Pattern.assert(pattern); + if (namedTypes.Identifier.check(pattern)) { + if (hasOwn.call(types, pattern.name)) { + types[pattern.name].push(patternPath); + } + else { + types[pattern.name] = [patternPath]; + } + } + } + Sp.lookup = function (name) { + for (var scope = this; scope; scope = scope.parent) + if (scope.declares(name)) + break; + return scope; + }; + Sp.lookupType = function (name) { + for (var scope = this; scope; scope = scope.parent) + if (scope.declaresType(name)) + break; + return scope; + }; + Sp.getGlobalScope = function () { + var scope = this; + while (!scope.isGlobal) + scope = scope.parent; + return scope; + }; + return Scope; +} +exports["default"] = scopePlugin; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js": +/*!*************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/shared.js ***! + \*************************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +"use strict"; +; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var types_1 = tslib_1.__importDefault(__webpack_require__(/*! ./types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js")); +function default_1(fork) { + var types = fork.use(types_1.default); + var Type = types.Type; + var builtin = types.builtInTypes; + var isNumber = builtin.number; + // An example of constructing a new type with arbitrary constraints from + // an existing type. + function geq(than) { + return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); + } + ; + // Default value-returning functions that may optionally be passed as a + // third argument to Def.prototype.field. + var defaults = { + // Functions were used because (among other reasons) that's the most + // elegant way to allow for the emptyArray one always to give a new + // array instance. + "null": function () { return null; }, + "emptyArray": function () { return []; }, + "false": function () { return false; }, + "true": function () { return true; }, + "undefined": function () { }, + "use strict": function () { return "use strict"; } + }; + var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined); + var isPrimitive = Type.from(function (value) { + if (value === null) + return true; + var type = typeof value; + if (type === "object" || + type === "function") { + return false; + } + return true; + }, naiveIsPrimitive.toString()); + return { + geq: geq, + defaults: defaults, + isPrimitive: isPrimitive, + }; +} +exports["default"] = default_1; +module.exports = exports["default"]; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/lib/types.js ***! + \************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Def = void 0; +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var Op = Object.prototype; +var objToStr = Op.toString; +var hasOwn = Op.hasOwnProperty; +var BaseType = /** @class */ (function () { + function BaseType() { + } + BaseType.prototype.assert = function (value, deep) { + if (!this.check(value, deep)) { + var str = shallowStringify(value); + throw new Error(str + " does not match type " + this); + } + return true; + }; + BaseType.prototype.arrayOf = function () { + var elemType = this; + return new ArrayType(elemType); + }; + return BaseType; +}()); +var ArrayType = /** @class */ (function (_super) { + tslib_1.__extends(ArrayType, _super); + function ArrayType(elemType) { + var _this = _super.call(this) || this; + _this.elemType = elemType; + _this.kind = "ArrayType"; + return _this; + } + ArrayType.prototype.toString = function () { + return "[" + this.elemType + "]"; + }; + ArrayType.prototype.check = function (value, deep) { + var _this = this; + return Array.isArray(value) && value.every(function (elem) { return _this.elemType.check(elem, deep); }); + }; + return ArrayType; +}(BaseType)); +var IdentityType = /** @class */ (function (_super) { + tslib_1.__extends(IdentityType, _super); + function IdentityType(value) { + var _this = _super.call(this) || this; + _this.value = value; + _this.kind = "IdentityType"; + return _this; + } + IdentityType.prototype.toString = function () { + return String(this.value); + }; + IdentityType.prototype.check = function (value, deep) { + var result = value === this.value; + if (!result && typeof deep === "function") { + deep(this, value); + } + return result; + }; + return IdentityType; +}(BaseType)); +var ObjectType = /** @class */ (function (_super) { + tslib_1.__extends(ObjectType, _super); + function ObjectType(fields) { + var _this = _super.call(this) || this; + _this.fields = fields; + _this.kind = "ObjectType"; + return _this; + } + ObjectType.prototype.toString = function () { + return "{ " + this.fields.join(", ") + " }"; + }; + ObjectType.prototype.check = function (value, deep) { + return (objToStr.call(value) === objToStr.call({}) && + this.fields.every(function (field) { + return field.type.check(value[field.name], deep); + })); + }; + return ObjectType; +}(BaseType)); +var OrType = /** @class */ (function (_super) { + tslib_1.__extends(OrType, _super); + function OrType(types) { + var _this = _super.call(this) || this; + _this.types = types; + _this.kind = "OrType"; + return _this; + } + OrType.prototype.toString = function () { + return this.types.join(" | "); + }; + OrType.prototype.check = function (value, deep) { + return this.types.some(function (type) { + return type.check(value, deep); + }); + }; + return OrType; +}(BaseType)); +var PredicateType = /** @class */ (function (_super) { + tslib_1.__extends(PredicateType, _super); + function PredicateType(name, predicate) { + var _this = _super.call(this) || this; + _this.name = name; + _this.predicate = predicate; + _this.kind = "PredicateType"; + return _this; + } + PredicateType.prototype.toString = function () { + return this.name; + }; + PredicateType.prototype.check = function (value, deep) { + var result = this.predicate(value, deep); + if (!result && typeof deep === "function") { + deep(this, value); + } + return result; + }; + return PredicateType; +}(BaseType)); +var Def = /** @class */ (function () { + function Def(type, typeName) { + this.type = type; + this.typeName = typeName; + this.baseNames = []; + this.ownFields = Object.create(null); + // Includes own typeName. Populated during finalization. + this.allSupertypes = Object.create(null); + // Linear inheritance hierarchy. Populated during finalization. + this.supertypeList = []; + // Includes inherited fields. + this.allFields = Object.create(null); + // Non-hidden keys of allFields. + this.fieldNames = []; + // This property will be overridden as true by individual Def instances + // when they are finalized. + this.finalized = false; + // False by default until .build(...) is called on an instance. + this.buildable = false; + this.buildParams = []; + } + Def.prototype.isSupertypeOf = function (that) { + if (that instanceof Def) { + if (this.finalized !== true || + that.finalized !== true) { + throw new Error(""); + } + return hasOwn.call(that.allSupertypes, this.typeName); + } + else { + throw new Error(that + " is not a Def"); + } + }; + Def.prototype.checkAllFields = function (value, deep) { + var allFields = this.allFields; + if (this.finalized !== true) { + throw new Error("" + this.typeName); + } + function checkFieldByName(name) { + var field = allFields[name]; + var type = field.type; + var child = field.getValue(value); + return type.check(child, deep); + } + return value !== null && + typeof value === "object" && + Object.keys(allFields).every(checkFieldByName); + }; + Def.prototype.bases = function () { + var supertypeNames = []; + for (var _i = 0; _i < arguments.length; _i++) { + supertypeNames[_i] = arguments[_i]; + } + var bases = this.baseNames; + if (this.finalized) { + if (supertypeNames.length !== bases.length) { + throw new Error(""); + } + for (var i = 0; i < supertypeNames.length; i++) { + if (supertypeNames[i] !== bases[i]) { + throw new Error(""); + } + } + return this; + } + supertypeNames.forEach(function (baseName) { + // This indexOf lookup may be O(n), but the typical number of base + // names is very small, and indexOf is a native Array method. + if (bases.indexOf(baseName) < 0) { + bases.push(baseName); + } + }); + return this; // For chaining. + }; + return Def; +}()); +exports.Def = Def; +var Field = /** @class */ (function () { + function Field(name, type, defaultFn, hidden) { + this.name = name; + this.type = type; + this.defaultFn = defaultFn; + this.hidden = !!hidden; + } + Field.prototype.toString = function () { + return JSON.stringify(this.name) + ": " + this.type; + }; + Field.prototype.getValue = function (obj) { + var value = obj[this.name]; + if (typeof value !== "undefined") { + return value; + } + if (typeof this.defaultFn === "function") { + value = this.defaultFn.call(obj); + } + return value; + }; + return Field; +}()); +function shallowStringify(value) { + if (Array.isArray(value)) { + return "[" + value.map(shallowStringify).join(", ") + "]"; + } + if (value && typeof value === "object") { + return "{ " + Object.keys(value).map(function (key) { + return key + ": " + value[key]; + }).join(", ") + " }"; + } + return JSON.stringify(value); +} +function typesPlugin(_fork) { + var Type = { + or: function () { + var types = []; + for (var _i = 0; _i < arguments.length; _i++) { + types[_i] = arguments[_i]; + } + return new OrType(types.map(function (type) { return Type.from(type); })); + }, + from: function (value, name) { + if (value instanceof ArrayType || + value instanceof IdentityType || + value instanceof ObjectType || + value instanceof OrType || + value instanceof PredicateType) { + return value; + } + // The Def type is used as a helper for constructing compound + // interface types for AST nodes. + if (value instanceof Def) { + return value.type; + } + // Support [ElemType] syntax. + if (isArray.check(value)) { + if (value.length !== 1) { + throw new Error("only one element type is permitted for typed arrays"); + } + return new ArrayType(Type.from(value[0])); + } + // Support { someField: FieldType, ... } syntax. + if (isObject.check(value)) { + return new ObjectType(Object.keys(value).map(function (name) { + return new Field(name, Type.from(value[name], name)); + })); + } + if (typeof value === "function") { + var bicfIndex = builtInCtorFns.indexOf(value); + if (bicfIndex >= 0) { + return builtInCtorTypes[bicfIndex]; + } + if (typeof name !== "string") { + throw new Error("missing name"); + } + return new PredicateType(name, value); + } + // As a last resort, toType returns a type that matches any value that + // is === from. This is primarily useful for literal values like + // toType(null), but it has the additional advantage of allowing + // toType to be a total function. + return new IdentityType(value); + }, + // Define a type whose name is registered in a namespace (the defCache) so + // that future definitions will return the same type given the same name. + // In particular, this system allows for circular and forward definitions. + // The Def object d returned from Type.def may be used to configure the + // type d.type by calling methods such as d.bases, d.build, and d.field. + def: function (typeName) { + return hasOwn.call(defCache, typeName) + ? defCache[typeName] + : defCache[typeName] = new DefImpl(typeName); + }, + hasDef: function (typeName) { + return hasOwn.call(defCache, typeName); + } + }; + var builtInCtorFns = []; + var builtInCtorTypes = []; + function defBuiltInType(name, example) { + var objStr = objToStr.call(example); + var type = new PredicateType(name, function (value) { return objToStr.call(value) === objStr; }); + if (example && typeof example.constructor === "function") { + builtInCtorFns.push(example.constructor); + builtInCtorTypes.push(type); + } + return type; + } + // These types check the underlying [[Class]] attribute of the given + // value, rather than using the problematic typeof operator. Note however + // that no subtyping is considered; so, for instance, isObject.check + // returns false for [], /./, new Date, and null. + var isString = defBuiltInType("string", "truthy"); + var isFunction = defBuiltInType("function", function () { }); + var isArray = defBuiltInType("array", []); + var isObject = defBuiltInType("object", {}); + var isRegExp = defBuiltInType("RegExp", /./); + var isDate = defBuiltInType("Date", new Date()); + var isNumber = defBuiltInType("number", 3); + var isBoolean = defBuiltInType("boolean", true); + var isNull = defBuiltInType("null", null); + var isUndefined = defBuiltInType("undefined", undefined); + var builtInTypes = { + string: isString, + function: isFunction, + array: isArray, + object: isObject, + RegExp: isRegExp, + Date: isDate, + number: isNumber, + boolean: isBoolean, + null: isNull, + undefined: isUndefined, + }; + // In order to return the same Def instance every time Type.def is called + // with a particular name, those instances need to be stored in a cache. + var defCache = Object.create(null); + function defFromValue(value) { + if (value && typeof value === "object") { + var type = value.type; + if (typeof type === "string" && + hasOwn.call(defCache, type)) { + var d = defCache[type]; + if (d.finalized) { + return d; + } + } + } + return null; + } + var DefImpl = /** @class */ (function (_super) { + tslib_1.__extends(DefImpl, _super); + function DefImpl(typeName) { + var _this = _super.call(this, new PredicateType(typeName, function (value, deep) { return _this.check(value, deep); }), typeName) || this; + return _this; + } + DefImpl.prototype.check = function (value, deep) { + if (this.finalized !== true) { + throw new Error("prematurely checking unfinalized type " + this.typeName); + } + // A Def type can only match an object value. + if (value === null || typeof value !== "object") { + return false; + } + var vDef = defFromValue(value); + if (!vDef) { + // If we couldn't infer the Def associated with the given value, + // and we expected it to be a SourceLocation or a Position, it was + // probably just missing a "type" field (because Esprima does not + // assign a type property to such nodes). Be optimistic and let + // this.checkAllFields make the final decision. + if (this.typeName === "SourceLocation" || + this.typeName === "Position") { + return this.checkAllFields(value, deep); + } + // Calling this.checkAllFields for any other type of node is both + // bad for performance and way too forgiving. + return false; + } + // If checking deeply and vDef === this, then we only need to call + // checkAllFields once. Calling checkAllFields is too strict when deep + // is false, because then we only care about this.isSupertypeOf(vDef). + if (deep && vDef === this) { + return this.checkAllFields(value, deep); + } + // In most cases we rely exclusively on isSupertypeOf to make O(1) + // subtyping determinations. This suffices in most situations outside + // of unit tests, since interface conformance is checked whenever new + // instances are created using builder functions. + if (!this.isSupertypeOf(vDef)) { + return false; + } + // The exception is when deep is true; then, we recursively check all + // fields. + if (!deep) { + return true; + } + // Use the more specific Def (vDef) to perform the deep check, but + // shallow-check fields defined by the less specific Def (this). + return vDef.checkAllFields(value, deep) + && this.checkAllFields(value, false); + }; + DefImpl.prototype.build = function () { + var _this = this; + var buildParams = []; + for (var _i = 0; _i < arguments.length; _i++) { + buildParams[_i] = arguments[_i]; + } + // Calling Def.prototype.build multiple times has the effect of merely + // redefining this property. + this.buildParams = buildParams; + if (this.buildable) { + // If this Def is already buildable, update self.buildParams and + // continue using the old builder function. + return this; + } + // Every buildable type will have its "type" field filled in + // automatically. This includes types that are not subtypes of Node, + // like SourceLocation, but that seems harmless (TODO?). + this.field("type", String, function () { return _this.typeName; }); + // Override Dp.buildable for this Def instance. + this.buildable = true; + var addParam = function (built, param, arg, isArgAvailable) { + if (hasOwn.call(built, param)) + return; + var all = _this.allFields; + if (!hasOwn.call(all, param)) { + throw new Error("" + param); + } + var field = all[param]; + var type = field.type; + var value; + if (isArgAvailable) { + value = arg; + } + else if (field.defaultFn) { + // Expose the partially-built object to the default + // function as its `this` object. + value = field.defaultFn.call(built); + } + else { + var message = "no value or default function given for field " + + JSON.stringify(param) + " of " + _this.typeName + "(" + + _this.buildParams.map(function (name) { + return all[name]; + }).join(", ") + ")"; + throw new Error(message); + } + if (!type.check(value)) { + throw new Error(shallowStringify(value) + + " does not match field " + field + + " of type " + _this.typeName); + } + built[param] = value; + }; + // Calling the builder function will construct an instance of the Def, + // with positional arguments mapped to the fields original passed to .build. + // If not enough arguments are provided, the default value for the remaining fields + // will be used. + var builder = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var argc = args.length; + if (!_this.finalized) { + throw new Error("attempting to instantiate unfinalized type " + + _this.typeName); + } + var built = Object.create(nodePrototype); + _this.buildParams.forEach(function (param, i) { + if (i < argc) { + addParam(built, param, args[i], true); + } + else { + addParam(built, param, null, false); + } + }); + Object.keys(_this.allFields).forEach(function (param) { + // Use the default value. + addParam(built, param, null, false); + }); + // Make sure that the "type" field was filled automatically. + if (built.type !== _this.typeName) { + throw new Error(""); + } + return built; + }; + // Calling .from on the builder function will construct an instance of the Def, + // using field values from the passed object. For fields missing from the passed object, + // their default value will be used. + builder.from = function (obj) { + if (!_this.finalized) { + throw new Error("attempting to instantiate unfinalized type " + + _this.typeName); + } + var built = Object.create(nodePrototype); + Object.keys(_this.allFields).forEach(function (param) { + if (hasOwn.call(obj, param)) { + addParam(built, param, obj[param], true); + } + else { + addParam(built, param, null, false); + } + }); + // Make sure that the "type" field was filled automatically. + if (built.type !== _this.typeName) { + throw new Error(""); + } + return built; + }; + Object.defineProperty(builders, getBuilderName(this.typeName), { + enumerable: true, + value: builder + }); + return this; + }; + // The reason fields are specified using .field(...) instead of an object + // literal syntax is somewhat subtle: the object literal syntax would + // support only one key and one value, but with .field(...) we can pass + // any number of arguments to specify the field. + DefImpl.prototype.field = function (name, type, defaultFn, hidden) { + if (this.finalized) { + console.error("Ignoring attempt to redefine field " + + JSON.stringify(name) + " of finalized type " + + JSON.stringify(this.typeName)); + return this; + } + this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden); + return this; // For chaining. + }; + DefImpl.prototype.finalize = function () { + var _this = this; + // It's not an error to finalize a type more than once, but only the + // first call to .finalize does anything. + if (!this.finalized) { + var allFields = this.allFields; + var allSupertypes = this.allSupertypes; + this.baseNames.forEach(function (name) { + var def = defCache[name]; + if (def instanceof Def) { + def.finalize(); + extend(allFields, def.allFields); + extend(allSupertypes, def.allSupertypes); + } + else { + var message = "unknown supertype name " + + JSON.stringify(name) + + " for subtype " + + JSON.stringify(_this.typeName); + throw new Error(message); + } + }); + // TODO Warn if fields are overridden with incompatible types. + extend(allFields, this.ownFields); + allSupertypes[this.typeName] = this; + this.fieldNames.length = 0; + for (var fieldName in allFields) { + if (hasOwn.call(allFields, fieldName) && + !allFields[fieldName].hidden) { + this.fieldNames.push(fieldName); + } + } + // Types are exported only once they have been finalized. + Object.defineProperty(namedTypes, this.typeName, { + enumerable: true, + value: this.type + }); + this.finalized = true; + // A linearization of the inheritance hierarchy. + populateSupertypeList(this.typeName, this.supertypeList); + if (this.buildable && + this.supertypeList.lastIndexOf("Expression") >= 0) { + wrapExpressionBuilderWithStatement(this.typeName); + } + } + }; + return DefImpl; + }(Def)); + // Note that the list returned by this function is a copy of the internal + // supertypeList, *without* the typeName itself as the first element. + function getSupertypeNames(typeName) { + if (!hasOwn.call(defCache, typeName)) { + throw new Error(""); + } + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error(""); + } + return d.supertypeList.slice(1); + } + // Returns an object mapping from every known type in the defCache to the + // most specific supertype whose name is an own property of the candidates + // object. + function computeSupertypeLookupTable(candidates) { + var table = {}; + var typeNames = Object.keys(defCache); + var typeNameCount = typeNames.length; + for (var i = 0; i < typeNameCount; ++i) { + var typeName = typeNames[i]; + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error("" + typeName); + } + for (var j = 0; j < d.supertypeList.length; ++j) { + var superTypeName = d.supertypeList[j]; + if (hasOwn.call(candidates, superTypeName)) { + table[typeName] = superTypeName; + break; + } + } + } + return table; + } + var builders = Object.create(null); + // This object is used as prototype for any node created by a builder. + var nodePrototype = {}; + // Call this function to define a new method to be shared by all AST + // nodes. The replaced method (if any) is returned for easy wrapping. + function defineMethod(name, func) { + var old = nodePrototype[name]; + // Pass undefined as func to delete nodePrototype[name]. + if (isUndefined.check(func)) { + delete nodePrototype[name]; + } + else { + isFunction.assert(func); + Object.defineProperty(nodePrototype, name, { + enumerable: true, + configurable: true, + value: func + }); + } + return old; + } + function getBuilderName(typeName) { + return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) { + var len = upperCasePrefix.length; + switch (len) { + case 0: return ""; + // If there's only one initial capital letter, just lower-case it. + case 1: return upperCasePrefix.toLowerCase(); + default: + // If there's more than one initial capital letter, lower-case + // all but the last one, so that XMLDefaultDeclaration (for + // example) becomes xmlDefaultDeclaration. + return upperCasePrefix.slice(0, len - 1).toLowerCase() + + upperCasePrefix.charAt(len - 1); + } + }); + } + function getStatementBuilderName(typeName) { + typeName = getBuilderName(typeName); + return typeName.replace(/(Expression)?$/, "Statement"); + } + var namedTypes = {}; + // Like Object.keys, but aware of what fields each AST type should have. + function getFieldNames(object) { + var d = defFromValue(object); + if (d) { + return d.fieldNames.slice(0); + } + if ("type" in object) { + throw new Error("did not recognize object of type " + + JSON.stringify(object.type)); + } + return Object.keys(object); + } + // Get the value of an object property, taking object.type and default + // functions into account. + function getFieldValue(object, fieldName) { + var d = defFromValue(object); + if (d) { + var field = d.allFields[fieldName]; + if (field) { + return field.getValue(object); + } + } + return object && object[fieldName]; + } + // Iterate over all defined fields of an object, including those missing + // or undefined, passing each field name and effective value (as returned + // by getFieldValue) to the callback. If the object has no corresponding + // Def, the callback will never be called. + function eachField(object, callback, context) { + getFieldNames(object).forEach(function (name) { + callback.call(this, name, getFieldValue(object, name)); + }, context); + } + // Similar to eachField, except that iteration stops as soon as the + // callback returns a truthy value. Like Array.prototype.some, the final + // result is either true or false to indicates whether the callback + // returned true for any element or not. + function someField(object, callback, context) { + return getFieldNames(object).some(function (name) { + return callback.call(this, name, getFieldValue(object, name)); + }, context); + } + // Adds an additional builder for Expression subtypes + // that wraps the built Expression in an ExpressionStatements. + function wrapExpressionBuilderWithStatement(typeName) { + var wrapperName = getStatementBuilderName(typeName); + // skip if the builder already exists + if (builders[wrapperName]) + return; + // the builder function to wrap with builders.ExpressionStatement + var wrapped = builders[getBuilderName(typeName)]; + // skip if there is nothing to wrap + if (!wrapped) + return; + var builder = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return builders.expressionStatement(wrapped.apply(builders, args)); + }; + builder.from = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return builders.expressionStatement(wrapped.from.apply(builders, args)); + }; + builders[wrapperName] = builder; + } + function populateSupertypeList(typeName, list) { + list.length = 0; + list.push(typeName); + var lastSeen = Object.create(null); + for (var pos = 0; pos < list.length; ++pos) { + typeName = list[pos]; + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error(""); + } + // If we saw typeName earlier in the breadth-first traversal, + // delete the last-seen occurrence. + if (hasOwn.call(lastSeen, typeName)) { + delete list[lastSeen[typeName]]; + } + // Record the new index of the last-seen occurrence of typeName. + lastSeen[typeName] = pos; + // Enqueue the base names of this type. + list.push.apply(list, d.baseNames); + } + // Compaction loop to remove array holes. + for (var to = 0, from = to, len = list.length; from < len; ++from) { + if (hasOwn.call(list, from)) { + list[to++] = list[from]; + } + } + list.length = to; + } + function extend(into, from) { + Object.keys(from).forEach(function (name) { + into[name] = from[name]; + }); + return into; + } + function finalize() { + Object.keys(defCache).forEach(function (name) { + defCache[name].finalize(); + }); + } + return { + Type: Type, + builtInTypes: builtInTypes, + getSupertypeNames: getSupertypeNames, + computeSupertypeLookupTable: computeSupertypeLookupTable, + builders: builders, + defineMethod: defineMethod, + getBuilderName: getBuilderName, + getStatementBuilderName: getStatementBuilderName, + namedTypes: namedTypes, + getFieldNames: getFieldNames, + getFieldValue: getFieldValue, + eachField: eachField, + someField: someField, + finalize: finalize, + }; +} +exports["default"] = typesPlugin; +; + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/main.js": +/*!*******************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/main.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.visit = exports.use = exports.Type = exports.someField = exports.PathVisitor = exports.Path = exports.NodePath = exports.namedTypes = exports.getSupertypeNames = exports.getFieldValue = exports.getFieldNames = exports.getBuilderName = exports.finalize = exports.eachField = exports.defineMethod = exports.builtInTypes = exports.builders = exports.astNodesAreEquivalent = void 0; +var tslib_1 = __webpack_require__(/*! tslib */ "../../../.yarn/berry/cache/tslib-npm-2.4.0-9cb6dc5030-9.zip/node_modules/tslib/tslib.es6.js"); +var fork_1 = tslib_1.__importDefault(__webpack_require__(/*! ./fork */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/fork.js")); +var core_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/core */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/core.js")); +var es6_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/es6 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es6.js")); +var es7_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/es7 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es7.js")); +var es2020_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/es2020 */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es2020.js")); +var jsx_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/jsx */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/jsx.js")); +var flow_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/flow */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/flow.js")); +var esprima_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/esprima */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/esprima.js")); +var babel_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/babel */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/babel.js")); +var typescript_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/typescript */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/typescript.js")); +var es_proposals_1 = tslib_1.__importDefault(__webpack_require__(/*! ./def/es-proposals */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/def/es-proposals.js")); +var namedTypes_1 = __webpack_require__(/*! ./gen/namedTypes */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/gen/namedTypes.js"); +Object.defineProperty(exports, "namedTypes", ({ enumerable: true, get: function () { return namedTypes_1.namedTypes; } })); +var _a = fork_1.default([ + // This core module of AST types captures ES5 as it is parsed today by + // git://github.com/ariya/esprima.git#master. + core_1.default, + // Feel free to add to or remove from this list of extension modules to + // configure the precise type hierarchy that you need. + es6_1.default, + es7_1.default, + es2020_1.default, + jsx_1.default, + flow_1.default, + esprima_1.default, + babel_1.default, + typescript_1.default, + es_proposals_1.default, +]), astNodesAreEquivalent = _a.astNodesAreEquivalent, builders = _a.builders, builtInTypes = _a.builtInTypes, defineMethod = _a.defineMethod, eachField = _a.eachField, finalize = _a.finalize, getBuilderName = _a.getBuilderName, getFieldNames = _a.getFieldNames, getFieldValue = _a.getFieldValue, getSupertypeNames = _a.getSupertypeNames, n = _a.namedTypes, NodePath = _a.NodePath, Path = _a.Path, PathVisitor = _a.PathVisitor, someField = _a.someField, Type = _a.Type, use = _a.use, visit = _a.visit; +exports.astNodesAreEquivalent = astNodesAreEquivalent; +exports.builders = builders; +exports.builtInTypes = builtInTypes; +exports.defineMethod = defineMethod; +exports.eachField = eachField; +exports.finalize = finalize; +exports.getBuilderName = getBuilderName; +exports.getFieldNames = getFieldNames; +exports.getFieldValue = getFieldValue; +exports.getSupertypeNames = getSupertypeNames; +exports.NodePath = NodePath; +exports.Path = Path; +exports.PathVisitor = PathVisitor; +exports.someField = someField; +exports.Type = Type; +exports.use = use; +exports.visit = visit; +// Populate the exported fields of the namedTypes namespace, while still +// retaining its member types. +Object.assign(namedTypes_1.namedTypes, n); + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/bytes-npm-3.1.2-28b8643004-9.zip/node_modules/bytes/index.js": +/*!***********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/bytes-npm-3.1.2-28b8643004-9.zip/node_modules/bytes/index.js ***! + \***********************************************************************************************/ +/***/ ((module) => { + +"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + + + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/core-util-is-npm-1.0.3-ca74b76c90-9.zip/node_modules/core-util-is/lib/util.js": +/*!****************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/core-util-is-npm-1.0.3-ca74b76c90-9.zip/node_modules/core-util-is/lib/util.js ***! + \****************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(/*! buffer */ "buffer").Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/data-uri-to-buffer-npm-3.0.1-830646f9ee-9.zip/node_modules/data-uri-to-buffer/dist/src/index.js": +/*!**********************************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/data-uri-to-buffer-npm-3.0.1-830646f9ee-9.zip/node_modules/data-uri-to-buffer/dist/src/index.js ***! + \**********************************************************************************************************************************/ +/***/ ((module) => { + +"use strict"; + +/** + * Returns a `Buffer` instance from the given data URI `uri`. + * + * @param {String} uri Data URI to turn into a Buffer instance + * @return {Buffer} Buffer instance from Data URI + * @api public + */ +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + // strip newlines + uri = uri.replace(/\r?\n/g, ''); + // split the URI up into the "metadata" and the "data" portions + const firstComma = uri.indexOf(','); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError('malformed data: URI'); + } + // remove the "data:" scheme and parse the metadata + const meta = uri.substring(5, firstComma).split(';'); + let charset = ''; + let base64 = false; + const type = meta[0] || 'text/plain'; + let typeFull = type; + for (let i = 1; i < meta.length; i++) { + if (meta[i] === 'base64') { + base64 = true; + } + else { + typeFull += `;${meta[i]}`; + if (meta[i].indexOf('charset=') === 0) { + charset = meta[i].substring(8); + } + } + } + // defaults to US-ASCII only if type is not provided + if (!meta[0] && !charset.length) { + typeFull += ';charset=US-ASCII'; + charset = 'US-ASCII'; + } + // get the encoded data portion and decode URI-encoded chars + const encoding = base64 ? 'base64' : 'ascii'; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + // set `.type` and `.typeFull` properties to MIME type + buffer.type = type; + buffer.typeFull = typeFull; + // set the `.charset` property + buffer.charset = charset; + return buffer; +} +module.exports = dataUriToBuffer; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "../../../.yarn/berry/cache/degenerator-npm-3.0.2-3b38df9d12-9.zip/node_modules/degenerator/dist/src/index.js": +/*!********************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/degenerator-npm-3.0.2-3b38df9d12-9.zip/node_modules/degenerator/dist/src/index.js ***! + \********************************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +const util_1 = __webpack_require__(/*! util */ "util"); +const escodegen_1 = __webpack_require__(/*! escodegen */ "../../../.yarn/berry/cache/escodegen-npm-1.14.3-a4dedc6eeb-9.zip/node_modules/escodegen/escodegen.js"); +const esprima_1 = __webpack_require__(/*! esprima */ "../../../.yarn/berry/cache/esprima-npm-4.0.1-1084e98778-9.zip/node_modules/esprima/dist/esprima.js"); +const ast_types_1 = __webpack_require__(/*! ast-types */ "../../../.yarn/berry/cache/ast-types-npm-0.13.4-69f7e68df8-9.zip/node_modules/ast-types/main.js"); +const vm2_1 = __webpack_require__(/*! vm2 */ "../../../.yarn/berry/cache/vm2-patch-b52c0bba95-9.zip/node_modules/vm2/index.js"); +/** + * Compiles sync JavaScript code into JavaScript with async Functions. + * + * @param {String} code JavaScript string to convert + * @param {Array} names Array of function names to add `await` operators to + * @return {String} Converted JavaScript string with async/await injected + * @api public + */ +function degenerator(code, _names) { + if (!Array.isArray(_names)) { + throw new TypeError('an array of async function "names" is required'); + } + // Duplicate the `names` array since it's rude to augment the user args + const names = _names.slice(0); + const ast = esprima_1.parseScript(code); + // First pass is to find the `function` nodes and turn them into async or + // generator functions only if their body includes `CallExpressions` to + // function in `names`. We also add the names of the functions to the `names` + // array. We'll iterate several time, as every iteration might add new items + // to the `names` array, until no new names were added in the iteration. + let lastNamesLength = 0; + do { + lastNamesLength = names.length; + ast_types_1.visit(ast, { + visitVariableDeclaration(path) { + if (path.node.declarations) { + for (let i = 0; i < path.node.declarations.length; i++) { + const declaration = path.node.declarations[i]; + if (ast_types_1.namedTypes.VariableDeclarator.check(declaration) && + ast_types_1.namedTypes.Identifier.check(declaration.init) && + ast_types_1.namedTypes.Identifier.check(declaration.id) && + checkName(declaration.init.name, names) && + !checkName(declaration.id.name, names)) { + names.push(declaration.id.name); + } + } + } + return false; + }, + visitAssignmentExpression(path) { + if (ast_types_1.namedTypes.Identifier.check(path.node.left) && + ast_types_1.namedTypes.Identifier.check(path.node.right) && + checkName(path.node.right.name, names) && + !checkName(path.node.left.name, names)) { + names.push(path.node.left.name); + } + return false; + }, + visitFunction(path) { + if (path.node.id) { + let shouldDegenerate = false; + ast_types_1.visit(path.node, { + visitCallExpression(path) { + if (checkNames(path.node, names)) { + shouldDegenerate = true; + } + return false; + }, + }); + if (!shouldDegenerate) { + return false; + } + // Got a "function" expression/statement, + // convert it into an async function + path.node.async = true; + // Add function name to `names` array + if (!checkName(path.node.id.name, names)) { + names.push(path.node.id.name); + } + } + this.traverse(path); + }, + }); + } while (lastNamesLength !== names.length); + // Second pass is for adding `await`/`yield` statements to any function + // invocations that match the given `names` array. + ast_types_1.visit(ast, { + visitCallExpression(path) { + if (checkNames(path.node, names)) { + // A "function invocation" expression, + // we need to inject a `AwaitExpression`/`YieldExpression` + const delegate = false; + const { name, parent: { node: pNode }, } = path; + const expr = ast_types_1.builders.awaitExpression(path.node, delegate); + if (ast_types_1.namedTypes.CallExpression.check(pNode)) { + pNode.arguments[name] = expr; + } + else { + pNode[name] = expr; + } + } + this.traverse(path); + }, + }); + return escodegen_1.generate(ast); +} +(function (degenerator) { + function compile(code, returnName, names, options = {}) { + const compiled = degenerator(code, names); + const vm = new vm2_1.VM(options); + const script = new vm2_1.VMScript(`${compiled};${returnName}`, { + filename: options.filename, + }); + const fn = vm.run(script); + if (typeof fn !== 'function') { + throw new Error(`Expected a "function" to be returned for \`${returnName}\`, but got "${typeof fn}"`); + } + const r = function (...args) { + try { + const p = fn.apply(this, args); + if (typeof (p === null || p === void 0 ? void 0 : p.then) === 'function') { + return p; + } + return Promise.resolve(p); + } + catch (err) { + return Promise.reject(err); + } + }; + Object.defineProperty(r, 'toString', { + value: fn.toString.bind(fn), + enumerable: false, + }); + return r; + } + degenerator.compile = compile; +})(degenerator || (degenerator = {})); +/** + * Returns `true` if `node` has a matching name to one of the entries in the + * `names` array. + * + * @param {types.Node} node + * @param {Array} names Array of function names to return true for + * @return {Boolean} + * @api private + */ +function checkNames({ callee }, names) { + let name; + if (ast_types_1.namedTypes.Identifier.check(callee)) { + name = callee.name; + } + else if (ast_types_1.namedTypes.MemberExpression.check(callee)) { + if (ast_types_1.namedTypes.Identifier.check(callee.object) && + ast_types_1.namedTypes.Identifier.check(callee.property)) { + name = `${callee.object.name}.${callee.property.name}`; + } + else { + return false; + } + } + else if (ast_types_1.namedTypes.FunctionExpression.check(callee)) { + if (callee.id) { + name = callee.id.name; + } + else { + return false; + } + } + else { + throw new Error(`Don't know how to get name for: ${callee.type}`); + } + return checkName(name, names); +} +function checkName(name, names) { + // now that we have the `name`, check if any entries match in the `names` array + for (let i = 0; i < names.length; i++) { + const n = names[i]; + if (util_1.isRegExp(n)) { + if (n.test(name)) { + return true; + } + } + else if (name === n) { + return true; + } + } + return false; +} +module.exports = degenerator; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "../../../.yarn/berry/cache/depd-npm-2.0.0-b6c51a4b43-9.zip/node_modules/depd/index.js": +/*!*********************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/depd-npm-2.0.0-b6c51a4b43-9.zip/node_modules/depd/index.js ***! + \*********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*! + * depd + * Copyright(c) 2014-2018 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var relative = (__webpack_require__(/*! path */ "path").relative) + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if event emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function eehaslisteners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eehaslisteners(process, 'deprecation') + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-new-func + var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', + '"use strict"\n' + + 'return function (' + args + ') {' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '}')(fn, log, this, message, site) + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/escodegen-npm-1.14.3-a4dedc6eeb-9.zip/node_modules/escodegen/escodegen.js": +/*!************************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/escodegen-npm-1.14.3-a4dedc6eeb-9.zip/node_modules/escodegen/escodegen.js ***! + \************************************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2015 Ingvar Stepanyan + Copyright (C) 2014 Ivan Nikulin + Copyright (C) 2012-2013 Michael Ficarra + Copyright (C) 2012-2013 Mathias Bynens + Copyright (C) 2013 Irakli Gozalishvili + Copyright (C) 2012 Robert Gust-Bardon + Copyright (C) 2012 John Freeman + Copyright (C) 2011-2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Arpad Borsos + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*global exports:true, require:true, global:true*/ +(function () { + 'use strict'; + + var Syntax, + Precedence, + BinaryPrecedence, + SourceNode, + estraverse, + esutils, + base, + indent, + json, + renumber, + hexadecimal, + quotes, + escapeless, + newline, + space, + parentheses, + semicolons, + safeConcatenation, + directive, + extra, + parse, + sourceMap, + sourceCode, + preserveBlankLines, + FORMAT_MINIFY, + FORMAT_DEFAULTS; + + estraverse = __webpack_require__(/*! estraverse */ "../../../.yarn/berry/cache/estraverse-npm-4.3.0-920a32f3c6-9.zip/node_modules/estraverse/estraverse.js"); + esutils = __webpack_require__(/*! esutils */ "../../../.yarn/berry/cache/esutils-npm-2.0.3-f865beafd5-9.zip/node_modules/esutils/lib/utils.js"); + + Syntax = estraverse.Syntax; + + // Generation is done by generateExpression. + function isExpression(node) { + return CodeGenerator.Expression.hasOwnProperty(node.type); + } + + // Generation is done by generateStatement. + function isStatement(node) { + return CodeGenerator.Statement.hasOwnProperty(node.type); + } + + Precedence = { + Sequence: 0, + Yield: 1, + Assignment: 1, + Conditional: 2, + ArrowFunction: 2, + LogicalOR: 3, + LogicalAND: 4, + BitwiseOR: 5, + BitwiseXOR: 6, + BitwiseAND: 7, + Equality: 8, + Relational: 9, + BitwiseSHIFT: 10, + Additive: 11, + Multiplicative: 12, + Exponentiation: 13, + Await: 14, + Unary: 14, + Postfix: 15, + Call: 16, + New: 17, + TaggedTemplate: 18, + Member: 19, + Primary: 20 + }; + + BinaryPrecedence = { + '||': Precedence.LogicalOR, + '&&': Precedence.LogicalAND, + '|': Precedence.BitwiseOR, + '^': Precedence.BitwiseXOR, + '&': Precedence.BitwiseAND, + '==': Precedence.Equality, + '!=': Precedence.Equality, + '===': Precedence.Equality, + '!==': Precedence.Equality, + 'is': Precedence.Equality, + 'isnt': Precedence.Equality, + '<': Precedence.Relational, + '>': Precedence.Relational, + '<=': Precedence.Relational, + '>=': Precedence.Relational, + 'in': Precedence.Relational, + 'instanceof': Precedence.Relational, + '<<': Precedence.BitwiseSHIFT, + '>>': Precedence.BitwiseSHIFT, + '>>>': Precedence.BitwiseSHIFT, + '+': Precedence.Additive, + '-': Precedence.Additive, + '*': Precedence.Multiplicative, + '%': Precedence.Multiplicative, + '/': Precedence.Multiplicative, + '**': Precedence.Exponentiation + }; + + //Flags + var F_ALLOW_IN = 1, + F_ALLOW_CALL = 1 << 1, + F_ALLOW_UNPARATH_NEW = 1 << 2, + F_FUNC_BODY = 1 << 3, + F_DIRECTIVE_CTX = 1 << 4, + F_SEMICOLON_OPT = 1 << 5; + + //Expression flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_ALLOW_CALL + // F_ALLOW_UNPARATH_NEW + var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TTF = F_ALLOW_IN | F_ALLOW_CALL, + E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, + E_TFF = F_ALLOW_IN, + E_FFT = F_ALLOW_UNPARATH_NEW, + E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW; + + //Statement flag sets + //NOTE: Flag order: + // F_ALLOW_IN + // F_FUNC_BODY + // F_DIRECTIVE_CTX + // F_SEMICOLON_OPT + var S_TFFF = F_ALLOW_IN, + S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, + S_FFFF = 0x00, + S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, + S_TTFF = F_ALLOW_IN | F_FUNC_BODY; + + function getDefaultOptions() { + // default options + return { + indent: null, + base: null, + parse: null, + comment: false, + format: { + indent: { + style: ' ', + base: 0, + adjustMultilineComment: false + }, + newline: '\n', + space: ' ', + json: false, + renumber: false, + hexadecimal: false, + quotes: 'single', + escapeless: false, + compact: false, + parentheses: true, + semicolons: true, + safeConcatenation: false, + preserveBlankLines: false + }, + moz: { + comprehensionExpressionStartsWithAssignment: false, + starlessGenerator: false + }, + sourceMap: null, + sourceMapRoot: null, + sourceMapWithCode: false, + directive: false, + raw: true, + verbatim: null, + sourceCode: null + }; + } + + function stringRepeat(str, num) { + var result = ''; + + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + + return result; + } + + function hasLineTerminator(str) { + return (/[\r\n]/g).test(str); + } + + function endsWithLineTerminator(str) { + var len = str.length; + return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1)); + } + + function merge(target, override) { + var key; + for (key in override) { + if (override.hasOwnProperty(key)) { + target[key] = override[key]; + } + } + return target; + } + + function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; + } + + function generateNumber(value) { + var result, point, temp, exponent, pos; + + if (value !== value) { + throw new Error('Numeric literal whose value is NaN'); + } + if (value < 0 || (value === 0 && 1 / value < 0)) { + throw new Error('Numeric literal whose value is negative'); + } + + if (value === 1 / 0) { + return json ? 'null' : renumber ? '1e400' : '1e+400'; + } + + result = '' + value; + if (!renumber || result.length < 3) { + return result; + } + + point = result.indexOf('.'); + if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) { + point = 0; + result = result.slice(1); + } + temp = result; + result = result.replace('e+', 'e'); + exponent = 0; + if ((pos = temp.indexOf('e')) > 0) { + exponent = +temp.slice(pos + 1); + temp = temp.slice(0, pos); + } + if (point >= 0) { + exponent -= temp.length - point - 1; + temp = +(temp.slice(0, point) + temp.slice(point + 1)) + ''; + } + pos = 0; + while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) { + --pos; + } + if (pos !== 0) { + exponent -= pos; + temp = temp.slice(0, pos); + } + if (exponent !== 0) { + temp += 'e' + exponent; + } + if ((temp.length < result.length || + (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) && + +temp === value) { + result = temp; + } + + return result; + } + + // Generate valid RegExp expression. + // This function is based on https://github.com/Constellation/iv Engine + + function escapeRegExpCharacter(ch, previousIsBackslash) { + // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence + if ((ch & ~1) === 0x2028) { + return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029'); + } else if (ch === 10 || ch === 13) { // \n, \r + return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r'); + } + return String.fromCharCode(ch); + } + + function generateRegExp(reg) { + var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash; + + result = reg.toString(); + + if (reg.source) { + // extract flag from toString result + match = result.match(/\/([^/]*)$/); + if (!match) { + return result; + } + + flags = match[1]; + result = ''; + + characterInBrack = false; + previousIsBackslash = false; + for (i = 0, iz = reg.source.length; i < iz; ++i) { + ch = reg.source.charCodeAt(i); + + if (!previousIsBackslash) { + if (characterInBrack) { + if (ch === 93) { // ] + characterInBrack = false; + } + } else { + if (ch === 47) { // / + result += '\\'; + } else if (ch === 91) { // [ + characterInBrack = true; + } + } + result += escapeRegExpCharacter(ch, previousIsBackslash); + previousIsBackslash = ch === 92; // \ + } else { + // if new RegExp("\\\n') is provided, create /\n/ + result += escapeRegExpCharacter(ch, previousIsBackslash); + // prevent like /\\[/]/ + previousIsBackslash = false; + } + } + + return '/' + result + '/' + flags; + } + + return result; + } + + function escapeAllowedCharacter(code, next) { + var hex; + + if (code === 0x08 /* \b */) { + return '\\b'; + } + + if (code === 0x0C /* \f */) { + return '\\f'; + } + + if (code === 0x09 /* \t */) { + return '\\t'; + } + + hex = code.toString(16).toUpperCase(); + if (json || code > 0xFF) { + return '\\u' + '0000'.slice(hex.length) + hex; + } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) { + return '\\0'; + } else if (code === 0x000B /* \v */) { // '\v' + return '\\x0B'; + } else { + return '\\x' + '00'.slice(hex.length) + hex; + } + } + + function escapeDisallowedCharacter(code) { + if (code === 0x5C /* \ */) { + return '\\\\'; + } + + if (code === 0x0A /* \n */) { + return '\\n'; + } + + if (code === 0x0D /* \r */) { + return '\\r'; + } + + if (code === 0x2028) { + return '\\u2028'; + } + + if (code === 0x2029) { + return '\\u2029'; + } + + throw new Error('Incorrectly classified character'); + } + + function escapeDirective(str) { + var i, iz, code, quote; + + quote = quotes === 'double' ? '"' : '\''; + for (i = 0, iz = str.length; i < iz; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + quote = '"'; + break; + } else if (code === 0x22 /* " */) { + quote = '\''; + break; + } else if (code === 0x5C /* \ */) { + ++i; + } + } + + return quote + str + quote; + } + + function escapeString(str) { + var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if (code === 0x27 /* ' */) { + ++singleQuotes; + } else if (code === 0x22 /* " */) { + ++doubleQuotes; + } else if (code === 0x2F /* / */ && json) { + result += '\\'; + } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) { + result += escapeDisallowedCharacter(code); + continue; + } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && (code < 0x20 /* SP */ || code > 0x7E /* ~ */))) { + result += escapeAllowedCharacter(code, str.charCodeAt(i + 1)); + continue; + } + result += String.fromCharCode(code); + } + + single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes)); + quote = single ? '\'' : '"'; + + if (!(single ? singleQuotes : doubleQuotes)) { + return quote + result + quote; + } + + str = result; + result = quote; + + for (i = 0, len = str.length; i < len; ++i) { + code = str.charCodeAt(i); + if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) { + result += '\\'; + } + result += String.fromCharCode(code); + } + + return result + quote; + } + + /** + * flatten an array to a string, where the array can contain + * either strings or nested arrays + */ + function flattenToString(arr) { + var i, iz, elem, result = ''; + for (i = 0, iz = arr.length; i < iz; ++i) { + elem = arr[i]; + result += Array.isArray(elem) ? flattenToString(elem) : elem; + } + return result; + } + + /** + * convert generated to a SourceNode when source maps are enabled. + */ + function toSourceNodeWhenNeeded(generated, node) { + if (!sourceMap) { + // with no source maps, generated is either an + // array or a string. if an array, flatten it. + // if a string, just return it + if (Array.isArray(generated)) { + return flattenToString(generated); + } else { + return generated; + } + } + if (node == null) { + if (generated instanceof SourceNode) { + return generated; + } else { + node = {}; + } + } + if (node.loc == null) { + return new SourceNode(null, null, sourceMap, generated, node.name || null); + } + return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null); + } + + function noEmptySpace() { + return (space) ? space : ' '; + } + + function join(left, right) { + var leftSource, + rightSource, + leftCharCode, + rightCharCode; + + leftSource = toSourceNodeWhenNeeded(left).toString(); + if (leftSource.length === 0) { + return [right]; + } + + rightSource = toSourceNodeWhenNeeded(right).toString(); + if (rightSource.length === 0) { + return [left]; + } + + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = rightSource.charCodeAt(0); + + if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode || + esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) || + leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i` + return [left, noEmptySpace(), right]; + } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || + esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) { + return [left, right]; + } + return [left, space, right]; + } + + function addIndent(stmt) { + return [base, stmt]; + } + + function withIndent(fn) { + var previousBase; + previousBase = base; + base += indent; + fn(base); + base = previousBase; + } + + function calculateSpaces(str) { + var i; + for (i = str.length - 1; i >= 0; --i) { + if (esutils.code.isLineTerminator(str.charCodeAt(i))) { + break; + } + } + return (str.length - 1) - i; + } + + function adjustMultilineComment(value, specialBase) { + var array, i, len, line, j, spaces, previousBase, sn; + + array = value.split(/\r\n|[\r\n]/); + spaces = Number.MAX_VALUE; + + // first line doesn't have indentation + for (i = 1, len = array.length; i < len; ++i) { + line = array[i]; + j = 0; + while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) { + ++j; + } + if (spaces > j) { + spaces = j; + } + } + + if (typeof specialBase !== 'undefined') { + // pattern like + // { + // var t = 20; /* + // * this is comment + // */ + // } + previousBase = base; + if (array[1][spaces] === '*') { + specialBase += ' '; + } + base = specialBase; + } else { + if (spaces & 1) { + // /* + // * + // */ + // If spaces are odd number, above pattern is considered. + // We waste 1 space. + --spaces; + } + previousBase = base; + } + + for (i = 1, len = array.length; i < len; ++i) { + sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces))); + array[i] = sourceMap ? sn.join('') : sn; + } + + base = previousBase; + + return array.join('\n'); + } + + function generateComment(comment, specialBase) { + if (comment.type === 'Line') { + if (endsWithLineTerminator(comment.value)) { + return '//' + comment.value; + } else { + // Always use LineTerminator + var result = '//' + comment.value; + if (!preserveBlankLines) { + result += '\n'; + } + return result; + } + } + if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) { + return adjustMultilineComment('/*' + comment.value + '*/', specialBase); + } + return '/*' + comment.value + '*/'; + } + + function addComments(stmt, result) { + var i, len, comment, save, tailingToStatement, specialBase, fragment, + extRange, range, prevRange, prefix, infix, suffix, count; + + if (stmt.leadingComments && stmt.leadingComments.length > 0) { + save = result; + + if (preserveBlankLines) { + comment = stmt.leadingComments[0]; + result = []; + + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + + prevRange = range; + + for (i = 1, len = stmt.leadingComments.length; i < len; i++) { + comment = stmt.leadingComments[i]; + range = comment.range; + + infix = sourceCode.substring(prevRange[1], range[0]); + count = (infix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + + prevRange = range; + } + + suffix = sourceCode.substring(range[1], extRange[1]); + count = (suffix.match(/\n/g) || []).length; + result.push(stringRepeat('\n', count)); + } else { + comment = stmt.leadingComments[0]; + result = []; + if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) { + result.push('\n'); + } + result.push(generateComment(comment)); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push('\n'); + } + + for (i = 1, len = stmt.leadingComments.length; i < len; ++i) { + comment = stmt.leadingComments[i]; + fragment = [generateComment(comment)]; + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + fragment.push('\n'); + } + result.push(addIndent(fragment)); + } + } + + result.push(addIndent(save)); + } + + if (stmt.trailingComments) { + + if (preserveBlankLines) { + comment = stmt.trailingComments[0]; + extRange = comment.extendedRange; + range = comment.range; + + prefix = sourceCode.substring(extRange[0], range[0]); + count = (prefix.match(/\n/g) || []).length; + + if (count > 0) { + result.push(stringRepeat('\n', count)); + result.push(addIndent(generateComment(comment))); + } else { + result.push(prefix); + result.push(generateComment(comment)); + } + } else { + tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString())); + for (i = 0, len = stmt.trailingComments.length; i < len; ++i) { + comment = stmt.trailingComments[i]; + if (tailingToStatement) { + // We assume target like following script + // + // var t = 20; /** + // * This is comment of t + // */ + if (i === 0) { + // first case + result = [result, indent]; + } else { + result = [result, specialBase]; + } + result.push(generateComment(comment, specialBase)); + } else { + result = [result, addIndent(generateComment(comment))]; + } + if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result = [result, '\n']; + } + } + } + } + + return result; + } + + function generateBlankLines(start, end, result) { + var j, newlineCount = 0; + + for (j = start; j < end; j++) { + if (sourceCode[j] === '\n') { + newlineCount++; + } + } + + for (j = 1; j < newlineCount; j++) { + result.push(newline); + } + } + + function parenthesize(text, current, should) { + if (current < should) { + return ['(', text, ')']; + } + return text; + } + + function generateVerbatimString(string) { + var i, iz, result; + result = string.split(/\r\n|\n/); + for (i = 1, iz = result.length; i < iz; i++) { + result[i] = newline + base + result[i]; + } + return result; + } + + function generateVerbatim(expr, precedence) { + var verbatim, result, prec; + verbatim = expr[extra.verbatim]; + + if (typeof verbatim === 'string') { + result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence); + } else { + // verbatim is object + result = generateVerbatimString(verbatim.content); + prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence; + result = parenthesize(result, prec, precedence); + } + + return toSourceNodeWhenNeeded(result, expr); + } + + function CodeGenerator() { + } + + // Helpers. + + CodeGenerator.prototype.maybeBlock = function(stmt, flags) { + var result, noLeadingComment, that = this; + + noLeadingComment = !extra.comment || !stmt.leadingComments; + + if (stmt.type === Syntax.BlockStatement && noLeadingComment) { + return [space, this.generateStatement(stmt, flags)]; + } + + if (stmt.type === Syntax.EmptyStatement && noLeadingComment) { + return ';'; + } + + withIndent(function () { + result = [ + newline, + addIndent(that.generateStatement(stmt, flags)) + ]; + }); + + return result; + }; + + CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) { + var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString()); + if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) { + return [result, space]; + } + if (ends) { + return [result, base]; + } + return [result, newline, base]; + }; + + function generateIdentifier(node) { + return toSourceNodeWhenNeeded(node.name, node); + } + + function generateAsyncPrefix(node, spaceRequired) { + return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : ''; + } + + function generateStarSuffix(node) { + var isGenerator = node.generator && !extra.moz.starlessGenerator; + return isGenerator ? '*' + space : ''; + } + + function generateMethodPrefix(prop) { + var func = prop.value, prefix = ''; + if (func.async) { + prefix += generateAsyncPrefix(func, !prop.computed); + } + if (func.generator) { + // avoid space before method name + prefix += generateStarSuffix(func) ? '*' : ''; + } + return prefix; + } + + CodeGenerator.prototype.generatePattern = function (node, precedence, flags) { + if (node.type === Syntax.Identifier) { + return generateIdentifier(node); + } + return this.generateExpression(node, precedence, flags); + }; + + CodeGenerator.prototype.generateFunctionParams = function (node) { + var i, iz, result, hasDefault; + + hasDefault = false; + + if (node.type === Syntax.ArrowFunctionExpression && + !node.rest && (!node.defaults || node.defaults.length === 0) && + node.params.length === 1 && node.params[0].type === Syntax.Identifier) { + // arg => { } case + result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])]; + } else { + result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : []; + result.push('('); + if (node.defaults) { + hasDefault = true; + } + for (i = 0, iz = node.params.length; i < iz; ++i) { + if (hasDefault && node.defaults[i]) { + // Handle default values. + result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT)); + } else { + result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + space); + } + } + + if (node.rest) { + if (node.params.length) { + result.push(',' + space); + } + result.push('...'); + result.push(generateIdentifier(node.rest)); + } + + result.push(')'); + } + + return result; + }; + + CodeGenerator.prototype.generateFunctionBody = function (node) { + var result, expr; + + result = this.generateFunctionParams(node); + + if (node.type === Syntax.ArrowFunctionExpression) { + result.push(space); + result.push('=>'); + } + + if (node.expression) { + result.push(space); + expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT); + if (expr.toString().charAt(0) === '{') { + expr = ['(', expr, ')']; + } + result.push(expr); + } else { + result.push(this.maybeBlock(node.body, S_TTFF)); + } + + return result; + }; + + CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) { + var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this; + withIndent(function () { + if (stmt.left.type === Syntax.VariableDeclaration) { + withIndent(function () { + result.push(stmt.left.kind + noEmptySpace()); + result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF)); + }); + } else { + result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT)); + } + + result = join(result, operator); + result = [join( + result, + that.generateExpression(stmt.right, Precedence.Assignment, E_TTT) + ), ')']; + }); + result.push(this.maybeBlock(stmt.body, flags)); + return result; + }; + + CodeGenerator.prototype.generatePropertyKey = function (expr, computed) { + var result = []; + + if (computed) { + result.push('['); + } + + result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT)); + + if (computed) { + result.push(']'); + } + + return result; + }; + + CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) { + if (Precedence.Assignment < precedence) { + flags |= F_ALLOW_IN; + } + + return parenthesize( + [ + this.generateExpression(left, Precedence.Call, flags), + space + operator + space, + this.generateExpression(right, Precedence.Assignment, flags) + ], + Precedence.Assignment, + precedence + ); + }; + + CodeGenerator.prototype.semicolon = function (flags) { + if (!semicolons && flags & F_SEMICOLON_OPT) { + return ''; + } + return ';'; + }; + + // Statements. + + CodeGenerator.Statement = { + + BlockStatement: function (stmt, flags) { + var range, content, result = ['{', newline], that = this; + + withIndent(function () { + // handle functions without any code + if (stmt.body.length === 0 && preserveBlankLines) { + range = stmt.range; + if (range[1] - range[0] > 2) { + content = sourceCode.substring(range[0] + 1, range[1] - 1); + if (content[0] === '\n') { + result = ['{']; + } + result.push(content); + } + } + + var i, iz, fragment, bodyFlags; + bodyFlags = S_TFFF; + if (flags & F_FUNC_BODY) { + bodyFlags |= F_DIRECTIVE_CTX; + } + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (stmt.body[0].leadingComments) { + range = stmt.body[0].leadingComments[0].extendedRange; + content = sourceCode.substring(range[0], range[1]); + if (content[0] === '\n') { + result = ['{']; + } + } + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[0].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (stmt.body[i].leadingComments && preserveBlankLines) { + fragment = that.generateStatement(stmt.body[i], bodyFlags); + } else { + fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags)); + } + + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines && i < iz - 1) { + // don't add a new line if there are leading coments + // in the next statement + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + }); + + result.push(addIndent('}')); + return result; + }, + + BreakStatement: function (stmt, flags) { + if (stmt.label) { + return 'break ' + stmt.label.name + this.semicolon(flags); + } + return 'break' + this.semicolon(flags); + }, + + ContinueStatement: function (stmt, flags) { + if (stmt.label) { + return 'continue ' + stmt.label.name + this.semicolon(flags); + } + return 'continue' + this.semicolon(flags); + }, + + ClassBody: function (stmt, flags) { + var result = [ '{', newline], that = this; + + withIndent(function (indent) { + var i, iz; + + for (i = 0, iz = stmt.body.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(newline); + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + ClassDeclaration: function (stmt, flags) { + var result, fragment; + result = ['class']; + if (stmt.id) { + result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT)); + } + if (stmt.superClass) { + fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(stmt.body, S_TFFT)); + return result; + }, + + DirectiveStatement: function (stmt, flags) { + if (extra.raw && stmt.raw) { + return stmt.raw + this.semicolon(flags); + } + return escapeDirective(stmt.directive) + this.semicolon(flags); + }, + + DoWhileStatement: function (stmt, flags) { + // Because `do 42 while (cond)` is Syntax Error. We need semicolon. + var result = join('do', this.maybeBlock(stmt.body, S_TFFF)); + result = this.maybeBlockSuffix(stmt.body, result); + return join(result, [ + 'while' + space + '(', + this.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + this.semicolon(flags) + ]); + }, + + CatchClause: function (stmt, flags) { + var result, that = this; + withIndent(function () { + var guard; + + if (stmt.param) { + result = [ + 'catch' + space + '(', + that.generateExpression(stmt.param, Precedence.Sequence, E_TTT), + ')' + ]; + + if (stmt.guard) { + guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT); + result.splice(2, 0, ' if ', guard); + } + } else { + result = ['catch']; + } + }); + result.push(this.maybeBlock(stmt.body, S_TFFF)); + return result; + }, + + DebuggerStatement: function (stmt, flags) { + return 'debugger' + this.semicolon(flags); + }, + + EmptyStatement: function (stmt, flags) { + return ';'; + }, + + ExportDefaultDeclaration: function (stmt, flags) { + var result = [ 'export' ], bodyFlags; + + bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF; + + // export default HoistableDeclaration[Default] + // export default AssignmentExpression[In] ; + result = join(result, 'default'); + if (isStatement(stmt.declaration)) { + result = join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } else { + result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags)); + } + return result; + }, + + ExportNamedDeclaration: function (stmt, flags) { + var result = [ 'export' ], bodyFlags, that = this; + + bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF; + + // export VariableStatement + // export Declaration[Default] + if (stmt.declaration) { + return join(result, this.generateStatement(stmt.declaration, bodyFlags)); + } + + // export ExportClause[NoReference] FromClause ; + // export ExportClause ; + if (stmt.specifiers) { + if (stmt.specifiers.length === 0) { + result = join(result, '{' + space + '}'); + } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) { + result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT)); + } else { + result = join(result, '{'); + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}'); + } + + if (stmt.source) { + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + } else { + result.push(this.semicolon(flags)); + } + } + return result; + }, + + ExportAllDeclaration: function (stmt, flags) { + // export * FromClause ; + return [ + 'export' + space, + '*' + space, + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]; + }, + + ExpressionStatement: function (stmt, flags) { + var result, fragment; + + function isClassPrefixed(fragment) { + var code; + if (fragment.slice(0, 5) !== 'class') { + return false; + } + code = fragment.charCodeAt(5); + return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code); + } + + function isFunctionPrefixed(fragment) { + var code; + if (fragment.slice(0, 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + function isAsyncPrefixed(fragment) { + var code, i, iz; + if (fragment.slice(0, 5) !== 'async') { + return false; + } + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) { + return false; + } + for (i = 6, iz = fragment.length; i < iz; ++i) { + if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) { + break; + } + } + if (i === iz) { + return false; + } + if (fragment.slice(i, i + 8) !== 'function') { + return false; + } + code = fragment.charCodeAt(i + 8); + return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code); + } + + result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)]; + // 12.4 '{', 'function', 'class' is not allowed in this position. + // wrap expression with parentheses + fragment = toSourceNodeWhenNeeded(result).toString(); + if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression + isClassPrefixed(fragment) || + isFunctionPrefixed(fragment) || + isAsyncPrefixed(fragment) || + (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) { + result = ['(', result, ')' + this.semicolon(flags)]; + } else { + result.push(this.semicolon(flags)); + } + return result; + }, + + ImportDeclaration: function (stmt, flags) { + // ES6: 15.2.1 valid import declarations: + // - import ImportClause FromClause ; + // - import ModuleSpecifier ; + var result, cursor, that = this; + + // If no ImportClause is present, + // this should be `import ModuleSpecifier` so skip `from` + // ModuleSpecifier is StringLiteral. + if (stmt.specifiers.length === 0) { + // import ModuleSpecifier ; + return [ + 'import', + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]; + } + + // import ImportClause FromClause ; + result = [ + 'import' + ]; + cursor = 0; + + // ImportedBinding + if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) { + result = join(result, [ + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + ++cursor; + } + + if (stmt.specifiers[cursor]) { + if (cursor !== 0) { + result.push(','); + } + + if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) { + // NameSpaceImport + result = join(result, [ + space, + this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT) + ]); + } else { + // NamedImports + result.push(space + '{'); + + if ((stmt.specifiers.length - cursor) === 1) { + // import { ... } from "..."; + result.push(space); + result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)); + result.push(space + '}' + space); + } else { + // import { + // ..., + // ..., + // } from "..."; + withIndent(function (indent) { + var i, iz; + result.push(newline); + for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + }); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base + '}' + space); + } + } + } + + result = join(result, [ + 'from' + space, + // ModuleSpecifier + this.generateExpression(stmt.source, Precedence.Sequence, E_TTT), + this.semicolon(flags) + ]); + return result; + }, + + VariableDeclarator: function (stmt, flags) { + var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT; + if (stmt.init) { + return [ + this.generateExpression(stmt.id, Precedence.Assignment, itemFlags), + space, + '=', + space, + this.generateExpression(stmt.init, Precedence.Assignment, itemFlags) + ]; + } + return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags); + }, + + VariableDeclaration: function (stmt, flags) { + // VariableDeclarator is typed as Statement, + // but joined with comma (not LineTerminator). + // So if comment is attached to target node, we should specialize. + var result, i, iz, node, bodyFlags, that = this; + + result = [ stmt.kind ]; + + bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF; + + function block() { + node = stmt.declarations[0]; + if (extra.comment && node.leadingComments) { + result.push('\n'); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(noEmptySpace()); + result.push(that.generateStatement(node, bodyFlags)); + } + + for (i = 1, iz = stmt.declarations.length; i < iz; ++i) { + node = stmt.declarations[i]; + if (extra.comment && node.leadingComments) { + result.push(',' + newline); + result.push(addIndent(that.generateStatement(node, bodyFlags))); + } else { + result.push(',' + space); + result.push(that.generateStatement(node, bodyFlags)); + } + } + } + + if (stmt.declarations.length > 1) { + withIndent(block); + } else { + block(); + } + + result.push(this.semicolon(flags)); + + return result; + }, + + ThrowStatement: function (stmt, flags) { + return [join( + 'throw', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + }, + + TryStatement: function (stmt, flags) { + var result, i, iz, guardedHandlers; + + result = ['try', this.maybeBlock(stmt.block, S_TFFF)]; + result = this.maybeBlockSuffix(stmt.block, result); + + if (stmt.handlers) { + // old interface + for (i = 0, iz = stmt.handlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handlers[i].body, result); + } + } + } else { + guardedHandlers = stmt.guardedHandlers || []; + + for (i = 0, iz = guardedHandlers.length; i < iz; ++i) { + result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(guardedHandlers[i].body, result); + } + } + + // new interface + if (stmt.handler) { + if (Array.isArray(stmt.handler)) { + for (i = 0, iz = stmt.handler.length; i < iz; ++i) { + result = join(result, this.generateStatement(stmt.handler[i], S_TFFF)); + if (stmt.finalizer || i + 1 !== iz) { + result = this.maybeBlockSuffix(stmt.handler[i].body, result); + } + } + } else { + result = join(result, this.generateStatement(stmt.handler, S_TFFF)); + if (stmt.finalizer) { + result = this.maybeBlockSuffix(stmt.handler.body, result); + } + } + } + } + if (stmt.finalizer) { + result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]); + } + return result; + }, + + SwitchStatement: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + result = [ + 'switch' + space + '(', + that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT), + ')' + space + '{' + newline + ]; + }); + if (stmt.cases) { + bodyFlags = S_TFFF; + for (i = 0, iz = stmt.cases.length; i < iz; ++i) { + if (i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags)); + result.push(fragment); + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + } + result.push(addIndent('}')); + return result; + }, + + SwitchCase: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags, that = this; + withIndent(function () { + if (stmt.test) { + result = [ + join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)), + ':' + ]; + } else { + result = ['default:']; + } + + i = 0; + iz = stmt.consequent.length; + if (iz && stmt.consequent[0].type === Syntax.BlockStatement) { + fragment = that.maybeBlock(stmt.consequent[0], S_TFFF); + result.push(fragment); + i = 1; + } + + if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + + bodyFlags = S_TFFF; + for (; i < iz; ++i) { + if (i === iz - 1 && flags & F_SEMICOLON_OPT) { + bodyFlags |= F_SEMICOLON_OPT; + } + fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags)); + result.push(fragment); + if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + result.push(newline); + } + } + }); + return result; + }, + + IfStatement: function (stmt, flags) { + var result, bodyFlags, semicolonOptional, that = this; + withIndent(function () { + result = [ + 'if' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + semicolonOptional = flags & F_SEMICOLON_OPT; + bodyFlags = S_TFFF; + if (semicolonOptional) { + bodyFlags |= F_SEMICOLON_OPT; + } + if (stmt.alternate) { + result.push(this.maybeBlock(stmt.consequent, S_TFFF)); + result = this.maybeBlockSuffix(stmt.consequent, result); + if (stmt.alternate.type === Syntax.IfStatement) { + result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]); + } else { + result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags))); + } + } else { + result.push(this.maybeBlock(stmt.consequent, bodyFlags)); + } + return result; + }, + + ForStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = ['for' + space + '(']; + if (stmt.init) { + if (stmt.init.type === Syntax.VariableDeclaration) { + result.push(that.generateStatement(stmt.init, S_FFFF)); + } else { + // F_ALLOW_IN becomes false. + result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT)); + result.push(';'); + } + } else { + result.push(';'); + } + + if (stmt.test) { + result.push(space); + result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)); + result.push(';'); + } else { + result.push(';'); + } + + if (stmt.update) { + result.push(space); + result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT)); + result.push(')'); + } else { + result.push(')'); + } + }); + + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + ForInStatement: function (stmt, flags) { + return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + ForOfStatement: function (stmt, flags) { + return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF); + }, + + LabeledStatement: function (stmt, flags) { + return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)]; + }, + + Program: function (stmt, flags) { + var result, fragment, i, iz, bodyFlags; + iz = stmt.body.length; + result = [safeConcatenation && iz > 0 ? '\n' : '']; + bodyFlags = S_TFTF; + for (i = 0; i < iz; ++i) { + if (!safeConcatenation && i === iz - 1) { + bodyFlags |= F_SEMICOLON_OPT; + } + + if (preserveBlankLines) { + // handle spaces before the first line + if (i === 0) { + if (!stmt.body[0].leadingComments) { + generateBlankLines(stmt.range[0], stmt.body[i].range[0], result); + } + } + + // handle spaces between lines + if (i > 0) { + if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) { + generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result); + } + } + } + + fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags)); + result.push(fragment); + if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + if (preserveBlankLines) { + if (!stmt.body[i + 1].leadingComments) { + result.push(newline); + } + } else { + result.push(newline); + } + } + + if (preserveBlankLines) { + // handle spaces after the last line + if (i === iz - 1) { + if (!stmt.body[i].trailingComments) { + generateBlankLines(stmt.body[i].range[1], stmt.range[1], result); + } + } + } + } + return result; + }, + + FunctionDeclaration: function (stmt, flags) { + return [ + generateAsyncPrefix(stmt, true), + 'function', + generateStarSuffix(stmt) || noEmptySpace(), + stmt.id ? generateIdentifier(stmt.id) : '', + this.generateFunctionBody(stmt) + ]; + }, + + ReturnStatement: function (stmt, flags) { + if (stmt.argument) { + return [join( + 'return', + this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT) + ), this.semicolon(flags)]; + } + return ['return' + this.semicolon(flags)]; + }, + + WhileStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'while' + space + '(', + that.generateExpression(stmt.test, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + }, + + WithStatement: function (stmt, flags) { + var result, that = this; + withIndent(function () { + result = [ + 'with' + space + '(', + that.generateExpression(stmt.object, Precedence.Sequence, E_TTT), + ')' + ]; + }); + result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)); + return result; + } + + }; + + merge(CodeGenerator.prototype, CodeGenerator.Statement); + + // Expressions. + + CodeGenerator.Expression = { + + SequenceExpression: function (expr, precedence, flags) { + var result, i, iz; + if (Precedence.Sequence < precedence) { + flags |= F_ALLOW_IN; + } + result = []; + for (i = 0, iz = expr.expressions.length; i < iz; ++i) { + result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + return parenthesize(result, Precedence.Sequence, precedence); + }, + + AssignmentExpression: function (expr, precedence, flags) { + return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags); + }, + + ArrowFunctionExpression: function (expr, precedence, flags) { + return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence); + }, + + ConditionalExpression: function (expr, precedence, flags) { + if (Precedence.Conditional < precedence) { + flags |= F_ALLOW_IN; + } + return parenthesize( + [ + this.generateExpression(expr.test, Precedence.LogicalOR, flags), + space + '?' + space, + this.generateExpression(expr.consequent, Precedence.Assignment, flags), + space + ':' + space, + this.generateExpression(expr.alternate, Precedence.Assignment, flags) + ], + Precedence.Conditional, + precedence + ); + }, + + LogicalExpression: function (expr, precedence, flags) { + return this.BinaryExpression(expr, precedence, flags); + }, + + BinaryExpression: function (expr, precedence, flags) { + var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource; + currentPrecedence = BinaryPrecedence[expr.operator]; + leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence; + rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1; + + if (currentPrecedence < precedence) { + flags |= F_ALLOW_IN; + } + + fragment = this.generateExpression(expr.left, leftPrecedence, flags); + + leftSource = fragment.toString(); + + if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) { + result = [fragment, noEmptySpace(), expr.operator]; + } else { + result = join(fragment, expr.operator); + } + + fragment = this.generateExpression(expr.right, rightPrecedence, flags); + + if (expr.operator === '/' && fragment.toString().charAt(0) === '/' || + expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') { + // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start + result.push(noEmptySpace()); + result.push(fragment); + } else { + result = join(result, fragment); + } + + if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) { + return ['(', result, ')']; + } + return parenthesize(result, currentPrecedence, precedence); + }, + + CallExpression: function (expr, precedence, flags) { + var result, i, iz; + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)]; + result.push('('); + for (i = 0, iz = expr['arguments'].length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + + if (!(flags & F_ALLOW_CALL)) { + return ['(', result, ')']; + } + return parenthesize(result, Precedence.Call, precedence); + }, + + NewExpression: function (expr, precedence, flags) { + var result, length, i, iz, itemFlags; + length = expr['arguments'].length; + + // F_ALLOW_CALL becomes false. + // F_ALLOW_UNPARATH_NEW may become false. + itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF; + + result = join( + 'new', + this.generateExpression(expr.callee, Precedence.New, itemFlags) + ); + + if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) { + result.push('('); + for (i = 0, iz = length; i < iz; ++i) { + result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT)); + if (i + 1 < iz) { + result.push(',' + space); + } + } + result.push(')'); + } + + return parenthesize(result, Precedence.New, precedence); + }, + + MemberExpression: function (expr, precedence, flags) { + var result, fragment; + + // F_ALLOW_UNPARATH_NEW becomes false. + result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)]; + + if (expr.computed) { + result.push('['); + result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT)); + result.push(']'); + } else { + if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') { + fragment = toSourceNodeWhenNeeded(result).toString(); + // When the following conditions are all true, + // 1. No floating point + // 2. Don't have exponents + // 3. The last character is a decimal digit + // 4. Not hexadecimal OR octal number literal + // we should add a floating point. + if ( + fragment.indexOf('.') < 0 && + !/[eExX]/.test(fragment) && + esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && + !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0' + ) { + result.push(' '); + } + } + result.push('.'); + result.push(generateIdentifier(expr.property)); + } + + return parenthesize(result, Precedence.Member, precedence); + }, + + MetaProperty: function (expr, precedence, flags) { + var result; + result = []; + result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta)); + result.push('.'); + result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property)); + return parenthesize(result, Precedence.Member, precedence); + }, + + UnaryExpression: function (expr, precedence, flags) { + var result, fragment, rightCharCode, leftSource, leftCharCode; + fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT); + + if (space === '') { + result = join(expr.operator, fragment); + } else { + result = [expr.operator]; + if (expr.operator.length > 2) { + // delete, void, typeof + // get `typeof []`, not `typeof[]` + result = join(result, fragment); + } else { + // Prevent inserting spaces between operator and argument if it is unnecessary + // like, `!cond` + leftSource = toSourceNodeWhenNeeded(result).toString(); + leftCharCode = leftSource.charCodeAt(leftSource.length - 1); + rightCharCode = fragment.toString().charCodeAt(0); + + if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) || + (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) { + result.push(noEmptySpace()); + result.push(fragment); + } else { + result.push(fragment); + } + } + } + return parenthesize(result, Precedence.Unary, precedence); + }, + + YieldExpression: function (expr, precedence, flags) { + var result; + if (expr.delegate) { + result = 'yield*'; + } else { + result = 'yield'; + } + if (expr.argument) { + result = join( + result, + this.generateExpression(expr.argument, Precedence.Yield, E_TTT) + ); + } + return parenthesize(result, Precedence.Yield, precedence); + }, + + AwaitExpression: function (expr, precedence, flags) { + var result = join( + expr.all ? 'await*' : 'await', + this.generateExpression(expr.argument, Precedence.Await, E_TTT) + ); + return parenthesize(result, Precedence.Await, precedence); + }, + + UpdateExpression: function (expr, precedence, flags) { + if (expr.prefix) { + return parenthesize( + [ + expr.operator, + this.generateExpression(expr.argument, Precedence.Unary, E_TTT) + ], + Precedence.Unary, + precedence + ); + } + return parenthesize( + [ + this.generateExpression(expr.argument, Precedence.Postfix, E_TTT), + expr.operator + ], + Precedence.Postfix, + precedence + ); + }, + + FunctionExpression: function (expr, precedence, flags) { + var result = [ + generateAsyncPrefix(expr, true), + 'function' + ]; + if (expr.id) { + result.push(generateStarSuffix(expr) || noEmptySpace()); + result.push(generateIdentifier(expr.id)); + } else { + result.push(generateStarSuffix(expr) || space); + } + result.push(this.generateFunctionBody(expr)); + return result; + }, + + ArrayPattern: function (expr, precedence, flags) { + return this.ArrayExpression(expr, precedence, flags, true); + }, + + ArrayExpression: function (expr, precedence, flags, isPattern) { + var result, multiline, that = this; + if (!expr.elements.length) { + return '[]'; + } + multiline = isPattern ? false : expr.elements.length > 1; + result = ['[', multiline ? newline : '']; + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.elements.length; i < iz; ++i) { + if (!expr.elements[i]) { + if (multiline) { + result.push(indent); + } + if (i + 1 === iz) { + result.push(','); + } + } else { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT)); + } + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push(']'); + return result; + }, + + RestElement: function(expr, precedence, flags) { + return '...' + this.generatePattern(expr.argument); + }, + + ClassExpression: function (expr, precedence, flags) { + var result, fragment; + result = ['class']; + if (expr.id) { + result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT)); + } + if (expr.superClass) { + fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT)); + result = join(result, fragment); + } + result.push(space); + result.push(this.generateStatement(expr.body, S_TFFT)); + return result; + }, + + MethodDefinition: function (expr, precedence, flags) { + var result, fragment; + if (expr['static']) { + result = ['static' + space]; + } else { + result = []; + } + if (expr.kind === 'get' || expr.kind === 'set') { + fragment = [ + join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)), + this.generateFunctionBody(expr.value) + ]; + } else { + fragment = [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + return join(result, fragment); + }, + + Property: function (expr, precedence, flags) { + if (expr.kind === 'get' || expr.kind === 'set') { + return [ + expr.kind, noEmptySpace(), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + + if (expr.shorthand) { + if (expr.value.type === "AssignmentPattern") { + return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT); + } + return this.generatePropertyKey(expr.key, expr.computed); + } + + if (expr.method) { + return [ + generateMethodPrefix(expr), + this.generatePropertyKey(expr.key, expr.computed), + this.generateFunctionBody(expr.value) + ]; + } + + return [ + this.generatePropertyKey(expr.key, expr.computed), + ':' + space, + this.generateExpression(expr.value, Precedence.Assignment, E_TTT) + ]; + }, + + ObjectExpression: function (expr, precedence, flags) { + var multiline, result, fragment, that = this; + + if (!expr.properties.length) { + return '{}'; + } + multiline = expr.properties.length > 1; + + withIndent(function () { + fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT); + }); + + if (!multiline) { + // issues 4 + // Do not transform from + // dejavu.Class.declare({ + // method2: function () {} + // }); + // to + // dejavu.Class.declare({method2: function () { + // }}); + if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) { + return [ '{', space, fragment, space, '}' ]; + } + } + + withIndent(function (indent) { + var i, iz; + result = [ '{', newline, indent, fragment ]; + + if (multiline) { + result.push(',' + newline); + for (i = 1, iz = expr.properties.length; i < iz; ++i) { + result.push(indent); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + newline); + } + } + } + }); + + if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(base); + result.push('}'); + return result; + }, + + AssignmentPattern: function(expr, precedence, flags) { + return this.generateAssignment(expr.left, expr.right, '=', precedence, flags); + }, + + ObjectPattern: function (expr, precedence, flags) { + var result, i, iz, multiline, property, that = this; + if (!expr.properties.length) { + return '{}'; + } + + multiline = false; + if (expr.properties.length === 1) { + property = expr.properties[0]; + if ( + property.type === Syntax.Property + && property.value.type !== Syntax.Identifier + ) { + multiline = true; + } + } else { + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + property = expr.properties[i]; + if ( + property.type === Syntax.Property + && !property.shorthand + ) { + multiline = true; + break; + } + } + } + result = ['{', multiline ? newline : '' ]; + + withIndent(function (indent) { + var i, iz; + for (i = 0, iz = expr.properties.length; i < iz; ++i) { + result.push(multiline ? indent : ''); + result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT)); + if (i + 1 < iz) { + result.push(',' + (multiline ? newline : space)); + } + } + }); + + if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) { + result.push(newline); + } + result.push(multiline ? base : ''); + result.push('}'); + return result; + }, + + ThisExpression: function (expr, precedence, flags) { + return 'this'; + }, + + Super: function (expr, precedence, flags) { + return 'super'; + }, + + Identifier: function (expr, precedence, flags) { + return generateIdentifier(expr); + }, + + ImportDefaultSpecifier: function (expr, precedence, flags) { + return generateIdentifier(expr.id || expr.local); + }, + + ImportNamespaceSpecifier: function (expr, precedence, flags) { + var result = ['*']; + var id = expr.id || expr.local; + if (id) { + result.push(space + 'as' + noEmptySpace() + generateIdentifier(id)); + } + return result; + }, + + ImportSpecifier: function (expr, precedence, flags) { + var imported = expr.imported; + var result = [ imported.name ]; + var local = expr.local; + if (local && local.name !== imported.name) { + result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local)); + } + return result; + }, + + ExportSpecifier: function (expr, precedence, flags) { + var local = expr.local; + var result = [ local.name ]; + var exported = expr.exported; + if (exported && exported.name !== local.name) { + result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported)); + } + return result; + }, + + Literal: function (expr, precedence, flags) { + var raw; + if (expr.hasOwnProperty('raw') && parse && extra.raw) { + try { + raw = parse(expr.raw).body[0].expression; + if (raw.type === Syntax.Literal) { + if (raw.value === expr.value) { + return expr.raw; + } + } + } catch (e) { + // not use raw property + } + } + + if (expr.regex) { + return '/' + expr.regex.pattern + '/' + expr.regex.flags; + } + + if (expr.value === null) { + return 'null'; + } + + if (typeof expr.value === 'string') { + return escapeString(expr.value); + } + + if (typeof expr.value === 'number') { + return generateNumber(expr.value); + } + + if (typeof expr.value === 'boolean') { + return expr.value ? 'true' : 'false'; + } + + return generateRegExp(expr.value); + }, + + GeneratorExpression: function (expr, precedence, flags) { + return this.ComprehensionExpression(expr, precedence, flags); + }, + + ComprehensionExpression: function (expr, precedence, flags) { + // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...] + // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6 + + var result, i, iz, fragment, that = this; + result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['[']; + + if (extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + result.push(fragment); + } + + if (expr.blocks) { + withIndent(function () { + for (i = 0, iz = expr.blocks.length; i < iz; ++i) { + fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT); + if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) { + result = join(result, fragment); + } else { + result.push(fragment); + } + } + }); + } + + if (expr.filter) { + result = join(result, 'if' + space); + fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT); + result = join(result, [ '(', fragment, ')' ]); + } + + if (!extra.moz.comprehensionExpressionStartsWithAssignment) { + fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT); + + result = join(result, fragment); + } + + result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']'); + return result; + }, + + ComprehensionBlock: function (expr, precedence, flags) { + var fragment; + if (expr.left.type === Syntax.VariableDeclaration) { + fragment = [ + expr.left.kind, noEmptySpace(), + this.generateStatement(expr.left.declarations[0], S_FFFF) + ]; + } else { + fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT); + } + + fragment = join(fragment, expr.of ? 'of' : 'in'); + fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT)); + + return [ 'for' + space + '(', fragment, ')' ]; + }, + + SpreadElement: function (expr, precedence, flags) { + return [ + '...', + this.generateExpression(expr.argument, Precedence.Assignment, E_TTT) + ]; + }, + + TaggedTemplateExpression: function (expr, precedence, flags) { + var itemFlags = E_TTF; + if (!(flags & F_ALLOW_CALL)) { + itemFlags = E_TFF; + } + var result = [ + this.generateExpression(expr.tag, Precedence.Call, itemFlags), + this.generateExpression(expr.quasi, Precedence.Primary, E_FFT) + ]; + return parenthesize(result, Precedence.TaggedTemplate, precedence); + }, + + TemplateElement: function (expr, precedence, flags) { + // Don't use "cooked". Since tagged template can use raw template + // representation. So if we do so, it breaks the script semantics. + return expr.value.raw; + }, + + TemplateLiteral: function (expr, precedence, flags) { + var result, i, iz; + result = [ '`' ]; + for (i = 0, iz = expr.quasis.length; i < iz; ++i) { + result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT)); + if (i + 1 < iz) { + result.push('${' + space); + result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT)); + result.push(space + '}'); + } + } + result.push('`'); + return result; + }, + + ModuleSpecifier: function (expr, precedence, flags) { + return this.Literal(expr, precedence, flags); + }, + + ImportExpression: function(expr, precedence, flag) { + return parenthesize([ + 'import(', + this.generateExpression(expr.source, Precedence.Assignment, E_TTT), + ')' + ], Precedence.Call, precedence); + }, + + }; + + merge(CodeGenerator.prototype, CodeGenerator.Expression); + + CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) { + var result, type; + + type = expr.type || Syntax.Property; + + if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) { + return generateVerbatim(expr, precedence); + } + + result = this[type](expr, precedence, flags); + + + if (extra.comment) { + result = addComments(expr, result); + } + return toSourceNodeWhenNeeded(result, expr); + }; + + CodeGenerator.prototype.generateStatement = function (stmt, flags) { + var result, + fragment; + + result = this[stmt.type](stmt, flags); + + // Attach comments + + if (extra.comment) { + result = addComments(stmt, result); + } + + fragment = toSourceNodeWhenNeeded(result).toString(); + if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') { + result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, ''); + } + + return toSourceNodeWhenNeeded(result, stmt); + }; + + function generateInternal(node) { + var codegen; + + codegen = new CodeGenerator(); + if (isStatement(node)) { + return codegen.generateStatement(node, S_TFFF); + } + + if (isExpression(node)) { + return codegen.generateExpression(node, Precedence.Sequence, E_TTT); + } + + throw new Error('Unknown node type: ' + node.type); + } + + function generate(node, options) { + var defaultOptions = getDefaultOptions(), result, pair; + + if (options != null) { + // Obsolete options + // + // `options.indent` + // `options.base` + // + // Instead of them, we can use `option.format.indent`. + if (typeof options.indent === 'string') { + defaultOptions.format.indent.style = options.indent; + } + if (typeof options.base === 'number') { + defaultOptions.format.indent.base = options.base; + } + options = updateDeeply(defaultOptions, options); + indent = options.format.indent.style; + if (typeof options.base === 'string') { + base = options.base; + } else { + base = stringRepeat(indent, options.format.indent.base); + } + } else { + options = defaultOptions; + indent = options.format.indent.style; + base = stringRepeat(indent, options.format.indent.base); + } + json = options.format.json; + renumber = options.format.renumber; + hexadecimal = json ? false : options.format.hexadecimal; + quotes = json ? 'double' : options.format.quotes; + escapeless = options.format.escapeless; + newline = options.format.newline; + space = options.format.space; + if (options.format.compact) { + newline = space = indent = base = ''; + } + parentheses = options.format.parentheses; + semicolons = options.format.semicolons; + safeConcatenation = options.format.safeConcatenation; + directive = options.directive; + parse = json ? null : options.parse; + sourceMap = options.sourceMap; + sourceCode = options.sourceCode; + preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null; + extra = options; + + if (sourceMap) { + if (!exports.browser) { + // We assume environment is node.js + // And prevent from including source-map by browserify + SourceNode = (__webpack_require__(/*! source-map */ "../../../.yarn/berry/cache/source-map-npm-0.6.1-1a3621db16-9.zip/node_modules/source-map/source-map.js").SourceNode); + } else { + SourceNode = global.sourceMap.SourceNode; + } + } + + result = generateInternal(node); + + if (!sourceMap) { + pair = {code: result.toString(), map: null}; + return options.sourceMapWithCode ? pair : pair.code; + } + + + pair = result.toStringWithSourceMap({ + file: options.file, + sourceRoot: options.sourceMapRoot + }); + + if (options.sourceContent) { + pair.map.setSourceContent(options.sourceMap, + options.sourceContent); + } + + if (options.sourceMapWithCode) { + return pair; + } + + return pair.map.toString(); + } + + FORMAT_MINIFY = { + indent: { + style: '', + base: 0 + }, + renumber: true, + hexadecimal: true, + quotes: 'auto', + escapeless: true, + compact: true, + parentheses: false, + semicolons: false + }; + + FORMAT_DEFAULTS = getDefaultOptions().format; + + exports.version = __webpack_require__(/*! ./package.json */ "../../../.yarn/berry/cache/escodegen-npm-1.14.3-a4dedc6eeb-9.zip/node_modules/escodegen/package.json").version; + exports.generate = generate; + exports.attachComments = estraverse.attachComments; + exports.Precedence = updateDeeply({}, Precedence); + exports.browser = false; + exports.FORMAT_MINIFY = FORMAT_MINIFY; + exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ + + +/***/ }), + +/***/ "../../../.yarn/berry/cache/esprima-npm-4.0.1-1084e98778-9.zip/node_modules/esprima/dist/esprima.js": +/*!**********************************************************************************************************!*\ + !*** ../../../.yarn/berry/cache/esprima-npm-4.0.1-1084e98778-9.zip/node_modules/esprima/dist/esprima.js ***! + \**********************************************************************************************************/ +/***/ (function(module) { + +(function webpackUniversalModuleDefinition(root, factory) { +/* istanbul ignore next */ + if(true) + module.exports = factory(); + else {} +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __nested_webpack_require_583__(moduleId) { + +/******/ // Check if module is in cache +/* istanbul ignore if */ +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_583__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __nested_webpack_require_583__.m = modules; + +/******/ // expose the module cache +/******/ __nested_webpack_require_583__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __nested_webpack_require_583__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __nested_webpack_require_583__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __nested_webpack_require_1808__) { + + "use strict"; + /* + Copyright JS Foundation and other contributors, https://js.foundation/ + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var comment_handler_1 = __nested_webpack_require_1808__(1); + var jsx_parser_1 = __nested_webpack_require_1808__(3); + var parser_1 = __nested_webpack_require_1808__(8); + var tokenizer_1 = __nested_webpack_require_1808__(15); + function parse(code, options, delegate) { + var commentHandler = null; + var proxyDelegate = function (node, metadata) { + if (delegate) { + delegate(node, metadata); + } + if (commentHandler) { + commentHandler.visit(node, metadata); + } + }; + var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; + var collectComment = false; + if (options) { + collectComment = (typeof options.comment === 'boolean' && options.comment); + var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); + if (collectComment || attachComment) { + commentHandler = new comment_handler_1.CommentHandler(); + commentHandler.attach = attachComment; + options.comment = true; + parserDelegate = proxyDelegate; + } + } + var isModule = false; + if (options && typeof options.sourceType === 'string') { + isModule = (options.sourceType === 'module'); + } + var parser; + if (options && typeof options.jsx === 'boolean' && options.jsx) { + parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); + } + else { + parser = new parser_1.Parser(code, options, parserDelegate); + } + var program = isModule ? parser.parseModule() : parser.parseScript(); + var ast = program; + if (collectComment && commentHandler) { + ast.comments = commentHandler.comments; + } + if (parser.config.tokens) { + ast.tokens = parser.tokens; + } + if (parser.config.tolerant) { + ast.errors = parser.errorHandler.errors; + } + return ast; + } + exports.parse = parse; + function parseModule(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'module'; + return parse(code, parsingOptions, delegate); + } + exports.parseModule = parseModule; + function parseScript(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'script'; + return parse(code, parsingOptions, delegate); + } + exports.parseScript = parseScript; + function tokenize(code, options, delegate) { + var tokenizer = new tokenizer_1.Tokenizer(code, options); + var tokens; + tokens = []; + try { + while (true) { + var token = tokenizer.getNextToken(); + if (!token) { + break; + } + if (delegate) { + token = delegate(token); + } + tokens.push(token); + } + } + catch (e) { + tokenizer.errorHandler.tolerate(e); + } + if (tokenizer.errorHandler.tolerant) { + tokens.errors = tokenizer.errors(); + } + return tokens; + } + exports.tokenize = tokenize; + var syntax_1 = __nested_webpack_require_1808__(2); + exports.Syntax = syntax_1.Syntax; + // Sync with *.json manifests. + exports.version = '4.0.1'; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __nested_webpack_require_6456__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __nested_webpack_require_6456__(2); + var CommentHandler = (function () { + function CommentHandler() { + this.attach = false; + this.comments = []; + this.stack = []; + this.leading = []; + this.trailing = []; + } + CommentHandler.prototype.insertInnerComments = function (node, metadata) { + // innnerComments for properties empty block + // `function a() {/** comments **\/}` + if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { + var innerComments = []; + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (metadata.end.offset >= entry.start) { + innerComments.unshift(entry.comment); + this.leading.splice(i, 1); + this.trailing.splice(i, 1); + } + } + if (innerComments.length) { + node.innerComments = innerComments; + } + } + }; + CommentHandler.prototype.findTrailingComments = function (metadata) { + var trailingComments = []; + if (this.trailing.length > 0) { + for (var i = this.trailing.length - 1; i >= 0; --i) { + var entry_1 = this.trailing[i]; + if (entry_1.start >= metadata.end.offset) { + trailingComments.unshift(entry_1.comment); + } + } + this.trailing.length = 0; + return trailingComments; + } + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.node.trailingComments) { + var firstComment = entry.node.trailingComments[0]; + if (firstComment && firstComment.range[0] >= metadata.end.offset) { + trailingComments = entry.node.trailingComments; + delete entry.node.trailingComments; + } + } + return trailingComments; + }; + CommentHandler.prototype.findLeadingComments = function (metadata) { + var leadingComments = []; + var target; + while (this.stack.length > 0) { + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.start >= metadata.start.offset) { + target = entry.node; + this.stack.pop(); + } + else { + break; + } + } + if (target) { + var count = target.leadingComments ? target.leadingComments.length : 0; + for (var i = count - 1; i >= 0; --i) { + var comment = target.leadingComments[i]; + if (comment.range[1] <= metadata.start.offset) { + leadingComments.unshift(comment); + target.leadingComments.splice(i, 1); + } + } + if (target.leadingComments && target.leadingComments.length === 0) { + delete target.leadingComments; + } + return leadingComments; + } + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (entry.start <= metadata.start.offset) { + leadingComments.unshift(entry.comment); + this.leading.splice(i, 1); + } + } + return leadingComments; + }; + CommentHandler.prototype.visitNode = function (node, metadata) { + if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { + return; + } + this.insertInnerComments(node, metadata); + var trailingComments = this.findTrailingComments(metadata); + var leadingComments = this.findLeadingComments(metadata); + if (leadingComments.length > 0) { + node.leadingComments = leadingComments; + } + if (trailingComments.length > 0) { + node.trailingComments = trailingComments; + } + this.stack.push({ + node: node, + start: metadata.start.offset + }); + }; + CommentHandler.prototype.visitComment = function (node, metadata) { + var type = (node.type[0] === 'L') ? 'Line' : 'Block'; + var comment = { + type: type, + value: node.value + }; + if (node.range) { + comment.range = node.range; + } + if (node.loc) { + comment.loc = node.loc; + } + this.comments.push(comment); + if (this.attach) { + var entry = { + comment: { + type: type, + value: node.value, + range: [metadata.start.offset, metadata.end.offset] + }, + start: metadata.start.offset + }; + if (node.loc) { + entry.comment.loc = node.loc; + } + node.type = type; + this.leading.push(entry); + this.trailing.push(entry); + } + }; + CommentHandler.prototype.visit = function (node, metadata) { + if (node.type === 'LineComment') { + this.visitComment(node, metadata); + } + else if (node.type === 'BlockComment') { + this.visitComment(node, metadata); + } + else if (this.attach) { + this.visitNode(node, metadata); + } + }; + return CommentHandler; + }()); + exports.CommentHandler = CommentHandler; + + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __nested_webpack_require_15019__) { + + "use strict"; +/* istanbul ignore next */ + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var character_1 = __nested_webpack_require_15019__(4); + var JSXNode = __nested_webpack_require_15019__(5); + var jsx_syntax_1 = __nested_webpack_require_15019__(6); + var Node = __nested_webpack_require_15019__(7); + var parser_1 = __nested_webpack_require_15019__(8); + var token_1 = __nested_webpack_require_15019__(13); + var xhtml_entities_1 = __nested_webpack_require_15019__(14); + token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; + token_1.TokenName[101 /* Text */] = 'JSXText'; + // Fully qualified element name, e.g. returns "svg:path" + function getQualifiedElementName(elementName) { + var qualifiedName; + switch (elementName.type) { + case jsx_syntax_1.JSXSyntax.JSXIdentifier: + var id = elementName; + qualifiedName = id.name; + break; + case jsx_syntax_1.JSXSyntax.JSXNamespacedName: + var ns = elementName; + qualifiedName = getQualifiedElementName(ns.namespace) + ':' + + getQualifiedElementName(ns.name); + break; + case jsx_syntax_1.JSXSyntax.JSXMemberExpression: + var expr = elementName; + qualifiedName = getQualifiedElementName(expr.object) + '.' + + getQualifiedElementName(expr.property); + break; + /* istanbul ignore next */ + default: + break; + } + return qualifiedName; + } + var JSXParser = (function (_super) { + __extends(JSXParser, _super); + function JSXParser(code, options, delegate) { + return _super.call(this, code, options, delegate) || this; + } + JSXParser.prototype.parsePrimaryExpression = function () { + return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); + }; + JSXParser.prototype.startJSX = function () { + // Unwind the scanner before the lookahead token. + this.scanner.index = this.startMarker.index; + this.scanner.lineNumber = this.startMarker.line; + this.scanner.lineStart = this.startMarker.index - this.startMarker.column; + }; + JSXParser.prototype.finishJSX = function () { + // Prime the next lookahead. + this.nextToken(); + }; + JSXParser.prototype.reenterJSX = function () { + this.startJSX(); + this.expectJSX('}'); + // Pop the closing '}' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + }; + JSXParser.prototype.createJSXNode = function () { + this.collectComments(); + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.createJSXChildNode = function () { + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.scanXHTMLEntity = function (quote) { + var result = '&'; + var valid = true; + var terminated = false; + var numeric = false; + var hex = false; + while (!this.scanner.eof() && valid && !terminated) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === quote) { + break; + } + terminated = (ch === ';'); + result += ch; + ++this.scanner.index; + if (!terminated) { + switch (result.length) { + case 2: + // e.g. '{' + numeric = (ch === '#'); + break; + case 3: + if (numeric) { + // e.g. 'A' + hex = (ch === 'x'); + valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); + numeric = numeric && !hex; + } + break; + default: + valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); + valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); + break; + } + } + } + if (valid && terminated && result.length > 2) { + // e.g. 'A' becomes just '#x41' + var str = result.substr(1, result.length - 2); + if (numeric && str.length > 1) { + result = String.fromCharCode(parseInt(str.substr(1), 10)); + } + else if (hex && str.length > 2) { + result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); + } + else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { + result = xhtml_entities_1.XHTMLEntities[str]; + } + } + return result; + }; + // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. + JSXParser.prototype.lexJSX = function () { + var cp = this.scanner.source.charCodeAt(this.scanner.index); + // < > / : = { } + if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { + var value = this.scanner.source[this.scanner.index++]; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index - 1, + end: this.scanner.index + }; + } + // " ' + if (cp === 34 || cp === 39) { + var start = this.scanner.index; + var quote = this.scanner.source[this.scanner.index++]; + var str = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index++]; + if (ch === quote) { + break; + } + else if (ch === '&') { + str += this.scanXHTMLEntity(quote); + } + else { + str += ch; + } + } + return { + type: 8 /* StringLiteral */, + value: str, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ... or . + if (cp === 46) { + var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); + var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); + var value = (n1 === 46 && n2 === 46) ? '...' : '.'; + var start = this.scanner.index; + this.scanner.index += value.length; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ` + if (cp === 96) { + // Only placeholder, since it will be rescanned as a real assignment expression. + return { + type: 10 /* Template */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index, + end: this.scanner.index + }; + } + // Identifer can not contain backslash (char code 92). + if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { + var start = this.scanner.index; + ++this.scanner.index; + while (!this.scanner.eof()) { + var ch = this.scanner.source.charCodeAt(this.scanner.index); + if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { + ++this.scanner.index; + } + else if (ch === 45) { + // Hyphen (char code 45) can be part of an identifier. + ++this.scanner.index; + } + else { + break; + } + } + var id = this.scanner.source.slice(start, this.scanner.index); + return { + type: 100 /* Identifier */, + value: id, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + return this.scanner.lex(); + }; + JSXParser.prototype.nextJSXToken = function () { + this.collectComments(); + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var token = this.lexJSX(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + if (this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.nextJSXText = function () { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var start = this.scanner.index; + var text = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === '{' || ch === '<') { + break; + } + ++this.scanner.index; + text += ch; + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.scanner.lineNumber; + if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { + ++this.scanner.index; + } + this.scanner.lineStart = this.scanner.index; + } + } + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + var token = { + type: 101 /* Text */, + value: text, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + if ((text.length > 0) && this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.peekJSXToken = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.lexJSX(); + this.scanner.restoreState(state); + return next; + }; + // Expect the next JSX token to match the specified punctuator. + // If not, an exception will be thrown. + JSXParser.prototype.expectJSX = function (value) { + var token = this.nextJSXToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next JSX token matches the specified punctuator. + JSXParser.prototype.matchJSX = function (value) { + var next = this.peekJSXToken(); + return next.type === 7 /* Punctuator */ && next.value === value; + }; + JSXParser.prototype.parseJSXIdentifier = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 100 /* Identifier */) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); + }; + JSXParser.prototype.parseJSXElementName = function () { + var node = this.createJSXNode(); + var elementName = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = elementName; + this.expectJSX(':'); + var name_1 = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); + } + else if (this.matchJSX('.')) { + while (this.matchJSX('.')) { + var object = elementName; + this.expectJSX('.'); + var property = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); + } + } + return elementName; + }; + JSXParser.prototype.parseJSXAttributeName = function () { + var node = this.createJSXNode(); + var attributeName; + var identifier = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = identifier; + this.expectJSX(':'); + var name_2 = this.parseJSXIdentifier(); + attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); + } + else { + attributeName = identifier; + } + return attributeName; + }; + JSXParser.prototype.parseJSXStringLiteralAttribute = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 8 /* StringLiteral */) { + this.throwUnexpectedToken(token); + } + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + JSXParser.prototype.parseJSXExpressionAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.finishJSX(); + if (this.match('}')) { + this.tolerateError('JSX attributes must only be assigned a non-empty expression'); + } + var expression = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXAttributeValue = function () { + return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : + this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); + }; + JSXParser.prototype.parseJSXNameValueAttribute = function () { + var node = this.createJSXNode(); + var name = this.parseJSXAttributeName(); + var value = null; + if (this.matchJSX('=')) { + this.expectJSX('='); + value = this.parseJSXAttributeValue(); + } + return this.finalize(node, new JSXNode.JSXAttribute(name, value)); + }; + JSXParser.prototype.parseJSXSpreadAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.expectJSX('...'); + this.finishJSX(); + var argument = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); + }; + JSXParser.prototype.parseJSXAttributes = function () { + var attributes = []; + while (!this.matchJSX('/') && !this.matchJSX('>')) { + var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : + this.parseJSXNameValueAttribute(); + attributes.push(attribute); + } + return attributes; + }; + JSXParser.prototype.parseJSXOpeningElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXBoundaryElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + if (this.matchJSX('/')) { + this.expectJSX('/'); + var name_3 = this.parseJSXElementName(); + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); + } + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXEmptyExpression = function () { + var node = this.createJSXChildNode(); + this.collectComments(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + return this.finalize(node, new JSXNode.JSXEmptyExpression()); + }; + JSXParser.prototype.parseJSXExpressionContainer = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + var expression; + if (this.matchJSX('}')) { + expression = this.parseJSXEmptyExpression(); + this.expectJSX('}'); + } + else { + this.finishJSX(); + expression = this.parseAssignmentExpression(); + this.reenterJSX(); + } + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXChildren = function () { + var children = []; + while (!this.scanner.eof()) { + var node = this.createJSXChildNode(); + var token = this.nextJSXText(); + if (token.start < token.end) { + var raw = this.getTokenRaw(token); + var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); + children.push(child); + } + if (this.scanner.source[this.scanner.index] === '{') { + var container = this.parseJSXExpressionContainer(); + children.push(container); + } + else { + break; + } + } + return children; + }; + JSXParser.prototype.parseComplexJSXElement = function (el) { + var stack = []; + while (!this.scanner.eof()) { + el.children = el.children.concat(this.parseJSXChildren()); + var node = this.createJSXChildNode(); + var element = this.parseJSXBoundaryElement(); + if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { + var opening = element; + if (opening.selfClosing) { + var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); + el.children.push(child); + } + else { + stack.push(el); + el = { node: node, opening: opening, closing: null, children: [] }; + } + } + if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { + el.closing = element; + var open_1 = getQualifiedElementName(el.opening.name); + var close_1 = getQualifiedElementName(el.closing.name); + if (open_1 !== close_1) { + this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); + } + if (stack.length > 0) { + var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); + el = stack[stack.length - 1]; + el.children.push(child); + stack.pop(); + } + else { + break; + } + } + } + return el; + }; + JSXParser.prototype.parseJSXElement = function () { + var node = this.createJSXNode(); + var opening = this.parseJSXOpeningElement(); + var children = []; + var closing = null; + if (!opening.selfClosing) { + var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); + children = el.children; + closing = el.closing; + } + return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); + }; + JSXParser.prototype.parseJSXRoot = function () { + // Pop the opening '<' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + this.startJSX(); + var element = this.parseJSXElement(); + this.finishJSX(); + return element; + }; + JSXParser.prototype.isStartOfExpression = function () { + return _super.prototype.isStartOfExpression.call(this) || this.match('<'); + }; + return JSXParser; + }(parser_1.Parser)); + exports.JSXParser = JSXParser; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // See also tools/generate-unicode-regex.js. + var Regex = { + // Unicode v8.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // Unicode v8.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + exports.Character = { + /* tslint:disable:no-bitwise */ + fromCodePoint: function (cp) { + return (cp < 0x10000) ? String.fromCharCode(cp) : + String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); + }, + // https://tc39.github.io/ecma262/#sec-white-space + isWhiteSpace: function (cp) { + return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || + (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); + }, + // https://tc39.github.io/ecma262/#sec-line-terminators + isLineTerminator: function (cp) { + return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); + }, + // https://tc39.github.io/ecma262/#sec-names-and-keywords + isIdentifierStart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); + }, + isIdentifierPart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp >= 0x30 && cp <= 0x39) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); + }, + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + isDecimalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39); // 0..9 + }, + isHexDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x46) || + (cp >= 0x61 && cp <= 0x66); // a..f + }, + isOctalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x37); // 0..7 + } + }; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __nested_webpack_require_54354__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var jsx_syntax_1 = __nested_webpack_require_54354__(6); + /* tslint:disable:max-classes-per-file */ + var JSXClosingElement = (function () { + function JSXClosingElement(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; + this.name = name; + } + return JSXClosingElement; + }()); + exports.JSXClosingElement = JSXClosingElement; + var JSXElement = (function () { + function JSXElement(openingElement, children, closingElement) { + this.type = jsx_syntax_1.JSXSyntax.JSXElement; + this.openingElement = openingElement; + this.children = children; + this.closingElement = closingElement; + } + return JSXElement; + }()); + exports.JSXElement = JSXElement; + var JSXEmptyExpression = (function () { + function JSXEmptyExpression() { + this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; + } + return JSXEmptyExpression; + }()); + exports.JSXEmptyExpression = JSXEmptyExpression; + var JSXExpressionContainer = (function () { + function JSXExpressionContainer(expression) { + this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; + this.expression = expression; + } + return JSXExpressionContainer; + }()); + exports.JSXExpressionContainer = JSXExpressionContainer; + var JSXIdentifier = (function () { + function JSXIdentifier(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; + this.name = name; + } + return JSXIdentifier; + }()); + exports.JSXIdentifier = JSXIdentifier; + var JSXMemberExpression = (function () { + function JSXMemberExpression(object, property) { + this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; + this.object = object; + this.property = property; + } + return JSXMemberExpression; + }()); + exports.JSXMemberExpression = JSXMemberExpression; + var JSXAttribute = (function () { + function JSXAttribute(name, value) { + this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; + this.name = name; + this.value = value; + } + return JSXAttribute; + }()); + exports.JSXAttribute = JSXAttribute; + var JSXNamespacedName = (function () { + function JSXNamespacedName(namespace, name) { + this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; + this.namespace = namespace; + this.name = name; + } + return JSXNamespacedName; + }()); + exports.JSXNamespacedName = JSXNamespacedName; + var JSXOpeningElement = (function () { + function JSXOpeningElement(name, selfClosing, attributes) { + this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; + this.name = name; + this.selfClosing = selfClosing; + this.attributes = attributes; + } + return JSXOpeningElement; + }()); + exports.JSXOpeningElement = JSXOpeningElement; + var JSXSpreadAttribute = (function () { + function JSXSpreadAttribute(argument) { + this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; + this.argument = argument; + } + return JSXSpreadAttribute; + }()); + exports.JSXSpreadAttribute = JSXSpreadAttribute; + var JSXText = (function () { + function JSXText(value, raw) { + this.type = jsx_syntax_1.JSXSyntax.JSXText; + this.value = value; + this.raw = raw; + } + return JSXText; + }()); + exports.JSXText = JSXText; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSXSyntax = { + JSXAttribute: 'JSXAttribute', + JSXClosingElement: 'JSXClosingElement', + JSXElement: 'JSXElement', + JSXEmptyExpression: 'JSXEmptyExpression', + JSXExpressionContainer: 'JSXExpressionContainer', + JSXIdentifier: 'JSXIdentifier', + JSXMemberExpression: 'JSXMemberExpression', + JSXNamespacedName: 'JSXNamespacedName', + JSXOpeningElement: 'JSXOpeningElement', + JSXSpreadAttribute: 'JSXSpreadAttribute', + JSXText: 'JSXText' + }; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __nested_webpack_require_58416__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __nested_webpack_require_58416__(2); + /* tslint:disable:max-classes-per-file */ + var ArrayExpression = (function () { + function ArrayExpression(elements) { + this.type = syntax_1.Syntax.ArrayExpression; + this.elements = elements; + } + return ArrayExpression; + }()); + exports.ArrayExpression = ArrayExpression; + var ArrayPattern = (function () { + function ArrayPattern(elements) { + this.type = syntax_1.Syntax.ArrayPattern; + this.elements = elements; + } + return ArrayPattern; + }()); + exports.ArrayPattern = ArrayPattern; + var ArrowFunctionExpression = (function () { + function ArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = false; + } + return ArrowFunctionExpression; + }()); + exports.ArrowFunctionExpression = ArrowFunctionExpression; + var AssignmentExpression = (function () { + function AssignmentExpression(operator, left, right) { + this.type = syntax_1.Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return AssignmentExpression; + }()); + exports.AssignmentExpression = AssignmentExpression; + var AssignmentPattern = (function () { + function AssignmentPattern(left, right) { + this.type = syntax_1.Syntax.AssignmentPattern; + this.left = left; + this.right = right; + } + return AssignmentPattern; + }()); + exports.AssignmentPattern = AssignmentPattern; + var AsyncArrowFunctionExpression = (function () { + function AsyncArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = true; + } + return AsyncArrowFunctionExpression; + }()); + exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; + var AsyncFunctionDeclaration = (function () { + function AsyncFunctionDeclaration(id, params, body) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionDeclaration; + }()); + exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; + var AsyncFunctionExpression = (function () { + function AsyncFunctionExpression(id, params, body) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionExpression; + }()); + exports.AsyncFunctionExpression = AsyncFunctionExpression; + var AwaitExpression = (function () { + function AwaitExpression(argument) { + this.type = syntax_1.Syntax.AwaitExpression; + this.argument = argument; + } + return AwaitExpression; + }()); + exports.AwaitExpression = AwaitExpression; + var BinaryExpression = (function () { + function BinaryExpression(operator, left, right) { + var logical = (operator === '||' || operator === '&&'); + this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return BinaryExpression; + }()); + exports.BinaryExpression = BinaryExpression; + var BlockStatement = (function () { + function BlockStatement(body) { + this.type = syntax_1.Syntax.BlockStatement; + this.body = body; + } + return BlockStatement; + }()); + exports.BlockStatement = BlockStatement; + var BreakStatement = (function () { + function BreakStatement(label) { + this.type = syntax_1.Syntax.BreakStatement; + this.label = label; + } + return BreakStatement; + }()); + exports.BreakStatement = BreakStatement; + var CallExpression = (function () { + function CallExpression(callee, args) { + this.type = syntax_1.Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + } + return CallExpression; + }()); + exports.CallExpression = CallExpression; + var CatchClause = (function () { + function CatchClause(param, body) { + this.type = syntax_1.Syntax.CatchClause; + this.param = param; + this.body = body; + } + return CatchClause; + }()); + exports.CatchClause = CatchClause; + var ClassBody = (function () { + function ClassBody(body) { + this.type = syntax_1.Syntax.ClassBody; + this.body = body; + } + return ClassBody; + }()); + exports.ClassBody = ClassBody; + var ClassDeclaration = (function () { + function ClassDeclaration(id, superClass, body) { + this.type = syntax_1.Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassDeclaration; + }()); + exports.ClassDeclaration = ClassDeclaration; + var ClassExpression = (function () { + function ClassExpression(id, superClass, body) { + this.type = syntax_1.Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassExpression; + }()); + exports.ClassExpression = ClassExpression; + var ComputedMemberExpression = (function () { + function ComputedMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = true; + this.object = object; + this.property = property; + } + return ComputedMemberExpression; + }()); + exports.ComputedMemberExpression = ComputedMemberExpression; + var ConditionalExpression = (function () { + function ConditionalExpression(test, consequent, alternate) { + this.type = syntax_1.Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return ConditionalExpression; + }()); + exports.ConditionalExpression = ConditionalExpression; + var ContinueStatement = (function () { + function ContinueStatement(label) { + this.type = syntax_1.Syntax.ContinueStatement; + this.label = label; + } + return ContinueStatement; + }()); + exports.ContinueStatement = ContinueStatement; + var DebuggerStatement = (function () { + function DebuggerStatement() { + this.type = syntax_1.Syntax.DebuggerStatement; + } + return DebuggerStatement; + }()); + exports.DebuggerStatement = DebuggerStatement; + var Directive = (function () { + function Directive(expression, directive) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + this.directive = directive; + } + return Directive; + }()); + exports.Directive = Directive; + var DoWhileStatement = (function () { + function DoWhileStatement(body, test) { + this.type = syntax_1.Syntax.DoWhileStatement; + this.body = body; + this.test = test; + } + return DoWhileStatement; + }()); + exports.DoWhileStatement = DoWhileStatement; + var EmptyStatement = (function () { + function EmptyStatement() { + this.type = syntax_1.Syntax.EmptyStatement; + } + return EmptyStatement; + }()); + exports.EmptyStatement = EmptyStatement; + var ExportAllDeclaration = (function () { + function ExportAllDeclaration(source) { + this.type = syntax_1.Syntax.ExportAllDeclaration; + this.source = source; + } + return ExportAllDeclaration; + }()); + exports.ExportAllDeclaration = ExportAllDeclaration; + var ExportDefaultDeclaration = (function () { + function ExportDefaultDeclaration(declaration) { + this.type = syntax_1.Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + } + return ExportDefaultDeclaration; + }()); + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + var ExportNamedDeclaration = (function () { + function ExportNamedDeclaration(declaration, specifiers, source) { + this.type = syntax_1.Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = source; + } + return ExportNamedDeclaration; + }()); + exports.ExportNamedDeclaration = ExportNamedDeclaration; + var ExportSpecifier = (function () { + function ExportSpecifier(local, exported) { + this.type = syntax_1.Syntax.ExportSpecifier; + this.exported = exported; + this.local = local; + } + return ExportSpecifier; + }()); + exports.ExportSpecifier = ExportSpecifier; + var ExpressionStatement = (function () { + function ExpressionStatement(expression) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + } + return ExpressionStatement; + }()); + exports.ExpressionStatement = ExpressionStatement; + var ForInStatement = (function () { + function ForInStatement(left, right, body) { + this.type = syntax_1.Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + } + return ForInStatement; + }()); + exports.ForInStatement = ForInStatement; + var ForOfStatement = (function () { + function ForOfStatement(left, right, body) { + this.type = syntax_1.Syntax.ForOfStatement; + this.left = left; + this.right = right; + this.body = body; + } + return ForOfStatement; + }()); + exports.ForOfStatement = ForOfStatement; + var ForStatement = (function () { + function ForStatement(init, test, update, body) { + this.type = syntax_1.Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + } + return ForStatement; + }()); + exports.ForStatement = ForStatement; + var FunctionDeclaration = (function () { + function FunctionDeclaration(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionDeclaration; + }()); + exports.FunctionDeclaration = FunctionDeclaration; + var FunctionExpression = (function () { + function FunctionExpression(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionExpression; + }()); + exports.FunctionExpression = FunctionExpression; + var Identifier = (function () { + function Identifier(name) { + this.type = syntax_1.Syntax.Identifier; + this.name = name; + } + return Identifier; + }()); + exports.Identifier = Identifier; + var IfStatement = (function () { + function IfStatement(test, consequent, alternate) { + this.type = syntax_1.Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return IfStatement; + }()); + exports.IfStatement = IfStatement; + var ImportDeclaration = (function () { + function ImportDeclaration(specifiers, source) { + this.type = syntax_1.Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = source; + } + return ImportDeclaration; + }()); + exports.ImportDeclaration = ImportDeclaration; + var ImportDefaultSpecifier = (function () { + function ImportDefaultSpecifier(local) { + this.type = syntax_1.Syntax.ImportDefaultSpecifier; + this.local = local; + } + return ImportDefaultSpecifier; + }()); + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + var ImportNamespaceSpecifier = (function () { + function ImportNamespaceSpecifier(local) { + this.type = syntax_1.Syntax.ImportNamespaceSpecifier; + this.local = local; + } + return ImportNamespaceSpecifier; + }()); + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + var ImportSpecifier = (function () { + function ImportSpecifier(local, imported) { + this.type = syntax_1.Syntax.ImportSpecifier; + this.local = local; + this.imported = imported; + } + return ImportSpecifier; + }()); + exports.ImportSpecifier = ImportSpecifier; + var LabeledStatement = (function () { + function LabeledStatement(label, body) { + this.type = syntax_1.Syntax.LabeledStatement; + this.label = label; + this.body = body; + } + return LabeledStatement; + }()); + exports.LabeledStatement = LabeledStatement; + var Literal = (function () { + function Literal(value, raw) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + } + return Literal; + }()); + exports.Literal = Literal; + var MetaProperty = (function () { + function MetaProperty(meta, property) { + this.type = syntax_1.Syntax.MetaProperty; + this.meta = meta; + this.property = property; + } + return MetaProperty; + }()); + exports.MetaProperty = MetaProperty; + var MethodDefinition = (function () { + function MethodDefinition(key, computed, value, kind, isStatic) { + this.type = syntax_1.Syntax.MethodDefinition; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.static = isStatic; + } + return MethodDefinition; + }()); + exports.MethodDefinition = MethodDefinition; + var Module = (function () { + function Module(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'module'; + } + return Module; + }()); + exports.Module = Module; + var NewExpression = (function () { + function NewExpression(callee, args) { + this.type = syntax_1.Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + } + return NewExpression; + }()); + exports.NewExpression = NewExpression; + var ObjectExpression = (function () { + function ObjectExpression(properties) { + this.type = syntax_1.Syntax.ObjectExpression; + this.properties = properties; + } + return ObjectExpression; + }()); + exports.ObjectExpression = ObjectExpression; + var ObjectPattern = (function () { + function ObjectPattern(properties) { + this.type = syntax_1.Syntax.ObjectPattern; + this.properties = properties; + } + return ObjectPattern; + }()); + exports.ObjectPattern = ObjectPattern; + var Property = (function () { + function Property(kind, key, computed, value, method, shorthand) { + this.type = syntax_1.Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + } + return Property; + }()); + exports.Property = Property; + var RegexLiteral = (function () { + function RegexLiteral(value, raw, pattern, flags) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + this.regex = { pattern: pattern, flags: flags }; + } + return RegexLiteral; + }()); + exports.RegexLiteral = RegexLiteral; + var RestElement = (function () { + function RestElement(argument) { + this.type = syntax_1.Syntax.RestElement; + this.argument = argument; + } + return RestElement; + }()); + exports.RestElement = RestElement; + var ReturnStatement = (function () { + function ReturnStatement(argument) { + this.type = syntax_1.Syntax.ReturnStatement; + this.argument = argument; + } + return ReturnStatement; + }()); + exports.ReturnStatement = ReturnStatement; + var Script = (function () { + function Script(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'script'; + } + return Script; + }()); + exports.Script = Script; + var SequenceExpression = (function () { + function SequenceExpression(expressions) { + this.type = syntax_1.Syntax.SequenceExpression; + this.expressions = expressions; + } + return SequenceExpression; + }()); + exports.SequenceExpression = SequenceExpression; + var SpreadElement = (function () { + function SpreadElement(argument) { + this.type = syntax_1.Syntax.SpreadElement; + this.argument = argument; + } + return SpreadElement; + }()); + exports.SpreadElement = SpreadElement; + var StaticMemberExpression = (function () { + function StaticMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = false; + this.object = object; + this.property = property; + } + return StaticMemberExpression; + }()); + exports.StaticMemberExpression = StaticMemberExpression; + var Super = (function () { + function Super() { + this.type = syntax_1.Syntax.Super; + } + return Super; + }()); + exports.Super = Super; + var SwitchCase = (function () { + function SwitchCase(test, consequent) { + this.type = syntax_1.Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + } + return SwitchCase; + }()); + exports.SwitchCase = SwitchCase; + var SwitchStatement = (function () { + function SwitchStatement(discriminant, cases) { + this.type = syntax_1.Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + } + return SwitchStatement; + }()); + exports.SwitchStatement = SwitchStatement; + var TaggedTemplateExpression = (function () { + function TaggedTemplateExpression(tag, quasi) { + this.type = syntax_1.Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + } + return TaggedTemplateExpression; + }()); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + var TemplateElement = (function () { + function TemplateElement(value, tail) { + this.type = syntax_1.Syntax.TemplateElement; + this.value = value; + this.tail = tail; + } + return TemplateElement; + }()); + exports.TemplateElement = TemplateElement; + var TemplateLiteral = (function () { + function TemplateLiteral(quasis, expressions) { + this.type = syntax_1.Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + } + return TemplateLiteral; + }()); + exports.TemplateLiteral = TemplateLiteral; + var ThisExpression = (function () { + function ThisExpression() { + this.type = syntax_1.Syntax.ThisExpression; + } + return ThisExpression; + }()); + exports.ThisExpression = ThisExpression; + var ThrowStatement = (function () { + function ThrowStatement(argument) { + this.type = syntax_1.Syntax.ThrowStatement; + this.argument = argument; + } + return ThrowStatement; + }()); + exports.ThrowStatement = ThrowStatement; + var TryStatement = (function () { + function TryStatement(block, handler, finalizer) { + this.type = syntax_1.Syntax.TryStatement; + this.block = block; + this.handler = handler; + this.finalizer = finalizer; + } + return TryStatement; + }()); + exports.TryStatement = TryStatement; + var UnaryExpression = (function () { + function UnaryExpression(operator, argument) { + this.type = syntax_1.Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + } + return UnaryExpression; + }()); + exports.UnaryExpression = UnaryExpression; + var UpdateExpression = (function () { + function UpdateExpression(operator, argument, prefix) { + this.type = syntax_1.Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = prefix; + } + return UpdateExpression; + }()); + exports.UpdateExpression = UpdateExpression; + var VariableDeclaration = (function () { + function VariableDeclaration(declarations, kind) { + this.type = syntax_1.Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + } + return VariableDeclaration; + }()); + exports.VariableDeclaration = VariableDeclaration; + var VariableDeclarator = (function () { + function VariableDeclarator(id, init) { + this.type = syntax_1.Syntax.VariableDeclarator; + this.id = id; + this.init = init; + } + return VariableDeclarator; + }()); + exports.VariableDeclarator = VariableDeclarator; + var WhileStatement = (function () { + function WhileStatement(test, body) { + this.type = syntax_1.Syntax.WhileStatement; + this.test = test; + this.body = body; + } + return WhileStatement; + }()); + exports.WhileStatement = WhileStatement; + var WithStatement = (function () { + function WithStatement(object, body) { + this.type = syntax_1.Syntax.WithStatement; + this.object = object; + this.body = body; + } + return WithStatement; + }()); + exports.WithStatement = WithStatement; + var YieldExpression = (function () { + function YieldExpression(argument, delegate) { + this.type = syntax_1.Syntax.YieldExpression; + this.argument = argument; + this.delegate = delegate; + } + return YieldExpression; + }()); + exports.YieldExpression = YieldExpression; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __nested_webpack_require_80491__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __nested_webpack_require_80491__(9); + var error_handler_1 = __nested_webpack_require_80491__(10); + var messages_1 = __nested_webpack_require_80491__(11); + var Node = __nested_webpack_require_80491__(7); + var scanner_1 = __nested_webpack_require_80491__(12); + var syntax_1 = __nested_webpack_require_80491__(2); + var token_1 = __nested_webpack_require_80491__(13); + var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; + var Parser = (function () { + function Parser(code, options, delegate) { + if (options === void 0) { options = {}; } + this.config = { + range: (typeof options.range === 'boolean') && options.range, + loc: (typeof options.loc === 'boolean') && options.loc, + source: null, + tokens: (typeof options.tokens === 'boolean') && options.tokens, + comment: (typeof options.comment === 'boolean') && options.comment, + tolerant: (typeof options.tolerant === 'boolean') && options.tolerant + }; + if (this.config.loc && options.source && options.source !== null) { + this.config.source = String(options.source); + } + this.delegate = delegate; + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = this.config.tolerant; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = this.config.comment; + this.operatorPrecedence = { + ')': 0, + ';': 0, + ',': 0, + '=': 0, + ']': 0, + '||': 1, + '&&': 2, + '|': 3, + '^': 4, + '&': 5, + '==': 6, + '!=': 6, + '===': 6, + '!==': 6, + '<': 7, + '>': 7, + '<=': 7, + '>=': 7, + '<<': 8, + '>>': 8, + '>>>': 8, + '+': 9, + '-': 9, + '*': 11, + '/': 11, + '%': 11 + }; + this.lookahead = { + type: 2 /* EOF */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: 0, + start: 0, + end: 0 + }; + this.hasLineTerminator = false; + this.context = { + isModule: false, + await: false, + allowIn: true, + allowStrictDirective: true, + allowYield: true, + firstCoverInitializedNameError: null, + isAssignmentTarget: false, + isBindingElement: false, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + labelSet: {}, + strict: false + }; + this.tokens = []; + this.startMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.lastMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.nextToken(); + this.lastMarker = { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + } + Parser.prototype.throwError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + throw this.errorHandler.createError(index, line, column, msg); + }; + Parser.prototype.tolerateError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.scanner.lineNumber; + var column = this.lastMarker.column + 1; + this.errorHandler.tolerateError(index, line, column, msg); + }; + // Throw an exception because of the token. + Parser.prototype.unexpectedTokenError = function (token, message) { + var msg = message || messages_1.Messages.UnexpectedToken; + var value; + if (token) { + if (!message) { + msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : + (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : + (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : + (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : + (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : + messages_1.Messages.UnexpectedToken; + if (token.type === 4 /* Keyword */) { + if (this.scanner.isFutureReservedWord(token.value)) { + msg = messages_1.Messages.UnexpectedReserved; + } + else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { + msg = messages_1.Messages.StrictReservedWord; + } + } + } + value = token.value; + } + else { + value = 'ILLEGAL'; + } + msg = msg.replace('%0', value); + if (token && typeof token.lineNumber === 'number') { + var index = token.start; + var line = token.lineNumber; + var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; + var column = token.start - lastMarkerLineStart + 1; + return this.errorHandler.createError(index, line, column, msg); + } + else { + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + return this.errorHandler.createError(index, line, column, msg); + } + }; + Parser.prototype.throwUnexpectedToken = function (token, message) { + throw this.unexpectedTokenError(token, message); + }; + Parser.prototype.tolerateUnexpectedToken = function (token, message) { + this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); + }; + Parser.prototype.collectComments = function () { + if (!this.config.comment) { + this.scanner.scanComments(); + } + else { + var comments = this.scanner.scanComments(); + if (comments.length > 0 && this.delegate) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var node = void 0; + node = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: this.scanner.source.slice(e.slice[0], e.slice[1]) + }; + if (this.config.range) { + node.range = e.range; + } + if (this.config.loc) { + node.loc = e.loc; + } + var metadata = { + start: { + line: e.loc.start.line, + column: e.loc.start.column, + offset: e.range[0] + }, + end: { + line: e.loc.end.line, + column: e.loc.end.column, + offset: e.range[1] + } + }; + this.delegate(node, metadata); + } + } + } + }; + // From internal representation to an external structure + Parser.prototype.getTokenRaw = function (token) { + return this.scanner.source.slice(token.start, token.end); + }; + Parser.prototype.convertToken = function (token) { + var t = { + type: token_1.TokenName[token.type], + value: this.getTokenRaw(token) + }; + if (this.config.range) { + t.range = [token.start, token.end]; + } + if (this.config.loc) { + t.loc = { + start: { + line: this.startMarker.line, + column: this.startMarker.column + }, + end: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + } + }; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + t.regex = { pattern: pattern, flags: flags }; + } + return t; + }; + Parser.prototype.nextToken = function () { + var token = this.lookahead; + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + this.collectComments(); + if (this.scanner.index !== this.startMarker.index) { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + } + var next = this.scanner.lex(); + this.hasLineTerminator = (token.lineNumber !== next.lineNumber); + if (next && this.context.strict && next.type === 3 /* Identifier */) { + if (this.scanner.isStrictModeReservedWord(next.value)) { + next.type = 4 /* Keyword */; + } + } + this.lookahead = next; + if (this.config.tokens && next.type !== 2 /* EOF */) { + this.tokens.push(this.convertToken(next)); + } + return token; + }; + Parser.prototype.nextRegexToken = function () { + this.collectComments(); + var token = this.scanner.scanRegExp(); + if (this.config.tokens) { + // Pop the previous token, '/' or '/=' + // This is added from the lookahead token. + this.tokens.pop(); + this.tokens.push(this.convertToken(token)); + } + // Prime the next lookahead. + this.lookahead = token; + this.nextToken(); + return token; + }; + Parser.prototype.createNode = function () { + return { + index: this.startMarker.index, + line: this.startMarker.line, + column: this.startMarker.column + }; + }; + Parser.prototype.startNode = function (token, lastLineStart) { + if (lastLineStart === void 0) { lastLineStart = 0; } + var column = token.start - token.lineStart; + var line = token.lineNumber; + if (column < 0) { + column += lastLineStart; + line--; + } + return { + index: token.start, + line: line, + column: column + }; + }; + Parser.prototype.finalize = function (marker, node) { + if (this.config.range) { + node.range = [marker.index, this.lastMarker.index]; + } + if (this.config.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.column, + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column + } + }; + if (this.config.source) { + node.loc.source = this.config.source; + } + } + if (this.delegate) { + var metadata = { + start: { + line: marker.line, + column: marker.column, + offset: marker.index + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column, + offset: this.lastMarker.index + } + }; + this.delegate(node, metadata); + } + return node; + }; + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + Parser.prototype.expect = function (value) { + var token = this.nextToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). + Parser.prototype.expectCommaSeparator = function () { + if (this.config.tolerant) { + var token = this.lookahead; + if (token.type === 7 /* Punctuator */ && token.value === ',') { + this.nextToken(); + } + else if (token.type === 7 /* Punctuator */ && token.value === ';') { + this.nextToken(); + this.tolerateUnexpectedToken(token); + } + else { + this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); + } + } + else { + this.expect(','); + } + }; + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + Parser.prototype.expectKeyword = function (keyword) { + var token = this.nextToken(); + if (token.type !== 4 /* Keyword */ || token.value !== keyword) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next token matches the specified punctuator. + Parser.prototype.match = function (value) { + return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; + }; + // Return true if the next token matches the specified keyword + Parser.prototype.matchKeyword = function (keyword) { + return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; + }; + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + Parser.prototype.matchContextualKeyword = function (keyword) { + return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; + }; + // Return true if the next token is an assignment operator + Parser.prototype.matchAssign = function () { + if (this.lookahead.type !== 7 /* Punctuator */) { + return false; + } + var op = this.lookahead.value; + return op === '=' || + op === '*=' || + op === '**=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + }; + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + Parser.prototype.isolateCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + if (this.context.firstCoverInitializedNameError !== null) { + this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); + } + this.context.isBindingElement = previousIsBindingElement; + this.context.isAssignmentTarget = previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; + return result; + }; + Parser.prototype.inheritCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; + this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; + return result; + }; + Parser.prototype.consumeSemicolon = function () { + if (this.match(';')) { + this.nextToken(); + } + else if (!this.hasLineTerminator) { + if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { + this.throwUnexpectedToken(this.lookahead); + } + this.lastMarker.index = this.startMarker.index; + this.lastMarker.line = this.startMarker.line; + this.lastMarker.column = this.startMarker.column; + } + }; + // https://tc39.github.io/ecma262/#sec-primary-expression + Parser.prototype.parsePrimaryExpression = function () { + var node = this.createNode(); + var expr; + var token, raw; + switch (this.lookahead.type) { + case 3 /* Identifier */: + if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { + this.tolerateUnexpectedToken(this.lookahead); + } + expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); + break; + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + if (this.context.strict && this.lookahead.octal) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 1 /* BooleanLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); + break; + case 5 /* NullLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(null, raw)); + break; + case 10 /* Template */: + expr = this.parseTemplateLiteral(); + break; + case 7 /* Punctuator */: + switch (this.lookahead.value) { + case '(': + this.context.isBindingElement = false; + expr = this.inheritCoverGrammar(this.parseGroupExpression); + break; + case '[': + expr = this.inheritCoverGrammar(this.parseArrayInitializer); + break; + case '{': + expr = this.inheritCoverGrammar(this.parseObjectInitializer); + break; + case '/': + case '/=': + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.scanner.index = this.startMarker.index; + token = this.nextRegexToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + break; + case 4 /* Keyword */: + if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseIdentifierName(); + } + else if (!this.context.strict && this.matchKeyword('let')) { + expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); + } + else { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + if (this.matchKeyword('function')) { + expr = this.parseFunctionExpression(); + } + else if (this.matchKeyword('this')) { + this.nextToken(); + expr = this.finalize(node, new Node.ThisExpression()); + } + else if (this.matchKeyword('class')) { + expr = this.parseClassExpression(); + } + else { + expr = this.throwUnexpectedToken(this.nextToken()); + } + } + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-array-initializer + Parser.prototype.parseSpreadElement = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadElement(arg)); + }; + Parser.prototype.parseArrayInitializer = function () { + var node = this.createNode(); + var elements = []; + this.expect('['); + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else if (this.match('...')) { + var element = this.parseSpreadElement(); + if (!this.match(']')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.expect(','); + } + elements.push(element); + } + else { + elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayExpression(elements)); + }; + // https://tc39.github.io/ecma262/#sec-object-initializer + Parser.prototype.parsePropertyMethod = function (params) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = params.simple; + var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); + if (this.context.strict && params.firstRestricted) { + this.tolerateUnexpectedToken(params.firstRestricted, params.message); + } + if (this.context.strict && params.stricted) { + this.tolerateUnexpectedToken(params.stricted, params.message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + return body; + }; + Parser.prototype.parsePropertyMethodFunction = function () { + var isGenerator = false; + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + Parser.prototype.parsePropertyMethodAsyncFunction = function () { + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = false; + this.context.await = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); + }; + Parser.prototype.parseObjectPropertyKey = function () { + var node = this.createNode(); + var token = this.nextToken(); + var key; + switch (token.type) { + case 8 /* StringLiteral */: + case 6 /* NumericLiteral */: + if (this.context.strict && token.octal) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); + } + var raw = this.getTokenRaw(token); + key = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 3 /* Identifier */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 4 /* Keyword */: + key = this.finalize(node, new Node.Identifier(token.value)); + break; + case 7 /* Punctuator */: + if (token.value === '[') { + key = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.expect(']'); + } + else { + key = this.throwUnexpectedToken(token); + } + break; + default: + key = this.throwUnexpectedToken(token); + } + return key; + }; + Parser.prototype.isPropertyKey = function (key, value) { + return (key.type === syntax_1.Syntax.Identifier && key.name === value) || + (key.type === syntax_1.Syntax.Literal && key.value === value); + }; + Parser.prototype.parseObjectProperty = function (hasProto) { + var node = this.createNode(); + var token = this.lookahead; + var kind; + var key = null; + var value = null; + var computed = false; + var method = false; + var shorthand = false; + var isAsync = false; + if (token.type === 3 /* Identifier */) { + var id = token.value; + this.nextToken(); + computed = this.match('['); + isAsync = !this.hasLineTerminator && (id === 'async') && + !this.match(':') && !this.match('(') && !this.match('*') && !this.match(','); + key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); + } + else if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + else { + if (!key) { + this.throwUnexpectedToken(this.lookahead); + } + kind = 'init'; + if (this.match(':') && !isAsync) { + if (!computed && this.isPropertyKey(key, '__proto__')) { + if (hasProto.value) { + this.tolerateError(messages_1.Messages.DuplicateProtoProperty); + } + hasProto.value = true; + } + this.nextToken(); + value = this.inheritCoverGrammar(this.parseAssignmentExpression); + } + else if (this.match('(')) { + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + else if (token.type === 3 /* Identifier */) { + var id = this.finalize(node, new Node.Identifier(token.value)); + if (this.match('=')) { + this.context.firstCoverInitializedNameError = this.lookahead; + this.nextToken(); + shorthand = true; + var init = this.isolateCoverGrammar(this.parseAssignmentExpression); + value = this.finalize(node, new Node.AssignmentPattern(id, init)); + } + else { + shorthand = true; + value = id; + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectInitializer = function () { + var node = this.createNode(); + this.expect('{'); + var properties = []; + var hasProto = { value: false }; + while (!this.match('}')) { + properties.push(this.parseObjectProperty(hasProto)); + if (!this.match('}')) { + this.expectCommaSeparator(); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectExpression(properties)); + }; + // https://tc39.github.io/ecma262/#sec-template-literals + Parser.prototype.parseTemplateHead = function () { + assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateElement = function () { + if (this.lookahead.type !== 10 /* Template */) { + this.throwUnexpectedToken(); + } + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateLiteral = function () { + var node = this.createNode(); + var expressions = []; + var quasis = []; + var quasi = this.parseTemplateHead(); + quasis.push(quasi); + while (!quasi.tail) { + expressions.push(this.parseExpression()); + quasi = this.parseTemplateElement(); + quasis.push(quasi); + } + return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); + }; + // https://tc39.github.io/ecma262/#sec-grouping-operator + Parser.prototype.reinterpretExpressionAsPattern = function (expr) { + switch (expr.type) { + case syntax_1.Syntax.Identifier: + case syntax_1.Syntax.MemberExpression: + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.AssignmentPattern: + break; + case syntax_1.Syntax.SpreadElement: + expr.type = syntax_1.Syntax.RestElement; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.ArrayExpression: + expr.type = syntax_1.Syntax.ArrayPattern; + for (var i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + this.reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectExpression: + expr.type = syntax_1.Syntax.ObjectPattern; + for (var i = 0; i < expr.properties.length; i++) { + this.reinterpretExpressionAsPattern(expr.properties[i].value); + } + break; + case syntax_1.Syntax.AssignmentExpression: + expr.type = syntax_1.Syntax.AssignmentPattern; + delete expr.operator; + this.reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + }; + Parser.prototype.parseGroupExpression = function () { + var expr; + this.expect('('); + if (this.match(')')) { + this.nextToken(); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [], + async: false + }; + } + else { + var startToken = this.lookahead; + var params = []; + if (this.match('...')) { + expr = this.parseRestElement(params); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + else { + var arrow = false; + this.context.isBindingElement = true; + expr = this.inheritCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + this.context.isAssignmentTarget = false; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + if (this.match(')')) { + this.nextToken(); + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else if (this.match('...')) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + expressions.push(this.parseRestElement(params)); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + this.context.isBindingElement = false; + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else { + expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + } + if (arrow) { + break; + } + } + if (!arrow) { + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + } + if (!arrow) { + this.expect(')'); + if (this.match('=>')) { + if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + if (!arrow) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + if (expr.type === syntax_1.Syntax.SequenceExpression) { + for (var i = 0; i < expr.expressions.length; i++) { + this.reinterpretExpressionAsPattern(expr.expressions[i]); + } + } + else { + this.reinterpretExpressionAsPattern(expr); + } + var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); + expr = { + type: ArrowParameterPlaceHolder, + params: parameters, + async: false + }; + } + } + this.context.isBindingElement = false; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions + Parser.prototype.parseArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.isIdentifierName = function (token) { + return token.type === 3 /* Identifier */ || + token.type === 4 /* Keyword */ || + token.type === 1 /* BooleanLiteral */ || + token.type === 5 /* NullLiteral */; + }; + Parser.prototype.parseIdentifierName = function () { + var node = this.createNode(); + var token = this.nextToken(); + if (!this.isIdentifierName(token)) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseNewExpression = function () { + var node = this.createNode(); + var id = this.parseIdentifierName(); + assert_1.assert(id.name === 'new', 'New expression must start with `new`'); + var expr; + if (this.match('.')) { + this.nextToken(); + if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { + var property = this.parseIdentifierName(); + expr = new Node.MetaProperty(id, property); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); + var args = this.match('(') ? this.parseArguments() : []; + expr = new Node.NewExpression(callee, args); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return this.finalize(node, expr); + }; + Parser.prototype.parseAsyncArgument = function () { + var arg = this.parseAssignmentExpression(); + this.context.firstCoverInitializedNameError = null; + return arg; + }; + Parser.prototype.parseAsyncArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAsyncArgument); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { + var startToken = this.lookahead; + var maybeAsync = this.matchContextualKeyword('async'); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var expr; + if (this.matchKeyword('super') && this.context.inFunctionBody) { + expr = this.createNode(); + this.nextToken(); + expr = this.finalize(expr, new Node.Super()); + if (!this.match('(') && !this.match('.') && !this.match('[')) { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + } + while (true) { + if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); + } + else if (this.match('(')) { + var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); + this.context.isBindingElement = false; + this.context.isAssignmentTarget = false; + var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); + expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); + if (asyncArrow && this.match('=>')) { + for (var i = 0; i < args.length; ++i) { + this.reinterpretExpressionAsPattern(args[i]); + } + expr = { + type: ArrowParameterPlaceHolder, + params: args, + async: true + }; + } + } + else if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + this.context.allowIn = previousAllowIn; + return expr; + }; + Parser.prototype.parseSuper = function () { + var node = this.createNode(); + this.expectKeyword('super'); + if (!this.match('[') && !this.match('.')) { + this.throwUnexpectedToken(this.lookahead); + } + return this.finalize(node, new Node.Super()); + }; + Parser.prototype.parseLeftHandSideExpression = function () { + assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); + var node = this.startNode(this.lookahead); + var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : + this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + while (true) { + if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); + } + else if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-update-expressions + Parser.prototype.parseUpdateExpression = function () { + var expr; + var startToken = this.lookahead; + if (this.match('++') || this.match('--')) { + var node = this.startNode(startToken); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPrefix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + var prefix = true; + expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { + if (this.match('++') || this.match('--')) { + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPostfix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var operator = this.nextToken().value; + var prefix = false; + expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-unary-operators + Parser.prototype.parseAwaitExpression = function () { + var node = this.createNode(); + this.nextToken(); + var argument = this.parseUnaryExpression(); + return this.finalize(node, new Node.AwaitExpression(argument)); + }; + Parser.prototype.parseUnaryExpression = function () { + var expr; + if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || + this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { + var node = this.startNode(this.lookahead); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); + if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { + this.tolerateError(messages_1.Messages.StrictDelete); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else if (this.context.await && this.matchContextualKeyword('await')) { + expr = this.parseAwaitExpression(); + } + else { + expr = this.parseUpdateExpression(); + } + return expr; + }; + Parser.prototype.parseExponentiationExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-exp-operator + // https://tc39.github.io/ecma262/#sec-multiplicative-operators + // https://tc39.github.io/ecma262/#sec-additive-operators + // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators + // https://tc39.github.io/ecma262/#sec-relational-operators + // https://tc39.github.io/ecma262/#sec-equality-operators + // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators + // https://tc39.github.io/ecma262/#sec-binary-logical-operators + Parser.prototype.binaryPrecedence = function (token) { + var op = token.value; + var precedence; + if (token.type === 7 /* Punctuator */) { + precedence = this.operatorPrecedence[op] || 0; + } + else if (token.type === 4 /* Keyword */) { + precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; + } + else { + precedence = 0; + } + return precedence; + }; + Parser.prototype.parseBinaryExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); + var token = this.lookahead; + var prec = this.binaryPrecedence(token); + if (prec > 0) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var markers = [startToken, this.lookahead]; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + var stack = [left, token.value, right]; + var precedences = [prec]; + while (true) { + prec = this.binaryPrecedence(this.lookahead); + if (prec <= 0) { + break; + } + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { + right = stack.pop(); + var operator = stack.pop(); + precedences.pop(); + left = stack.pop(); + markers.pop(); + var node = this.startNode(markers[markers.length - 1]); + stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); + } + // Shift. + stack.push(this.nextToken().value); + precedences.push(prec); + markers.push(this.lookahead); + stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); + } + // Final reduce to clean-up the stack. + var i = stack.length - 1; + expr = stack[i]; + var lastMarker = markers.pop(); + while (i > 1) { + var marker = markers.pop(); + var lastLineStart = lastMarker && lastMarker.lineStart; + var node = this.startNode(marker, lastLineStart); + var operator = stack[i - 1]; + expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); + i -= 2; + lastMarker = marker; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-conditional-operator + Parser.prototype.parseConditionalExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseBinaryExpression); + if (this.match('?')) { + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + this.expect(':'); + var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-assignment-operators + Parser.prototype.checkPatternParam = function (options, param) { + switch (param.type) { + case syntax_1.Syntax.Identifier: + this.validateParam(options, param, param.name); + break; + case syntax_1.Syntax.RestElement: + this.checkPatternParam(options, param.argument); + break; + case syntax_1.Syntax.AssignmentPattern: + this.checkPatternParam(options, param.left); + break; + case syntax_1.Syntax.ArrayPattern: + for (var i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + this.checkPatternParam(options, param.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectPattern: + for (var i = 0; i < param.properties.length; i++) { + this.checkPatternParam(options, param.properties[i].value); + } + break; + default: + break; + } + options.simple = options.simple && (param instanceof Node.Identifier); + }; + Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { + var params = [expr]; + var options; + var asyncArrow = false; + switch (expr.type) { + case syntax_1.Syntax.Identifier: + break; + case ArrowParameterPlaceHolder: + params = expr.params; + asyncArrow = expr.async; + break; + default: + return null; + } + options = { + simple: true, + paramSet: {} + }; + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.AssignmentPattern) { + if (param.right.type === syntax_1.Syntax.YieldExpression) { + if (param.right.argument) { + this.throwUnexpectedToken(this.lookahead); + } + param.right.type = syntax_1.Syntax.Identifier; + param.right.name = 'yield'; + delete param.right.argument; + delete param.right.delegate; + } + } + else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { + this.throwUnexpectedToken(this.lookahead); + } + this.checkPatternParam(options, param); + params[i] = param; + } + if (this.context.strict || !this.context.allowYield) { + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.YieldExpression) { + this.throwUnexpectedToken(this.lookahead); + } + } + } + if (options.message === messages_1.Messages.StrictParamDupe) { + var token = this.context.strict ? options.stricted : options.firstRestricted; + this.throwUnexpectedToken(token, options.message); + } + return { + simple: options.simple, + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.parseAssignmentExpression = function () { + var expr; + if (!this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseYieldExpression(); + } + else { + var startToken = this.lookahead; + var token = startToken; + expr = this.parseConditionalExpression(); + if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { + if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { + var arg = this.parsePrimaryExpression(); + this.reinterpretExpressionAsPattern(arg); + expr = { + type: ArrowParameterPlaceHolder, + params: [arg], + async: true + }; + } + } + if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { + // https://tc39.github.io/ecma262/#sec-arrow-function-definitions + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var isAsync = expr.async; + var list = this.reinterpretAsCoverFormalsList(expr); + if (list) { + if (this.hasLineTerminator) { + this.tolerateUnexpectedToken(this.lookahead); + } + this.context.firstCoverInitializedNameError = null; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = list.simple; + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = true; + this.context.await = isAsync; + var node = this.startNode(startToken); + this.expect('=>'); + var body = void 0; + if (this.match('{')) { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + body = this.parseFunctionSourceElements(); + this.context.allowIn = previousAllowIn; + } + else { + body = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + var expression = body.type !== syntax_1.Syntax.BlockStatement; + if (this.context.strict && list.firstRestricted) { + this.throwUnexpectedToken(list.firstRestricted, list.message); + } + if (this.context.strict && list.stricted) { + this.tolerateUnexpectedToken(list.stricted, list.message); + } + expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : + this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + } + } + else { + if (this.matchAssign()) { + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { + var id = expr; + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); + } + if (this.scanner.isStrictModeReservedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + } + if (!this.match('=')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + this.reinterpretExpressionAsPattern(expr); + } + token = this.nextToken(); + var operator = token.value; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); + this.context.firstCoverInitializedNameError = null; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-comma-operator + Parser.prototype.parseExpression = function () { + var startToken = this.lookahead; + var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-block + Parser.prototype.parseStatementListItem = function () { + var statement; + this.context.isAssignmentTarget = true; + this.context.isBindingElement = true; + if (this.lookahead.type === 4 /* Keyword */) { + switch (this.lookahead.value) { + case 'export': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); + } + statement = this.parseExportDeclaration(); + break; + case 'import': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); + } + statement = this.parseImportDeclaration(); + break; + case 'const': + statement = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'class': + statement = this.parseClassDeclaration(); + break; + case 'let': + statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); + break; + default: + statement = this.parseStatement(); + break; + } + } + else { + statement = this.parseStatement(); + } + return statement; + }; + Parser.prototype.parseBlock = function () { + var node = this.createNode(); + this.expect('{'); + var block = []; + while (true) { + if (this.match('}')) { + break; + } + block.push(this.parseStatementListItem()); + } + this.expect('}'); + return this.finalize(node, new Node.BlockStatement(block)); + }; + // https://tc39.github.io/ecma262/#sec-let-and-const-declarations + Parser.prototype.parseLexicalBinding = function (kind, options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, kind); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (kind === 'const') { + if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else { + this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); + } + } + } + else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { + this.expect('='); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseBindingList = function (kind, options) { + var list = [this.parseLexicalBinding(kind, options)]; + while (this.match(',')) { + this.nextToken(); + list.push(this.parseLexicalBinding(kind, options)); + } + return list; + }; + Parser.prototype.isLexicalDeclaration = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + return (next.type === 3 /* Identifier */) || + (next.type === 7 /* Punctuator */ && next.value === '[') || + (next.type === 7 /* Punctuator */ && next.value === '{') || + (next.type === 4 /* Keyword */ && next.value === 'let') || + (next.type === 4 /* Keyword */ && next.value === 'yield'); + }; + Parser.prototype.parseLexicalDeclaration = function (options) { + var node = this.createNode(); + var kind = this.nextToken().value; + assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + var declarations = this.parseBindingList(kind, options); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); + }; + // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns + Parser.prototype.parseBindingRestElement = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params, kind); + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseArrayPattern = function (params, kind) { + var node = this.createNode(); + this.expect('['); + var elements = []; + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else { + if (this.match('...')) { + elements.push(this.parseBindingRestElement(params, kind)); + break; + } + else { + elements.push(this.parsePatternWithDefault(params, kind)); + } + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayPattern(elements)); + }; + Parser.prototype.parsePropertyPattern = function (params, kind) { + var node = this.createNode(); + var computed = false; + var shorthand = false; + var method = false; + var key; + var value; + if (this.lookahead.type === 3 /* Identifier */) { + var keyToken = this.lookahead; + key = this.parseVariableIdentifier(); + var init = this.finalize(node, new Node.Identifier(keyToken.value)); + if (this.match('=')) { + params.push(keyToken); + shorthand = true; + this.nextToken(); + var expr = this.parseAssignmentExpression(); + value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); + } + else if (!this.match(':')) { + params.push(keyToken); + shorthand = true; + value = init; + } + else { + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectPattern = function (params, kind) { + var node = this.createNode(); + var properties = []; + this.expect('{'); + while (!this.match('}')) { + properties.push(this.parsePropertyPattern(params, kind)); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectPattern(properties)); + }; + Parser.prototype.parsePattern = function (params, kind) { + var pattern; + if (this.match('[')) { + pattern = this.parseArrayPattern(params, kind); + } + else if (this.match('{')) { + pattern = this.parseObjectPattern(params, kind); + } + else { + if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); + } + params.push(this.lookahead); + pattern = this.parseVariableIdentifier(kind); + } + return pattern; + }; + Parser.prototype.parsePatternWithDefault = function (params, kind) { + var startToken = this.lookahead; + var pattern = this.parsePattern(params, kind); + if (this.match('=')) { + this.nextToken(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowYield = previousAllowYield; + pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); + } + return pattern; + }; + // https://tc39.github.io/ecma262/#sec-variable-statement + Parser.prototype.parseVariableIdentifier = function (kind) { + var node = this.createNode(); + var token = this.nextToken(); + if (token.type === 4 /* Keyword */ && token.value === 'yield') { + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else if (!this.context.allowYield) { + this.throwUnexpectedToken(token); + } + } + else if (token.type !== 3 /* Identifier */) { + if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else { + if (this.context.strict || token.value !== 'let' || kind !== 'var') { + this.throwUnexpectedToken(token); + } + } + } + else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { + this.tolerateUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseVariableDeclaration = function (options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, 'var'); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { + this.expect('='); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseVariableDeclarationList = function (options) { + var opt = { inFor: options.inFor }; + var list = []; + list.push(this.parseVariableDeclaration(opt)); + while (this.match(',')) { + this.nextToken(); + list.push(this.parseVariableDeclaration(opt)); + } + return list; + }; + Parser.prototype.parseVariableStatement = function () { + var node = this.createNode(); + this.expectKeyword('var'); + var declarations = this.parseVariableDeclarationList({ inFor: false }); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); + }; + // https://tc39.github.io/ecma262/#sec-empty-statement + Parser.prototype.parseEmptyStatement = function () { + var node = this.createNode(); + this.expect(';'); + return this.finalize(node, new Node.EmptyStatement()); + }; + // https://tc39.github.io/ecma262/#sec-expression-statement + Parser.prototype.parseExpressionStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ExpressionStatement(expr)); + }; + // https://tc39.github.io/ecma262/#sec-if-statement + Parser.prototype.parseIfClause = function () { + if (this.context.strict && this.matchKeyword('function')) { + this.tolerateError(messages_1.Messages.StrictFunction); + } + return this.parseStatement(); + }; + Parser.prototype.parseIfStatement = function () { + var node = this.createNode(); + var consequent; + var alternate = null; + this.expectKeyword('if'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + consequent = this.parseIfClause(); + if (this.matchKeyword('else')) { + this.nextToken(); + alternate = this.parseIfClause(); + } + } + return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); + }; + // https://tc39.github.io/ecma262/#sec-do-while-statement + Parser.prototype.parseDoWhileStatement = function () { + var node = this.createNode(); + this.expectKeyword('do'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + var body = this.parseStatement(); + this.context.inIteration = previousInIteration; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + } + else { + this.expect(')'); + if (this.match(';')) { + this.nextToken(); + } + } + return this.finalize(node, new Node.DoWhileStatement(body, test)); + }; + // https://tc39.github.io/ecma262/#sec-while-statement + Parser.prototype.parseWhileStatement = function () { + var node = this.createNode(); + var body; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.parseStatement(); + this.context.inIteration = previousInIteration; + } + return this.finalize(node, new Node.WhileStatement(test, body)); + }; + // https://tc39.github.io/ecma262/#sec-for-statement + // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements + Parser.prototype.parseForStatement = function () { + var init = null; + var test = null; + var update = null; + var forIn = true; + var left, right; + var node = this.createNode(); + this.expectKeyword('for'); + this.expect('('); + if (this.match(';')) { + this.nextToken(); + } + else { + if (this.matchKeyword('var')) { + init = this.createNode(); + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseVariableDeclarationList({ inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && this.matchKeyword('in')) { + var decl = declarations[0]; + if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { + this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); + } + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.expect(';'); + } + } + else if (this.matchKeyword('const') || this.matchKeyword('let')) { + init = this.createNode(); + var kind = this.nextToken().value; + if (!this.context.strict && this.lookahead.value === 'in') { + init = this.finalize(init, new Node.Identifier(kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseBindingList(kind, { inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + this.consumeSemicolon(); + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + } + } + } + else { + var initStartToken = this.lookahead; + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + init = this.inheritCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + if (this.matchKeyword('in')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForIn); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseExpression(); + init = null; + } + else if (this.matchContextualKeyword('of')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + if (this.match(',')) { + var initSeq = [init]; + while (this.match(',')) { + this.nextToken(); + initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); + } + this.expect(';'); + } + } + } + if (typeof left === 'undefined') { + if (!this.match(';')) { + test = this.parseExpression(); + } + this.expect(';'); + if (!this.match(')')) { + update = this.parseExpression(); + } + } + var body; + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.isolateCoverGrammar(this.parseStatement); + this.context.inIteration = previousInIteration; + } + return (typeof left === 'undefined') ? + this.finalize(node, new Node.ForStatement(init, test, update, body)) : + forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : + this.finalize(node, new Node.ForOfStatement(left, right, body)); + }; + // https://tc39.github.io/ecma262/#sec-continue-statement + Parser.prototype.parseContinueStatement = function () { + var node = this.createNode(); + this.expectKeyword('continue'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + label = id; + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration) { + this.throwError(messages_1.Messages.IllegalContinue); + } + return this.finalize(node, new Node.ContinueStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-break-statement + Parser.prototype.parseBreakStatement = function () { + var node = this.createNode(); + this.expectKeyword('break'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + label = id; + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration && !this.context.inSwitch) { + this.throwError(messages_1.Messages.IllegalBreak); + } + return this.finalize(node, new Node.BreakStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-return-statement + Parser.prototype.parseReturnStatement = function () { + if (!this.context.inFunctionBody) { + this.tolerateError(messages_1.Messages.IllegalReturn); + } + var node = this.createNode(); + this.expectKeyword('return'); + var hasArgument = (!this.match(';') && !this.match('}') && + !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */) || + this.lookahead.type === 8 /* StringLiteral */ || + this.lookahead.type === 10 /* Template */; + var argument = hasArgument ? this.parseExpression() : null; + this.consumeSemicolon(); + return this.finalize(node, new Node.ReturnStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-with-statement + Parser.prototype.parseWithStatement = function () { + if (this.context.strict) { + this.tolerateError(messages_1.Messages.StrictModeWith); + } + var node = this.createNode(); + var body; + this.expectKeyword('with'); + this.expect('('); + var object = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + body = this.parseStatement(); + } + return this.finalize(node, new Node.WithStatement(object, body)); + }; + // https://tc39.github.io/ecma262/#sec-switch-statement + Parser.prototype.parseSwitchCase = function () { + var node = this.createNode(); + var test; + if (this.matchKeyword('default')) { + this.nextToken(); + test = null; + } + else { + this.expectKeyword('case'); + test = this.parseExpression(); + } + this.expect(':'); + var consequent = []; + while (true) { + if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { + break; + } + consequent.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.SwitchCase(test, consequent)); + }; + Parser.prototype.parseSwitchStatement = function () { + var node = this.createNode(); + this.expectKeyword('switch'); + this.expect('('); + var discriminant = this.parseExpression(); + this.expect(')'); + var previousInSwitch = this.context.inSwitch; + this.context.inSwitch = true; + var cases = []; + var defaultFound = false; + this.expect('{'); + while (true) { + if (this.match('}')) { + break; + } + var clause = this.parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + this.expect('}'); + this.context.inSwitch = previousInSwitch; + return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); + }; + // https://tc39.github.io/ecma262/#sec-labelled-statements + Parser.prototype.parseLabelledStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + var statement; + if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { + this.nextToken(); + var id = expr; + var key = '$' + id.name; + if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); + } + this.context.labelSet[key] = true; + var body = void 0; + if (this.matchKeyword('class')) { + this.tolerateUnexpectedToken(this.lookahead); + body = this.parseClassDeclaration(); + } + else if (this.matchKeyword('function')) { + var token = this.lookahead; + var declaration = this.parseFunctionDeclaration(); + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); + } + else if (declaration.generator) { + this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); + } + body = declaration; + } + else { + body = this.parseStatement(); + } + delete this.context.labelSet[key]; + statement = new Node.LabeledStatement(id, body); + } + else { + this.consumeSemicolon(); + statement = new Node.ExpressionStatement(expr); + } + return this.finalize(node, statement); + }; + // https://tc39.github.io/ecma262/#sec-throw-statement + Parser.prototype.parseThrowStatement = function () { + var node = this.createNode(); + this.expectKeyword('throw'); + if (this.hasLineTerminator) { + this.throwError(messages_1.Messages.NewlineAfterThrow); + } + var argument = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ThrowStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-try-statement + Parser.prototype.parseCatchClause = function () { + var node = this.createNode(); + this.expectKeyword('catch'); + this.expect('('); + if (this.match(')')) { + this.throwUnexpectedToken(this.lookahead); + } + var params = []; + var param = this.parsePattern(params); + var paramMap = {}; + for (var i = 0; i < params.length; i++) { + var key = '$' + params[i].value; + if (Object.prototype.hasOwnProperty.call(paramMap, key)) { + this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); + } + paramMap[key] = true; + } + if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(param.name)) { + this.tolerateError(messages_1.Messages.StrictCatchVariable); + } + } + this.expect(')'); + var body = this.parseBlock(); + return this.finalize(node, new Node.CatchClause(param, body)); + }; + Parser.prototype.parseFinallyClause = function () { + this.expectKeyword('finally'); + return this.parseBlock(); + }; + Parser.prototype.parseTryStatement = function () { + var node = this.createNode(); + this.expectKeyword('try'); + var block = this.parseBlock(); + var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; + var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; + if (!handler && !finalizer) { + this.throwError(messages_1.Messages.NoCatchOrFinally); + } + return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); + }; + // https://tc39.github.io/ecma262/#sec-debugger-statement + Parser.prototype.parseDebuggerStatement = function () { + var node = this.createNode(); + this.expectKeyword('debugger'); + this.consumeSemicolon(); + return this.finalize(node, new Node.DebuggerStatement()); + }; + // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations + Parser.prototype.parseStatement = function () { + var statement; + switch (this.lookahead.type) { + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* Template */: + case 9 /* RegularExpression */: + statement = this.parseExpressionStatement(); + break; + case 7 /* Punctuator */: + var value = this.lookahead.value; + if (value === '{') { + statement = this.parseBlock(); + } + else if (value === '(') { + statement = this.parseExpressionStatement(); + } + else if (value === ';') { + statement = this.parseEmptyStatement(); + } + else { + statement = this.parseExpressionStatement(); + } + break; + case 3 /* Identifier */: + statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); + break; + case 4 /* Keyword */: + switch (this.lookahead.value) { + case 'break': + statement = this.parseBreakStatement(); + break; + case 'continue': + statement = this.parseContinueStatement(); + break; + case 'debugger': + statement = this.parseDebuggerStatement(); + break; + case 'do': + statement = this.parseDoWhileStatement(); + break; + case 'for': + statement = this.parseForStatement(); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'if': + statement = this.parseIfStatement(); + break; + case 'return': + statement = this.parseReturnStatement(); + break; + case 'switch': + statement = this.parseSwitchStatement(); + break; + case 'throw': + statement = this.parseThrowStatement(); + break; + case 'try': + statement = this.parseTryStatement(); + break; + case 'var': + statement = this.parseVariableStatement(); + break; + case 'while': + statement = this.parseWhileStatement(); + break; + case 'with': + statement = this.parseWithStatement(); + break; + default: + statement = this.parseExpressionStatement(); + break; + } + break; + default: + statement = this.throwUnexpectedToken(this.lookahead); + } + return statement; + }; + // https://tc39.github.io/ecma262/#sec-function-definitions + Parser.prototype.parseFunctionSourceElements = function () { + var node = this.createNode(); + this.expect('{'); + var body = this.parseDirectivePrologues(); + var previousLabelSet = this.context.labelSet; + var previousInIteration = this.context.inIteration; + var previousInSwitch = this.context.inSwitch; + var previousInFunctionBody = this.context.inFunctionBody; + this.context.labelSet = {}; + this.context.inIteration = false; + this.context.inSwitch = false; + this.context.inFunctionBody = true; + while (this.lookahead.type !== 2 /* EOF */) { + if (this.match('}')) { + break; + } + body.push(this.parseStatementListItem()); + } + this.expect('}'); + this.context.labelSet = previousLabelSet; + this.context.inIteration = previousInIteration; + this.context.inSwitch = previousInSwitch; + this.context.inFunctionBody = previousInFunctionBody; + return this.finalize(node, new Node.BlockStatement(body)); + }; + Parser.prototype.validateParam = function (options, param, name) { + var key = '$' + name; + if (this.context.strict) { + if (this.scanner.isRestrictedWord(name)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + else if (!options.firstRestricted) { + if (this.scanner.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictParamName; + } + else if (this.scanner.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictReservedWord; + } + else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + /* istanbul ignore next */ + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); + } + else { + options.paramSet[key] = true; + } + }; + Parser.prototype.parseRestElement = function (params) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestParameter); + } + if (!this.match(')')) { + this.throwError(messages_1.Messages.ParameterAfterRestParameter); + } + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseFormalParameter = function (options) { + var params = []; + var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); + for (var i = 0; i < params.length; i++) { + this.validateParam(options, params[i], params[i].value); + } + options.simple = options.simple && (param instanceof Node.Identifier); + options.params.push(param); + }; + Parser.prototype.parseFormalParameters = function (firstRestricted) { + var options; + options = { + simple: true, + params: [], + firstRestricted: firstRestricted + }; + this.expect('('); + if (!this.match(')')) { + options.paramSet = {}; + while (this.lookahead.type !== 2 /* EOF */) { + this.parseFormalParameter(options); + if (this.match(')')) { + break; + } + this.expect(','); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return { + simple: options.simple, + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.matchAsyncFunction = function () { + var match = this.matchContextualKeyword('async'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); + } + return match; + }; + Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted = null; + if (!identifierIsOptional || !this.match('(')) { + var token = this.lookahead; + id = this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : + this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); + }; + Parser.prototype.parseFunctionExpression = function () { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted; + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + if (!this.match('(')) { + var token = this.lookahead; + id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : + this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive + Parser.prototype.parseDirective = function () { + var token = this.lookahead; + var node = this.createNode(); + var expr = this.parseExpression(); + var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; + this.consumeSemicolon(); + return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); + }; + Parser.prototype.parseDirectivePrologues = function () { + var firstRestricted = null; + var body = []; + while (true) { + var token = this.lookahead; + if (token.type !== 8 /* StringLiteral */) { + break; + } + var statement = this.parseDirective(); + body.push(statement); + var directive = statement.directive; + if (typeof directive !== 'string') { + break; + } + if (directive === 'use strict') { + this.context.strict = true; + if (firstRestricted) { + this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); + } + if (!this.context.allowStrictDirective) { + this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); + } + } + else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + return body; + }; + // https://tc39.github.io/ecma262/#sec-method-definitions + Parser.prototype.qualifiedPropertyName = function (token) { + switch (token.type) { + case 3 /* Identifier */: + case 8 /* StringLiteral */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 4 /* Keyword */: + return true; + case 7 /* Punctuator */: + return token.value === '['; + default: + break; + } + return false; + }; + Parser.prototype.parseGetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length > 0) { + this.tolerateError(messages_1.Messages.BadGetterArity); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseSetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length !== 1) { + this.tolerateError(messages_1.Messages.BadSetterArity); + } + else if (formalParameters.params[0] instanceof Node.RestElement) { + this.tolerateError(messages_1.Messages.BadSetterRestParameter); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseGeneratorMethod = function () { + var node = this.createNode(); + var isGenerator = true; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + this.context.allowYield = false; + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-generator-function-definitions + Parser.prototype.isStartOfExpression = function () { + var start = true; + var value = this.lookahead.value; + switch (this.lookahead.type) { + case 7 /* Punctuator */: + start = (value === '[') || (value === '(') || (value === '{') || + (value === '+') || (value === '-') || + (value === '!') || (value === '~') || + (value === '++') || (value === '--') || + (value === '/') || (value === '/='); // regular expression literal + break; + case 4 /* Keyword */: + start = (value === 'class') || (value === 'delete') || + (value === 'function') || (value === 'let') || (value === 'new') || + (value === 'super') || (value === 'this') || (value === 'typeof') || + (value === 'void') || (value === 'yield'); + break; + default: + break; + } + return start; + }; + Parser.prototype.parseYieldExpression = function () { + var node = this.createNode(); + this.expectKeyword('yield'); + var argument = null; + var delegate = false; + if (!this.hasLineTerminator) { + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + delegate = this.match('*'); + if (delegate) { + this.nextToken(); + argument = this.parseAssignmentExpression(); + } + else if (this.isStartOfExpression()) { + argument = this.parseAssignmentExpression(); + } + this.context.allowYield = previousAllowYield; + } + return this.finalize(node, new Node.YieldExpression(argument, delegate)); + }; + // https://tc39.github.io/ecma262/#sec-class-definitions + Parser.prototype.parseClassElement = function (hasConstructor) { + var token = this.lookahead; + var node = this.createNode(); + var kind = ''; + var key = null; + var value = null; + var computed = false; + var method = false; + var isStatic = false; + var isAsync = false; + if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + var id = key; + if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { + token = this.lookahead; + isStatic = true; + computed = this.match('['); + if (this.match('*')) { + this.nextToken(); + } + else { + key = this.parseObjectPropertyKey(); + } + } + if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + key = this.parseObjectPropertyKey(); + if (token.type === 3 /* Identifier */ && token.value === 'constructor') { + this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); + } + } + } + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + if (!kind && key && this.match('(')) { + kind = 'init'; + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + if (!kind) { + this.throwUnexpectedToken(this.lookahead); + } + if (kind === 'init') { + kind = 'method'; + } + if (!computed) { + if (isStatic && this.isPropertyKey(key, 'prototype')) { + this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); + } + if (!isStatic && this.isPropertyKey(key, 'constructor')) { + if (kind !== 'method' || !method || (value && value.generator)) { + this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); + } + if (hasConstructor.value) { + this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); + } + else { + hasConstructor.value = true; + } + kind = 'constructor'; + } + } + return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); + }; + Parser.prototype.parseClassElementList = function () { + var body = []; + var hasConstructor = { value: false }; + this.expect('{'); + while (!this.match('}')) { + if (this.match(';')) { + this.nextToken(); + } + else { + body.push(this.parseClassElement(hasConstructor)); + } + } + this.expect('}'); + return body; + }; + Parser.prototype.parseClassBody = function () { + var node = this.createNode(); + var elementList = this.parseClassElementList(); + return this.finalize(node, new Node.ClassBody(elementList)); + }; + Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); + }; + Parser.prototype.parseClassExpression = function () { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); + }; + // https://tc39.github.io/ecma262/#sec-scripts + // https://tc39.github.io/ecma262/#sec-modules + Parser.prototype.parseModule = function () { + this.context.strict = true; + this.context.isModule = true; + this.scanner.isModule = true; + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Module(body)); + }; + Parser.prototype.parseScript = function () { + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Script(body)); + }; + // https://tc39.github.io/ecma262/#sec-imports + Parser.prototype.parseModuleSpecifier = function () { + var node = this.createNode(); + if (this.lookahead.type !== 8 /* StringLiteral */) { + this.throwError(messages_1.Messages.InvalidModuleSpecifier); + } + var token = this.nextToken(); + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + // import {} ...; + Parser.prototype.parseImportSpecifier = function () { + var node = this.createNode(); + var imported; + var local; + if (this.lookahead.type === 3 /* Identifier */) { + imported = this.parseVariableIdentifier(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + } + else { + imported = this.parseIdentifierName(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.ImportSpecifier(local, imported)); + }; + // {foo, bar as bas} + Parser.prototype.parseNamedImports = function () { + this.expect('{'); + var specifiers = []; + while (!this.match('}')) { + specifiers.push(this.parseImportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return specifiers; + }; + // import ...; + Parser.prototype.parseImportDefaultSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportDefaultSpecifier(local)); + }; + // import <* as foo> ...; + Parser.prototype.parseImportNamespaceSpecifier = function () { + var node = this.createNode(); + this.expect('*'); + if (!this.matchContextualKeyword('as')) { + this.throwError(messages_1.Messages.NoAsAfterImportNamespace); + } + this.nextToken(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); + }; + Parser.prototype.parseImportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalImportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('import'); + var src; + var specifiers = []; + if (this.lookahead.type === 8 /* StringLiteral */) { + // import 'foo'; + src = this.parseModuleSpecifier(); + } + else { + if (this.match('{')) { + // import {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else if (this.match('*')) { + // import * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { + // import foo + specifiers.push(this.parseImportDefaultSpecifier()); + if (this.match(',')) { + this.nextToken(); + if (this.match('*')) { + // import foo, * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.match('{')) { + // import foo, {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + src = this.parseModuleSpecifier(); + } + this.consumeSemicolon(); + return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); + }; + // https://tc39.github.io/ecma262/#sec-exports + Parser.prototype.parseExportSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + var exported = local; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + exported = this.parseIdentifierName(); + } + return this.finalize(node, new Node.ExportSpecifier(local, exported)); + }; + Parser.prototype.parseExportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalExportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('export'); + var exportDeclaration; + if (this.matchKeyword('default')) { + // export default ... + this.nextToken(); + if (this.matchKeyword('function')) { + // export default function foo () {} + // export default function () {} + var declaration = this.parseFunctionDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchKeyword('class')) { + // export default class foo {} + var declaration = this.parseClassDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchContextualKeyword('async')) { + // export default async function f () {} + // export default async function () {} + // export default async x => x + var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else { + if (this.matchContextualKeyword('from')) { + this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); + } + // export default {}; + // export default []; + // export default (1 + 2); + var declaration = this.match('{') ? this.parseObjectInitializer() : + this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + } + else if (this.match('*')) { + // export * from 'foo'; + this.nextToken(); + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + var src = this.parseModuleSpecifier(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); + } + else if (this.lookahead.type === 4 /* Keyword */) { + // export var f = 1; + var declaration = void 0; + switch (this.lookahead.value) { + case 'let': + case 'const': + declaration = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'var': + case 'class': + case 'function': + declaration = this.parseStatementListItem(); + break; + default: + this.throwUnexpectedToken(this.lookahead); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else if (this.matchAsyncFunction()) { + var declaration = this.parseFunctionDeclaration(); + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else { + var specifiers = []; + var source = null; + var isExportFromIdentifier = false; + this.expect('{'); + while (!this.match('}')) { + isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); + specifiers.push(this.parseExportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + if (this.matchContextualKeyword('from')) { + // export {default} from 'foo'; + // export {foo} from 'foo'; + this.nextToken(); + source = this.parseModuleSpecifier(); + this.consumeSemicolon(); + } + else if (isExportFromIdentifier) { + // export {default}; // missing fromClause + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + else { + // export {foo}; + this.consumeSemicolon(); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); + } + return exportDeclaration; + }; + return Parser; + }()); + exports.Parser = Parser; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + Object.defineProperty(exports, "__esModule", { value: true }); + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + exports.assert = assert; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + /* tslint:disable:max-classes-per-file */ + Object.defineProperty(exports, "__esModule", { value: true }); + var ErrorHandler = (function () { + function ErrorHandler() { + this.errors = []; + this.tolerant = false; + } + ErrorHandler.prototype.recordError = function (error) { + this.errors.push(error); + }; + ErrorHandler.prototype.tolerate = function (error) { + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + ErrorHandler.prototype.constructError = function (msg, column) { + var error = new Error(msg); + try { + throw error; + } + catch (base) { + /* istanbul ignore else */ + if (Object.create && Object.defineProperty) { + error = Object.create(base); + Object.defineProperty(error, 'column', { value: column }); + } + } + /* istanbul ignore next */ + return error; + }; + ErrorHandler.prototype.createError = function (index, line, col, description) { + var msg = 'Line ' + line + ': ' + description; + var error = this.constructError(msg, col); + error.index = index; + error.lineNumber = line; + error.description = description; + return error; + }; + ErrorHandler.prototype.throwError = function (index, line, col, description) { + throw this.createError(index, line, col, description); + }; + ErrorHandler.prototype.tolerateError = function (index, line, col, description) { + var error = this.createError(index, line, col, description); + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + return ErrorHandler; + }()); + exports.ErrorHandler = ErrorHandler; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // Error messages should be identical to V8. + exports.Messages = { + BadGetterArity: 'Getter must not have any formal parameters', + BadSetterArity: 'Setter must have exactly one formal parameter', + BadSetterRestParameter: 'Setter function argument must not be a rest parameter', + ConstructorIsAsync: 'Class constructor may not be an async method', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DeclarationMissingInitializer: 'Missing initializer in %0 declaration', + DefaultRestParameter: 'Unexpected token =', + DuplicateBinding: 'Duplicate binding %0', + DuplicateConstructor: 'A class may only have one constructor', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', + GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', + IllegalBreak: 'Illegal break statement', + IllegalContinue: 'Illegal continue statement', + IllegalExportDeclaration: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', + IllegalReturn: 'Illegal return statement', + InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', + InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', + InvalidModuleSpecifier: 'Unexpected token', + InvalidRegExp: 'Invalid regular expression', + LetInLexicalBinding: 'let is disallowed as a lexically bound name', + MissingFromClause: 'Unexpected token', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NewlineAfterThrow: 'Illegal newline after throw', + NoAsAfterImportNamespace: 'Unexpected token', + NoCatchOrFinally: 'Missing catch or finally after try', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + Redeclaration: '%0 \'%1\' has already been declared', + StaticPrototype: 'Classes may not have static property named prototype', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + UnexpectedEOS: 'Unexpected end of input', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedNumber: 'Unexpected number', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedString: 'Unexpected string', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedToken: 'Unexpected token %0', + UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', + UnknownLabel: 'Undefined label \'%0\'', + UnterminatedRegExp: 'Invalid regular expression: missing /' + }; + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __nested_webpack_require_226595__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __nested_webpack_require_226595__(9); + var character_1 = __nested_webpack_require_226595__(4); + var messages_1 = __nested_webpack_require_226595__(11); + function hexValue(ch) { + return '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + function octalValue(ch) { + return '01234567'.indexOf(ch); + } + var Scanner = (function () { + function Scanner(code, handler) { + this.source = code; + this.errorHandler = handler; + this.trackComment = false; + this.isModule = false; + this.length = code.length; + this.index = 0; + this.lineNumber = (code.length > 0) ? 1 : 0; + this.lineStart = 0; + this.curlyStack = []; + } + Scanner.prototype.saveState = function () { + return { + index: this.index, + lineNumber: this.lineNumber, + lineStart: this.lineStart + }; + }; + Scanner.prototype.restoreState = function (state) { + this.index = state.index; + this.lineNumber = state.lineNumber; + this.lineStart = state.lineStart; + }; + Scanner.prototype.eof = function () { + return this.index >= this.length; + }; + Scanner.prototype.throwUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + Scanner.prototype.tolerateUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + // https://tc39.github.io/ecma262/#sec-comments + Scanner.prototype.skipSingleLineComment = function (offset) { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - offset; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - offset + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + ++this.index; + if (character_1.Character.isLineTerminator(ch)) { + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart - 1 + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index - 1], + range: [start, this.index - 1], + loc: loc + }; + comments.push(entry); + } + if (ch === 13 && this.source.charCodeAt(this.index) === 10) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + return comments; + } + } + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + }; + Scanner.prototype.skipMultiLineComment = function () { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - 2; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - 2 + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isLineTerminator(ch)) { + if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + ++this.index; + this.lineStart = this.index; + } + else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (this.source.charCodeAt(this.index + 1) === 0x2F) { + this.index += 2; + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index - 2], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + } + ++this.index; + } + else { + ++this.index; + } + } + // Ran off the end of the file - the whole thing is a comment + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + this.tolerateUnexpectedToken(); + return comments; + }; + Scanner.prototype.scanComments = function () { + var comments; + if (this.trackComment) { + comments = []; + } + var start = (this.index === 0); + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isWhiteSpace(ch)) { + ++this.index; + } + else if (character_1.Character.isLineTerminator(ch)) { + ++this.index; + if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + start = true; + } + else if (ch === 0x2F) { + ch = this.source.charCodeAt(this.index + 1); + if (ch === 0x2F) { + this.index += 2; + var comment = this.skipSingleLineComment(2); + if (this.trackComment) { + comments = comments.concat(comment); + } + start = true; + } + else if (ch === 0x2A) { + this.index += 2; + var comment = this.skipMultiLineComment(); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (start && ch === 0x2D) { + // U+003E is '>' + if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { + // '-->' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C && !this.isModule) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // ` + +If the `"."` export is the only export, the [`"exports"`][] field provides sugar +for this case being the direct [`"exports"`][] field value. + +```json +{ + "exports": { + ".": "./index.js" + } +} +``` + +can be written: + +```json +{ + "exports": "./index.js" +} +``` + ### Subpath imports -In addition to the [`"exports"`][] field, it is possible to define internal -package import maps that only apply to import specifiers from within the package -itself. +In addition to the [`"exports"`][] field, there is a package `"imports"` field +to create private mappings that only apply to import specifiers from within the +package itself. -Entries in the imports field must always start with `#` to ensure they are -disambiguated from package specifiers. +Entries in the `"imports"` field must always start with `#` to ensure they are +disambiguated from external package specifiers. For example, the imports field can be used to gain the benefits of conditional exports for internal modules: @@ -397,8 +461,8 @@ file `./dep-polyfill.js` relative to the package in other environments. Unlike the `"exports"` field, the `"imports"` field permits mapping to external packages. -The resolution rules for the imports field are otherwise -analogous to the exports field. +The resolution rules for the imports field are otherwise analogous to the +exports field. ### Subpath patterns @@ -406,6 +470,17 @@ analogous to the exports field. added: - v14.13.0 - v12.20.0 +changes: + - version: + - v16.10.0 + - v14.19.0 + pr-url: https://github.com/nodejs/node/pull/40041 + description: Support pattern trailers in "imports" field. + - version: + - v16.9.0 + - v14.19.0 + pr-url: https://github.com/nodejs/node/pull/39635 + description: Support pattern trailers. --> For packages with a small number of exports or imports, we recommend @@ -419,10 +494,10 @@ For these use cases, subpath export patterns can be used instead: // ./node_modules/es-module-package/package.json { "exports": { - "./features/*": "./src/features/*.js" + "./features/*.js": "./src/features/*.js" }, "imports": { - "#internal/*": "./src/internal/*.js" + "#internal/*.js": "./src/internal/*.js" } } ``` @@ -434,19 +509,19 @@ All instances of `*` on the right hand side will then be replaced with this value, including if it contains any `/` separators. ```js -import featureX from 'es-module-package/features/x'; +import featureX from 'es-module-package/features/x.js'; // Loads ./node_modules/es-module-package/src/features/x.js -import featureY from 'es-module-package/features/y/y'; +import featureY from 'es-module-package/features/y/y.js'; // Loads ./node_modules/es-module-package/src/features/y/y.js -import internalZ from '#internal/z'; +import internalZ from '#internal/z.js'; // Loads ./node_modules/es-module-package/src/internal/z.js ``` -This is a direct static replacement without any special handling for file -extensions. In the previous example, `pkg/features/x.json` would be resolved to -`./src/features/x.json.js` in the mapping. +This is a direct static matching and replacement without any special handling +for file extensions. Including the `"*.js"` on both sides of the mapping +restricts the exposed package exports to only JS files. The property of exports being statically enumerable is maintained with exports patterns since the individual exports for a package can be determined by @@ -460,48 +535,20 @@ To exclude private subfolders from patterns, `null` targets can be used: // ./node_modules/es-module-package/package.json { "exports": { - "./features/*": "./src/features/*.js", + "./features/*.js": "./src/features/*.js", "./features/private-internal/*": null } } ``` ```js -import featureInternal from 'es-module-package/features/private-internal/m'; +import featureInternal from 'es-module-package/features/private-internal/m.js'; // Throws: ERR_PACKAGE_PATH_NOT_EXPORTED -import featureX from 'es-module-package/features/x'; +import featureX from 'es-module-package/features/x.js'; // Loads ./node_modules/es-module-package/src/features/x.js ``` -### Exports sugar - - - -If the `"."` export is the only export, the [`"exports"`][] field provides sugar -for this case being the direct [`"exports"`][] field value. - -If the `"."` export has a fallback array or string value, then the -[`"exports"`][] field can be set to this value directly. - -```json -{ - "exports": { - ".": "./main.js" - } -} -``` - -can be written: - -```json -{ - "exports": "./main.js" -} -``` - ### Conditional exports @@ -584,7 +584,7 @@ The algorithms currently supported include: @@ -666,7 +666,7 @@ The algorithms currently supported include: @@ -893,7 +893,7 @@ The unwrapped key algorithms supported include: @@ -965,13 +965,13 @@ are simple JavaScript dictionary objects. ### Class: `AlgorithmIdentifier` #### `algorithmIdentifier.name` * Type: {string} @@ -1228,7 +1228,7 @@ added: v15.0.0 #### `ed448Params.name` * Type: {string} Must be `'Ed448'`. @@ -1236,7 +1236,7 @@ added: REPLACEME #### `ed448Params.context` * Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} diff --git a/doc/changelogs/CHANGELOG_V18.md b/doc/changelogs/CHANGELOG_V18.md index 75c9cf9970192b..4fa2894562a94c 100644 --- a/doc/changelogs/CHANGELOG_V18.md +++ b/doc/changelogs/CHANGELOG_V18.md @@ -8,6 +8,7 @@ +18.4.0
        18.3.0
        18.2.0
        18.1.0
        @@ -36,6 +37,118 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) + + +## 2022-06-16, Version 18.4.0 (Current), @danielleadams + +### Notable Changes + +* **crypto**: + * remove Node.js-specific webcrypto extensions (Filip Skokan) [#43310](https://github.com/nodejs/node/pull/43310) + * add CFRG curves to Web Crypto API (Filip Skokan) [#42507](https://github.com/nodejs/node/pull/42507) +* **dns**: + * accept `'IPv4'` and `'IPv6'` for `family` (Antoine du Hamel) [#43054](https://github.com/nodejs/node/pull/43054) +* **report**: + * add more heap infos in process report (theanarkh) [#43116](https://github.com/nodejs/node/pull/43116) + +### Commits + +* \[[`702bfa0b7c`](https://github.com/nodejs/node/commit/702bfa0b7c)] - **async\_hooks**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`f7c4015fd8`](https://github.com/nodejs/node/commit/f7c4015fd8)] - **bootstrap**: consolidate global properties definition (Chengzhong Wu) [#43357](https://github.com/nodejs/node/pull/43357) +* \[[`8d892f5259`](https://github.com/nodejs/node/commit/8d892f5259)] - **build**: add nonpm and nocorepack to vcbuild.bat (Darshan Sen) [#43219](https://github.com/nodejs/node/pull/43219) +* \[[`4109ddc005`](https://github.com/nodejs/node/commit/4109ddc005)] - **child\_process**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`7b5cb14f0c`](https://github.com/nodejs/node/commit/7b5cb14f0c)] - **cluster**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`9f1de2c005`](https://github.com/nodejs/node/commit/9f1de2c005)] - **crypto**: fix webcrypto import of cfrg raw public keys (Filip Skokan) [#43404](https://github.com/nodejs/node/pull/43404) +* \[[`7f02e22998`](https://github.com/nodejs/node/commit/7f02e22998)] - **crypto**: test webcrypto ec raw public key import (Filip Skokan) [#43405](https://github.com/nodejs/node/pull/43405) +* \[[`0a075cb548`](https://github.com/nodejs/node/commit/0a075cb548)] - **crypto**: fix webcrypto JWK EC and OKP import crv check (Filip Skokan) [#43346](https://github.com/nodejs/node/pull/43346) +* \[[`df0903c8e8`](https://github.com/nodejs/node/commit/df0903c8e8)] - **crypto**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`6d0053345e`](https://github.com/nodejs/node/commit/6d0053345e)] - **(SEMVER-MINOR)** **crypto**: remove Node.js-specific webcrypto extensions (Filip Skokan) [#43310](https://github.com/nodejs/node/pull/43310) +* \[[`28c034d6b5`](https://github.com/nodejs/node/commit/28c034d6b5)] - **(SEMVER-MINOR)** **crypto**: add CFRG curves to Web Crypto API (Filip Skokan) [#42507](https://github.com/nodejs/node/pull/42507) +* \[[`fe7fd85109`](https://github.com/nodejs/node/commit/fe7fd85109)] - **deps**: update Corepack to 0.11.2 (Maël Nison) [#43402](https://github.com/nodejs/node/pull/43402) +* \[[`517f17b214`](https://github.com/nodejs/node/commit/517f17b214)] - **deps**: update undici to 5.5.1 (Node.js GitHub Bot) [#43412](https://github.com/nodejs/node/pull/43412) +* \[[`f4c830fbe4`](https://github.com/nodejs/node/commit/f4c830fbe4)] - **deps**: upgrade npm to 8.12.1 (npm CLI robot) [#43301](https://github.com/nodejs/node/pull/43301) +* \[[`0bb84b09a5`](https://github.com/nodejs/node/commit/0bb84b09a5)] - **(SEMVER-MINOR)** **dns**: accept `'IPv4'` and `'IPv6'` for `family` (Antoine du Hamel) [#43054](https://github.com/nodejs/node/pull/43054) +* \[[`f91babe494`](https://github.com/nodejs/node/commit/f91babe494)] - **doc**: packages documentation updates for 12 EOL (Guy Bedford) [#43375](https://github.com/nodejs/node/pull/43375) +* \[[`066f963ec1`](https://github.com/nodejs/node/commit/066f963ec1)] - **doc**: add initial doc on how to update cjs-module-lexer (Michael Dawson) [#43255](https://github.com/nodejs/node/pull/43255) +* \[[`36e5684ae0`](https://github.com/nodejs/node/commit/36e5684ae0)] - **doc**: clarify use of deps/icu-small (Michael Dawson) [#43287](https://github.com/nodejs/node/pull/43287) +* \[[`b9634e7ef3`](https://github.com/nodejs/node/commit/b9634e7ef3)] - **doc**: remove llnode from diag tierlist (Tony Gorez) [#43289](https://github.com/nodejs/node/pull/43289) +* \[[`4caeb10e7b`](https://github.com/nodejs/node/commit/4caeb10e7b)] - **doc**: remove ETW from diag tierlist (Tony Gorez) [#43295](https://github.com/nodejs/node/pull/43295) +* \[[`41955e5ce5`](https://github.com/nodejs/node/commit/41955e5ce5)] - **doc**: use serial comma in report docs (Tobias Nießen) [#43394](https://github.com/nodejs/node/pull/43394) +* \[[`e30d4c1cb0`](https://github.com/nodejs/node/commit/e30d4c1cb0)] - **doc**: add fspromises mkdir example (Tierney Cyren) [#40843](https://github.com/nodejs/node/pull/40843) +* \[[`adec5fa929`](https://github.com/nodejs/node/commit/adec5fa929)] - **doc**: add F3n67u to triagers (Feng Yu) [#43350](https://github.com/nodejs/node/pull/43350) +* \[[`cc3505b192`](https://github.com/nodejs/node/commit/cc3505b192)] - **doc**: fix typo in globals.md (Daeyeon Jeong) [#43365](https://github.com/nodejs/node/pull/43365) +* \[[`052c8eaf6a`](https://github.com/nodejs/node/commit/052c8eaf6a)] - **doc**: use serial comma in webstreams docs (Tobias Nießen) [#43353](https://github.com/nodejs/node/pull/43353) +* \[[`b824a0b7d0`](https://github.com/nodejs/node/commit/b824a0b7d0)] - **doc**: fix specifier example in `esm.md` (hiroki osame) [#43351](https://github.com/nodejs/node/pull/43351) +* \[[`d558b3c028`](https://github.com/nodejs/node/commit/d558b3c028)] - **doc**: add undici to glossary (F3n67u) [#43327](https://github.com/nodejs/node/pull/43327) +* \[[`f9ad98f5cb`](https://github.com/nodejs/node/commit/f9ad98f5cb)] - **doc**: change glossary link in pull request guide to node's glossary doc (Feng Yu) [#43318](https://github.com/nodejs/node/pull/43318) +* \[[`02944a6783`](https://github.com/nodejs/node/commit/02944a6783)] - **doc**: fix typo in util.parseArgs usage example (Michael Ficarra) [#43332](https://github.com/nodejs/node/pull/43332) +* \[[`f2bc6a3f71`](https://github.com/nodejs/node/commit/f2bc6a3f71)] - **doc**: improve description of TZ (Tobias Nießen) [#43334](https://github.com/nodejs/node/pull/43334) +* \[[`9335ea6c35`](https://github.com/nodejs/node/commit/9335ea6c35)] - **doc**: use serial comma in net docs (Tobias Nießen) [#43335](https://github.com/nodejs/node/pull/43335) +* \[[`05f38c6c3e`](https://github.com/nodejs/node/commit/05f38c6c3e)] - **doc**: make clear the result of comparison between Symbol.for (Kohei Ueno) [#43309](https://github.com/nodejs/node/pull/43309) +* \[[`c9aed9de9f`](https://github.com/nodejs/node/commit/c9aed9de9f)] - **doc**: add missing require to stream api doc (Feng Yu) [#43237](https://github.com/nodejs/node/pull/43237) +* \[[`f3188c1c9c`](https://github.com/nodejs/node/commit/f3188c1c9c)] - **doc**: add CIGTM to `glossary.md` (Feng Yu) [#43316](https://github.com/nodejs/node/pull/43316) +* \[[`c572d2d115`](https://github.com/nodejs/node/commit/c572d2d115)] - **doc**: use serial comma in pull request doc (Feng Yu) [#43319](https://github.com/nodejs/node/pull/43319) +* \[[`8a4e1fa002`](https://github.com/nodejs/node/commit/8a4e1fa002)] - **doc**: use serial comma in ESM docs (Tobias Nießen) [#43322](https://github.com/nodejs/node/pull/43322) +* \[[`fff0560a66`](https://github.com/nodejs/node/commit/fff0560a66)] - **doc**: promote cdt to tier 3 (Tony Gorez) [#43290](https://github.com/nodejs/node/pull/43290) +* \[[`7d0f6da97f`](https://github.com/nodejs/node/commit/7d0f6da97f)] - **doc**: fix chromium document link in pull-requests.md (rikapo) [#43265](https://github.com/nodejs/node/pull/43265) +* \[[`4674b0d2a5`](https://github.com/nodejs/node/commit/4674b0d2a5)] - **doc**: fix 404 link of BUILDING.md (Feng Yu) [#43234](https://github.com/nodejs/node/pull/43234) +* \[[`ee392c5c0b`](https://github.com/nodejs/node/commit/ee392c5c0b)] - **doc**: update CHANGELOG\_V18.md (Filip Skokan) [#43298](https://github.com/nodejs/node/pull/43298) +* \[[`5a3a2a197f`](https://github.com/nodejs/node/commit/5a3a2a197f)] - **doc**: add src/crypto to CC list for nodejs/crypto (Tobias Nießen) [#43286](https://github.com/nodejs/node/pull/43286) +* \[[`69ce50396c`](https://github.com/nodejs/node/commit/69ce50396c)] - **doc**: use serial comma in console docs (Tobias Nießen) [#43257](https://github.com/nodejs/node/pull/43257) +* \[[`0c5092c51c`](https://github.com/nodejs/node/commit/0c5092c51c)] - **events**: fix adding abort listener in `events.once` (Daeyeon Jeong) [#43373](https://github.com/nodejs/node/pull/43373) +* \[[`fda2105481`](https://github.com/nodejs/node/commit/fda2105481)] - **events**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`63bf49b143`](https://github.com/nodejs/node/commit/63bf49b143)] - **fs**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`9b764531b9`](https://github.com/nodejs/node/commit/9b764531b9)] - **fs**: export constants from `fs/promises` (Feng Yu) [#43177](https://github.com/nodejs/node/pull/43177) +* \[[`a4409f85f8`](https://github.com/nodejs/node/commit/a4409f85f8)] - **http**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`2ffd54105a`](https://github.com/nodejs/node/commit/2ffd54105a)] - **http2**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`b468b8fe51`](https://github.com/nodejs/node/commit/b468b8fe51)] - **https**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`d2a98dc6cf`](https://github.com/nodejs/node/commit/d2a98dc6cf)] - **inspector**: add missing initialization (Michael Dawson) [#43254](https://github.com/nodejs/node/pull/43254) +* \[[`3b2f7eed39`](https://github.com/nodejs/node/commit/3b2f7eed39)] - **lib**: use `kEmptyObject` in various places (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`4a9511d971`](https://github.com/nodejs/node/commit/4a9511d971)] - **lib**: give names to promisified methods (LiviaMedeiros) [#43218](https://github.com/nodejs/node/pull/43218) +* \[[`b8644606eb`](https://github.com/nodejs/node/commit/b8644606eb)] - **lib**: use null-prototype objects for property descriptors (Antoine du Hamel) [#43270](https://github.com/nodejs/node/pull/43270) +* \[[`64edd6cbc3`](https://github.com/nodejs/node/commit/64edd6cbc3)] - **meta**: move one or more collaborators to emeritus (Node.js GitHub Bot) [#43399](https://github.com/nodejs/node/pull/43399) +* \[[`b05cea57ba`](https://github.com/nodejs/node/commit/b05cea57ba)] - **meta**: update AUTHORS (Node.js GitHub Bot) [#43387](https://github.com/nodejs/node/pull/43387) +* \[[`a8ecec57e3`](https://github.com/nodejs/node/commit/a8ecec57e3)] - **meta**: move one or more collaborators to emeritus (#43183) (Node.js GitHub Bot) [#43183](https://github.com/nodejs/node/pull/43183) +* \[[`60dc36244a`](https://github.com/nodejs/node/commit/60dc36244a)] - **meta**: update AUTHORS (Node.js GitHub Bot) [#43312](https://github.com/nodejs/node/pull/43312) +* \[[`9803b82ac7`](https://github.com/nodejs/node/commit/9803b82ac7)] - **net,dns**: move hasObserver out of perf function (theanarkh) [#43217](https://github.com/nodejs/node/pull/43217) +* \[[`112518fb1d`](https://github.com/nodejs/node/commit/112518fb1d)] - **perf\_hooks**: fix function wrapped by `timerify` to work correctly (Kohei Ueno) [#43330](https://github.com/nodejs/node/pull/43330) +* \[[`a3310d13bf`](https://github.com/nodejs/node/commit/a3310d13bf)] - **perf\_hooks**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`7e8a00a26d`](https://github.com/nodejs/node/commit/7e8a00a26d)] - **readline**: fix question stack overflow (Eugene Chapko) [#43320](https://github.com/nodejs/node/pull/43320) +* \[[`5e98cacf77`](https://github.com/nodejs/node/commit/5e98cacf77)] - **readline**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`66d956ca49`](https://github.com/nodejs/node/commit/66d956ca49)] - **repl**: make autocomplete case-insensitive (Sergey Petushkov) [#41632](https://github.com/nodejs/node/pull/41632) +* \[[`201f3d7f56`](https://github.com/nodejs/node/commit/201f3d7f56)] - **(SEMVER-MINOR)** **report**: add more heap infos in process report (theanarkh) [#43116](https://github.com/nodejs/node/pull/43116) +* \[[`a0568409b6`](https://github.com/nodejs/node/commit/a0568409b6)] - **src**: fix json utils escapes for U+000B (Chengzhong Wu) [#43206](https://github.com/nodejs/node/pull/43206) +* \[[`931ecfa033`](https://github.com/nodejs/node/commit/931ecfa033)] - **src**: fix memory leaks and refactor `ByteSource` (Tobias Nießen) [#43202](https://github.com/nodejs/node/pull/43202) +* \[[`5e65c1f3da`](https://github.com/nodejs/node/commit/5e65c1f3da)] - **src**: convey potential exceptions during StreamPipe construction (Darshan Sen) [#43240](https://github.com/nodejs/node/pull/43240) +* \[[`b200a5ff67`](https://github.com/nodejs/node/commit/b200a5ff67)] - **stream**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`1cc1a57cdb`](https://github.com/nodejs/node/commit/1cc1a57cdb)] - **test**: remove unused argument in test-util-inspect.js (Colin Ihrig) [#43395](https://github.com/nodejs/node/pull/43395) +* \[[`42c2115a82`](https://github.com/nodejs/node/commit/42c2115a82)] - **test**: mark test\_buffer/test\_finalizer flaky (Michael Dawson) [#43414](https://github.com/nodejs/node/pull/43414) +* \[[`71802c32d0`](https://github.com/nodejs/node/commit/71802c32d0)] - **test**: fix address in use error (Caleb Everett) [#43199](https://github.com/nodejs/node/pull/43199) +* \[[`e1b8c85a7a`](https://github.com/nodejs/node/commit/e1b8c85a7a)] - **test**: add test for short-option followed by its value (Kohei Ueno) [#43358](https://github.com/nodejs/node/pull/43358) +* \[[`f8d26c6011`](https://github.com/nodejs/node/commit/f8d26c6011)] - **test**: fix `common.mustNotCall` error message (Antoine du Hamel) [#42917](https://github.com/nodejs/node/pull/42917) +* \[[`18fffe6108`](https://github.com/nodejs/node/commit/18fffe6108)] - **test**: convert then to async/await (Meek Simbule) [#43292](https://github.com/nodejs/node/pull/43292) +* \[[`acd96d80eb`](https://github.com/nodejs/node/commit/acd96d80eb)] - **test**: add `BigInt`s to `common.getArrayBufferViews()` (LiviaMedeiros) [#43235](https://github.com/nodejs/node/pull/43235) +* \[[`e576a7fa50`](https://github.com/nodejs/node/commit/e576a7fa50)] - **test\_runner**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`fecad7a3a5`](https://github.com/nodejs/node/commit/fecad7a3a5)] - **timers**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`e31baca76a`](https://github.com/nodejs/node/commit/e31baca76a)] - **tls**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`7f8f61a749`](https://github.com/nodejs/node/commit/7f8f61a749)] - **tls**: fix performance regression in `convertALPNProtocols()` (LiviaMedeiros) [#43250](https://github.com/nodejs/node/pull/43250) +* \[[`ac9599a718`](https://github.com/nodejs/node/commit/ac9599a718)] - **tools**: report unsafe string and regex primordials as lint errors (Antoine du Hamel) [#43393](https://github.com/nodejs/node/pull/43393) +* \[[`b69d874592`](https://github.com/nodejs/node/commit/b69d874592)] - **tools**: fix `create-or-update-pull-request-action` hash on GHA (Antoine du Hamel) [#43378](https://github.com/nodejs/node/pull/43378) +* \[[`cf8a115983`](https://github.com/nodejs/node/commit/cf8a115983)] - **tools**: add `avoid-prototype-pollution` lint rule (Antoine du Hamel) [#43308](https://github.com/nodejs/node/pull/43308) +* \[[`8c0fe1e184`](https://github.com/nodejs/node/commit/8c0fe1e184)] - **tools**: fix find-inactive actions (LiviaMedeiros) [#43377](https://github.com/nodejs/node/pull/43377) +* \[[`7f45d69f83`](https://github.com/nodejs/node/commit/7f45d69f83)] - **tools**: update lint-md-dependencies to rollup\@2.75.5 (Node.js GitHub Bot) [#43313](https://github.com/nodejs/node/pull/43313) +* \[[`d5d0f01c5a`](https://github.com/nodejs/node/commit/d5d0f01c5a)] - **tools**: update eslint to 8.17.0 (Node.js GitHub Bot) [#43314](https://github.com/nodejs/node/pull/43314) +* \[[`f598fe1585`](https://github.com/nodejs/node/commit/f598fe1585)] - **tools**: use hashes instead of tags for external actions (#43284) (Antoine du Hamel) [#43284](https://github.com/nodejs/node/pull/43284) +* \[[`10f79947d9`](https://github.com/nodejs/node/commit/10f79947d9)] - **tools**: update `codecov/codecov-action` version (Antoine du Hamel) [#43297](https://github.com/nodejs/node/pull/43297) +* \[[`f93848fa50`](https://github.com/nodejs/node/commit/f93848fa50)] - **tools**: update lint-md-dependencies to rollup\@2.75.3 (Node.js GitHub Bot) [#43261](https://github.com/nodejs/node/pull/43261) +* \[[`b3d7dc1de8`](https://github.com/nodejs/node/commit/b3d7dc1de8)] - **tools**: update clang-format 1.7.0 to 1.8.0 (Darshan Sen) [#43241](https://github.com/nodejs/node/pull/43241) +* \[[`812140c65a`](https://github.com/nodejs/node/commit/812140c65a)] - **tools,doc**: add guards against prototype pollution when creating proxies (Antoine du Hamel) [#43391](https://github.com/nodejs/node/pull/43391) +* \[[`56b8cc5cef`](https://github.com/nodejs/node/commit/56b8cc5cef)] - **util**: freeze `kEnumerableProperty` (LiviaMedeiros) [#43390](https://github.com/nodejs/node/pull/43390) +* \[[`b187d55b6d`](https://github.com/nodejs/node/commit/b187d55b6d)] - **util**: add `kEmptyObject` to internal/util (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`024b396275`](https://github.com/nodejs/node/commit/024b396275)] - **vm**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`7fc432fa35`](https://github.com/nodejs/node/commit/7fc432fa35)] - **wasi**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) +* \[[`44b65d0ca7`](https://github.com/nodejs/node/commit/44b65d0ca7)] - **worker**: use `kEmptyObject` (LiviaMedeiros) [#43159](https://github.com/nodejs/node/pull/43159) + ## 2022-06-01, Version 18.3.0 (Current), @bengl diff --git a/src/node_version.h b/src/node_version.h index e5f48b1500c0f5..c672bd40af4fe8 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,13 +23,13 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 18 -#define NODE_MINOR_VERSION 3 -#define NODE_PATCH_VERSION 1 +#define NODE_MINOR_VERSION 4 +#define NODE_PATCH_VERSION 0 #define NODE_VERSION_IS_LTS 0 #define NODE_VERSION_LTS_CODENAME "" -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)