Add node_modules

This commit is contained in:
Anton Medvedev 2023-01-10 16:49:41 +01:00
commit 554eb0b122
994 changed files with 195567 additions and 0 deletions

202
node_modules/zx/LICENSE generated vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

576
node_modules/zx/README.md generated vendored Normal file
View file

@ -0,0 +1,576 @@
# 🐚 zx
```js
#!/usr/bin/env zx
await $`cat package.json | grep name`
let branch = await $`git branch --show-current`
await $`dep deploy --branch=${branch}`
await Promise.all([
$`sleep 1; echo 1`,
$`sleep 2; echo 2`,
$`sleep 3; echo 3`,
])
let name = 'foo bar'
await $`mkdir /tmp/${name}`
```
Bash is great, but when it comes to writing more complex scripts,
many people prefer a more convenient programming language.
JavaScript is a perfect choice, but the Node.js standard library
requires additional hassle before using. The `zx` package provides
useful wrappers around `child_process`, escapes arguments and
gives sensible defaults.
## Install
```bash
npm i -g zx
```
**Requirement**: Node version >= 16.0.0
## Goods
[$](#command-) · [cd()](#cd) · [fetch()](#fetch) · [question()](#question) · [sleep()](#sleep) · [echo()](#echo) · [stdin()](#stdin) · [within()](#within) ·
[chalk](#chalk-package) · [fs](#fs-package) · [os](#os-package) · [path](#path-package) · [glob](#globby-package) · [yaml](#yaml-package) · [minimist](#minimist-package) · [which](#which-package) ·
[__filename](#__filename--__dirname) · [__dirname](#__filename--__dirname) · [require()](#require)
## Documentation
Write your scripts in a file with an `.mjs` extension in order to
use `await` at the top level. If you prefer the `.js` extension,
wrap your scripts in something like `void async function () {...}()`.
Add the following shebang to the beginning of your `zx` scripts:
```bash
#!/usr/bin/env zx
```
Now you will be able to run your script like so:
```bash
chmod +x ./script.mjs
./script.mjs
```
Or via the `zx` executable:
```bash
zx ./script.mjs
```
All functions (`$`, `cd`, `fetch`, etc) are available straight away
without any imports.
Or import globals explicitly (for better autocomplete in VS Code).
```js
import 'zx/globals'
```
### ``$`command` ``
Executes a given command using the `spawn` func
and returns [`ProcessPromise`](#processpromise).
Everything passed through `${...}` will be automatically escaped and quoted.
```js
let name = 'foo & bar'
await $`mkdir ${name}`
```
**There is no need to add extra quotes.** Read more about it in
[quotes](docs/quotes.md).
You can pass an array of arguments if needed:
```js
let flags = [
'--oneline',
'--decorate',
'--color',
]
await $`git log ${flags}`
```
If the executed program returns a non-zero exit code,
[`ProcessOutput`](#processoutput) will be thrown.
```js
try {
await $`exit 1`
} catch (p) {
console.log(`Exit code: ${p.exitCode}`)
console.log(`Error: ${p.stderr}`)
}
```
### `ProcessPromise`
```ts
class ProcessPromise extends Promise<ProcessOutput> {
stdin: Writable
stdout: Readable
stderr: Readable
exitCode: Promise<number>
pipe(dest): ProcessPromise
kill(): Promise<void>
nothrow(): this
quiet(): this
}
```
Read more about the [ProcessPromise](docs/process-promise.md).
### `ProcessOutput`
```ts
class ProcessOutput {
readonly stdout: string
readonly stderr: string
readonly signal: string
readonly exitCode: number
toString(): string // Combined stdout & stderr.
}
```
The output of the process is captured as-is. Usually, programs print a new line `\n` at the end.
If `ProcessOutput` is used as an argument to some other `$` process,
**zx** will use stdout and trim the new line.
```js
let date = await $`date`
await $`echo Current date is ${date}.`
```
## Functions
### `cd()`
Changes the current working directory.
```js
cd('/tmp')
await $`pwd` // => /tmp
```
### `fetch()`
A wrapper around the [node-fetch](https://www.npmjs.com/package/node-fetch) package.
```js
let resp = await fetch('https://medv.io')
```
### `question()`
A wrapper around the [readline](https://nodejs.org/api/readline.html) package.
```js
let bear = await question('What kind of bear is best? ')
```
### `sleep()`
A wrapper around the `setTimeout` function.
```js
await sleep(1000)
```
### `echo()`
A `console.log()` alternative which can take [ProcessOutput](#processoutput).
```js
let branch = await $`git branch --show-current`
echo`Current branch is ${branch}.`
// or
echo('Current branch is', branch)
```
### `stdin()`
Returns the stdin as a string.
```js
let content = JSON.parse(await stdin())
```
### `within()`
Creates a new async context.
```js
await $`pwd` // => /home/path
within(async () => {
cd('/tmp')
setTimeout(async () => {
await $`pwd` // => /tmp
}, 1000)
})
await $`pwd` // => /home/path
```
```js
let version = await within(async () => {
$.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
await $`nvm use 16`
return $`node -v`
})
```
## Packages
The following packages are available without importing inside scripts.
### `chalk` package
The [chalk](https://www.npmjs.com/package/chalk) package.
```js
console.log(chalk.blue('Hello world!'))
```
### `fs` package
The [fs-extra](https://www.npmjs.com/package/fs-extra) package.
```js
let {version} = await fs.readJson('./package.json')
```
### `os` package
The [os](https://nodejs.org/api/os.html) package.
```js
await $`cd ${os.homedir()} && mkdir example`
```
### `path` package
The [path](https://nodejs.org/api/path.html) package.
```js
await $`mkdir ${path.join(basedir, 'output')}`
```
### `globby` package
The [globby](https://github.com/sindresorhus/globby) package.
```js
let packages = await glob(['package.json', 'packages/*/package.json'])
```
### `yaml` package
The [yaml](https://www.npmjs.com/package/yaml) package.
```js
console.log(YAML.parse('foo: bar').foo)
```
### `minimist` package
The [minimist](https://www.npmjs.com/package/minimist) package available
as global const `argv`.
```js
if( argv.someFlag ){ echo('yes') }
```
### `which` package
The [which](https://github.com/npm/node-which) package.
```js
let node = await which('node')
```
## Configuration
### `$.shell`
Specifies what shell is used. Default is `which bash`.
```js
$.shell = '/usr/bin/bash'
```
Or use a CLI argument: `--shell=/bin/bash`
### `$.spawn`
Specifies a `spawn` api. Defaults to `require('child_process').spawn`.
### `$.prefix`
Specifies the command that will be prefixed to all commands run.
Default is `set -euo pipefail;`.
Or use a CLI argument: `--prefix='set -e;'`
### `$.quote`
Specifies a function for escaping special characters during
command substitution.
### `$.verbose`
Specifies verbosity. Default is `true`.
In verbose mode, `zx` prints all executed commands alongside with their
outputs.
Or use the CLI argument `--quiet` to set `$.verbose = false`.
### `$.env`
Specifies an environment variables map.
Defaults to `process.env`.
### `$.cwd`
Specifies a current working directory of all processes created with the `$`.
The [cd()](#cd) func changes only `process.cwd()` and if no `$.cwd` specified,
all `$` processes use `process.cwd()` by default (same as `spawn` behavior).
### `$.log`
Specifies a [logging function](src/core.ts).
```ts
import { LogEntry, log } from 'zx/core'
$.log = (entry: LogEntry) => {
switch (entry.kind) {
case 'cmd':
// for example, apply custom data masker for cmd printing
process.stderr.write(masker(entry.cmd))
break
default:
log(entry)
}
}
```
## Polyfills
### `__filename` & `__dirname`
In [ESM](https://nodejs.org/api/esm.html) modules, Node.js does not provide
`__filename` and `__dirname` globals. As such globals are really handy in scripts,
`zx` provides these for use in `.mjs` files (when using the `zx` executable).
### `require()`
In [ESM](https://nodejs.org/api/modules.html#modules_module_createrequire_filename)
modules, the `require()` function is not defined.
The `zx` provides `require()` function, so it can be used with imports in `.mjs`
files (when using `zx` executable).
```js
let {version} = require('./package.json')
```
## Experimental
The zx provides a few experimental functions. Please leave feedback about
those features in [the discussion](https://github.com/google/zx/discussions/299).
To enable new features via CLI pass `--experimental` flag.
### `retry()`
Retries a callback for a few times. Will return after the first
successful attempt, or will throw after specifies attempts count.
```js
import { retry, expBackoff } from 'zx/experimental'
let p = await retry(10, () => $`curl https://medv.io`)
// With a specified delay between attempts.
let p = await retry(20, '1s', () => $`curl https://medv.io`)
// With an exponential backoff.
let p = await retry(30, expBackoff(), () => $`curl https://medv.io`)
```
### `spinner()`
Starts a simple CLI spinner.
```js
import { spinner } from 'zx/experimental'
await spinner(() => $`long-running command`)
// With a message.
await spinner('working...', () => $`sleep 99`)
```
## FAQ
### Passing env variables
```js
process.env.FOO = 'bar'
await $`echo $FOO`
```
### Passing array of values
When passing an array of values as an argument to `$`, items of the array will be escaped
individually and concatenated via space.
Example:
```js
let files = [...]
await $`tar cz ${files}`
```
### Importing into other scripts
It is possible to make use of `$` and other functions via explicit imports:
```js
#!/usr/bin/env node
import {$} from 'zx'
await $`date`
```
### Scripts without extensions
If script does not have a file extension (like `.git/hooks/pre-commit`), zx
assumes that it is an [ESM](https://nodejs.org/api/modules.html#modules_module_createrequire_filename)
module.
### Markdown scripts
The `zx` can execute [scripts written as markdown](docs/markdown.md):
```bash
zx docs/markdown.md
```
### TypeScript scripts
```ts
import {$} from 'zx'
// Or
import 'zx/globals'
void async function () {
await $`ls -la`
}()
```
Set [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type)
in **package.json** and [`"module": "ESNext"`](https://www.typescriptlang.org/tsconfig/#module)
in **tsconfig.json**.
### Executing remote scripts
If the argument to the `zx` executable starts with `https://`, the file will be
downloaded and executed.
```bash
zx https://medv.io/game-of-life.js
```
### Executing scripts from stdin
The `zx` supports executing scripts from stdin.
```js
zx <<'EOF'
await $`pwd`
EOF
```
### Executing scripts via --eval
Evaluate the following argument as a script.
```bash
cat package.json | zx --eval 'let v = JSON.parse(await stdin()).version; echo(v)'
```
### Installing dependencies via --install
```js
// script.mjs:
import sh from 'tinysh'
sh.say('Hello, world!')
```
Add `--install` flag to the `zx` command to install missing dependencies
automatically.
```bash
zx --install script.mjs
```
You can also specify needed version by adding comment with `@` after
the import.
```js
import sh from 'tinysh' // @^1
```
### Attaching a profile
By default `child_process` does not include aliases and bash functions.
But you are still able to do it by hand. Just attach necessary directives
to the `$.prefix`.
```js
$.prefix += 'export NVM_DIR=$HOME/.nvm; source $NVM_DIR/nvm.sh; '
await $`nvm -v`
```
### Using GitHub Actions
The default GitHub Action runner comes with `npx` installed.
```yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
env:
FORCE_COLOR: 3
run: |
npx zx <<'EOF'
await $`...`
EOF
```
### Canary / Beta / RC builds
Impatient early adopters can try the experimental zx versions. But keep in mind: these builds are ⚠️️ __unstable__ in every sense.
```bash
npm i zx@dev
npx zx@dev --install --quiet <<< 'import _ from "lodash" /* 4.17.15 */; console.log(_.VERSION)'
```
## License
[Apache-2.0](LICENSE)
Disclaimer: _This is not an officially supported Google product._

2
node_modules/zx/build/cli.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};

240
node_modules/zx/build/cli.js generated vendored Executable file
View file

@ -0,0 +1,240 @@
#!/usr/bin/env node
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import fs from 'fs-extra';
import minimist from 'minimist';
import { createRequire } from 'node:module';
import { basename, dirname, extname, join, resolve } from 'node:path';
import url from 'node:url';
import { updateArgv } from './goods.js';
import { $, chalk, fetch, ProcessOutput } from './index.js';
import { startRepl } from './repl.js';
import { randomId } from './util.js';
import { installDeps, parseDeps } from './deps.js';
function printUsage() {
// language=txt
console.log(`
${chalk.bold('zx ' + getVersion())}
A tool for writing better scripts
${chalk.bold('Usage')}
zx [options] <script>
${chalk.bold('Options')}
--quiet don't echo commands
--shell=<path> custom shell binary
--prefix=<command> prefix all commands
--eval=<js>, -e evaluate script
--install, -i install dependencies
--experimental enable experimental features
--version, -v print current zx version
--help, -h print help
--repl start repl
`);
}
const argv = minimist(process.argv.slice(2), {
string: ['shell', 'prefix', 'eval'],
boolean: ['version', 'help', 'quiet', 'install', 'repl', 'experimental'],
alias: { e: 'eval', i: 'install', v: 'version', h: 'help' },
stopEarly: true,
});
await (async function main() {
const globals = './globals.js';
await import(globals);
if (argv.quiet)
$.verbose = false;
if (argv.shell)
$.shell = argv.shell;
if (argv.prefix)
$.prefix = argv.prefix;
if (argv.experimental) {
Object.assign(global, await import('./experimental.js'));
}
if (argv.version) {
console.log(getVersion());
return;
}
if (argv.help) {
printUsage();
return;
}
if (argv.repl) {
startRepl();
return;
}
if (argv.eval) {
await runScript(argv.eval);
return;
}
const firstArg = argv._[0];
updateArgv(argv._.slice(firstArg === undefined ? 0 : 1));
if (!firstArg || firstArg === '-') {
const success = await scriptFromStdin();
if (!success)
printUsage();
return;
}
if (/^https?:/.test(firstArg)) {
await scriptFromHttp(firstArg);
return;
}
const filepath = firstArg.startsWith('file:///')
? url.fileURLToPath(firstArg)
: resolve(firstArg);
await importPath(filepath);
})().catch((err) => {
if (err instanceof ProcessOutput) {
console.error('Error:', err.message);
}
else {
console.error(err);
}
process.exitCode = 1;
});
async function runScript(script) {
const filepath = join(process.cwd(), `zx-${randomId()}.mjs`);
await writeAndImport(script, filepath);
}
async function scriptFromStdin() {
let script = '';
if (!process.stdin.isTTY) {
process.stdin.setEncoding('utf8');
for await (const chunk of process.stdin) {
script += chunk;
}
if (script.length > 0) {
await runScript(script);
return true;
}
}
return false;
}
async function scriptFromHttp(remote) {
const res = await fetch(remote);
if (!res.ok) {
console.error(`Error: Can't get ${remote}`);
process.exit(1);
}
const script = await res.text();
const pathname = new URL(remote).pathname;
const name = basename(pathname);
const ext = extname(pathname) || '.mjs';
const filepath = join(process.cwd(), `${name}-${randomId()}${ext}`);
await writeAndImport(script, filepath);
}
async function writeAndImport(script, filepath, origin = filepath) {
await fs.writeFile(filepath, script.toString());
try {
await importPath(filepath, origin);
}
finally {
await fs.rm(filepath);
}
}
async function importPath(filepath, origin = filepath) {
const ext = extname(filepath);
if (ext === '') {
const tmpFilename = fs.existsSync(`${filepath}.mjs`)
? `${basename(filepath)}-${randomId()}.mjs`
: `${basename(filepath)}.mjs`;
return writeAndImport(await fs.readFile(filepath), join(dirname(filepath), tmpFilename), origin);
}
if (ext === '.md') {
return writeAndImport(transformMarkdown(await fs.readFile(filepath)), join(dirname(filepath), basename(filepath) + '.mjs'), origin);
}
if (argv.install) {
const deps = parseDeps(await fs.readFile(filepath));
await installDeps(deps, dirname(filepath));
}
const __filename = resolve(origin);
const __dirname = dirname(__filename);
const require = createRequire(origin);
Object.assign(global, { __filename, __dirname, require });
await import(url.pathToFileURL(filepath).toString());
}
function transformMarkdown(buf) {
const source = buf.toString();
const output = [];
let state = 'root';
let prevLineIsEmpty = true;
for (let line of source.split('\n')) {
switch (state) {
case 'root':
if (/^( {4}|\t)/.test(line) && prevLineIsEmpty) {
output.push(line);
state = 'tab';
}
else if (/^```(js|javascript)$/.test(line)) {
output.push('');
state = 'js';
}
else if (/^```(sh|bash)$/.test(line)) {
output.push('await $`');
state = 'bash';
}
else if (/^```.*$/.test(line)) {
output.push('');
state = 'other';
}
else {
prevLineIsEmpty = line === '';
output.push('// ' + line);
}
break;
case 'tab':
if (/^( +|\t)/.test(line)) {
output.push(line);
}
else if (line === '') {
output.push('');
}
else {
output.push('// ' + line);
state = 'root';
}
break;
case 'js':
if (/^```$/.test(line)) {
output.push('');
state = 'root';
}
else {
output.push(line);
}
break;
case 'bash':
if (/^```$/.test(line)) {
output.push('`');
state = 'root';
}
else {
output.push(line);
}
break;
case 'other':
if (/^```$/.test(line)) {
output.push('');
state = 'root';
}
else {
output.push('// ' + line);
}
break;
}
}
return output.join('\n');
}
function getVersion() {
return createRequire(import.meta.url)('../package.json').version;
}

101
node_modules/zx/build/core.d.ts generated vendored Normal file
View file

@ -0,0 +1,101 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { ChildProcess, spawn, StdioNull, StdioPipe } from 'node:child_process';
import { Readable, Writable } from 'node:stream';
import { inspect } from 'node:util';
import { RequestInfo, RequestInit } from 'node-fetch';
import { Duration, noop, quote } from './util.js';
export declare type Shell = (pieces: TemplateStringsArray, ...args: any[]) => ProcessPromise;
declare const processCwd: unique symbol;
export declare type Options = {
[processCwd]: string;
cwd?: string;
verbose: boolean;
env: NodeJS.ProcessEnv;
shell: string | boolean;
prefix: string;
quote: typeof quote;
spawn: typeof spawn;
log: typeof log;
};
export declare const defaults: Options;
export declare const $: Shell & Options;
declare type Resolve = (out: ProcessOutput) => void;
declare type IO = StdioPipe | StdioNull;
export declare class ProcessPromise extends Promise<ProcessOutput> {
child?: ChildProcess;
private _command;
private _from;
private _resolve;
private _reject;
private _snapshot;
private _stdio;
private _nothrow;
private _quiet;
private _timeout?;
private _timeoutSignal?;
private _resolved;
private _halted;
private _piped;
_prerun: typeof noop;
_postrun: typeof noop;
_bind(cmd: string, from: string, resolve: Resolve, reject: Resolve, options: Options): void;
run(): ProcessPromise;
get stdin(): Writable;
get stdout(): Readable;
get stderr(): Readable;
get exitCode(): Promise<number | null>;
then<R = ProcessOutput, E = ProcessOutput>(onfulfilled?: ((value: ProcessOutput) => PromiseLike<R> | R) | undefined | null, onrejected?: ((reason: ProcessOutput) => PromiseLike<E> | E) | undefined | null): Promise<R | E>;
catch<T = ProcessOutput>(onrejected?: ((reason: ProcessOutput) => PromiseLike<T> | T) | undefined | null): Promise<ProcessOutput | T>;
pipe(dest: Writable | ProcessPromise): ProcessPromise;
kill(signal?: string): Promise<void>;
stdio(stdin: IO, stdout?: IO, stderr?: IO): ProcessPromise;
nothrow(): ProcessPromise;
quiet(): ProcessPromise;
timeout(d: Duration, signal?: string): ProcessPromise;
halt(): ProcessPromise;
get isHalted(): boolean;
}
export declare class ProcessOutput extends Error {
private readonly _code;
private readonly _signal;
private readonly _stdout;
private readonly _stderr;
private readonly _combined;
constructor(code: number | null, signal: NodeJS.Signals | null, stdout: string, stderr: string, combined: string, message: string);
toString(): string;
get stdout(): string;
get stderr(): string;
get exitCode(): number | null;
get signal(): NodeJS.Signals | null;
[inspect.custom](): string;
}
export declare function within<R>(callback: () => R): R;
export declare function cd(dir: string): void;
export declare type LogEntry = {
kind: 'cmd';
verbose: boolean;
cmd: string;
} | {
kind: 'stdout' | 'stderr';
verbose: boolean;
data: Buffer;
} | {
kind: 'cd';
dir: string;
} | {
kind: 'fetch';
url: RequestInfo;
init?: RequestInit;
} | {
kind: 'retry';
error: string;
} | {
kind: 'custom';
data: any;
};
export declare function log(entry: LogEntry): void;
export {};

361
node_modules/zx/build/core.js generated vendored Normal file
View file

@ -0,0 +1,361 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'node:assert';
import { spawn } from 'node:child_process';
import { AsyncLocalStorage, createHook } from 'node:async_hooks';
import { inspect } from 'node:util';
import chalk from 'chalk';
import which from 'which';
import { errnoMessage, exitCodeInfo, formatCmd, noop, parseDuration, psTree, quote, quotePowerShell, } from './util.js';
const processCwd = Symbol('processCwd');
const storage = new AsyncLocalStorage();
const hook = createHook({
init: syncCwd,
before: syncCwd,
promiseResolve: syncCwd,
after: syncCwd,
destroy: syncCwd,
});
hook.enable();
export const defaults = {
[processCwd]: process.cwd(),
verbose: true,
env: process.env,
shell: true,
prefix: '',
quote: () => {
throw new Error('No quote function is defined: https://ï.at/no-quote-func');
},
spawn,
log,
};
try {
defaults.shell = which.sync('bash');
defaults.prefix = 'set -euo pipefail;';
defaults.quote = quote;
}
catch (err) {
if (process.platform == 'win32') {
defaults.shell = which.sync('powershell.exe');
defaults.quote = quotePowerShell;
}
}
function getStore() {
return storage.getStore() || defaults;
}
export const $ = new Proxy(function (pieces, ...args) {
const from = new Error().stack.split(/^\s*at\s/m)[2].trim();
if (pieces.some((p) => p == undefined)) {
throw new Error(`Malformed command at ${from}`);
}
let resolve, reject;
const promise = new ProcessPromise((...args) => ([resolve, reject] = args));
let cmd = pieces[0], i = 0;
while (i < args.length) {
let s;
if (Array.isArray(args[i])) {
s = args[i].map((x) => $.quote(substitute(x))).join(' ');
}
else {
s = $.quote(substitute(args[i]));
}
cmd += s + pieces[++i];
}
promise._bind(cmd, from, resolve, reject, getStore());
// Postpone run to allow promise configuration.
setImmediate(() => promise.isHalted || promise.run());
return promise;
}, {
set(_, key, value) {
const target = key in Function.prototype ? _ : getStore();
Reflect.set(target, key, value);
return true;
},
get(_, key) {
const target = key in Function.prototype ? _ : getStore();
return Reflect.get(target, key);
},
});
function substitute(arg) {
if (arg?.stdout) {
return arg.stdout.replace(/\n$/, '');
}
return `${arg}`;
}
export class ProcessPromise extends Promise {
constructor() {
super(...arguments);
this._command = '';
this._from = '';
this._resolve = noop;
this._reject = noop;
this._snapshot = getStore();
this._stdio = ['inherit', 'pipe', 'pipe'];
this._nothrow = false;
this._quiet = false;
this._resolved = false;
this._halted = false;
this._piped = false;
this._prerun = noop;
this._postrun = noop;
}
_bind(cmd, from, resolve, reject, options) {
this._command = cmd;
this._from = from;
this._resolve = resolve;
this._reject = reject;
this._snapshot = { ...options };
}
run() {
const $ = this._snapshot;
if (this.child)
return this; // The _run() can be called from a few places.
this._prerun(); // In case $1.pipe($2), the $2 returned, and on $2._run() invoke $1._run().
$.log({
kind: 'cmd',
cmd: this._command,
verbose: $.verbose && !this._quiet,
});
this.child = $.spawn($.prefix + this._command, {
cwd: $.cwd ?? $[processCwd],
shell: typeof $.shell === 'string' ? $.shell : true,
stdio: this._stdio,
windowsHide: true,
env: $.env,
});
this.child.on('close', (code, signal) => {
let message = `exit code: ${code}`;
if (code != 0 || signal != null) {
message = `${stderr || '\n'} at ${this._from}`;
message += `\n exit code: ${code}${exitCodeInfo(code) ? ' (' + exitCodeInfo(code) + ')' : ''}`;
if (signal != null) {
message += `\n signal: ${signal}`;
}
}
let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);
if (code === 0 || this._nothrow) {
this._resolve(output);
}
else {
this._reject(output);
}
this._resolved = true;
});
this.child.on('error', (err) => {
const message = `${err.message}\n` +
` errno: ${err.errno} (${errnoMessage(err.errno)})\n` +
` code: ${err.code}\n` +
` at ${this._from}`;
this._reject(new ProcessOutput(null, null, stdout, stderr, combined, message));
this._resolved = true;
});
let stdout = '', stderr = '', combined = '';
let onStdout = (data) => {
$.log({ kind: 'stdout', data, verbose: $.verbose && !this._quiet });
stdout += data;
combined += data;
};
let onStderr = (data) => {
$.log({ kind: 'stderr', data, verbose: $.verbose && !this._quiet });
stderr += data;
combined += data;
};
if (!this._piped)
this.child.stdout?.on('data', onStdout); // If process is piped, don't collect or print output.
this.child.stderr?.on('data', onStderr); // Stderr should be printed regardless of piping.
this._postrun(); // In case $1.pipe($2), after both subprocesses are running, we can pipe $1.stdout to $2.stdin.
if (this._timeout && this._timeoutSignal) {
const t = setTimeout(() => this.kill(this._timeoutSignal), this._timeout);
this.finally(() => clearTimeout(t)).catch(noop);
}
return this;
}
get stdin() {
this.stdio('pipe');
this.run();
assert(this.child);
if (this.child.stdin == null)
throw new Error('The stdin of subprocess is null.');
return this.child.stdin;
}
get stdout() {
this.run();
assert(this.child);
if (this.child.stdout == null)
throw new Error('The stdout of subprocess is null.');
return this.child.stdout;
}
get stderr() {
this.run();
assert(this.child);
if (this.child.stderr == null)
throw new Error('The stderr of subprocess is null.');
return this.child.stderr;
}
get exitCode() {
return this.then((p) => p.exitCode, (p) => p.exitCode);
}
then(onfulfilled, onrejected) {
if (this.isHalted && !this.child) {
throw new Error('The process is halted!');
}
return super.then(onfulfilled, onrejected);
}
catch(onrejected) {
return super.catch(onrejected);
}
pipe(dest) {
if (typeof dest == 'string')
throw new Error('The pipe() method does not take strings. Forgot $?');
if (this._resolved) {
if (dest instanceof ProcessPromise)
dest.stdin.end(); // In case of piped stdin, we may want to close stdin of dest as well.
throw new Error("The pipe() method shouldn't be called after promise is already resolved!");
}
this._piped = true;
if (dest instanceof ProcessPromise) {
dest.stdio('pipe');
dest._prerun = this.run.bind(this);
dest._postrun = () => {
if (!dest.child)
throw new Error('Access to stdin of pipe destination without creation a subprocess.');
this.stdout.pipe(dest.stdin);
};
return dest;
}
else {
this._postrun = () => this.stdout.pipe(dest);
return this;
}
}
async kill(signal = 'SIGTERM') {
if (!this.child)
throw new Error('Trying to kill a process without creating one.');
if (!this.child.pid)
throw new Error('The process pid is undefined.');
let children = await psTree(this.child.pid);
for (const p of children) {
try {
process.kill(+p.PID, signal);
}
catch (e) { }
}
try {
process.kill(this.child.pid, signal);
}
catch (e) { }
}
stdio(stdin, stdout = 'pipe', stderr = 'pipe') {
this._stdio = [stdin, stdout, stderr];
return this;
}
nothrow() {
this._nothrow = true;
return this;
}
quiet() {
this._quiet = true;
return this;
}
timeout(d, signal = 'SIGTERM') {
this._timeout = parseDuration(d);
this._timeoutSignal = signal;
return this;
}
halt() {
this._halted = true;
return this;
}
get isHalted() {
return this._halted;
}
}
export class ProcessOutput extends Error {
constructor(code, signal, stdout, stderr, combined, message) {
super(message);
this._code = code;
this._signal = signal;
this._stdout = stdout;
this._stderr = stderr;
this._combined = combined;
}
toString() {
return this._combined;
}
get stdout() {
return this._stdout;
}
get stderr() {
return this._stderr;
}
get exitCode() {
return this._code;
}
get signal() {
return this._signal;
}
[inspect.custom]() {
let stringify = (s, c) => s.length === 0 ? "''" : c(inspect(s));
return `ProcessOutput {
stdout: ${stringify(this.stdout, chalk.green)},
stderr: ${stringify(this.stderr, chalk.red)},
signal: ${inspect(this.signal)},
exitCode: ${(this.exitCode === 0 ? chalk.green : chalk.red)(this.exitCode)}${exitCodeInfo(this.exitCode)
? chalk.grey(' (' + exitCodeInfo(this.exitCode) + ')')
: ''}
}`;
}
}
export function within(callback) {
return storage.run({ ...getStore() }, callback);
}
function syncCwd() {
if ($[processCwd] != process.cwd())
process.chdir($[processCwd]);
}
export function cd(dir) {
$.log({ kind: 'cd', dir });
process.chdir(dir);
$[processCwd] = process.cwd();
}
export function log(entry) {
switch (entry.kind) {
case 'cmd':
if (!entry.verbose)
return;
process.stderr.write(formatCmd(entry.cmd));
break;
case 'stdout':
case 'stderr':
if (!entry.verbose)
return;
process.stderr.write(entry.data);
break;
case 'cd':
if (!$.verbose)
return;
process.stderr.write('$ ' + chalk.greenBright('cd') + ` ${entry.dir}\n`);
break;
case 'fetch':
if (!$.verbose)
return;
const init = entry.init ? ' ' + inspect(entry.init) : '';
process.stderr.write('$ ' + chalk.greenBright('fetch') + ` ${entry.url}${init}\n`);
break;
case 'retry':
if (!$.verbose)
return;
process.stderr.write(entry.error + '\n');
}
}

3
node_modules/zx/build/deps.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
/// <reference types="node" resolution-mode="require"/>
export declare function installDeps(dependencies: Record<string, string>, prefix?: string): Promise<void>;
export declare function parseDeps(content: Buffer): Record<string, string>;

119
node_modules/zx/build/deps.js generated vendored Normal file
View file

@ -0,0 +1,119 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { $ } from './core.js';
import { spinner } from './experimental.js';
export async function installDeps(dependencies, prefix) {
const packages = Object.entries(dependencies).map(([name, version]) => `${name}@${version}`);
const flags = prefix ? `--prefix=${prefix}` : '';
if (packages.length === 0) {
return;
}
await spinner(`npm i ${packages.join(' ')}`, () => $ `npm install --no-save --no-audit --no-fund ${flags} ${packages}`.nothrow());
}
const builtins = new Set([
'_http_agent',
'_http_client',
'_http_common',
'_http_incoming',
'_http_outgoing',
'_http_server',
'_stream_duplex',
'_stream_passthrough',
'_stream_readable',
'_stream_transform',
'_stream_wrap',
'_stream_writable',
'_tls_common',
'_tls_wrap',
'assert',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'http2',
'https',
'inspector',
'module',
'net',
'os',
'path',
'perf_hooks',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'trace_events',
'tty',
'url',
'util',
'v8',
'vm',
'wasi',
'worker_threads',
'zlib',
]);
const importRe = [
/\bimport\s+['"](?<path>[^'"]+)['"]/,
/\bimport\(['"](?<path>[^'"]+)['"]\)/,
/\brequire\(['"](?<path>[^'"]+)['"]\)/,
/\bfrom\s+['"](?<path>[^'"]+)['"]/,
];
const nameRe = /^(?<name>(@[a-z0-9-]+\/)?[a-z0-9-]+)\/?.*$/i;
const versionRe = /(\/\/|\/\*)\s*@(?<version>[~^]?([\dvx*]+([-.][\dx*]+)*))/i;
export function parseDeps(content) {
const deps = {};
const lines = content.toString().split('\n');
for (let line of lines) {
const tuple = parseImports(line);
if (tuple) {
deps[tuple.name] = tuple.version;
}
}
return deps;
}
function parseImports(line) {
for (let re of importRe) {
const name = parsePackageName(re.exec(line)?.groups?.path);
const version = parseVersion(line);
if (name) {
return { name, version };
}
}
}
function parsePackageName(path) {
if (!path)
return;
const name = nameRe.exec(path)?.groups?.name;
if (name && !builtins.has(name)) {
return name;
}
}
function parseVersion(line) {
return versionRe.exec(line)?.groups?.version || 'latest';
}

6
node_modules/zx/build/experimental.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import { Duration } from './util.js';
export declare function retry<T>(count: number, callback: () => T): Promise<T>;
export declare function retry<T>(count: number, duration: Duration | Generator<number>, callback: () => T): Promise<T>;
export declare function expBackoff(max?: Duration, rand?: Duration): Generator<number, void, unknown>;
export declare function spinner<T>(callback: () => T): Promise<T>;
export declare function spinner<T>(title: string, callback: () => T): Promise<T>;

94
node_modules/zx/build/experimental.js generated vendored Normal file
View file

@ -0,0 +1,94 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'node:assert';
import chalk from 'chalk';
import { $, within } from './core.js';
import { sleep } from './goods.js';
import { parseDuration } from './util.js';
export async function retry(count, a, b) {
const total = count;
let callback;
let delayStatic = 0;
let delayGen;
if (typeof a == 'function') {
callback = a;
}
else {
if (typeof a == 'object') {
delayGen = a;
}
else {
delayStatic = parseDuration(a);
}
assert(b);
callback = b;
}
let lastErr;
let attempt = 0;
while (count-- > 0) {
attempt++;
try {
return await callback();
}
catch (err) {
let delay = 0;
if (delayStatic > 0)
delay = delayStatic;
if (delayGen)
delay = delayGen.next().value;
$.log({
kind: 'retry',
error: chalk.bgRed.white(' FAIL ') +
` Attempt: ${attempt}${total == Infinity ? '' : `/${total}`}` +
(delay > 0 ? `; next in ${delay}ms` : ''),
});
lastErr = err;
if (count == 0)
break;
if (delay)
await sleep(delay);
}
}
throw lastErr;
}
export function* expBackoff(max = '60s', rand = '100ms') {
const maxMs = parseDuration(max);
const randMs = parseDuration(rand);
let n = 1;
while (true) {
const ms = Math.floor(Math.random() * randMs);
yield Math.min(2 ** n++, maxMs) + ms;
}
}
export async function spinner(title, callback) {
if (typeof title == 'function') {
callback = title;
title = '';
}
let i = 0;
const spin = () => process.stderr.write(` ${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i++ % 10]} ${title}\r`);
return within(async () => {
$.verbose = false;
const id = setInterval(spin, 100);
let result;
try {
result = await callback();
}
finally {
clearInterval(id);
process.stderr.write(' '.repeat(process.stdout.columns - 1) + '\r');
}
return result;
});
}

31
node_modules/zx/build/globals.d.ts generated vendored Normal file
View file

@ -0,0 +1,31 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="which" />
import * as _ from './index.js';
declare global {
type ProcessPromise = _.ProcessPromise;
type ProcessOutput = _.ProcessOutput;
var ProcessPromise: typeof _.ProcessPromise;
var ProcessOutput: typeof _.ProcessOutput;
var log: typeof _.log;
var $: typeof _.$;
var argv: typeof _.argv;
var cd: typeof _.cd;
var chalk: typeof _.chalk;
var echo: typeof _.echo;
var fs: typeof _.fs;
var glob: typeof _.glob;
var globby: typeof _.globby;
var nothrow: typeof _.nothrow;
var os: typeof _.os;
var path: typeof _.path;
var question: typeof _.question;
var quiet: typeof _.quiet;
var quote: typeof _.quote;
var quotePowerShell: typeof _.quotePowerShell;
var sleep: typeof _.sleep;
var stdin: typeof _.stdin;
var which: typeof _.which;
var within: typeof _.within;
var YAML: typeof _.YAML;
}

15
node_modules/zx/build/globals.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as _ from './index.js';
Object.assign(global, _);

21
node_modules/zx/build/goods.d.ts generated vendored Normal file
View file

@ -0,0 +1,21 @@
import * as globbyModule from 'globby';
import minimist from 'minimist';
import { RequestInfo, RequestInit } from 'node-fetch';
import { Duration } from './util.js';
export { default as chalk } from 'chalk';
export { default as fs } from 'fs-extra';
export { default as which } from 'which';
export { default as YAML } from 'yaml';
export { default as path } from 'node:path';
export { default as os } from 'node:os';
export declare let argv: minimist.ParsedArgs;
export declare function updateArgv(args: string[]): void;
export declare const globby: ((patterns: string | readonly string[], options?: globbyModule.Options) => Promise<string[]>) & typeof globbyModule;
export declare const glob: ((patterns: string | readonly string[], options?: globbyModule.Options) => Promise<string[]>) & typeof globbyModule;
export declare function sleep(duration: Duration): Promise<unknown>;
export declare function fetch(url: RequestInfo, init?: RequestInit): Promise<import("node-fetch").Response>;
export declare function echo(...args: any[]): void;
export declare function question(query?: string, options?: {
choices: string[];
}): Promise<string>;
export declare function stdin(): Promise<string>;

92
node_modules/zx/build/goods.js generated vendored Normal file
View file

@ -0,0 +1,92 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as globbyModule from 'globby';
import minimist from 'minimist';
import nodeFetch from 'node-fetch';
import { createInterface } from 'node:readline';
import { $, ProcessOutput } from './core.js';
import { isString, parseDuration } from './util.js';
export { default as chalk } from 'chalk';
export { default as fs } from 'fs-extra';
export { default as which } from 'which';
export { default as YAML } from 'yaml';
export { default as path } from 'node:path';
export { default as os } from 'node:os';
export let argv = minimist(process.argv.slice(2));
export function updateArgv(args) {
argv = minimist(args);
global.argv = argv;
}
export const globby = Object.assign(function globby(patterns, options) {
return globbyModule.globby(patterns, options);
}, globbyModule);
export const glob = globby;
export function sleep(duration) {
return new Promise((resolve) => {
setTimeout(resolve, parseDuration(duration));
});
}
export async function fetch(url, init) {
$.log({ kind: 'fetch', url, init });
return nodeFetch(url, init);
}
export function echo(pieces, ...args) {
let msg;
const lastIdx = pieces.length - 1;
if (Array.isArray(pieces) &&
pieces.every(isString) &&
lastIdx === args.length) {
msg =
args.map((a, i) => pieces[i] + stringify(a)).join('') + pieces[lastIdx];
}
else {
msg = [pieces, ...args].map(stringify).join(' ');
}
console.log(msg);
}
function stringify(arg) {
if (arg instanceof ProcessOutput) {
return arg.toString().replace(/\n$/, '');
}
return `${arg}`;
}
export async function question(query, options) {
let completer = undefined;
if (options && Array.isArray(options.choices)) {
/* c8 ignore next 5 */
completer = function completer(line) {
const completions = options.choices;
const hits = completions.filter((c) => c.startsWith(line));
return [hits.length ? hits : completions, line];
};
}
const rl = createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
completer,
});
return new Promise((resolve) => rl.question(query ?? '', (answer) => {
rl.close();
resolve(answer);
}));
}
export async function stdin() {
let buf = '';
process.stdin.setEncoding('utf8');
for await (const chunk of process.stdin) {
buf += chunk;
}
return buf;
}

12
node_modules/zx/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
import { ProcessPromise } from './core.js';
export { $, Shell, Options, ProcessPromise, ProcessOutput, within, cd, log, LogEntry, } from './core.js';
export { argv, chalk, echo, fetch, fs, glob, globby, os, path, question, sleep, stdin, which, YAML, } from './goods.js';
export { Duration, quote, quotePowerShell } from './util.js';
/**
* @deprecated Use $.nothrow() instead.
*/
export declare function nothrow(promise: ProcessPromise): ProcessPromise;
/**
* @deprecated Use $.quiet() instead.
*/
export declare function quiet(promise: ProcessPromise): ProcessPromise;

28
node_modules/zx/build/index.js generated vendored Normal file
View file

@ -0,0 +1,28 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export { $, ProcessPromise, ProcessOutput, within, cd, log, } from './core.js';
export { argv, chalk, echo, fetch, fs, glob, globby, os, path, question, sleep, stdin, which, YAML, } from './goods.js';
export { quote, quotePowerShell } from './util.js';
/**
* @deprecated Use $.nothrow() instead.
*/
export function nothrow(promise) {
return promise.nothrow();
}
/**
* @deprecated Use $.quiet() instead.
*/
export function quiet(promise) {
return promise.quiet();
}

1
node_modules/zx/build/repl.d.ts generated vendored Normal file
View file

@ -0,0 +1 @@
export declare function startRepl(): void;

34
node_modules/zx/build/repl.js generated vendored Normal file
View file

@ -0,0 +1,34 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import chalk from 'chalk';
import os from 'node:os';
import path from 'node:path';
import repl from 'node:repl';
import { inspect } from 'node:util';
import { ProcessOutput, defaults } from './core.js';
export function startRepl() {
defaults.verbose = false;
const r = repl.start({
prompt: chalk.greenBright.bold(' '),
useGlobal: true,
preview: false,
writer(output) {
if (output instanceof ProcessOutput) {
return output.toString().replace(/\n$/, '');
}
return inspect(output, { colors: true });
},
});
r.setupHistory(path.join(os.homedir(), '.zx_repl_history'), () => { });
}

12
node_modules/zx/build/util.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
import psTreeModule from 'ps-tree';
export declare const psTree: (arg1: number) => Promise<readonly psTreeModule.PS[]>;
export declare function noop(): void;
export declare function randomId(): string;
export declare function isString(obj: any): boolean;
export declare function quote(arg: string): string;
export declare function quotePowerShell(arg: string): string;
export declare function exitCodeInfo(exitCode: number | null): string | undefined;
export declare function errnoMessage(errno: number | undefined): string;
export declare type Duration = number | `${number}s` | `${number}ms`;
export declare function parseDuration(d: Duration): number;
export declare function formatCmd(cmd?: string): string;

346
node_modules/zx/build/util.js generated vendored Normal file
View file

@ -0,0 +1,346 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import chalk from 'chalk';
import { promisify } from 'node:util';
import psTreeModule from 'ps-tree';
export const psTree = promisify(psTreeModule);
export function noop() { }
export function randomId() {
return Math.random().toString(36).slice(2);
}
export function isString(obj) {
return typeof obj === 'string';
}
export function quote(arg) {
if (/^[a-z0-9/_.\-@:=]+$/i.test(arg) || arg === '') {
return arg;
}
return (`$'` +
arg
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\f/g, '\\f')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v')
.replace(/\0/g, '\\0') +
`'`);
}
export function quotePowerShell(arg) {
if (/^[a-z0-9/_.\-]+$/i.test(arg) || arg === '') {
return arg;
}
return `'` + arg.replace(/'/g, "''") + `'`;
}
export function exitCodeInfo(exitCode) {
return {
2: 'Misuse of shell builtins',
126: 'Invoked command cannot execute',
127: 'Command not found',
128: 'Invalid exit argument',
129: 'Hangup',
130: 'Interrupt',
131: 'Quit and dump core',
132: 'Illegal instruction',
133: 'Trace/breakpoint trap',
134: 'Process aborted',
135: 'Bus error: "access to undefined portion of memory object"',
136: 'Floating point exception: "erroneous arithmetic operation"',
137: 'Kill (terminate immediately)',
138: 'User-defined 1',
139: 'Segmentation violation',
140: 'User-defined 2',
141: 'Write to pipe with no one reading',
142: 'Signal raised by alarm',
143: 'Termination (request to terminate)',
145: 'Child process terminated, stopped (or continued*)',
146: 'Continue if stopped',
147: 'Stop executing temporarily',
148: 'Terminal stop signal',
149: 'Background process attempting to read from tty ("in")',
150: 'Background process attempting to write to tty ("out")',
151: 'Urgent data available on socket',
152: 'CPU time limit exceeded',
153: 'File size limit exceeded',
154: 'Signal raised by timer counting virtual time: "virtual timer expired"',
155: 'Profiling timer expired',
157: 'Pollable event',
159: 'Bad syscall',
}[exitCode || -1];
}
export function errnoMessage(errno) {
if (errno === undefined) {
return 'Unknown error';
}
return ({
0: 'Success',
1: 'Not super-user',
2: 'No such file or directory',
3: 'No such process',
4: 'Interrupted system call',
5: 'I/O error',
6: 'No such device or address',
7: 'Arg list too long',
8: 'Exec format error',
9: 'Bad file number',
10: 'No children',
11: 'No more processes',
12: 'Not enough core',
13: 'Permission denied',
14: 'Bad address',
15: 'Block device required',
16: 'Mount device busy',
17: 'File exists',
18: 'Cross-device link',
19: 'No such device',
20: 'Not a directory',
21: 'Is a directory',
22: 'Invalid argument',
23: 'Too many open files in system',
24: 'Too many open files',
25: 'Not a typewriter',
26: 'Text file busy',
27: 'File too large',
28: 'No space left on device',
29: 'Illegal seek',
30: 'Read only file system',
31: 'Too many links',
32: 'Broken pipe',
33: 'Math arg out of domain of func',
34: 'Math result not representable',
35: 'File locking deadlock error',
36: 'File or path name too long',
37: 'No record locks available',
38: 'Function not implemented',
39: 'Directory not empty',
40: 'Too many symbolic links',
42: 'No message of desired type',
43: 'Identifier removed',
44: 'Channel number out of range',
45: 'Level 2 not synchronized',
46: 'Level 3 halted',
47: 'Level 3 reset',
48: 'Link number out of range',
49: 'Protocol driver not attached',
50: 'No CSI structure available',
51: 'Level 2 halted',
52: 'Invalid exchange',
53: 'Invalid request descriptor',
54: 'Exchange full',
55: 'No anode',
56: 'Invalid request code',
57: 'Invalid slot',
59: 'Bad font file fmt',
60: 'Device not a stream',
61: 'No data (for no delay io)',
62: 'Timer expired',
63: 'Out of streams resources',
64: 'Machine is not on the network',
65: 'Package not installed',
66: 'The object is remote',
67: 'The link has been severed',
68: 'Advertise error',
69: 'Srmount error',
70: 'Communication error on send',
71: 'Protocol error',
72: 'Multihop attempted',
73: 'Cross mount point (not really error)',
74: 'Trying to read unreadable message',
75: 'Value too large for defined data type',
76: 'Given log. name not unique',
77: 'f.d. invalid for this operation',
78: 'Remote address changed',
79: 'Can access a needed shared lib',
80: 'Accessing a corrupted shared lib',
81: '.lib section in a.out corrupted',
82: 'Attempting to link in too many libs',
83: 'Attempting to exec a shared library',
84: 'Illegal byte sequence',
86: 'Streams pipe error',
87: 'Too many users',
88: 'Socket operation on non-socket',
89: 'Destination address required',
90: 'Message too long',
91: 'Protocol wrong type for socket',
92: 'Protocol not available',
93: 'Unknown protocol',
94: 'Socket type not supported',
95: 'Not supported',
96: 'Protocol family not supported',
97: 'Address family not supported by protocol family',
98: 'Address already in use',
99: 'Address not available',
100: 'Network interface is not configured',
101: 'Network is unreachable',
102: 'Connection reset by network',
103: 'Connection aborted',
104: 'Connection reset by peer',
105: 'No buffer space available',
106: 'Socket is already connected',
107: 'Socket is not connected',
108: "Can't send after socket shutdown",
109: 'Too many references',
110: 'Connection timed out',
111: 'Connection refused',
112: 'Host is down',
113: 'Host is unreachable',
114: 'Socket already connected',
115: 'Connection already in progress',
116: 'Stale file handle',
122: 'Quota exceeded',
123: 'No medium (in tape drive)',
125: 'Operation canceled',
130: 'Previous owner died',
131: 'State not recoverable',
}[-errno] || 'Unknown error');
}
export function parseDuration(d) {
if (typeof d == 'number') {
if (isNaN(d) || d < 0)
throw new Error(`Invalid duration: "${d}".`);
return d;
}
else if (/\d+s/.test(d)) {
return +d.slice(0, -1) * 1000;
}
else if (/\d+ms/.test(d)) {
return +d.slice(0, -2);
}
throw new Error(`Unknown duration: "${d}".`);
}
export function formatCmd(cmd) {
if (cmd == undefined)
return chalk.grey('undefined');
const chars = [...cmd];
let out = '$ ';
let buf = '';
let ch;
let state = root;
let wordCount = 0;
while (state) {
ch = chars.shift() || 'EOF';
if (ch == '\n') {
out += style(state, buf) + '\n> ';
buf = '';
continue;
}
const next = ch == 'EOF' ? undefined : state();
if (next != state) {
out += style(state, buf);
buf = '';
}
state = next == root ? next() : next;
buf += ch;
}
function style(state, s) {
if (s == '')
return '';
if (reservedWords.includes(s)) {
return chalk.cyanBright(s);
}
if (state == word && wordCount == 0) {
wordCount++;
return chalk.greenBright(s);
}
if (state == syntax) {
wordCount = 0;
return chalk.cyanBright(s);
}
if (state == dollar)
return chalk.yellowBright(s);
if (state?.name.startsWith('str'))
return chalk.yellowBright(s);
return s;
}
function isSyntax(ch) {
return '()[]{}<>;:+|&='.includes(ch);
}
function root() {
if (/\s/.test(ch))
return space;
if (isSyntax(ch))
return syntax;
if (/[$]/.test(ch))
return dollar;
if (/["]/.test(ch))
return strDouble;
if (/[']/.test(ch))
return strSingle;
return word;
}
function space() {
if (/\s/.test(ch))
return space;
return root;
}
function word() {
if (/[0-9a-z/_.]/i.test(ch))
return word;
return root;
}
function syntax() {
if (isSyntax(ch))
return syntax;
return root;
}
function dollar() {
if (/[']/.test(ch))
return str;
return root;
}
function str() {
if (/[']/.test(ch))
return strEnd;
if (/[\\]/.test(ch))
return strBackslash;
return str;
}
function strBackslash() {
return strEscape;
}
function strEscape() {
return str;
}
function strDouble() {
if (/["]/.test(ch))
return strEnd;
return strDouble;
}
function strSingle() {
if (/[']/.test(ch))
return strEnd;
return strSingle;
}
function strEnd() {
return root;
}
return out + '\n';
}
const reservedWords = [
'if',
'then',
'else',
'elif',
'fi',
'case',
'esac',
'for',
'select',
'while',
'until',
'do',
'done',
'in',
];

91
node_modules/zx/package.json generated vendored Normal file
View file

@ -0,0 +1,91 @@
{
"name": "zx",
"version": "7.1.1",
"description": "A tool for writing better scripts.",
"type": "module",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"typesVersions": {
"*": {
".": [
"./build/index.d.ts"
],
"globals": [
"./build/globals.d.ts"
],
"experimental": [
"./build/experimental.d.ts"
],
"cli": [
"./build/cli.d.ts"
],
"core": [
"./build/core.d.ts"
]
}
},
"exports": {
".": "./build/index.js",
"./globals": "./build/globals.js",
"./experimental": "./build/experimental.js",
"./cli": "./build/cli.js",
"./core": "./build/core.js",
"./package.json": "./package.json"
},
"bin": {
"zx": "./build/cli.js"
},
"engines": {
"node": ">= 16.0.0"
},
"scripts": {
"fmt": "prettier --write .",
"fmt:check": "prettier --check .",
"build": "tsc --project tsconfig.prod.json",
"build:check": "tsc",
"test": "npm run build && PATH=$(env -i bash -c 'echo $PATH') node_modules/.bin/uvu test -i fixtures",
"test:types": "tsd",
"coverage": "c8 --check-coverage npm test -- -i package",
"mutation": "stryker run",
"circular": "madge --circular src/*"
},
"dependencies": {
"@types/fs-extra": "^9.0.13",
"@types/minimist": "^1.2.2",
"@types/node": "^18.7.20",
"@types/ps-tree": "^1.1.2",
"@types/which": "^2.0.1",
"chalk": "^5.0.1",
"fs-extra": "^10.1.0",
"globby": "^13.1.2",
"minimist": "^1.2.6",
"node-fetch": "3.2.10",
"ps-tree": "^1.2.0",
"which": "^2.0.2",
"yaml": "^2.1.1"
},
"devDependencies": {
"@stryker-mutator/core": "^6.2.2",
"c8": "^7.12.0",
"madge": "^5.0.1",
"prettier": "^2.7.1",
"tsd": "^0.24.1",
"typescript": "^4.8.3",
"uvu": "^0.5.6"
},
"publishConfig": {
"registry": "https://wombat-dressing-room.appspot.com"
},
"files": [
"build",
"zx.js"
],
"prettier": {
"semi": false,
"singleQuote": true,
"endOfLine": "lf"
},
"repository": "google/zx",
"author": "Anton Medvedev <anton@medv.io>",
"license": "Apache-2.0"
}