This commit is contained in:
2024-11-28 23:08:17 +01:00
parent 8895fde030
commit 0dda8e760c
16116 changed files with 2866428 additions and 71 deletions

21
node_modules/vite-plugin-vue-devtools/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 webfansplz
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.

31
node_modules/vite-plugin-vue-devtools/README.md generated vendored Normal file
View File

@@ -0,0 +1,31 @@
# vite-plugin-vue-devtools
> `vite-plugin-vue-devtools` is a `Vite` plugin designed to enhance the `Vue` developer experience.
## Installation
```sh
npm add -D vite-plugin-vue-devtools
```
## Usage
### Configuration Vite
```ts
import { defineConfig } from 'vite'
import VueDevTools from 'vite-plugin-vue-devtools'
export default defineConfig({
plugins: [
VueDevTools(),
vue(),
],
})
```
## Documentation
Check out all the DevTools details at [devtools.vuejs.org](https://devtools.vuejs.org).

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
const n=Object.freeze(JSON.parse('{"displayName":"Diff","name":"diff","patterns":[{"captures":{"1":{"name":"punctuation.definition.separator.diff"}},"match":"^((\\\\*{15})|(={67})|(-{3}))$\\\\n?","name":"meta.separator.diff"},{"match":"^\\\\d+(,\\\\d+)*(a|d|c)\\\\d+(,\\\\d+)*$\\\\n?","name":"meta.diff.range.normal"},{"captures":{"1":{"name":"punctuation.definition.range.diff"},"2":{"name":"meta.toc-list.line-number.diff"},"3":{"name":"punctuation.definition.range.diff"}},"match":"^(@@)\\\\s*(.+?)\\\\s*(@@)($\\\\n?)?","name":"meta.diff.range.unified"},{"captures":{"3":{"name":"punctuation.definition.range.diff"},"4":{"name":"punctuation.definition.range.diff"},"6":{"name":"punctuation.definition.range.diff"},"7":{"name":"punctuation.definition.range.diff"}},"match":"^(((-{3}) .+ (-{4}))|((\\\\*{3}) .+ (\\\\*{4})))$\\\\n?","name":"meta.diff.range.context"},{"match":"^diff --git a/.*$\\\\n?","name":"meta.diff.header.git"},{"match":"^diff (-|\\\\S+\\\\s+\\\\S+).*$\\\\n?","name":"meta.diff.header.command"},{"captures":{"4":{"name":"punctuation.definition.from-file.diff"},"6":{"name":"punctuation.definition.from-file.diff"},"7":{"name":"punctuation.definition.from-file.diff"}},"match":"(^(((-{3}) .+)|((\\\\*{3}) .+))$\\\\n?|^(={4}) .+(?= - ))","name":"meta.diff.header.from-file"},{"captures":{"2":{"name":"punctuation.definition.to-file.diff"},"3":{"name":"punctuation.definition.to-file.diff"},"4":{"name":"punctuation.definition.to-file.diff"}},"match":"(^(\\\\+{3}) .+$\\\\n?| (-) .* (={4})$\\\\n?)","name":"meta.diff.header.to-file"},{"captures":{"3":{"name":"punctuation.definition.inserted.diff"},"6":{"name":"punctuation.definition.inserted.diff"}},"match":"^(((>)( .*)?)|((\\\\+).*))$\\\\n?","name":"markup.inserted.diff"},{"captures":{"1":{"name":"punctuation.definition.changed.diff"}},"match":"^(!).*$\\\\n?","name":"markup.changed.diff"},{"captures":{"3":{"name":"punctuation.definition.deleted.diff"},"6":{"name":"punctuation.definition.deleted.diff"}},"match":"^(((<)( .*)?)|((-).*))$\\\\n?","name":"markup.deleted.diff"},{"begin":"^(#)","captures":{"1":{"name":"punctuation.definition.comment.diff"}},"comment":"Git produces unified diffs with embedded comments\\"","end":"\\\\n","name":"comment.line.number-sign.diff"},{"match":"^index [0-9a-f]{7,40}\\\\.\\\\.[0-9a-f]{7,40}.*$\\\\n?","name":"meta.diff.index.git"},{"captures":{"1":{"name":"punctuation.separator.key-value.diff"},"2":{"name":"meta.toc-list.file-name.diff"}},"match":"^Index(:) (.+)$\\\\n?","name":"meta.diff.index"},{"match":"^Only in .*: .*$\\\\n?","name":"meta.diff.only-in"}],"scopeName":"source.diff"}')),e=[n];export{e as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
const n=Object.freeze(JSON.parse('{"displayName":"JSON","name":"json","patterns":[{"include":"#value"}],"repository":{"array":{"begin":"\\\\[","beginCaptures":{"0":{"name":"punctuation.definition.array.begin.json"}},"end":"\\\\]","endCaptures":{"0":{"name":"punctuation.definition.array.end.json"}},"name":"meta.structure.array.json","patterns":[{"include":"#value"},{"match":",","name":"punctuation.separator.array.json"},{"match":"[^\\\\s\\\\]]","name":"invalid.illegal.expected-array-separator.json"}]},"comments":{"patterns":[{"begin":"/\\\\*\\\\*(?!/)","captures":{"0":{"name":"punctuation.definition.comment.json"}},"end":"\\\\*/","name":"comment.block.documentation.json"},{"begin":"/\\\\*","captures":{"0":{"name":"punctuation.definition.comment.json"}},"end":"\\\\*/","name":"comment.block.json"},{"captures":{"1":{"name":"punctuation.definition.comment.json"}},"match":"(//).*$\\\\n?","name":"comment.line.double-slash.js"}]},"constant":{"match":"\\\\b(?:true|false|null)\\\\b","name":"constant.language.json"},"number":{"match":"-?(?:0|[1-9]\\\\d*)(?:(?:\\\\.\\\\d+)?(?:[eE][+-]?\\\\d+)?)?","name":"constant.numeric.json"},"object":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.dictionary.begin.json"}},"end":"\\\\}","endCaptures":{"0":{"name":"punctuation.definition.dictionary.end.json"}},"name":"meta.structure.dictionary.json","patterns":[{"comment":"the JSON object key","include":"#objectkey"},{"include":"#comments"},{"begin":":","beginCaptures":{"0":{"name":"punctuation.separator.dictionary.key-value.json"}},"end":"(,)|(?=\\\\})","endCaptures":{"1":{"name":"punctuation.separator.dictionary.pair.json"}},"name":"meta.structure.dictionary.value.json","patterns":[{"comment":"the JSON object value","include":"#value"},{"match":"[^\\\\s,]","name":"invalid.illegal.expected-dictionary-separator.json"}]},{"match":"[^\\\\s}]","name":"invalid.illegal.expected-dictionary-separator.json"}]},"objectkey":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.support.type.property-name.begin.json"}},"end":"\\"","endCaptures":{"0":{"name":"punctuation.support.type.property-name.end.json"}},"name":"string.json support.type.property-name.json","patterns":[{"include":"#stringcontent"}]},"string":{"begin":"\\"","beginCaptures":{"0":{"name":"punctuation.definition.string.begin.json"}},"end":"\\"","endCaptures":{"0":{"name":"punctuation.definition.string.end.json"}},"name":"string.quoted.double.json","patterns":[{"include":"#stringcontent"}]},"stringcontent":{"patterns":[{"match":"\\\\\\\\(?:[\\"\\\\\\\\/bfnrt]|u[0-9a-fA-F]{4})","name":"constant.character.escape.json"},{"match":"\\\\\\\\.","name":"invalid.illegal.unrecognized-string-escape.json"}]},"value":{"patterns":[{"include":"#constant"},{"include":"#number"},{"include":"#string"},{"include":"#array"},{"include":"#object"},{"include":"#comments"}]}},"scopeName":"source.json"}')),e=[n];export{e as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
(function () {
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const setting = localStorage.getItem('color-schema') || 'auto'
if (setting === 'dark' || (prefersDark && setting !== 'light'))
document.documentElement.classList.toggle('dark', true)
})()

View File

@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="./logo.svg" type="image/svg+xml" />
<title>Vue DevTools Client</title>
<script src="./color-scheme.js"></script>
<script type="module" crossorigin src="./assets/index-BvYt1BTo.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-D7KMD2Av.css">
</head>
<body>
<div id="app"></div>
</body>
</html>

208
node_modules/vite-plugin-vue-devtools/client/logo.svg generated vendored Normal file
View File

@@ -0,0 +1,208 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="图层_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 246.52 208.87" style="enable-background:new 0 0 246.52 208.87;" xml:space="preserve">
<style type="text/css">
.st0{fill:url(#SVGID_1_);}
.st1{fill:url(#SVGID_2_);}
</style>
<g>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="-3449.4177" y1="3349.6663" x2="-3229.0247" y2="3349.6663" gradientTransform="matrix(-1 0 0 -1 -3219.187 3476.3691)">
<stop offset="5.291010e-03" style="stop-color:#008FC1"/>
<stop offset="1" style="stop-color:#00F879"/>
</linearGradient>
<polygon class="st0" points="120.03,212.11 230.23,41.3 9.84,41.3 "/>
<g>
<image style="overflow:visible;opacity:0.25;" width="249" height="186" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPkAAAC6CAYAAABsg+tSAAAACXBIWXMAAAsSAAALEgHS3X78AAAA
GXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAI+pJREFUeNrsnQl32tiyhQuM5zGO
48Rx0p1O3/7//+fde5N0Z47teB6wDTyfldpXm+II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ldqRAHynUPxX8sxS4y1r34JA77P+DfUMVfJvAf6rPN/sAj4o3qHtacUwR8I/S
Gx8+N2IUJ3r8JLiPpLvrLvf8c7gd8srBvkR++6qa6wx4DPgVSYZXMOwNo/I1ybcybtTe+DzF5kzh
PiIz/Jjg5n5+dxGf2+F2yCsDe0NBXdRjiVR7LQX4DT14QCNuGPMG9rkUf/6xgI/aG5+n2Jwq3OfS
u/tgE4naxnrw5ZBX5vzVKUjHCt8PeKvqmMi6Ynz3Bv1ftgXXYyDPozf+hTHDL0mxWbVjDTl9OeRT
oe6DgF8h6FcIbpj6KyZQt2RM+7kRIB+1N76dYtM0frartkPuwBuzftHcBFbIfOfXAP+CxPveZ1l5
9sZnHztLMpAvh3zmgG+YY578+gV6DbDHlHyYz6/o3vgOtkPuS3oj5HVz2Oj6HPnk7KOP6pNPqje+
L4d8Js89K3JderfMxhVdH1dvfF8OuX8ekRtAnr3mytAb35dD7msA/Hksh9mXL1++pmH9vwADAHAM
gc6+plHTAAAAAElFTkSuQmCC" transform="matrix(1 0 0 1 2.4348 -3.6377)">
</image>
<g>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="22.5895" y1="139.0657" x2="213.6784" y2="32.6144">
<stop offset="0" style="stop-color:#00FFFF"/>
<stop offset="0.3711" style="stop-color:#52F3AB"/>
<stop offset="1" style="stop-color:#D9E021"/>
</linearGradient>
<path class="st1" d="M242.01,37c-0.04-0.11-0.08-0.22-0.13-0.33c-0.6-1.25-1.9-1.89-3.31-2.28c0,0-0.01-0.01-0.01-0.01
c-1.49-0.4-3.42-0.57-5.76-0.51c-0.03-0.01-0.06-0.01-0.08,0c-4.16,0.12-8.13,0.76-12.39,1.57c-0.01,0-0.01,0-0.02,0.01
c-4.54,0.88-9.18,2.04-13.73,3.29c-0.94,0.26-1.9,0.53-2.87,0.8c-0.07,0.01-0.13,0.04-0.19,0.06c-1.04,0.3-2.09,0.61-3.17,0.93
c-0.02,0-0.04,0.01-0.06,0.01c-12.55,3.75-25.12,8.24-37.45,13.03c0,0,0,0,0,0c0,0,0,0-0.01,0c-0.14,0-15.72-5.1-15.86-5.13
c-0.61-0.2-0.92-0.88-0.68-1.47l6.23-15.29c0.1-0.26,0.3-0.47,0.56-0.59l20.96-9.74C118.88-27.47,29.43,12.85,30.45,87.28
l23.77-11.77C53.03,46.21,87.14,29.34,109.7,48.1L88.08,58.77l-6.17,18.28l15.77,5.3l0.01,0.01l2.56,0.86l21.58-10.68
c1.5,29.11-33.18,46.21-55.44,27.41l-15.76,7.8c-4.95,2.95-9.86,6.01-14.65,9.15c-0.01,0.01-0.01,0.01-0.01,0.01
c-1.19,0.78-2.35,1.55-3.47,2.31c-0.01,0-0.01,0-0.01,0.01c-4.57,3.09-9.06,6.32-13.15,9.62c-0.05,0.03-0.1,0.07-0.14,0.11
c-0.42,0.34-0.82,0.67-1.22,1c0,0,0,0,0,0c-1.47,1.21-2.91,2.47-4.29,3.76c-0.21,0.2-0.42,0.39-0.62,0.6
c-0.71,0.67-1.37,1.34-1.96,1.98c-0.01,0.01-0.02,0.01-0.03,0.03c-0.26,0.28-0.51,0.56-0.75,0.82c-0.03,0.03-0.05,0.06-0.07,0.09
c-0.14,0.16-0.27,0.31-0.4,0.46c-0.13,0.15-0.26,0.3-0.38,0.45c-0.38,0.44-0.71,0.88-1.02,1.31c-0.39,0.53-0.74,1.08-1.05,1.63
c-0.47,0.81-0.84,1.67-1.02,2.52c-0.02,0.09-0.04,0.18-0.05,0.27c0,0.04-0.01,0.09-0.01,0.13c-0.45,5.19,7.2,4.85,11.33,4.65
c0.69-0.04,1.37-0.1,2.06-0.18c0.39-0.04,0.79-0.08,1.19-0.13c0.34-0.04,0.68-0.08,1.03-0.13c9.58-1.34,18.99-3.95,28.3-6.74
c56.32,67.3,166.12,18.25,152.23-69.41c11.24-6.86,22.67-14.75,29.27-20.46c2.91-2.52,5.74-5.12,8.02-8.12
c0.11-0.14,0.22-0.28,0.31-0.42c0.2-0.28,0.39-0.56,0.56-0.83c0.38-0.61,0.75-1.24,1.02-1.89c0.04-0.1,0.08-0.19,0.12-0.29
c0.04-0.1,0.08-0.21,0.11-0.3C242.21,38.72,242.26,37.79,242.01,37z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 15 KiB

8139
node_modules/vite-plugin-vue-devtools/dist/vite.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

41
node_modules/vite-plugin-vue-devtools/dist/vite.d.cts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { PluginOption } from 'vite';
import { VitePluginInspectorOptions } from 'vite-plugin-vue-inspector';
interface VitePluginVueDevToolsOptions {
/**
* append an import to the module id ending with `appendTo` instead of adding a script into body
* useful for projects that do not use html file as an entry
*
* WARNING: only set this if you know exactly what it does.
* @default ''
*/
appendTo?: string | RegExp;
/**
* Enable vue component inspector
*
* @default true
*/
componentInspector?: boolean | VitePluginInspectorOptions;
/**
* Target editor when open in editor (v7.2.0+)
*
* @default code (Visual Studio Code)
*/
launchEditor?: 'appcode' | 'atom' | 'atom-beta' | 'brackets' | 'clion' | 'code' | 'code-insiders' | 'codium' | 'emacs' | 'idea' | 'notepad++' | 'pycharm' | 'phpstorm' | 'rubymine' | 'sublime' | 'vim' | 'visualstudio' | 'webstorm' | 'rider' | string;
/**
* Customize openInEditor host
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
openInEditorHost?: string | false;
/**
* DevTools client host
* useful for projects that use a reverse proxy
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
clientHost?: string | false;
}
declare function VitePluginVueDevTools(options?: VitePluginVueDevToolsOptions): PluginOption;
export { type VitePluginVueDevToolsOptions, VitePluginVueDevTools as default };

41
node_modules/vite-plugin-vue-devtools/dist/vite.d.mts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { PluginOption } from 'vite';
import { VitePluginInspectorOptions } from 'vite-plugin-vue-inspector';
interface VitePluginVueDevToolsOptions {
/**
* append an import to the module id ending with `appendTo` instead of adding a script into body
* useful for projects that do not use html file as an entry
*
* WARNING: only set this if you know exactly what it does.
* @default ''
*/
appendTo?: string | RegExp;
/**
* Enable vue component inspector
*
* @default true
*/
componentInspector?: boolean | VitePluginInspectorOptions;
/**
* Target editor when open in editor (v7.2.0+)
*
* @default code (Visual Studio Code)
*/
launchEditor?: 'appcode' | 'atom' | 'atom-beta' | 'brackets' | 'clion' | 'code' | 'code-insiders' | 'codium' | 'emacs' | 'idea' | 'notepad++' | 'pycharm' | 'phpstorm' | 'rubymine' | 'sublime' | 'vim' | 'visualstudio' | 'webstorm' | 'rider' | string;
/**
* Customize openInEditor host
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
openInEditorHost?: string | false;
/**
* DevTools client host
* useful for projects that use a reverse proxy
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
clientHost?: string | false;
}
declare function VitePluginVueDevTools(options?: VitePluginVueDevToolsOptions): PluginOption;
export { type VitePluginVueDevToolsOptions, VitePluginVueDevTools as default };

41
node_modules/vite-plugin-vue-devtools/dist/vite.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { PluginOption } from 'vite';
import { VitePluginInspectorOptions } from 'vite-plugin-vue-inspector';
interface VitePluginVueDevToolsOptions {
/**
* append an import to the module id ending with `appendTo` instead of adding a script into body
* useful for projects that do not use html file as an entry
*
* WARNING: only set this if you know exactly what it does.
* @default ''
*/
appendTo?: string | RegExp;
/**
* Enable vue component inspector
*
* @default true
*/
componentInspector?: boolean | VitePluginInspectorOptions;
/**
* Target editor when open in editor (v7.2.0+)
*
* @default code (Visual Studio Code)
*/
launchEditor?: 'appcode' | 'atom' | 'atom-beta' | 'brackets' | 'clion' | 'code' | 'code-insiders' | 'codium' | 'emacs' | 'idea' | 'notepad++' | 'pycharm' | 'phpstorm' | 'rubymine' | 'sublime' | 'vim' | 'visualstudio' | 'webstorm' | 'rider' | string;
/**
* Customize openInEditor host
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
openInEditorHost?: string | false;
/**
* DevTools client host
* useful for projects that use a reverse proxy
* @default false
* @deprecated This option is deprecated and removed in 7.1.0. The plugin now automatically detects the correct host.
*/
clientHost?: string | false;
}
declare function VitePluginVueDevTools(options?: VitePluginVueDevToolsOptions): PluginOption;
export { type VitePluginVueDevToolsOptions, VitePluginVueDevTools as default };

8122
node_modules/vite-plugin-vue-devtools/dist/vite.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,955 @@
import {type Buffer} from 'node:buffer';
import {type ChildProcess} from 'node:child_process';
import {type Stream, type Readable as ReadableStream, type Writable as WritableStream} from 'node:stream';
export type StdioOption =
| 'pipe'
| 'overlapped'
| 'ipc'
| 'ignore'
| 'inherit'
| Stream
| number
| undefined;
type EncodingOption =
| 'utf8'
// eslint-disable-next-line unicorn/text-encoding-identifier-case
| 'utf-8'
| 'utf16le'
| 'utf-16le'
| 'ucs2'
| 'ucs-2'
| 'latin1'
| 'binary'
| 'ascii'
| 'hex'
| 'base64'
| 'base64url'
| 'buffer'
| null
| undefined;
type DefaultEncodingOption = 'utf8';
type BufferEncodingOption = 'buffer' | null;
export type CommonOptions<EncodingType extends EncodingOption = DefaultEncodingOption> = {
/**
Kill the spawned process when the parent process exits unless either:
- the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
- the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
@default true
*/
readonly cleanup?: boolean;
/**
Prefer locally installed binaries when looking for a binary to execute.
If you `$ npm install foo`, you can then `execa('foo')`.
@default `true` with `$`, `false` otherwise
*/
readonly preferLocal?: boolean;
/**
Preferred path to find locally installed binaries in (use with `preferLocal`).
@default process.cwd()
*/
readonly localDir?: string | URL;
/**
Path to the Node.js executable to use in child processes.
This can be either an absolute path or a path relative to the `cwd` option.
Requires `preferLocal` to be `true`.
For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
@default process.execPath
*/
readonly execPath?: string;
/**
Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected.
If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.
@default true
*/
readonly buffer?: boolean;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default `inherit` with `$`, `pipe` otherwise
*/
readonly stdin?: StdioOption;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default 'pipe'
*/
readonly stdout?: StdioOption;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default 'pipe'
*/
readonly stderr?: StdioOption;
/**
Setting this to `false` resolves the promise with the error instead of rejecting it.
@default true
*/
readonly reject?: boolean;
/**
Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.
@default false
*/
readonly all?: boolean;
/**
Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
@default true
*/
readonly stripFinalNewline?: boolean;
/**
Set to `false` if you don't want to extend the environment variables when providing the `env` property.
@default true
*/
readonly extendEnv?: boolean;
/**
Current working directory of the child process.
@default process.cwd()
*/
readonly cwd?: string | URL;
/**
Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.
@default process.env
*/
readonly env?: NodeJS.ProcessEnv;
/**
Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.
*/
readonly argv0?: string;
/**
Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
@default 'pipe'
*/
readonly stdio?: 'pipe' | 'overlapped' | 'ignore' | 'inherit' | readonly StdioOption[];
/**
Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execaNode()`:
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
@default 'json'
*/
readonly serialization?: 'json' | 'advanced';
/**
Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).
@default false
*/
readonly detached?: boolean;
/**
Sets the user identity of the process.
*/
readonly uid?: number;
/**
Sets the group identity of the process.
*/
readonly gid?: number;
/**
If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.
We recommend against using this option since it is:
- not cross-platform, encouraging shell-specific syntax.
- slower, because of the additional shell interpretation.
- unsafe, potentially allowing command injection.
@default false
*/
readonly shell?: boolean | string;
/**
Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'` or `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.
@default 'utf8'
*/
readonly encoding?: EncodingType;
/**
If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.
@default 0
*/
readonly timeout?: number;
/**
Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.
@default 100_000_000
*/
readonly maxBuffer?: number;
/**
Signal value to be used when the spawned process will be killed.
@default 'SIGTERM'
*/
readonly killSignal?: string | number;
/**
You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
When `AbortController.abort()` is called, [`.isCanceled`](https://github.com/sindresorhus/execa#iscanceled) becomes `true`.
@example
```
import {execa} from 'execa';
const abortController = new AbortController();
const subprocess = execa('node', [], {signal: abortController.signal});
setTimeout(() => {
abortController.abort();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
```
*/
readonly signal?: AbortSignal;
/**
If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.
@default false
*/
readonly windowsVerbatimArguments?: boolean;
/**
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
@default true
*/
readonly windowsHide?: boolean;
/**
Print each command on `stderr` before executing it.
This can also be enabled by setting the `NODE_DEBUG=execa` environment variable in the current process.
@default false
*/
readonly verbose?: boolean;
};
export type Options<EncodingType extends EncodingOption = DefaultEncodingOption> = {
/**
Write some input to the `stdin` of your binary.
If the input is a file, use the `inputFile` option instead.
*/
readonly input?: string | Buffer | ReadableStream;
/**
Use a file as input to the the `stdin` of your binary.
If the input is not a file, use the `input` option instead.
*/
readonly inputFile?: string;
} & CommonOptions<EncodingType>;
export type SyncOptions<EncodingType extends EncodingOption = DefaultEncodingOption> = {
/**
Write some input to the `stdin` of your binary.
If the input is a file, use the `inputFile` option instead.
*/
readonly input?: string | Buffer;
/**
Use a file as input to the the `stdin` of your binary.
If the input is not a file, use the `input` option instead.
*/
readonly inputFile?: string;
} & CommonOptions<EncodingType>;
export type NodeOptions<EncodingType extends EncodingOption = DefaultEncodingOption> = {
/**
The Node.js executable to use.
@default process.execPath
*/
readonly nodePath?: string;
/**
List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
@default process.execArgv
*/
readonly nodeOptions?: string[];
} & Options<EncodingType>;
type StdoutStderrAll = string | Buffer | undefined;
export type ExecaReturnBase<StdoutStderrType extends StdoutStderrAll> = {
/**
The file and arguments that were run, for logging purposes.
This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.
*/
command: string;
/**
Same as `command` but escaped.
This is meant to be copy and pasted into a shell, for debugging purposes.
Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execaCommand()`.
*/
escapedCommand: string;
/**
The numeric exit code of the process that was run.
*/
exitCode: number;
/**
The output of the process on stdout.
*/
stdout: StdoutStderrType;
/**
The output of the process on stderr.
*/
stderr: StdoutStderrType;
/**
Whether the process failed to run.
*/
failed: boolean;
/**
Whether the process timed out.
*/
timedOut: boolean;
/**
Whether the process was killed.
*/
killed: boolean;
/**
The name of the signal that was used to terminate the process. For example, `SIGFPE`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
*/
signal?: string;
/**
A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.
*/
signalDescription?: string;
/**
The `cwd` of the command if provided in the command options. Otherwise it is `process.cwd()`.
*/
cwd: string;
};
export type ExecaSyncReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {
} & ExecaReturnBase<StdoutStderrType>;
/**
Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
The child process fails when:
- its exit code is not `0`
- it was killed with a signal
- timing out
- being canceled
- there's not enough memory or there are already too many child processes
*/
export type ExecaReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {
/**
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the `all` option is `false` (default value)
- `execaSync()` was used
*/
all?: StdoutStderrType;
/**
Whether the process was canceled.
You can cancel the spawned process using the [`signal`](https://github.com/sindresorhus/execa#signal-1) option.
*/
isCanceled: boolean;
} & ExecaSyncReturnValue<StdoutStderrType>;
export type ExecaSyncError<StdoutStderrType extends StdoutStderrAll = string> = {
/**
Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.
The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.
*/
message: string;
/**
This is the same as the `message` property except it does not include the child process stdout/stderr.
*/
shortMessage: string;
/**
Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa.
This is `undefined` unless the child process exited due to an `error` event or a timeout.
*/
originalMessage?: string;
} & Error & ExecaReturnBase<StdoutStderrType>;
export type ExecaError<StdoutStderrType extends StdoutStderrAll = string> = {
/**
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the `all` option is `false` (default value)
- `execaSync()` was used
*/
all?: StdoutStderrType;
/**
Whether the process was canceled.
*/
isCanceled: boolean;
} & ExecaSyncError<StdoutStderrType>;
export type KillOptions = {
/**
Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
Can be disabled with `false`.
@default 5000
*/
forceKillAfterTimeout?: number | false;
};
export type ExecaChildPromise<StdoutStderrType extends StdoutStderrAll> = {
/**
Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
This is `undefined` if either:
- the `all` option is `false` (the default value)
- both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
*/
all?: ReadableStream;
catch<ResultType = never>(
onRejected?: (reason: ExecaError<StdoutStderrType>) => ResultType | PromiseLike<ResultType>
): Promise<ExecaReturnValue<StdoutStderrType> | ResultType>;
/**
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`. Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).
*/
kill(signal?: string, options?: KillOptions): void;
/**
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This used to be preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`. But now this is deprecated and you should either use `.kill()` or the `signal` option when creating the child process.
*/
cancel(): void;
/**
[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:
- Another `execa()` return value
- A writable stream
- A file path string
If the `target` is another `execa()` return value, it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the final result.
The `stdout` option] must be kept as `pipe`, its default value.
*/
pipeStdout?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;
pipeStdout?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;
/**
Like `pipeStdout()` but piping the child process's `stderr` instead.
The `stderr` option must be kept as `pipe`, its default value.
*/
pipeStderr?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;
pipeStderr?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;
/**
Combines both `pipeStdout()` and `pipeStderr()`.
Either the `stdout` option or the `stderr` option must be kept as `pipe`, their default value. Also, the `all` option must be set to `true`.
*/
pipeAll?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;
pipeAll?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;
};
export type ExecaChildProcess<StdoutStderrType extends StdoutStderrAll = string> = ChildProcess &
ExecaChildPromise<StdoutStderrType> &
Promise<ExecaReturnValue<StdoutStderrType>>;
/**
Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a `childProcess`.
Arguments are automatically escaped. They can contain any character, including spaces.
This is the preferred method when executing single commands.
@param file - The program/script to execute.
@param arguments - Arguments to pass to `file` on execution.
@returns An `ExecaChildProcess` that is both:
- a `Promise` resolving or rejecting with a `childProcessResult`.
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.
@throws A `childProcessResult` error
@example <caption>Promise interface</caption>
```
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
```
@example <caption>Redirect output to a file</caption>
```
import {execa} from 'execa';
// Similar to `echo unicorns > stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStdout('stdout.txt');
// Similar to `echo unicorns 2> stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStderr('stderr.txt');
// Similar to `echo unicorns &> stdout.txt` in Bash
await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt');
```
@example <caption>Redirect input from a file</caption>
```
import {execa} from 'execa';
// Similar to `cat < stdin.txt` in Bash
const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
```
@example <caption>Save and pipe output from a child process</caption>
```
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);
// Prints `unicorns`
console.log(stdout);
// Also returns 'unicorns'
```
@example <caption>Pipe multiple processes</caption>
```
import {execa} from 'execa';
// Similar to `echo unicorns | cat` in Bash
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));
console.log(stdout);
//=> 'unicorns'
```
@example <caption>Handling errors</caption>
```
import {execa} from 'execa';
// Catching an error
try {
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawn unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false,
cwd: '/path/to/cwd'
}
\*\/
}
```
@example <caption>Graceful termination</caption>
```
const subprocess = execa('node');
setTimeout(() => {
subprocess.kill('SIGTERM', {
forceKillAfterTimeout: 2000
});
}, 1000);
```
*/
export function execa(
file: string,
arguments?: readonly string[],
options?: Options
): ExecaChildProcess;
export function execa(
file: string,
arguments?: readonly string[],
options?: Options<BufferEncodingOption>
): ExecaChildProcess<Buffer>;
export function execa(file: string, options?: Options): ExecaChildProcess;
export function execa(file: string, options?: Options<BufferEncodingOption>): ExecaChildProcess<Buffer>;
/**
Same as `execa()` but synchronous.
@param file - The program/script to execute.
@param arguments - Arguments to pass to `file` on execution.
@returns A `childProcessResult` object
@throws A `childProcessResult` error
@example <caption>Promise interface</caption>
```
import {execa} from 'execa';
const {stdout} = execaSync('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
```
@example <caption>Redirect input from a file</caption>
```
import {execa} from 'execa';
// Similar to `cat < stdin.txt` in Bash
const {stdout} = execaSync('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
```
@example <caption>Handling errors</caption>
```
import {execa} from 'execa';
// Catching an error
try {
execaSync('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawnSync unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawnSync unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false,
cwd: '/path/to/cwd'
}
\*\/
}
```
*/
export function execaSync(
file: string,
arguments?: readonly string[],
options?: SyncOptions
): ExecaSyncReturnValue;
export function execaSync(
file: string,
arguments?: readonly string[],
options?: SyncOptions<BufferEncodingOption>
): ExecaSyncReturnValue<Buffer>;
export function execaSync(file: string, options?: SyncOptions): ExecaSyncReturnValue;
export function execaSync(
file: string,
options?: SyncOptions<BufferEncodingOption>
): ExecaSyncReturnValue<Buffer>;
/**
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a `childProcess`.
Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.
This is the preferred method when executing a user-supplied `command` string, such as in a REPL.
@param command - The program/script to execute and its arguments.
@returns An `ExecaChildProcess` that is both:
- a `Promise` resolving or rejecting with a `childProcessResult`.
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.
@throws A `childProcessResult` error
@example
```
import {execaCommand} from 'execa';
const {stdout} = await execaCommand('echo unicorns');
console.log(stdout);
//=> 'unicorns'
```
*/
export function execaCommand(command: string, options?: Options): ExecaChildProcess;
export function execaCommand(command: string, options?: Options<BufferEncodingOption>): ExecaChildProcess<Buffer>;
/**
Same as `execaCommand()` but synchronous.
@param command - The program/script to execute and its arguments.
@returns A `childProcessResult` object
@throws A `childProcessResult` error
@example
```
import {execaCommandSync} from 'execa';
const {stdout} = execaCommandSync('echo unicorns');
console.log(stdout);
//=> 'unicorns'
```
*/
export function execaCommandSync(command: string, options?: SyncOptions): ExecaSyncReturnValue;
export function execaCommandSync(command: string, options?: SyncOptions<BufferEncodingOption>): ExecaSyncReturnValue<Buffer>;
type TemplateExpression =
| string
| number
| ExecaReturnValue<string | Buffer>
| ExecaSyncReturnValue<string | Buffer>
| Array<string | number | ExecaReturnValue<string | Buffer> | ExecaSyncReturnValue<string | Buffer>>;
type Execa$<StdoutStderrType extends StdoutStderrAll = string> = {
/**
Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones.
This can be used to either:
- Set options for a specific command: `` $(options)`command` ``
- Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand` ``
@param options - Options to set
@returns A new instance of `$` with those `options` set
@example
```
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
await $$`echo unicorns`;
//=> 'unicorns'
await $$`echo rainbows`;
//=> 'rainbows'
```
*/
(options: Options<undefined>): Execa$<StdoutStderrType>;
(options: Options): Execa$;
(options: Options<BufferEncodingOption>): Execa$<Buffer>;
(
templates: TemplateStringsArray,
...expressions: TemplateExpression[]
): ExecaChildProcess<StdoutStderrType>;
/**
Same as $\`command\` but synchronous.
@returns A `childProcessResult` object
@throws A `childProcessResult` error
@example <caption>Basic</caption>
```
import {$} from 'execa';
const branch = $.sync`git branch --show-current`;
$.sync`dep deploy --branch=${branch}`;
```
@example <caption>Multiple arguments</caption>
```
import {$} from 'execa';
const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = $.sync`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'
```
@example <caption>With options</caption>
```
import {$} from 'execa';
$.sync({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'
```
@example <caption>Shared options</caption>
```
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
$$.sync`echo unicorns`;
//=> 'unicorns'
$$.sync`echo rainbows`;
//=> 'rainbows'
```
*/
sync(
templates: TemplateStringsArray,
...expressions: TemplateExpression[]
): ExecaSyncReturnValue<StdoutStderrType>;
};
/**
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a `childProcess`.
Arguments are automatically escaped. They can contain any character, but spaces must use `${}` like `` $`echo ${'has space'}` ``.
This is the preferred method when executing multiple commands in a script file.
The `command` string can inject any `${value}` with the following types: string, number, `childProcess` or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used.
@returns An `ExecaChildProcess` that is both:
- a `Promise` resolving or rejecting with a `childProcessResult`.
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.
@throws A `childProcessResult` error
@example <caption>Basic</caption>
```
import {$} from 'execa';
const branch = await $`git branch --show-current`;
await $`dep deploy --branch=${branch}`;
```
@example <caption>Multiple arguments</caption>
```
import {$} from 'execa';
const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = await $`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'
```
@example <caption>With options</caption>
```
import {$} from 'execa';
await $({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'
```
@example <caption>Shared options</caption>
```
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
await $$`echo unicorns`;
//=> 'unicorns'
await $$`echo rainbows`;
//=> 'rainbows'
```
*/
export const $: Execa$;
/**
Execute a Node.js script as a child process.
Arguments are automatically escaped. They can contain any character, including spaces.
This is the preferred method when executing Node.js files.
Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options):
- the current Node version and options are used. This can be overridden using the `nodePath` and `nodeOptions` options.
- the `shell` option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to `stdio`
@param scriptPath - Node.js script to execute.
@param arguments - Arguments to pass to `scriptPath` on execution.
@returns An `ExecaChildProcess` that is both:
- a `Promise` resolving or rejecting with a `childProcessResult`.
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.
@throws A `childProcessResult` error
@example
```
import {execa} from 'execa';
await execaNode('scriptPath', ['argument']);
```
*/
export function execaNode(
scriptPath: string,
arguments?: readonly string[],
options?: NodeOptions
): ExecaChildProcess;
export function execaNode(
scriptPath: string,
arguments?: readonly string[],
options?: NodeOptions<BufferEncodingOption>
): ExecaChildProcess<Buffer>;
export function execaNode(scriptPath: string, options?: NodeOptions): ExecaChildProcess;
export function execaNode(scriptPath: string, options?: NodeOptions<BufferEncodingOption>): ExecaChildProcess<Buffer>;

View File

@@ -0,0 +1,309 @@
import {Buffer} from 'node:buffer';
import path from 'node:path';
import childProcess from 'node:child_process';
import process from 'node:process';
import crossSpawn from 'cross-spawn';
import stripFinalNewline from 'strip-final-newline';
import {npmRunPathEnv} from 'npm-run-path';
import onetime from 'onetime';
import {makeError} from './lib/error.js';
import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';
import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';
import {addPipeMethods} from './lib/pipe.js';
import {handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';
import {mergePromise, getSpawnedPromise} from './lib/promise.js';
import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';
import {logCommand, verboseDefault} from './lib/verbose.js';
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
const env = extendEnv ? {...process.env, ...envOption} : envOption;
if (preferLocal) {
return npmRunPathEnv({env, cwd: localDir, execPath});
}
return env;
};
const handleArguments = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || process.cwd(),
execPath: process.execPath,
encoding: 'utf8',
reject: true,
cleanup: true,
all: false,
windowsHide: true,
verbose: verboseDefault,
...options,
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {
// #116
args.unshift('/q');
}
return {file, args, options, parsed};
};
const handleOutput = (options, value, error) => {
if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
// When `execaSync()` errors, we normalize it to '' to mimic `execa()`
return error === undefined ? undefined : '';
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
};
export function execa(file, args, options) {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
logCommand(escapedCommand, parsed.options);
validateTimeout(parsed.options);
let spawned;
try {
spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
} catch (error) {
// Ensure the returned error is always both a promise and a child process
const dummySpawned = new childProcess.ChildProcess();
const errorPromise = Promise.reject(makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
killed: false,
}));
mergePromise(dummySpawned, errorPromise);
return dummySpawned;
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context = {isCanceled: false};
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context);
const handlePromise = async () => {
const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout = handleOutput(parsed.options, stdoutResult);
const stderr = handleOutput(parsed.options, stderrResult);
const all = handleOutput(parsed.options, allResult);
if (error || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error,
exitCode,
signal,
stdout,
stderr,
all,
command,
escapedCommand,
parsed,
timedOut,
isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
killed: spawned.killed,
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command,
escapedCommand,
exitCode: 0,
stdout,
stderr,
all,
failed: false,
timedOut: false,
isCanceled: false,
killed: false,
};
};
const handlePromiseOnce = onetime(handlePromise);
handleInput(spawned, parsed.options);
spawned.all = makeAllStream(spawned, parsed.options);
addPipeMethods(spawned);
mergePromise(spawned, handlePromiseOnce);
return spawned;
}
export function execaSync(file, args, options) {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
logCommand(escapedCommand, parsed.options);
const input = handleInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input});
} catch (error) {
throw makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
killed: false,
});
}
const stdout = handleOutput(parsed.options, result.stdout, result.error);
const stderr = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error = makeError({
stdout,
stderr,
error: result.error,
signal: result.signal,
exitCode: result.status,
command,
escapedCommand,
parsed,
timedOut: result.error && result.error.code === 'ETIMEDOUT',
isCanceled: false,
killed: result.signal !== null,
});
if (!parsed.options.reject) {
return error;
}
throw error;
}
return {
command,
escapedCommand,
exitCode: 0,
stdout,
stderr,
failed: false,
timedOut: false,
isCanceled: false,
killed: false,
};
}
const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined
? {stdin: 'inherit'}
: {};
const normalizeScriptOptions = (options = {}) => ({
preferLocal: true,
...normalizeScriptStdin(options),
...options,
});
function create$(options) {
function $(templatesOrOptions, ...expressions) {
if (!Array.isArray(templatesOrOptions)) {
return create$({...options, ...templatesOrOptions});
}
const [file, ...args] = parseTemplates(templatesOrOptions, expressions);
return execa(file, args, normalizeScriptOptions(options));
}
$.sync = (templates, ...expressions) => {
if (!Array.isArray(templates)) {
throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');
}
const [file, ...args] = parseTemplates(templates, expressions);
return execaSync(file, args, normalizeScriptOptions(options));
};
return $;
}
export const $ = create$();
export function execaCommand(command, options) {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
}
export function execaCommandSync(command, options) {
const [file, ...args] = parseCommand(command);
return execaSync(file, args, options);
}
export function execaNode(scriptPath, args, options = {}) {
if (args && !Array.isArray(args) && typeof args === 'object') {
options = args;
args = [];
}
const stdio = normalizeStdioNode(options);
const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
const {
nodePath = process.execPath,
nodeOptions = defaultExecArgv,
} = options;
return execa(
nodePath,
[
...nodeOptions,
scriptPath,
...(Array.isArray(args) ? args : []),
],
{
...options,
stdin: undefined,
stdout: undefined,
stderr: undefined,
stdio,
shell: false,
},
);
}

View File

@@ -0,0 +1,119 @@
import {Buffer} from 'node:buffer';
import {ChildProcess} from 'node:child_process';
const normalizeArgs = (file, args = []) => {
if (!Array.isArray(args)) {
return [file];
}
return [file, ...args];
};
const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
const escapeArg = arg => {
if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
return arg;
}
return `"${arg.replaceAll('"', '\\"')}"`;
};
export const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');
export const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
const SPACES_REGEXP = / +/g;
// Handle `execaCommand()`
export const parseCommand = command => {
const tokens = [];
for (const token of command.trim().split(SPACES_REGEXP)) {
// Allow spaces to be escaped by a backslash if not meant as a delimiter
const previousToken = tokens.at(-1);
if (previousToken && previousToken.endsWith('\\')) {
// Merge previous token with current one
tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
} else {
tokens.push(token);
}
}
return tokens;
};
const parseExpression = expression => {
const typeOfExpression = typeof expression;
if (typeOfExpression === 'string') {
return expression;
}
if (typeOfExpression === 'number') {
return String(expression);
}
if (
typeOfExpression === 'object'
&& expression !== null
&& !(expression instanceof ChildProcess)
&& 'stdout' in expression
) {
const typeOfStdout = typeof expression.stdout;
if (typeOfStdout === 'string') {
return expression.stdout;
}
if (Buffer.isBuffer(expression.stdout)) {
return expression.stdout.toString();
}
throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);
}
throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);
};
const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 0
? [...tokens, ...nextTokens]
: [
...tokens.slice(0, -1),
`${tokens.at(-1)}${nextTokens[0]}`,
...nextTokens.slice(1),
];
const parseTemplate = ({templates, expressions, tokens, index, template}) => {
const templateString = template ?? templates.raw[index];
const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);
const newTokens = concatTokens(
tokens,
templateTokens,
templateString.startsWith(' '),
);
if (index === expressions.length) {
return newTokens;
}
const expression = expressions[index];
const expressionTokens = Array.isArray(expression)
? expression.map(expression => parseExpression(expression))
: [parseExpression(expression)];
return concatTokens(
newTokens,
expressionTokens,
templateString.endsWith(' '),
);
};
export const parseTemplates = (templates, expressions) => {
let tokens = [];
for (const [index, template] of templates.entries()) {
tokens = parseTemplate({templates, expressions, tokens, index, template});
}
return tokens;
};

View File

@@ -0,0 +1,87 @@
import process from 'node:process';
import {signalsByName} from 'human-signals';
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
if (timedOut) {
return `timed out after ${timeout} milliseconds`;
}
if (isCanceled) {
return 'was canceled';
}
if (errorCode !== undefined) {
return `failed with ${errorCode}`;
}
if (signal !== undefined) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== undefined) {
return `failed with exit code ${exitCode}`;
}
return 'failed';
};
export const makeError = ({
stdout,
stderr,
all,
error,
signal,
exitCode,
command,
escapedCommand,
timedOut,
isCanceled,
killed,
parsed: {options: {timeout, cwd = process.cwd()}},
}) => {
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
// We normalize them to `undefined`
exitCode = exitCode === null ? undefined : exitCode;
signal = signal === null ? undefined : signal;
const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
const errorCode = error && error.code;
const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
const execaMessage = `Command ${prefix}: ${command}`;
const isError = Object.prototype.toString.call(error) === '[object Error]';
const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
if (isError) {
error.originalMessage = error.message;
error.message = message;
} else {
error = new Error(message);
}
error.shortMessage = shortMessage;
error.command = command;
error.escapedCommand = escapedCommand;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
error.stdout = stdout;
error.stderr = stderr;
error.cwd = cwd;
if (all !== undefined) {
error.all = all;
}
if ('bufferedData' in error) {
delete error.bufferedData;
}
error.failed = true;
error.timedOut = Boolean(timedOut);
error.isCanceled = isCanceled;
error.killed = killed && !timedOut;
return error;
};

View File

@@ -0,0 +1,102 @@
import os from 'node:os';
import {onExit} from 'signal-exit';
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
};
const setKillTimeout = (kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
return;
}
const timeout = getForceKillAfterTimeout(options);
const t = setTimeout(() => {
kill('SIGKILL');
}, timeout);
// Guarded because there's no `.unref()` when `execa` is used in the renderer
// process in Electron. This cannot be tested since we don't run tests in
// Electron.
// istanbul ignore else
if (t.unref) {
t.unref();
}
};
const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
const isSigterm = signal => signal === os.constants.signals.SIGTERM
|| (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
return forceKillAfterTimeout;
};
// `childProcess.cancel()`
export const spawnedCancel = (spawned, context) => {
const killResult = spawned.kill();
if (killResult) {
context.isCanceled = true;
}
};
const timeoutKill = (spawned, signal, reject) => {
spawned.kill(signal);
reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
};
// `timeout` option handling
export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
if (timeout === 0 || timeout === undefined) {
return spawnedPromise;
}
let timeoutId;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
timeoutKill(spawned, killSignal, reject);
}, timeout);
});
const safeSpawnedPromise = spawnedPromise.finally(() => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
export const validateTimeout = ({timeout}) => {
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
};
// `cleanup` option handling
export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
const removeExitHandler = onExit(() => {
spawned.kill();
});
return timedPromise.finally(() => {
removeExitHandler();
});
};

View File

@@ -0,0 +1,42 @@
import {createWriteStream} from 'node:fs';
import {ChildProcess} from 'node:child_process';
import {isWritableStream} from 'is-stream';
const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';
const pipeToTarget = (spawned, streamName, target) => {
if (typeof target === 'string') {
spawned[streamName].pipe(createWriteStream(target));
return spawned;
}
if (isWritableStream(target)) {
spawned[streamName].pipe(target);
return spawned;
}
if (!isExecaChildProcess(target)) {
throw new TypeError('The second argument must be a string, a stream or an Execa child process.');
}
if (!isWritableStream(target.stdin)) {
throw new TypeError('The target child process\'s stdin must be available.');
}
spawned[streamName].pipe(target.stdin);
return target;
};
export const addPipeMethods = spawned => {
if (spawned.stdout !== null) {
spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout');
}
if (spawned.stderr !== null) {
spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr');
}
if (spawned.all !== undefined) {
spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all');
}
};

View File

@@ -0,0 +1,36 @@
// eslint-disable-next-line unicorn/prefer-top-level-await
const nativePromisePrototype = (async () => {})().constructor.prototype;
const descriptors = ['then', 'catch', 'finally'].map(property => [
property,
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
]);
// The return value is a mixin of `childProcess` and `Promise`
export const mergePromise = (spawned, promise) => {
for (const [property, descriptor] of descriptors) {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function'
? (...args) => Reflect.apply(descriptor.value, promise(), args)
: descriptor.value.bind(promise);
Reflect.defineProperty(spawned, property, {...descriptor, value});
}
};
// Use promises instead of `child_process` events
export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
spawned.on('exit', (exitCode, signal) => {
resolve({exitCode, signal});
});
spawned.on('error', error => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on('error', error => {
reject(error);
});
}
});

View File

@@ -0,0 +1,49 @@
const aliases = ['stdin', 'stdout', 'stderr'];
const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
export const normalizeStdio = options => {
if (!options) {
return;
}
const {stdio} = options;
if (stdio === undefined) {
return aliases.map(alias => options[alias]);
}
if (hasAlias(options)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
}
if (typeof stdio === 'string') {
return stdio;
}
if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}
const length = Math.max(stdio.length, aliases.length);
return Array.from({length}, (value, index) => stdio[index]);
};
// `ipc` is pushed unless it is already present
export const normalizeStdioNode = options => {
const stdio = normalizeStdio(options);
if (stdio === 'ipc') {
return 'ipc';
}
if (stdio === undefined || typeof stdio === 'string') {
return [stdio, stdio, stdio, 'ipc'];
}
if (stdio.includes('ipc')) {
return stdio;
}
return [...stdio, 'ipc'];
};

View File

@@ -0,0 +1,133 @@
import {createReadStream, readFileSync} from 'node:fs';
import {setTimeout} from 'node:timers/promises';
import {isStream} from 'is-stream';
import getStream, {getStreamAsBuffer} from 'get-stream';
import mergeStream from 'merge-stream';
const validateInputOptions = input => {
if (input !== undefined) {
throw new TypeError('The `input` and `inputFile` options cannot be both set.');
}
};
const getInputSync = ({input, inputFile}) => {
if (typeof inputFile !== 'string') {
return input;
}
validateInputOptions(input);
return readFileSync(inputFile);
};
// `input` and `inputFile` option in sync mode
export const handleInputSync = options => {
const input = getInputSync(options);
if (isStream(input)) {
throw new TypeError('The `input` option cannot be a stream in sync mode');
}
return input;
};
const getInput = ({input, inputFile}) => {
if (typeof inputFile !== 'string') {
return input;
}
validateInputOptions(input);
return createReadStream(inputFile);
};
// `input` and `inputFile` option in async mode
export const handleInput = (spawned, options) => {
const input = getInput(options);
if (input === undefined) {
return;
}
if (isStream(input)) {
input.pipe(spawned.stdin);
} else {
spawned.stdin.end(input);
}
};
// `all` interleaves `stdout` and `stderr`
export const makeAllStream = (spawned, {all}) => {
if (!all || (!spawned.stdout && !spawned.stderr)) {
return;
}
const mixed = mergeStream();
if (spawned.stdout) {
mixed.add(spawned.stdout);
}
if (spawned.stderr) {
mixed.add(spawned.stderr);
}
return mixed;
};
// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
const getBufferedData = async (stream, streamPromise) => {
// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve
if (!stream || streamPromise === undefined) {
return;
}
// Wait for the `all` stream to receive the last chunk before destroying the stream
await setTimeout(0);
stream.destroy();
try {
return await streamPromise;
} catch (error) {
return error.bufferedData;
}
};
const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
if (!stream || !buffer) {
return;
}
// eslint-disable-next-line unicorn/text-encoding-identifier-case
if (encoding === 'utf8' || encoding === 'utf-8') {
return getStream(stream, {maxBuffer});
}
if (encoding === null || encoding === 'buffer') {
return getStreamAsBuffer(stream, {maxBuffer});
}
return applyEncoding(stream, maxBuffer, encoding);
};
const applyEncoding = async (stream, maxBuffer, encoding) => {
const buffer = await getStreamAsBuffer(stream, {maxBuffer});
return buffer.toString(encoding);
};
// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
try {
return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
} catch (error) {
return Promise.all([
{error, signal: error.signal, timedOut: error.timedOut},
getBufferedData(stdout, stdoutPromise),
getBufferedData(stderr, stderrPromise),
getBufferedData(all, allPromise),
]);
}
};

View File

@@ -0,0 +1,19 @@
import {debuglog} from 'node:util';
import process from 'node:process';
export const verboseDefault = debuglog('execa').enabled;
const padField = (field, padding) => String(field).padStart(padding, '0');
const getTimestamp = () => {
const date = new Date();
return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;
};
export const logCommand = (escapedCommand, {verbose}) => {
if (!verbose) {
return;
}
process.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`);
};

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,90 @@
{
"name": "execa",
"version": "8.0.1",
"description": "Process execution for humans",
"license": "MIT",
"repository": "sindresorhus/execa",
"funding": "https://github.com/sindresorhus/execa?sponsor=1",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"types": "./index.d.ts",
"default": "./index.js"
},
"engines": {
"node": ">=16.17"
},
"scripts": {
"test": "xo && c8 ava && tsd"
},
"files": [
"index.js",
"index.d.ts",
"lib"
],
"keywords": [
"exec",
"child",
"process",
"execute",
"fork",
"execfile",
"spawn",
"file",
"shell",
"bin",
"binary",
"binaries",
"npm",
"path",
"local",
"zx"
],
"dependencies": {
"cross-spawn": "^7.0.3",
"get-stream": "^8.0.1",
"human-signals": "^5.0.0",
"is-stream": "^3.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^5.1.0",
"onetime": "^6.0.0",
"signal-exit": "^4.1.0",
"strip-final-newline": "^3.0.0"
},
"devDependencies": {
"@types/node": "^20.4.0",
"ava": "^5.2.0",
"c8": "^8.0.1",
"get-node": "^14.2.0",
"is-running": "^2.1.0",
"p-event": "^6.0.0",
"path-key": "^4.0.0",
"tempfile": "^5.0.0",
"tsd": "^0.28.1",
"xo": "^0.55.0"
},
"c8": {
"reporter": [
"text",
"lcov"
],
"exclude": [
"**/fixtures/**",
"**/test.js",
"**/test/**"
]
},
"ava": {
"workerThreads": false
},
"xo": {
"rules": {
"unicorn/no-empty-file": "off",
"@typescript-eslint/ban-types": "off"
}
}
}

View File

@@ -0,0 +1,822 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="media/logo_dark.svg">
<img alt="execa logo" src="media/logo.svg" width="400">
</picture>
<br>
[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa)
> Process execution for humans
<br>
---
<div align="center">
<p>
<p>
<sup>
<a href="https://github.com/sponsors/sindresorhus">Sindre's open source work is supported by the community</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://transloadit.com?utm_source=sindresorhus&utm_medium=referral&utm_campaign=sponsorship&utm_content=execa">
<picture>
<source width="360" media="(prefers-color-scheme: dark)" srcset="https://sindresorhus.com/assets/thanks/transloadit-logo-dark.svg">
<source width="360" media="(prefers-color-scheme: light)" srcset="https://sindresorhus.com/assets/thanks/transloadit-logo.svg">
<img width="360" src="https://sindresorhus.com/assets/thanks/transloadit-logo.svg" alt="Transloadit logo">
</picture>
</a>
<br>
<br>
</p>
</div>
---
<br>
## Why
This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
- [Promise interface](#execacommandcommand-options).
- [Scripts interface](#scripts-interface), like `zx`.
- Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.
- Executes [locally installed binaries](#preferlocal) without `npx`.
- [Cleans up](#cleanup) child processes when the parent process ends.
- [Graceful termination](#optionsforcekillaftertimeout).
- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.
- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.
- Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file).
- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.
- [Verbose mode](#verbose-mode) for debugging.
- More descriptive errors.
- Higher max buffer: 100 MB instead of 1 MB.
## Install
```sh
npm install execa
```
## Usage
### Promise interface
```js
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
```
### Scripts interface
For more information about Execa scripts, please see [this page](docs/scripts.md).
#### Basic
```js
import {$} from 'execa';
const branch = await $`git branch --show-current`;
await $`dep deploy --branch=${branch}`;
```
#### Multiple arguments
```js
import {$} from 'execa';
const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = await $`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'
```
#### With options
```js
import {$} from 'execa';
await $({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'
```
#### Shared options
```js
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
await $$`echo unicorns`;
//=> 'unicorns'
await $$`echo rainbows`;
//=> 'rainbows'
```
#### Verbose mode
```sh
> node file.js
unicorns
rainbows
> NODE_DEBUG=execa node file.js
[16:50:03.305] echo unicorns
unicorns
[16:50:03.308] echo rainbows
rainbows
```
### Input/output
#### Redirect output to a file
```js
import {execa} from 'execa';
// Similar to `echo unicorns > stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStdout('stdout.txt');
// Similar to `echo unicorns 2> stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStderr('stderr.txt');
// Similar to `echo unicorns &> stdout.txt` in Bash
await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt');
```
#### Redirect input from a file
```js
import {execa} from 'execa';
// Similar to `cat < stdin.txt` in Bash
const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
```
#### Save and pipe output from a child process
```js
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);
// Prints `unicorns`
console.log(stdout);
// Also returns 'unicorns'
```
#### Pipe multiple processes
```js
import {execa} from 'execa';
// Similar to `echo unicorns | cat` in Bash
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));
console.log(stdout);
//=> 'unicorns'
```
### Handling Errors
```js
import {execa} from 'execa';
// Catching an error
try {
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawn unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
```
### Graceful termination
Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
```js
const subprocess = execa('node');
setTimeout(() => {
subprocess.kill('SIGTERM', {
forceKillAfterTimeout: 2000
});
}, 1000);
```
## API
### Methods
#### execa(file, arguments?, options?)
Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.
This is the preferred method when executing single commands.
#### execaNode(scriptPath, arguments?, options?)
Executes a Node.js file using `node scriptPath ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.
This is the preferred method when executing Node.js files.
Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options):
- the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.
- the [`shell`](#shell) option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
#### $\`command\`
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must use `${}` like `` $`echo ${'has space'}` ``.
This is the preferred method when executing multiple commands in a script file.
The `command` string can inject any `${value}` with the following types: string, number, [`childProcess`](#childprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used.
For more information, please see [this section](#scripts-interface) and [this page](docs/scripts.md).
#### $(options)
Returns a new instance of [`$`](#command) but with different default `options`. Consecutive calls are merged to previous ones.
This can be used to either:
- Set options for a specific command: `` $(options)`command` ``
- Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand`; ``
#### execaCommand(command, options?)
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.
This is the preferred method when executing a user-supplied `command` string, such as in a REPL.
### execaSync(file, arguments?, options?)
Same as [`execa()`](#execacommandcommand-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### $.sync\`command\`
Same as [$\`command\`](#command) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execaCommandSync(command, options?)
Same as [`execaCommand()`](#execacommand-command-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### Shell syntax
For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.
### childProcess
The return value of all [asynchronous methods](#methods) is both:
- a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties.
#### kill(signal?, options?)
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
Note that this graceful termination does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events) (`SIGKILL` and `SIGTERM` has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as [`taskkill`](https://github.com/sindresorhus/taskkill).
##### options.forceKillAfterTimeout
Type: `number | false`\
Default: `5000`
Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
Can be disabled with `false`.
#### all
Type: `ReadableStream | undefined`
Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
#### pipeStdout(target)
[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:
- Another [`execa()` return value](#pipe-multiple-processes)
- A [writable stream](#save-and-pipe-output-from-a-child-process)
- A [file path string](#redirect-output-to-a-file)
If the `target` is another [`execa()` return value](#execacommandcommand-options), it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the [final result](#childprocessresult).
The [`stdout` option](#stdout-1) must be kept as `pipe`, its default value.
#### pipeStderr(target)
Like [`pipeStdout()`](#pipestdouttarget) but piping the child process's `stderr` instead.
The [`stderr` option](#stderr-1) must be kept as `pipe`, its default value.
#### pipeAll(target)
Combines both [`pipeStdout()`](#pipestdouttarget) and [`pipeStderr()`](#pipestderrtarget).
Either the [`stdout` option](#stdout-1) or the [`stderr` option](#stderr-1) must be kept as `pipe`, their default value. Also, the [`all` option](#all-2) must be set to `true`.
### childProcessResult
Type: `object`
Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
The child process [fails](#failed) when:
- its [exit code](#exitcode) is not `0`
- it was [killed](#killed) with a [signal](#signal)
- [timing out](#timedout)
- [being canceled](#iscanceled)
- there's not enough memory or there are already too many child processes
#### command
Type: `string`
The file and arguments that were run, for logging purposes.
This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).
#### escapedCommand
Type: `string`
Same as [`command`](#command-1) but escaped.
This is meant to be copy and pasted into a shell, for debugging purposes.
Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).
#### exitCode
Type: `number`
The numeric exit code of the process that was run.
#### stdout
Type: `string | Buffer`
The output of the process on stdout.
#### stderr
Type: `string | Buffer`
The output of the process on stderr.
#### all
Type: `string | Buffer | undefined`
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- `execaSync()` was used
#### failed
Type: `boolean`
Whether the process failed to run.
#### timedOut
Type: `boolean`
Whether the process timed out.
#### isCanceled
Type: `boolean`
Whether the process was canceled.
You can cancel the spawned process using the [`signal`](#signal-1) option.
#### killed
Type: `boolean`
Whether the process was killed.
#### signal
Type: `string | undefined`
The name of the signal that was used to terminate the process. For example, `SIGFPE`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
#### signalDescription
Type: `string | undefined`
A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.
#### cwd
Type: `string`
The `cwd` of the command if provided in the [command options](#cwd-1). Otherwise it is `process.cwd()`.
#### message
Type: `string`
Error message when the child process failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the child process errored.
The child process [stderr](#stderr) then [stdout](#stdout) are appended to the end, separated with newlines and not interleaved.
#### shortMessage
Type: `string`
This is the same as the [`message` property](#message) except it does not include the child process stdout/stderr.
#### originalMessage
Type: `string | undefined`
Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa.
This is `undefined` unless the child process exited due to an `error` event or a timeout.
### options
Type: `object`
#### cleanup
Type: `boolean`\
Default: `true`
Kill the spawned process when the parent process exits unless either:
- the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
- the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
#### preferLocal
Type: `boolean`\
Default: `true` with [`$`](#command), `false` otherwise
Prefer locally installed binaries when looking for a binary to execute.\
If you `$ npm install foo`, you can then `execa('foo')`.
#### localDir
Type: `string | URL`\
Default: `process.cwd()`
Preferred path to find locally installed binaries in (use with `preferLocal`).
#### execPath
Type: `string`\
Default: `process.execPath` (Current Node.js executable)
Path to the Node.js executable to use in child processes.
This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
Requires [`preferLocal`](#preferlocal) to be `true`.
For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
#### buffer
Type: `boolean`\
Default: `true`
Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.
If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.
#### input
Type: `string | Buffer | stream.Readable`
Write some input to the `stdin` of your binary.\
Streams are not allowed when using the synchronous methods.
If the input is a file, use the [`inputFile` option](#inputfile) instead.
#### inputFile
Type: `string`
Use a file as input to the the `stdin` of your binary.
If the input is not a file, use the [`input` option](#input) instead.
#### stdin
Type: `string | number | Stream | undefined`\
Default: `inherit` with [`$`](#command), `pipe` otherwise
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stdout
Type: `string | number | Stream | undefined`\
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stderr
Type: `string | number | Stream | undefined`\
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### all
Type: `boolean`\
Default: `false`
Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` interleaved.
#### reject
Type: `boolean`\
Default: `true`
Setting this to `false` resolves the promise with the error instead of rejecting it.
#### stripFinalNewline
Type: `boolean`\
Default: `true`
Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
#### extendEnv
Type: `boolean`\
Default: `true`
Set to `false` if you don't want to extend the environment variables when providing the `env` property.
---
Execa also accepts the below options which are the same as the options for [`child_process#spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)/[`child_process#exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)
#### cwd
Type: `string | URL`\
Default: `process.cwd()`
Current working directory of the child process.
#### env
Type: `object`\
Default: `process.env`
Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this.
#### argv0
Type: `string`
Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.
#### stdio
Type: `string | string[]`\
Default: `pipe`
Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
#### serialization
Type: `string`\
Default: `'json'`
Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
#### detached
Type: `boolean`
Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).
#### uid
Type: `number`
Sets the user identity of the process.
#### gid
Type: `number`
Sets the group identity of the process.
#### shell
Type: `boolean | string`\
Default: `false`
If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.
We recommend against using this option since it is:
- not cross-platform, encouraging shell-specific syntax.
- slower, because of the additional shell interpretation.
- unsafe, potentially allowing command injection.
#### encoding
Type: `string | null`\
Default: `utf8`
Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'` or `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.
#### timeout
Type: `number`\
Default: `0`
If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds.
#### maxBuffer
Type: `number`\
Default: `100_000_000` (100 MB)
Largest amount of data in bytes allowed on `stdout` or `stderr`.
#### killSignal
Type: `string | number`\
Default: `SIGTERM`
Signal value to be used when the spawned process will be killed.
#### signal
Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
When `AbortController.abort()` is called, [`.isCanceled`](#iscanceled) becomes `true`.
#### windowsVerbatimArguments
Type: `boolean`\
Default: `false`
If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.
#### windowsHide
Type: `boolean`\
Default: `true`
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
#### verbose
Type: `boolean`\
Default: `false`
[Print each command](#verbose-mode) on `stderr` before executing it.
This can also be enabled by setting the `NODE_DEBUG=execa` environment variable in the current process.
#### nodePath *(For `.node()` only)*
Type: `string`\
Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)
Node.js executable used to create the child process.
#### nodeOptions *(For `.node()` only)*
Type: `string[]`\
Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)
List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
## Tips
### Retry on error
Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:
```js
import pRetry from 'p-retry';
const run = async () => {
const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
return results;
};
console.log(await pRetry(run, {retries: 5}));
```
### Cancelling a spawned process
```js
import {execa} from 'execa';
const abortController = new AbortController();
const subprocess = execa('node', [], {signal: abortController.signal});
setTimeout(() => {
abortController.abort();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
```
### Execute the current package's binary
```js
import {getBinPath} from 'get-bin-path';
const binPath = await getBinPath();
await execa(binPath);
```
`execa` can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up.
## Related
- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa`
- [nvexeca](https://github.com/ehmicky/nvexeca) - Run `execa` using any Node.js version
- [sudo-prompt](https://github.com/jorangreef/sudo-prompt) - Run commands with elevated privileges.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [@ehmicky](https://github.com/ehmicky)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-execa?utm_source=npm-execa&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,53 @@
{
"name": "get-stream",
"version": "8.0.1",
"description": "Get a stream as a string, Buffer, ArrayBuffer or array",
"license": "MIT",
"repository": "sindresorhus/get-stream",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"types": "./source/index.d.ts",
"default": "./source/index.js"
},
"engines": {
"node": ">=16"
},
"scripts": {
"benchmark": "node benchmarks/index.js",
"test": "xo && ava && tsd --typings=source/index.d.ts --files=source/index.test-d.ts"
},
"files": [
"source",
"!*.test-d.ts"
],
"keywords": [
"get",
"stream",
"promise",
"concat",
"string",
"text",
"buffer",
"read",
"data",
"consume",
"readable",
"readablestream",
"object",
"concat"
],
"devDependencies": {
"@types/node": "^20.5.0",
"ava": "^5.3.1",
"precise-now": "^2.0.0",
"stream-json": "^1.8.0",
"tsd": "^0.28.1",
"xo": "^0.56.0"
}
}

View File

@@ -0,0 +1,291 @@
# get-stream
> Get a stream as a string, Buffer, ArrayBuffer or array
## Features
- Works in any JavaScript environment ([Node.js](#nodejs-streams), [browsers](#web-streams), etc.).
- Supports [text streams](#getstreamstream-options), [binary streams](#getstreamasbufferstream-options) and [object streams](#getstreamasarraystream-options).
- Supports [async iterables](#async-iterables).
- Can set a [maximum stream size](#maxbuffer).
- Returns [partially read data](#errors) when the stream errors.
- [Fast](#benchmarks).
## Install
```sh
npm install get-stream
```
## Usage
### Node.js streams
```js
import fs from 'node:fs';
import getStream from 'get-stream';
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
/*
,,))))))));,
__)))))))))))))),
\|/ -\(((((''''((((((((.
-*-==//////(('' . `)))))),
/|\ ))| o ;-. '((((( ,(,
( `| / ) ;))))' ,_))^;(~
| | | ,))((((_ _____------~~~-. %,;(;(>';'~
o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
; ''''```` `: `:::|\,__,%% );`'; ~
| _ ) / `:|`----' `-'
______/\/~ | / /
/~;;.____/;;' / ___--,-( `;;;/
/ // _;______;'------~~~~~ /;;/\ /
// | | / ; \;;,\
(<_ | ; /',/-----' _>
\_| ||_ //~;~~~~~~~~~
`\_| (,~~
\~\
~~
*/
```
### Web streams
```js
import getStream from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStream(readableStream));
```
### Async iterables
```js
import {opendir} from 'node:fs/promises';
import {getStreamAsArray} from 'get-stream';
const asyncIterable = await opendir(directory);
console.log(await getStreamAsArray(asyncIterable));
```
## API
The following methods read the stream's contents and return it as a promise.
### getStream(stream, options?)
`stream`: [`stream.Readable`](https://nodejs.org/api/stream.html#class-streamreadable), [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), or [`AsyncIterable<string | Buffer | ArrayBuffer | DataView | TypedArray>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)\
`options`: [`Options`](#options)
Get the given `stream` as a string.
### getStreamAsBuffer(stream, options?)
Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).
```js
import {getStreamAsBuffer} from 'get-stream';
const stream = fs.createReadStream('unicorn.png');
console.log(await getStreamAsBuffer(stream));
```
### getStreamAsArrayBuffer(stream, options?)
Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
```js
import {getStreamAsArrayBuffer} from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStreamAsArrayBuffer(readableStream));
```
### getStreamAsArray(stream, options?)
Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode).
```js
import {getStreamAsArray} from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStreamAsArray(readableStream));
```
#### options
Type: `object`
##### maxBuffer
Type: `number`\
Default: `Infinity`
Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`.
Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length).
## Errors
If the stream errors, the returned promise will be rejected with the `error`. Any contents already read from the stream will be set to `error.bufferedData`, which is a `string`, a `Buffer`, an `ArrayBuffer` or an array depending on the [method used](#api).
```js
import getStream from 'get-stream';
try {
await getStream(streamThatErrorsAtTheEnd('unicorn'));
} catch (error) {
console.log(error.bufferedData);
//=> 'unicorn'
}
```
## Tips
### Alternatives
If you do not need the [`maxBuffer`](#maxbuffer) option, [`error.bufferedData`](#errors), nor browser support, you can use the following methods instead of this package.
#### [`streamConsumers.text()`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream)
```js
import fs from 'node:fs';
import {text} from 'node:stream/consumers';
const stream = fs.createReadStream('unicorn.txt', {encoding: 'utf8'});
console.log(await text(stream))
```
#### [`streamConsumers.buffer()`](https://nodejs.org/api/webstreams.html#streamconsumersbufferstream)
```js
import {buffer} from 'node:stream/consumers';
console.log(await buffer(stream))
```
#### [`streamConsumers.arrayBuffer()`](https://nodejs.org/api/webstreams.html#streamconsumersarraybufferstream)
```js
import {arrayBuffer} from 'node:stream/consumers';
console.log(await arrayBuffer(stream))
```
#### [`readable.toArray()`](https://nodejs.org/api/stream.html#readabletoarrayoptions)
```js
console.log(await stream.toArray())
```
#### [`Array.fromAsync()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync)
If your [environment supports it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync#browser_compatibility):
```js
console.log(await Array.fromAsync(stream))
```
### Non-UTF-8 encoding
When all of the following conditions apply:
- [`getStream()`](#getstreamstream-options) is used (as opposed to [`getStreamAsBuffer()`](#getstreamasbufferstream-options) or [`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options))
- The stream is binary (not text)
- The stream's encoding is not UTF-8 (for example, it is UTF-16, hexadecimal, or Base64)
Then the stream must be decoded using a transform stream like [`TextDecoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) or [`b64`](https://github.com/hapijs/b64).
```js
import getStream from 'get-stream';
const textDecoderStream = new TextDecoderStream('utf-16le');
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStream(readableStream.pipeThrough(textDecoderStream)));
```
### Blobs
[`getStreamAsArrayBuffer()`](#getstreamasarraybufferstream-options) can be used to create [Blobs](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
```js
import {getStreamAsArrayBuffer} from 'get-stream';
const stream = fs.createReadStream('unicorn.txt');
console.log(new Blob([await getStreamAsArrayBuffer(stream)]));
```
### JSON streaming
[`getStreamAsArray()`](#getstreamasarraystream-options) can be combined with JSON streaming utilities to parse JSON incrementally.
```js
import fs from 'node:fs';
import {compose as composeStreams} from 'node:stream';
import {getStreamAsArray} from 'get-stream';
import streamJson from 'stream-json';
import streamJsonArray from 'stream-json/streamers/StreamArray.js';
const stream = fs.createReadStream('big-array-of-objects.json');
console.log(await getStreamAsArray(
composeStreams(stream, streamJson.parser(), streamJsonArray.streamArray()),
));
```
## Benchmarks
### Node.js stream (100 MB, binary)
- `getStream()`: 142ms
- `text()`: 139ms
- `getStreamAsBuffer()`: 106ms
- `buffer()`: 83ms
- `getStreamAsArrayBuffer()`: 105ms
- `arrayBuffer()`: 81ms
- `getStreamAsArray()`: 24ms
- `stream.toArray()`: 21ms
### Node.js stream (100 MB, text)
- `getStream()`: 90ms
- `text()`: 89ms
- `getStreamAsBuffer()`: 127ms
- `buffer()`: 192ms
- `getStreamAsArrayBuffer()`: 129ms
- `arrayBuffer()`: 195ms
- `getStreamAsArray()`: 89ms
- `stream.toArray()`: 90ms
### Web ReadableStream (100 MB, binary)
- `getStream()`: 223ms
- `text()`: 221ms
- `getStreamAsBuffer()`: 182ms
- `buffer()`: 153ms
- `getStreamAsArrayBuffer()`: 171ms
- `arrayBuffer()`: 155ms
- `getStreamAsArray()`: 83ms
### Web ReadableStream (100 MB, text)
- `getStream()`: 141ms
- `text()`: 139ms
- `getStreamAsBuffer()`: 91ms
- `buffer()`: 80ms
- `getStreamAsArrayBuffer()`: 89ms
- `arrayBuffer()`: 81ms
- `getStreamAsArray()`: 21ms
[Benchmarks' source file](benchmarks/index.js).
## FAQ
### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)?
This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, `Buffer`, an `ArrayBuffer` or an array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package.
## Related
- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer
- [into-stream](https://github.com/sindresorhus/into-stream) - The opposite of this package

View File

@@ -0,0 +1,84 @@
import {getStreamContents} from './contents.js';
import {noop, throwObjectStream, getLengthProp} from './utils.js';
export async function getStreamAsArrayBuffer(stream, options) {
return getStreamContents(stream, arrayBufferMethods, options);
}
const initArrayBuffer = () => ({contents: new ArrayBuffer(0)});
const useTextEncoder = chunk => textEncoder.encode(chunk);
const textEncoder = new TextEncoder();
const useUint8Array = chunk => new Uint8Array(chunk);
const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);
// `contents` is an increasingly growing `Uint8Array`.
const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => {
const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length);
new Uint8Array(newContents).set(convertedChunk, previousLength);
return newContents;
};
// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2.
// This means its last bytes are zeroes (not stream data), which need to be
// trimmed at the end with `ArrayBuffer.slice()`.
const resizeArrayBufferSlow = (contents, length) => {
if (length <= contents.byteLength) {
return contents;
}
const arrayBuffer = new ArrayBuffer(getNewContentsLength(length));
new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);
return arrayBuffer;
};
// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of
// the stream data. It does not include extraneous zeroes to trim at the end.
// The underlying `ArrayBuffer` does allocate a number of bytes that is a power
// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`.
const resizeArrayBuffer = (contents, length) => {
if (length <= contents.maxByteLength) {
contents.resize(length);
return contents;
}
const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)});
new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);
return arrayBuffer;
};
// Retrieve the closest `length` that is both >= and a power of 2
const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR));
const SCALE_FACTOR = 2;
const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length);
// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available
// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead.
// eslint-disable-next-line no-warning-comments
// TODO: remove after dropping support for Node 20.
// eslint-disable-next-line no-warning-comments
// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available
const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype;
const arrayBufferMethods = {
init: initArrayBuffer,
convertChunk: {
string: useTextEncoder,
buffer: useUint8Array,
arrayBuffer: useUint8Array,
dataView: useUint8ArrayWithOffset,
typedArray: useUint8ArrayWithOffset,
others: throwObjectStream,
},
getSize: getLengthProp,
truncateChunk: truncateArrayBufferChunk,
addChunk: addArrayBufferChunk,
getFinalChunk: noop,
finalize: finalizeArrayBuffer,
};

View File

@@ -0,0 +1,32 @@
import {getStreamContents} from './contents.js';
import {identity, noop, getContentsProp} from './utils.js';
export async function getStreamAsArray(stream, options) {
return getStreamContents(stream, arrayMethods, options);
}
const initArray = () => ({contents: []});
const increment = () => 1;
const addArrayChunk = (convertedChunk, {contents}) => {
contents.push(convertedChunk);
return contents;
};
const arrayMethods = {
init: initArray,
convertChunk: {
string: identity,
buffer: identity,
arrayBuffer: identity,
dataView: identity,
typedArray: identity,
others: identity,
},
getSize: increment,
truncateChunk: noop,
addChunk: addArrayChunk,
getFinalChunk: noop,
finalize: getContentsProp,
};

View File

@@ -0,0 +1,20 @@
import {getStreamAsArrayBuffer} from './array-buffer.js';
export async function getStreamAsBuffer(stream, options) {
if (!('Buffer' in globalThis)) {
throw new Error('getStreamAsBuffer() is only supported in Node.js');
}
try {
return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options));
} catch (error) {
if (error.bufferedData !== undefined) {
error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData);
}
throw error;
}
}
// eslint-disable-next-line n/prefer-global/buffer
const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer);

View File

@@ -0,0 +1,101 @@
export const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => {
if (!isAsyncIterable(stream)) {
throw new Error('The first argument must be a Readable, a ReadableStream, or an async iterable.');
}
const state = init();
state.length = 0;
try {
for await (const chunk of stream) {
const chunkType = getChunkType(chunk);
const convertedChunk = convertChunk[chunkType](chunk, state);
appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer});
}
appendFinalChunk({state, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer});
return finalize(state);
} catch (error) {
error.bufferedData = finalize(state);
throw error;
}
};
const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => {
const convertedChunk = getFinalChunk(state);
if (convertedChunk !== undefined) {
appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer});
}
};
const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => {
const chunkSize = getSize(convertedChunk);
const newLength = state.length + chunkSize;
if (newLength <= maxBuffer) {
addNewChunk(convertedChunk, state, addChunk, newLength);
return;
}
const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length);
if (truncatedChunk !== undefined) {
addNewChunk(truncatedChunk, state, addChunk, maxBuffer);
}
throw new MaxBufferError();
};
const addNewChunk = (convertedChunk, state, addChunk, newLength) => {
state.contents = addChunk(convertedChunk, state, newLength);
state.length = newLength;
};
const isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function';
const getChunkType = chunk => {
const typeOfChunk = typeof chunk;
if (typeOfChunk === 'string') {
return 'string';
}
if (typeOfChunk !== 'object' || chunk === null) {
return 'others';
}
// eslint-disable-next-line n/prefer-global/buffer
if (globalThis.Buffer?.isBuffer(chunk)) {
return 'buffer';
}
const prototypeName = objectToString.call(chunk);
if (prototypeName === '[object ArrayBuffer]') {
return 'arrayBuffer';
}
if (prototypeName === '[object DataView]') {
return 'dataView';
}
if (
Number.isInteger(chunk.byteLength)
&& Number.isInteger(chunk.byteOffset)
&& objectToString.call(chunk.buffer) === '[object ArrayBuffer]'
) {
return 'typedArray';
}
return 'others';
};
const {toString: objectToString} = Object.prototype;
export class MaxBufferError extends Error {
name = 'MaxBufferError';
constructor() {
super('maxBuffer exceeded');
}
}

View File

@@ -0,0 +1,119 @@
import {type Readable} from 'node:stream';
import {type Buffer} from 'node:buffer';
export class MaxBufferError extends Error {
readonly name: 'MaxBufferError';
constructor();
}
type TextStreamItem = string | Buffer | ArrayBuffer | ArrayBufferView;
export type AnyStream<SteamItem = TextStreamItem> = Readable | ReadableStream<SteamItem> | AsyncIterable<SteamItem>;
export type Options = {
/**
Maximum length of the stream. If exceeded, the promise will be rejected with a `MaxBufferError`.
Depending on the [method](#api), the length is measured with [`string.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), [`buffer.length`](https://nodejs.org/api/buffer.html#buflength), [`arrayBuffer.byteLength`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength) or [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length).
@default Infinity
*/
readonly maxBuffer?: number;
};
/**
Get the given `stream` as a string.
@returns The stream's contents as a promise.
@example
```
import fs from 'node:fs';
import getStream from 'get-stream';
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
// ,,))))))));,
// __)))))))))))))),
// \|/ -\(((((''''((((((((.
// -*-==//////(('' . `)))))),
// /|\ ))| o ;-. '((((( ,(,
// ( `| / ) ;))))' ,_))^;(~
// | | | ,))((((_ _____------~~~-. %,;(;(>';'~
// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
// ; ''''```` `: `:::|\,__,%% );`'; ~
// | _ ) / `:|`----' `-'
// ______/\/~ | / /
// /~;;.____/;;' / ___--,-( `;;;/
// / // _;______;'------~~~~~ /;;/\ /
// // | | / ; \;;,\
// (<_ | ; /',/-----' _>
// \_| ||_ //~;~~~~~~~~~
// `\_| (,~~
// \~\
// ~~
```
@example
```
import getStream from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStream(readableStream));
```
@example
```
import {opendir} from 'node:fs/promises';
import {getStreamAsArray} from 'get-stream';
const asyncIterable = await opendir(directory);
console.log(await getStreamAsArray(asyncIterable));
```
*/
export default function getStream(stream: AnyStream, options?: Options): Promise<string>;
/**
Get the given `stream` as a Node.js [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).
@returns The stream's contents as a promise.
@example
```
import {getStreamAsBuffer} from 'get-stream';
const stream = fs.createReadStream('unicorn.png');
console.log(await getStreamAsBuffer(stream));
```
*/
export function getStreamAsBuffer(stream: AnyStream, options?: Options): Promise<Buffer>;
/**
Get the given `stream` as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
@returns The stream's contents as a promise.
@example
```
import {getStreamAsArrayBuffer} from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStreamAsArrayBuffer(readableStream));
```
*/
export function getStreamAsArrayBuffer(stream: AnyStream, options?: Options): Promise<ArrayBuffer>;
/**
Get the given `stream` as an array. Unlike [other methods](#api), this supports [streams of objects](https://nodejs.org/api/stream.html#object-mode).
@returns The stream's contents as a promise.
@example
```
import {getStreamAsArray} from 'get-stream';
const {body: readableStream} = await fetch('https://example.com');
console.log(await getStreamAsArray(readableStream));
```
*/
export function getStreamAsArray<Item>(stream: AnyStream<Item>, options?: Options): Promise<Item[]>;

View File

@@ -0,0 +1,5 @@
export {getStreamAsArray} from './array.js';
export {getStreamAsArrayBuffer} from './array-buffer.js';
export {getStreamAsBuffer} from './buffer.js';
export {getStreamAsString as default} from './string.js';
export {MaxBufferError} from './contents.js';

View File

@@ -0,0 +1,36 @@
import {getStreamContents} from './contents.js';
import {identity, getContentsProp, throwObjectStream, getLengthProp} from './utils.js';
export async function getStreamAsString(stream, options) {
return getStreamContents(stream, stringMethods, options);
}
const initString = () => ({contents: '', textDecoder: new TextDecoder()});
const useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true});
const addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk;
const truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);
const getFinalStringChunk = ({textDecoder}) => {
const finalChunk = textDecoder.decode();
return finalChunk === '' ? undefined : finalChunk;
};
const stringMethods = {
init: initString,
convertChunk: {
string: identity,
buffer: useTextDecoder,
arrayBuffer: useTextDecoder,
dataView: useTextDecoder,
typedArray: useTextDecoder,
others: throwObjectStream,
},
getSize: getLengthProp,
truncateChunk: truncateStringChunk,
addChunk: addStringChunk,
getFinalChunk: getFinalStringChunk,
finalize: getContentsProp,
};

View File

@@ -0,0 +1,11 @@
export const identity = value => value;
export const noop = () => undefined;
export const getContentsProp = ({contents}) => contents;
export const throwObjectStream = chunk => {
throw new Error(`Streams in object mode are not supported: ${String(chunk)}`);
};
export const getLengthProp = convertedChunk => convertedChunk.length;

View File

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

View File

@@ -0,0 +1,168 @@
[![Node](https://img.shields.io/badge/-Node.js-808080?logo=node.js&colorA=404040&logoColor=66cc33)](https://www.npmjs.com/package/human-signals)
[![TypeScript](https://img.shields.io/badge/-Typed-808080?logo=typescript&colorA=404040&logoColor=0096ff)](/src/main.d.ts)
[![Codecov](https://img.shields.io/badge/-Tested%20100%25-808080?logo=codecov&colorA=404040)](https://codecov.io/gh/ehmicky/human-signals)
[![Mastodon](https://img.shields.io/badge/-Mastodon-808080.svg?logo=mastodon&colorA=404040&logoColor=9590F9)](https://fosstodon.org/@ehmicky)
[![Medium](https://img.shields.io/badge/-Medium-808080.svg?logo=medium&colorA=404040)](https://medium.com/@ehmicky)
Human-friendly process signals.
This is a map of known process signals with some information about each signal.
Unlike
[`os.constants.signals`](https://nodejs.org/api/os.html#os_signal_constants)
this includes:
- human-friendly [descriptions](#description)
- [default actions](#action), including whether they [can be prevented](#forced)
- whether the signal is [supported](#supported) by the current OS
# Example
```js
import { signalsByName, signalsByNumber } from 'human-signals'
console.log(signalsByName.SIGINT)
// {
// name: 'SIGINT',
// number: 2,
// description: 'User interruption with CTRL-C',
// supported: true,
// action: 'terminate',
// forced: false,
// standard: 'ansi'
// }
console.log(signalsByNumber[8])
// {
// name: 'SIGFPE',
// number: 8,
// description: 'Floating point arithmetic error',
// supported: true,
// action: 'core',
// forced: false,
// standard: 'ansi'
// }
```
# Install
```bash
npm install human-signals
```
This package works in Node.js >=16.17.0.
This is an ES module. It must be loaded using
[an `import` or `import()` statement](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c),
not `require()`. If TypeScript is used, it must be configured to
[output ES modules](https://www.typescriptlang.org/docs/handbook/esm-node.html),
not CommonJS.
# Usage
## signalsByName
_Type_: `object`
Object whose keys are signal [names](#name) and values are
[signal objects](#signal).
## signalsByNumber
_Type_: `object`
Object whose keys are signal [numbers](#number) and values are
[signal objects](#signal).
## signal
_Type_: `object`
Signal object with the following properties.
### name
_Type_: `string`
Standard name of the signal, for example `'SIGINT'`.
### number
_Type_: `number`
Code number of the signal, for example `2`. While most `number` are
cross-platform, some are different between different OS.
### description
_Type_: `string`
Human-friendly description for the signal, for example
`'User interruption with CTRL-C'`.
### supported
_Type_: `boolean`
Whether the current OS can handle this signal in Node.js using
[`process.on(name, handler)`](https://nodejs.org/api/process.html#process_signal_events).
The list of supported signals
[is OS-specific](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals).
### action
_Type_: `string`\
_Enum_: `'terminate'`, `'core'`, `'ignore'`, `'pause'`, `'unpause'`
What is the default action for this signal when it is not handled.
### forced
_Type_: `boolean`
Whether the signal's default action cannot be prevented. This is `true` for
`SIGTERM`, `SIGKILL` and `SIGSTOP`.
### standard
_Type_: `string`\
_Enum_: `'ansi'`, `'posix'`, `'bsd'`, `'systemv'`, `'other'`
Which standard defined that signal.
# Support
For any question, _don't hesitate_ to [submit an issue on GitHub](../../issues).
Everyone is welcome regardless of personal background. We enforce a
[Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and
inclusive environment.
# Contributing
This project was made with ❤️. The simplest way to give back is by starring and
sharing it online.
If the documentation is unclear or has a typo, please click on the page's `Edit`
button (pencil icon) and suggest a correction.
If you would like to help us fix a bug or add a new feature, please check our
[guidelines](CONTRIBUTING.md). Pull requests are welcome!
Thanks go to our wonderful contributors:
<!-- ALL-CONTRIBUTORS-LIST:START -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://fosstodon.org/@ehmicky"><img src="https://avatars2.githubusercontent.com/u/8136211?v=4" width="100px;" alt=""/><br /><sub><b>ehmicky</b></sub></a><br /><a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Code">💻</a> <a href="#design-ehmicky" title="Design">🎨</a> <a href="#ideas-ehmicky" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Documentation">📖</a></td>
<td align="center"><a href="http://www.electrovir.com"><img src="https://avatars0.githubusercontent.com/u/1205860?v=4" width="100px;" alt=""/><br /><sub><b>electrovir</b></sub></a><br /><a href="https://github.com/ehmicky/human-signals/commits?author=electrovir" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

View File

@@ -0,0 +1,273 @@
export const SIGNALS=[
{
name:"SIGHUP",
number:1,
action:"terminate",
description:"Terminal closed",
standard:"posix"
},
{
name:"SIGINT",
number:2,
action:"terminate",
description:"User interruption with CTRL-C",
standard:"ansi"
},
{
name:"SIGQUIT",
number:3,
action:"core",
description:"User interruption with CTRL-\\",
standard:"posix"
},
{
name:"SIGILL",
number:4,
action:"core",
description:"Invalid machine instruction",
standard:"ansi"
},
{
name:"SIGTRAP",
number:5,
action:"core",
description:"Debugger breakpoint",
standard:"posix"
},
{
name:"SIGABRT",
number:6,
action:"core",
description:"Aborted",
standard:"ansi"
},
{
name:"SIGIOT",
number:6,
action:"core",
description:"Aborted",
standard:"bsd"
},
{
name:"SIGBUS",
number:7,
action:"core",
description:
"Bus error due to misaligned, non-existing address or paging error",
standard:"bsd"
},
{
name:"SIGEMT",
number:7,
action:"terminate",
description:"Command should be emulated but is not implemented",
standard:"other"
},
{
name:"SIGFPE",
number:8,
action:"core",
description:"Floating point arithmetic error",
standard:"ansi"
},
{
name:"SIGKILL",
number:9,
action:"terminate",
description:"Forced termination",
standard:"posix",
forced:true
},
{
name:"SIGUSR1",
number:10,
action:"terminate",
description:"Application-specific signal",
standard:"posix"
},
{
name:"SIGSEGV",
number:11,
action:"core",
description:"Segmentation fault",
standard:"ansi"
},
{
name:"SIGUSR2",
number:12,
action:"terminate",
description:"Application-specific signal",
standard:"posix"
},
{
name:"SIGPIPE",
number:13,
action:"terminate",
description:"Broken pipe or socket",
standard:"posix"
},
{
name:"SIGALRM",
number:14,
action:"terminate",
description:"Timeout or timer",
standard:"posix"
},
{
name:"SIGTERM",
number:15,
action:"terminate",
description:"Termination",
standard:"ansi"
},
{
name:"SIGSTKFLT",
number:16,
action:"terminate",
description:"Stack is empty or overflowed",
standard:"other"
},
{
name:"SIGCHLD",
number:17,
action:"ignore",
description:"Child process terminated, paused or unpaused",
standard:"posix"
},
{
name:"SIGCLD",
number:17,
action:"ignore",
description:"Child process terminated, paused or unpaused",
standard:"other"
},
{
name:"SIGCONT",
number:18,
action:"unpause",
description:"Unpaused",
standard:"posix",
forced:true
},
{
name:"SIGSTOP",
number:19,
action:"pause",
description:"Paused",
standard:"posix",
forced:true
},
{
name:"SIGTSTP",
number:20,
action:"pause",
description:"Paused using CTRL-Z or \"suspend\"",
standard:"posix"
},
{
name:"SIGTTIN",
number:21,
action:"pause",
description:"Background process cannot read terminal input",
standard:"posix"
},
{
name:"SIGBREAK",
number:21,
action:"terminate",
description:"User interruption with CTRL-BREAK",
standard:"other"
},
{
name:"SIGTTOU",
number:22,
action:"pause",
description:"Background process cannot write to terminal output",
standard:"posix"
},
{
name:"SIGURG",
number:23,
action:"ignore",
description:"Socket received out-of-band data",
standard:"bsd"
},
{
name:"SIGXCPU",
number:24,
action:"core",
description:"Process timed out",
standard:"bsd"
},
{
name:"SIGXFSZ",
number:25,
action:"core",
description:"File too big",
standard:"bsd"
},
{
name:"SIGVTALRM",
number:26,
action:"terminate",
description:"Timeout or timer",
standard:"bsd"
},
{
name:"SIGPROF",
number:27,
action:"terminate",
description:"Timeout or timer",
standard:"bsd"
},
{
name:"SIGWINCH",
number:28,
action:"ignore",
description:"Terminal window size changed",
standard:"bsd"
},
{
name:"SIGIO",
number:29,
action:"terminate",
description:"I/O is available",
standard:"other"
},
{
name:"SIGPOLL",
number:29,
action:"terminate",
description:"Watched event",
standard:"other"
},
{
name:"SIGINFO",
number:29,
action:"ignore",
description:"Request for process information",
standard:"other"
},
{
name:"SIGPWR",
number:30,
action:"terminate",
description:"Device running out of power",
standard:"systemv"
},
{
name:"SIGSYS",
number:31,
action:"core",
description:"Invalid system call",
standard:"other"
},
{
name:"SIGUNUSED",
number:31,
action:"terminate",
description:"Invalid system call",
standard:"other"
}];

View File

@@ -0,0 +1,73 @@
/**
* What is the default action for this signal when it is not handled.
*/
export type SignalAction = 'terminate' | 'core' | 'ignore' | 'pause' | 'unpause'
/**
* Which standard defined that signal.
*/
export type SignalStandard = 'ansi' | 'posix' | 'bsd' | 'systemv' | 'other'
/**
* Standard name of the signal, for example 'SIGINT'.
*/
export type SignalName = `SIG${string}`
/**
* Code number of the signal, for example 2.
* While most number are cross-platform, some are different between different
* OS.
*/
export type SignalNumber = number
export interface Signal {
/**
* Standard name of the signal, for example 'SIGINT'.
*/
name: SignalName
/**
* Code number of the signal, for example 2.
* While most number are cross-platform, some are different between different
* OS.
*/
number: SignalNumber
/**
* Human-friendly description for the signal, for example
* 'User interruption with CTRL-C'.
*/
description: string
/**
* Whether the current OS can handle this signal in Node.js using
* `process.on(name, handler)`. The list of supported signals is OS-specific.
*/
supported: boolean
/**
* What is the default action for this signal when it is not handled.
*/
action: SignalAction
/**
* Whether the signal's default action cannot be prevented.
* This is true for SIGTERM, SIGKILL and SIGSTOP.
*/
forced: boolean
/**
* Which standard defined that signal.
*/
standard: SignalStandard
}
/**
* Object whose keys are signal names and values are signal objects.
*/
export declare const signalsByName: { [signalName: SignalName]: Signal }
/**
* Object whose keys are signal numbers and values are signal objects.
*/
export declare const signalsByNumber: { [signalNumber: SignalNumber]: Signal }

View File

@@ -0,0 +1,70 @@
import{constants}from"node:os";
import{SIGRTMAX}from"./realtime.js";
import{getSignals}from"./signals.js";
const getSignalsByName=()=>{
const signals=getSignals();
return Object.fromEntries(signals.map(getSignalByName))
};
const getSignalByName=({
name,
number,
description,
supported,
action,
forced,
standard
})=>[name,{name,number,description,supported,action,forced,standard}];
export const signalsByName=getSignalsByName();
const getSignalsByNumber=()=>{
const signals=getSignals();
const length=SIGRTMAX+1;
const signalsA=Array.from({length},(value,number)=>
getSignalByNumber(number,signals)
);
return Object.assign({},...signalsA)
};
const getSignalByNumber=(number,signals)=>{
const signal=findSignalByNumber(number,signals);
if(signal===undefined){
return{}
}
const{name,description,supported,action,forced,standard}=signal;
return{
[number]:{
name,
number,
description,
supported,
action,
forced,
standard
}
}
};
const findSignalByNumber=(number,signals)=>{
const signal=signals.find(({name})=>constants.signals[name]===number);
if(signal!==undefined){
return signal
}
return signals.find((signalA)=>signalA.number===number)
};
export const signalsByNumber=getSignalsByNumber();

View File

@@ -0,0 +1,16 @@
export const getRealtimeSignals=()=>{
const length=SIGRTMAX-SIGRTMIN+1;
return Array.from({length},getRealtimeSignal)
};
const getRealtimeSignal=(value,index)=>({
name:`SIGRT${index+1}`,
number:SIGRTMIN+index,
action:"terminate",
description:"Application-specific signal (realtime)",
standard:"posix"
});
const SIGRTMIN=34;
export const SIGRTMAX=64;

View File

@@ -0,0 +1,34 @@
import{constants}from"node:os";
import{SIGNALS}from"./core.js";
import{getRealtimeSignals}from"./realtime.js";
export const getSignals=()=>{
const realtimeSignals=getRealtimeSignals();
const signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal);
return signals
};
const normalizeSignal=({
name,
number:defaultNumber,
description,
action,
forced=false,
standard
})=>{
const{
signals:{[name]:constantSignal}
}=constants;
const supported=constantSignal!==undefined;
const number=supported?constantSignal:defaultNumber;
return{name,number,description,supported,action,forced,standard}
};

View File

@@ -0,0 +1,61 @@
{
"name": "human-signals",
"version": "5.0.0",
"type": "module",
"exports": {
"types": "./build/src/main.d.ts",
"default": "./build/src/main.js"
},
"main": "./build/src/main.js",
"types": "./build/src/main.d.ts",
"files": [
"build/src/**/*.{js,json,d.ts}",
"!build/src/**/*.test.js",
"!build/src/{helpers,fixtures}"
],
"sideEffects": false,
"scripts": {
"test": "gulp test"
},
"description": "Human-friendly process signals",
"keywords": [
"signal",
"signals",
"handlers",
"error-handling",
"interrupts",
"sigterm",
"sigint",
"irq",
"process",
"exit",
"exit-code",
"status",
"operating-system",
"es6",
"javascript",
"typescript",
"linux",
"macos",
"windows",
"nodejs"
],
"license": "Apache-2.0",
"homepage": "https://www.github.com/ehmicky/human-signals",
"repository": "ehmicky/human-signals",
"bugs": {
"url": "https://github.com/ehmicky/human-signals/issues"
},
"author": "ehmicky <ehmicky@gmail.com> (https://github.com/ehmicky)",
"directories": {
"lib": "src"
},
"devDependencies": {
"@ehmicky/dev-tasks": "^2.0.80",
"ajv": "^8.12.0",
"test-each": "^6.0.0"
},
"engines": {
"node": ">=16.17.0"
}
}

View File

@@ -0,0 +1,81 @@
import {
Stream,
Writable as WritableStream,
Readable as ReadableStream,
Duplex as DuplexStream,
Transform as TransformStream,
} from 'node:stream';
/**
@returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream).
@example
```
import fs from 'node:fs';
import {isStream} from 'is-stream';
isStream(fs.createReadStream('unicorn.png'));
//=> true
isStream({});
//=> false
```
*/
export function isStream(stream: unknown): stream is Stream;
/**
@returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable).
@example
```
import fs from 'node:fs';
import {isWritableStream} from 'is-stream';
isWritableStream(fs.createWriteStrem('unicorn.txt'));
//=> true
```
*/
export function isWritableStream(stream: unknown): stream is WritableStream;
/**
@returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable).
@example
```
import fs from 'node:fs';
import {isReadableStream} from 'is-stream';
isReadableStream(fs.createReadStream('unicorn.png'));
//=> true
```
*/
export function isReadableStream(stream: unknown): stream is ReadableStream;
/**
@returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex).
@example
```
import {Duplex as DuplexStream} from 'node:stream';
import {isDuplexStream} from 'is-stream';
isDuplexStream(new DuplexStream());
//=> true
```
*/
export function isDuplexStream(stream: unknown): stream is DuplexStream;
/**
@returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform).
@example
```
import fs from 'node:fs';
import StringifyStream from 'streaming-json-stringify';
import {isTransformStream} from 'is-stream';
isTransformStream(StringifyStream());
//=> true
```
*/
export function isTransformStream(stream: unknown): stream is TransformStream;

View File

@@ -0,0 +1,29 @@
export function isStream(stream) {
return stream !== null
&& typeof stream === 'object'
&& typeof stream.pipe === 'function';
}
export function isWritableStream(stream) {
return isStream(stream)
&& stream.writable !== false
&& typeof stream._write === 'function'
&& typeof stream._writableState === 'object';
}
export function isReadableStream(stream) {
return isStream(stream)
&& stream.readable !== false
&& typeof stream._read === 'function'
&& typeof stream._readableState === 'object';
}
export function isDuplexStream(stream) {
return isWritableStream(stream)
&& isReadableStream(stream);
}
export function isTransformStream(stream) {
return isDuplexStream(stream)
&& typeof stream._transform === 'function';
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,44 @@
{
"name": "is-stream",
"version": "3.0.0",
"description": "Check if something is a Node.js stream",
"license": "MIT",
"repository": "sindresorhus/is-stream",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"stream",
"type",
"streams",
"writable",
"readable",
"duplex",
"transform",
"check",
"detect",
"is"
],
"devDependencies": {
"@types/node": "^16.4.13",
"ava": "^3.15.0",
"tempy": "^1.0.1",
"tsd": "^0.17.0",
"xo": "^0.44.0"
}
}

View File

@@ -0,0 +1,60 @@
# is-stream
> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html)
## Install
```
$ npm install is-stream
```
## Usage
```js
import fs from 'node:fs';
import {isStream} from 'is-stream';
isStream(fs.createReadStream('unicorn.png'));
//=> true
isStream({});
//=> false
```
## API
### isStream(stream)
Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream).
#### isWritableStream(stream)
Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable).
#### isReadableStream(stream)
Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable).
#### isDuplexStream(stream)
Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex).
#### isTransformStream(stream)
Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform).
## Related
- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-is-stream?utm_source=npm-is-stream&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View File

@@ -0,0 +1,52 @@
export interface Options {
/**
Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error.
@default false
*/
readonly ignoreNonConfigurable?: boolean;
}
/**
Modifies the `to` function to mimic the `from` function. Returns the `to` function.
`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied.
`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment.
@param to - Mimicking function.
@param from - Function to mimic.
@returns The modified `to` function.
@example
```
import mimicFunction from 'mimic-fn';
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo();
}
console.log(wrapper.name);
//=> 'wrapper'
mimicFunction(wrapper, foo);
console.log(wrapper.name);
//=> 'foo'
console.log(wrapper.unicorn);
//=> '🦄'
```
*/
export default function mimicFunction<
ArgumentsType extends unknown[],
ReturnType,
FunctionType extends (...arguments: ArgumentsType) => ReturnType
>(
to: (...arguments: ArgumentsType) => ReturnType,
from: FunctionType,
options?: Options,
): FunctionType;

View File

@@ -0,0 +1,71 @@
const copyProperty = (to, from, property, ignoreNonConfigurable) => {
// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
// `Function#prototype` is non-writable and non-configurable so can never be modified.
if (property === 'length' || property === 'prototype') {
return;
}
// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
if (property === 'arguments' || property === 'caller') {
return;
}
const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
return;
}
Object.defineProperty(to, property, fromDescriptor);
};
// `Object.defineProperty()` throws if the property exists, is not configurable and either:
// - one its descriptors is changed
// - it is non-writable and its value is changed
const canCopyProperty = function (toDescriptor, fromDescriptor) {
return toDescriptor === undefined || toDescriptor.configurable || (
toDescriptor.writable === fromDescriptor.writable &&
toDescriptor.enumerable === fromDescriptor.enumerable &&
toDescriptor.configurable === fromDescriptor.configurable &&
(toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
);
};
const changePrototype = (to, from) => {
const fromPrototype = Object.getPrototypeOf(from);
if (fromPrototype === Object.getPrototypeOf(to)) {
return;
}
Object.setPrototypeOf(to, fromPrototype);
};
const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
// We use `bind()` instead of a closure for the same reason.
// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
const changeToString = (to, from, name) => {
const withName = name === '' ? '' : `with ${name.trim()}() `;
const newToString = wrappedToString.bind(null, withName, from.toString());
// Ensure `to.toString.toString` is non-enumerable and has the same `same`
Object.defineProperty(newToString, 'name', toStringName);
Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
};
export default function mimicFunction(to, from, {ignoreNonConfigurable = false} = {}) {
const {name} = to;
for (const property of Reflect.ownKeys(from)) {
copyProperty(to, from, property, ignoreNonConfigurable);
}
changePrototype(to, from);
changeToString(to, from, name);
return to;
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,45 @@
{
"name": "mimic-fn",
"version": "4.0.0",
"description": "Make a function mimic another one",
"license": "MIT",
"repository": "sindresorhus/mimic-fn",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"function",
"mimic",
"imitate",
"rename",
"copy",
"inherit",
"properties",
"name",
"func",
"fn",
"set",
"infer",
"change"
],
"devDependencies": {
"ava": "^3.15.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}

View File

@@ -0,0 +1,90 @@
<img src="media/logo.svg" alt="mimic-fn" width="400">
<br>
> Make a function mimic another one
Useful when you wrap a function in another function and like to preserve the original name and other properties.
## Install
```
$ npm install mimic-fn
```
## Usage
```js
import mimicFunction from 'mimic-fn';
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo();
}
console.log(wrapper.name);
//=> 'wrapper'
mimicFunction(wrapper, foo);
console.log(wrapper.name);
//=> 'foo'
console.log(wrapper.unicorn);
//=> '🦄'
console.log(String(wrapper));
//=> '/* Wrapped with wrapper() */\nfunction foo() {}'
```
## API
### mimicFunction(to, from, options?)
Modifies the `to` function to mimic the `from` function. Returns the `to` function.
`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied.
`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment.
#### to
Type: `Function`
Mimicking function.
#### from
Type: `Function`
Function to mimic.
#### options
Type: `object`
##### ignoreNonConfigurable
Type: `boolean`\
Default: `false`
Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error.
## Related
- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-mimic-fn?utm_source=npm-mimic-fn&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View File

@@ -0,0 +1,90 @@
type CommonOptions = {
/**
Working directory.
@default process.cwd()
*/
readonly cwd?: string | URL;
/**
The path to the current Node.js executable.
This can be either an absolute path or a path relative to the `cwd` option.
@default [process.execPath](https://nodejs.org/api/process.html#processexecpath)
*/
readonly execPath?: string | URL;
/**
Whether to push the current Node.js executable's directory (`execPath` option) to the front of PATH.
@default true
*/
readonly addExecPath?: boolean;
/**
Whether to push the locally installed binaries' directory to the front of PATH.
@default true
*/
readonly preferLocal?: boolean;
};
export type RunPathOptions = CommonOptions & {
/**
PATH to be appended.
Set it to an empty string to exclude the default PATH.
@default [`PATH`](https://github.com/sindresorhus/path-key)
*/
readonly path?: string;
};
export type ProcessEnv = Record<string, string | undefined>;
export type EnvOptions = CommonOptions & {
/**
Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options.
@default [process.env](https://nodejs.org/api/process.html#processenv)
*/
readonly env?: ProcessEnv;
};
/**
Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries.
@returns The augmented path string.
@example
```
import childProcess from 'node:child_process';
import {npmRunPath} from 'npm-run-path';
console.log(process.env.PATH);
//=> '/usr/local/bin'
console.log(npmRunPath());
//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin'
```
*/
export function npmRunPath(options?: RunPathOptions): string;
/**
Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries.
@returns The augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object.
@example
```
import childProcess from 'node:child_process';
import {npmRunPathEnv} from 'npm-run-path';
// `foo` is a locally installed binary
childProcess.execFileSync('foo', {
env: npmRunPathEnv()
});
```
*/
export function npmRunPathEnv(options?: EnvOptions): ProcessEnv;

View File

@@ -0,0 +1,52 @@
import process from 'node:process';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import pathKey from 'path-key';
export const npmRunPath = ({
cwd = process.cwd(),
path: pathOption = process.env[pathKey()],
preferLocal = true,
execPath = process.execPath,
addExecPath = true,
} = {}) => {
const cwdString = cwd instanceof URL ? fileURLToPath(cwd) : cwd;
const cwdPath = path.resolve(cwdString);
const result = [];
if (preferLocal) {
applyPreferLocal(result, cwdPath);
}
if (addExecPath) {
applyExecPath(result, execPath, cwdPath);
}
return [...result, pathOption].join(path.delimiter);
};
const applyPreferLocal = (result, cwdPath) => {
let previous;
while (previous !== cwdPath) {
result.push(path.join(cwdPath, 'node_modules/.bin'));
previous = cwdPath;
cwdPath = path.resolve(cwdPath, '..');
}
};
// Ensure the running `node` binary is used
const applyExecPath = (result, execPath, cwdPath) => {
const execPathString = execPath instanceof URL ? fileURLToPath(execPath) : execPath;
result.push(path.resolve(cwdPath, execPathString, '..'));
};
export const npmRunPathEnv = ({env = process.env, ...options} = {}) => {
env = {...env};
const pathName = pathKey({env});
options.path = env[pathName];
env[pathName] = npmRunPath(options);
return env;
};

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,49 @@
{
"name": "npm-run-path",
"version": "5.3.0",
"description": "Get your PATH prepended with locally installed binaries",
"license": "MIT",
"repository": "sindresorhus/npm-run-path",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"types": "./index.d.ts",
"sideEffects": false,
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"npm",
"run",
"path",
"package",
"bin",
"binary",
"binaries",
"script",
"cli",
"command-line",
"execute",
"executable"
],
"dependencies": {
"path-key": "^4.0.0"
},
"devDependencies": {
"ava": "^3.15.0",
"tsd": "^0.17.0",
"xo": "^0.45.0"
}
}

View File

@@ -0,0 +1,104 @@
# npm-run-path
> Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries
In [npm run scripts](https://docs.npmjs.com/cli/run-script) you can execute locally installed binaries by name. This enables the same outside npm.
## Install
```sh
npm install npm-run-path
```
## Usage
```js
import childProcess from 'node:child_process';
import {npmRunPath, npmRunPathEnv} from 'npm-run-path';
console.log(process.env.PATH);
//=> '/usr/local/bin'
console.log(npmRunPath());
//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin'
// `foo` is a locally installed binary
childProcess.execFileSync('foo', {
env: npmRunPathEnv()
});
```
## API
### npmRunPath(options?)
`options`: [`Options`](#options)\
_Returns_: `string`
Returns the augmented PATH string.
### npmRunPathEnv(options?)
`options`: [`Options`](#options)\
_Returns_: `object`
Returns the augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object.
### options
Type: `object`
#### cwd
Type: `string | URL`\
Default: `process.cwd()`
The working directory.
#### execPath
Type: `string | URL`\
Default: [`process.execPath`](https://nodejs.org/api/process.html#processexecpath)
The path to the current Node.js executable.
This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
#### addExecPath
Type: `boolean`\
Default: `true`
Whether to push the current Node.js executable's directory ([`execPath`](#execpath) option) to the front of PATH.
#### preferLocal
Type: `boolean`\
Default: `true`
Whether to push the locally installed binaries' directory to the front of PATH.
#### path
Type: `string`\
Default: [`PATH`](https://github.com/sindresorhus/path-key)
The PATH to be appended.
Set it to an empty string to exclude the default PATH.
Only available with [`npmRunPath()`](#npmrunpathoptions), not [`npmRunPathEnv()`](#npmrunpathenvoptions).
#### env
Type: `object`\
Default: [`process.env`](https://nodejs.org/api/process.html#processenv)
Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options.
Only available with [`npmRunPathEnv()`](#npmrunpathenvoptions), not [`npmRunPath()`](#npmrunpathoptions).
## Related
- [npm-run-path-cli](https://github.com/sindresorhus/npm-run-path-cli) - CLI for this module
- [execa](https://github.com/sindresorhus/execa) - Execute a locally installed binary

View File

@@ -0,0 +1,59 @@
export interface Options {
/**
Throw an error when called more than once.
@default false
*/
readonly throw?: boolean;
}
declare const onetime: {
/**
Ensure a function is only called once. When called multiple times it will return the return value from the first call.
@param fn - Function that should only be called once.
@returns A function that only calls `fn` once.
@example
```
import onetime from 'onetime';
let index = 0;
const foo = onetime(() => ++index);
foo(); //=> 1
foo(); //=> 1
foo(); //=> 1
onetime.callCount(foo); //=> 3
```
*/
<ArgumentsType extends unknown[], ReturnType>(
fn: (...arguments: ArgumentsType) => ReturnType,
options?: Options
): (...arguments: ArgumentsType) => ReturnType;
/**
Get the number of times `fn` has been called.
@param fn - Function to get call count from.
@returns A number representing how many times `fn` has been called.
@example
```
import onetime from 'onetime';
const foo = onetime(() => {});
foo();
foo();
foo();
console.log(onetime.callCount(foo));
//=> 3
```
*/
callCount(fn: (...arguments: any[]) => unknown): number;
};
export default onetime;

View File

@@ -0,0 +1,41 @@
import mimicFunction from 'mimic-fn';
const calledFunctions = new WeakMap();
const onetime = (function_, options = {}) => {
if (typeof function_ !== 'function') {
throw new TypeError('Expected a function');
}
let returnValue;
let callCount = 0;
const functionName = function_.displayName || function_.name || '<anonymous>';
const onetime = function (...arguments_) {
calledFunctions.set(onetime, ++callCount);
if (callCount === 1) {
returnValue = function_.apply(this, arguments_);
function_ = null;
} else if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return returnValue;
};
mimicFunction(onetime, function_);
calledFunctions.set(onetime, callCount);
return onetime;
};
onetime.callCount = function_ => {
if (!calledFunctions.has(function_)) {
throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(function_);
};
export default onetime;

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,45 @@
{
"name": "onetime",
"version": "6.0.0",
"description": "Ensure a function is only called once",
"license": "MIT",
"repository": "sindresorhus/onetime",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"once",
"function",
"one",
"onetime",
"func",
"fn",
"single",
"call",
"called",
"prevent"
],
"dependencies": {
"mimic-fn": "^4.0.0"
},
"devDependencies": {
"ava": "^3.15.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}

View File

@@ -0,0 +1,94 @@
# onetime
> Ensure a function is only called once
When called multiple times it will return the return value from the first call.
*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.*
## Install
```
$ npm install onetime
```
## Usage
```js
import onetime from 'onetime';
let index = 0;
const foo = onetime(() => ++index);
foo(); //=> 1
foo(); //=> 1
foo(); //=> 1
onetime.callCount(foo); //=> 3
```
```js
import onetime from 'onetime';
const foo = onetime(() => {}, {throw: true});
foo();
foo();
//=> Error: Function `foo` can only be called once
```
## API
### onetime(fn, options?)
Returns a function that only calls `fn` once.
#### fn
Type: `Function`
Function that should only be called once.
#### options
Type: `object`
##### throw
Type: `boolean`\
Default: `false`
Throw an error when called more than once.
### onetime.callCount(fn)
Returns a number representing how many times `fn` has been called.
Note: It throws an error if you pass in a function that is not wrapped by `onetime`.
```js
import onetime from 'onetime';
const foo = onetime(() => {});
foo();
foo();
foo();
console.log(onetime.callCount(foo));
//=> 3
```
#### fn
Type: `Function`
Function to get call count from.
## onetime for enterprise
Available as part of the Tidelift Subscription.
The maintainers of onetime and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

View File

@@ -0,0 +1,31 @@
export interface Options {
/**
Use a custom environment variables object.
Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env).
*/
readonly env?: Record<string, string | undefined>;
/**
Get the PATH key for a specific platform.
Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform).
*/
readonly platform?: NodeJS.Platform;
}
/**
Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform.
@example
```
import pathKey from 'path-key';
const key = pathKey();
//=> 'PATH'
const PATH = process.env[key];
//=> '/usr/local/bin:/usr/bin:/bin'
```
*/
export default function pathKey(options?: Options): string;

View File

@@ -0,0 +1,12 @@
export default function pathKey(options = {}) {
const {
env = process.env,
platform = process.platform
} = options;
if (platform !== 'win32') {
return 'PATH';
}
return Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
}

View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,41 @@
{
"name": "path-key",
"version": "4.0.0",
"description": "Get the PATH environment variable key cross-platform",
"license": "MIT",
"repository": "sindresorhus/path-key",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"path",
"key",
"environment",
"env",
"variable",
"get",
"cross-platform",
"windows"
],
"devDependencies": {
"@types/node": "^14.14.37",
"ava": "^3.15.0",
"tsd": "^0.14.0",
"xo": "^0.38.2"
}
}

View File

@@ -0,0 +1,57 @@
# path-key
> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform
It's usually `PATH` but on Windows it can be any casing like `Path`...
## Install
```
$ npm install path-key
```
## Usage
```js
import pathKey from 'path-key';
const key = pathKey();
//=> 'PATH'
const PATH = process.env[key];
//=> '/usr/local/bin:/usr/bin:/bin'
```
## API
### pathKey(options?)
#### options
Type: `object`
##### env
Type: `object`\
Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env)
Use a custom environment variables object.
#### platform
Type: `string`\
Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform)
Get the PATH key for a specific platform.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-path-key?utm_source=npm-path-key&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View File

@@ -0,0 +1,16 @@
The ISC License
Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,74 @@
# signal-exit
When you want to fire an event no matter how a process exits:
- reaching the end of execution.
- explicitly having `process.exit(code)` called.
- having `process.kill(pid, sig)` called.
- receiving a fatal signal from outside the process
Use `signal-exit`.
```js
// Hybrid module, either works
import { onExit } from 'signal-exit'
// or:
// const { onExit } = require('signal-exit')
onExit((code, signal) => {
console.log('process exited!', code, signal)
})
```
## API
`remove = onExit((code, signal) => {}, options)`
The return value of the function is a function that will remove
the handler.
Note that the function _only_ fires for signals if the signal
would cause the process to exit. That is, there are no other
listeners, and it is a fatal signal.
If the global `process` object is not suitable for this purpose
(ie, it's unset, or doesn't have an `emit` method, etc.) then the
`onExit` function is a no-op that returns a no-op `remove` method.
### Options
- `alwaysLast`: Run this handler after any other signal or exit
handlers. This causes `process.emit` to be monkeypatched.
### Capturing Signal Exits
If the handler returns an exact boolean `true`, and the exit is a
due to signal, then the signal will be considered handled, and
will _not_ trigger a synthetic `process.kill(process.pid,
signal)` after firing the `onExit` handlers.
In this case, it your responsibility as the caller to exit with a
signal (for example, by calling `process.kill()`) if you wish to
preserve the same exit status that would otherwise have occurred.
If you do not, then the process will likely exit gracefully with
status 0 at some point, assuming that no other terminating signal
or other exit trigger occurs.
Prior to calling handlers, the `onExit` machinery is unloaded, so
any subsequent exits or signals will not be handled, even if the
signal is captured and the exit is thus prevented.
Note that numeric code exits may indicate that the process is
already committed to exiting, for example due to a fatal
exception or unhandled promise rejection, and so there is no way to
prevent it safely.
### Browser Fallback
The `'signal-exit/browser'` module is the same fallback shim that
just doesn't do anything, but presents the same function
interface.
Patches welcome to add something that hooks onto
`window.onbeforeunload` or similar, but it might just not be a
thing that makes sense there.

View File

@@ -0,0 +1,12 @@
/**
* This is a browser shim that provides the same functional interface
* as the main node export, but it does nothing.
* @module
*/
import type { Handler } from './index.js';
export declare const onExit: (cb: Handler, opts: {
alwaysLast?: boolean;
}) => () => void;
export declare const load: () => void;
export declare const unload: () => void;
//# sourceMappingURL=browser.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACzC,eAAO,MAAM,MAAM,EAAE,CACnB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3B,MAAM,IAAqB,CAAA;AAChC,eAAO,MAAM,IAAI,YAAW,CAAA;AAC5B,eAAO,MAAM,MAAM,YAAW,CAAA"}

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unload = exports.load = exports.onExit = void 0;
const onExit = () => () => { };
exports.onExit = onExit;
const load = () => { };
exports.load = load;
const unload = () => { };
exports.unload = unload;
//# sourceMappingURL=browser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browser.js","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":";;;AAMO,MAAM,MAAM,GAGD,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC,CAAA;AAHnB,QAAA,MAAM,UAGa;AACzB,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAAf,QAAA,IAAI,QAAW;AACrB,MAAM,MAAM,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAAjB,QAAA,MAAM,UAAW","sourcesContent":["/**\n * This is a browser shim that provides the same functional interface\n * as the main node export, but it does nothing.\n * @module\n */\nimport type { Handler } from './index.js'\nexport const onExit: (\n cb: Handler,\n opts: { alwaysLast?: boolean }\n) => () => void = () => () => {}\nexport const load = () => {}\nexport const unload = () => {}\n"]}

View File

@@ -0,0 +1,48 @@
/// <reference types="node" />
import { signals } from './signals.js';
export { signals };
/**
* A function that takes an exit code and signal as arguments
*
* In the case of signal exits *only*, a return value of true
* will indicate that the signal is being handled, and we should
* not synthetically exit with the signal we received. Regardless
* of the handler return value, the handler is unloaded when an
* otherwise fatal signal is received, so you get exactly 1 shot
* at it, unless you add another onExit handler at that point.
*
* In the case of numeric code exits, we may already have committed
* to exiting the process, for example via a fatal exception or
* unhandled promise rejection, so it is impossible to stop safely.
*/
export type Handler = (code: number | null | undefined, signal: NodeJS.Signals | null) => true | void;
export declare const
/**
* Called when the process is exiting, whether via signal, explicit
* exit, or running out of stuff to do.
*
* If the global process object is not suitable for instrumentation,
* then this will be a no-op.
*
* Returns a function that may be used to unload signal-exit.
*/
onExit: (cb: Handler, opts?: {
alwaysLast?: boolean | undefined;
} | undefined) => () => void,
/**
* Load the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
load: () => void,
/**
* Unload the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
unload: () => void;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,CAAA;AAuBlB;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,KAC1B,IAAI,GAAG,IAAI,CAAA;AA8QhB,eAAO;AACL;;;;;;;;GAQG;AACH,MAAM,OAzMO,OAAO;;wBAPiD,IAAI;AAkNzE;;;;;;GAMG;AACH,IAAI;AAEJ;;;;;;GAMG;AACH,MAAM,YAGP,CAAA"}

View File

@@ -0,0 +1,279 @@
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unload = exports.load = exports.onExit = exports.signals = void 0;
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
// grab a reference to node's real process object right away
const signals_js_1 = require("./signals.js");
Object.defineProperty(exports, "signals", { enumerable: true, get: function () { return signals_js_1.signals; } });
const processOk = (process) => !!process &&
typeof process === 'object' &&
typeof process.removeListener === 'function' &&
typeof process.emit === 'function' &&
typeof process.reallyExit === 'function' &&
typeof process.listeners === 'function' &&
typeof process.kill === 'function' &&
typeof process.pid === 'number' &&
typeof process.on === 'function';
const kExitEmitter = Symbol.for('signal-exit emitter');
const global = globalThis;
const ObjectDefineProperty = Object.defineProperty.bind(Object);
// teeny special purpose ee
class Emitter {
emitted = {
afterExit: false,
exit: false,
};
listeners = {
afterExit: [],
exit: [],
};
count = 0;
id = Math.random();
constructor() {
if (global[kExitEmitter]) {
return global[kExitEmitter];
}
ObjectDefineProperty(global, kExitEmitter, {
value: this,
writable: false,
enumerable: false,
configurable: false,
});
}
on(ev, fn) {
this.listeners[ev].push(fn);
}
removeListener(ev, fn) {
const list = this.listeners[ev];
const i = list.indexOf(fn);
/* c8 ignore start */
if (i === -1) {
return;
}
/* c8 ignore stop */
if (i === 0 && list.length === 1) {
list.length = 0;
}
else {
list.splice(i, 1);
}
}
emit(ev, code, signal) {
if (this.emitted[ev]) {
return false;
}
this.emitted[ev] = true;
let ret = false;
for (const fn of this.listeners[ev]) {
ret = fn(code, signal) === true || ret;
}
if (ev === 'exit') {
ret = this.emit('afterExit', code, signal) || ret;
}
return ret;
}
}
class SignalExitBase {
}
const signalExitWrap = (handler) => {
return {
onExit(cb, opts) {
return handler.onExit(cb, opts);
},
load() {
return handler.load();
},
unload() {
return handler.unload();
},
};
};
class SignalExitFallback extends SignalExitBase {
onExit() {
return () => { };
}
load() { }
unload() { }
}
class SignalExit extends SignalExitBase {
// "SIGHUP" throws an `ENOSYS` error on Windows,
// so use a supported signal instead
/* c8 ignore start */
#hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';
/* c8 ignore stop */
#emitter = new Emitter();
#process;
#originalProcessEmit;
#originalProcessReallyExit;
#sigListeners = {};
#loaded = false;
constructor(process) {
super();
this.#process = process;
// { <signal>: <listener fn>, ... }
this.#sigListeners = {};
for (const sig of signals_js_1.signals) {
this.#sigListeners[sig] = () => {
// If there are no other listeners, an exit is coming!
// Simplest way: remove us and then re-send the signal.
// We know that this will kill the process, so we can
// safely emit now.
const listeners = this.#process.listeners(sig);
let { count } = this.#emitter;
// This is a workaround for the fact that signal-exit v3 and signal
// exit v4 are not aware of each other, and each will attempt to let
// the other handle it, so neither of them do. To correct this, we
// detect if we're the only handler *except* for previous versions
// of signal-exit, and increment by the count of listeners it has
// created.
/* c8 ignore start */
const p = process;
if (typeof p.__signal_exit_emitter__ === 'object' &&
typeof p.__signal_exit_emitter__.count === 'number') {
count += p.__signal_exit_emitter__.count;
}
/* c8 ignore stop */
if (listeners.length === count) {
this.unload();
const ret = this.#emitter.emit('exit', null, sig);
/* c8 ignore start */
const s = sig === 'SIGHUP' ? this.#hupSig : sig;
if (!ret)
process.kill(process.pid, s);
/* c8 ignore stop */
}
};
}
this.#originalProcessReallyExit = process.reallyExit;
this.#originalProcessEmit = process.emit;
}
onExit(cb, opts) {
/* c8 ignore start */
if (!processOk(this.#process)) {
return () => { };
}
/* c8 ignore stop */
if (this.#loaded === false) {
this.load();
}
const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
this.#emitter.on(ev, cb);
return () => {
this.#emitter.removeListener(ev, cb);
if (this.#emitter.listeners['exit'].length === 0 &&
this.#emitter.listeners['afterExit'].length === 0) {
this.unload();
}
};
}
load() {
if (this.#loaded) {
return;
}
this.#loaded = true;
// This is the number of onSignalExit's that are in play.
// It's important so that we can count the correct number of
// listeners on signals, and don't wait for the other one to
// handle it instead of us.
this.#emitter.count += 1;
for (const sig of signals_js_1.signals) {
try {
const fn = this.#sigListeners[sig];
if (fn)
this.#process.on(sig, fn);
}
catch (_) { }
}
this.#process.emit = (ev, ...a) => {
return this.#processEmit(ev, ...a);
};
this.#process.reallyExit = (code) => {
return this.#processReallyExit(code);
};
}
unload() {
if (!this.#loaded) {
return;
}
this.#loaded = false;
signals_js_1.signals.forEach(sig => {
const listener = this.#sigListeners[sig];
/* c8 ignore start */
if (!listener) {
throw new Error('Listener not defined for signal: ' + sig);
}
/* c8 ignore stop */
try {
this.#process.removeListener(sig, listener);
/* c8 ignore start */
}
catch (_) { }
/* c8 ignore stop */
});
this.#process.emit = this.#originalProcessEmit;
this.#process.reallyExit = this.#originalProcessReallyExit;
this.#emitter.count -= 1;
}
#processReallyExit(code) {
/* c8 ignore start */
if (!processOk(this.#process)) {
return 0;
}
this.#process.exitCode = code || 0;
/* c8 ignore stop */
this.#emitter.emit('exit', this.#process.exitCode, null);
return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
}
#processEmit(ev, ...args) {
const og = this.#originalProcessEmit;
if (ev === 'exit' && processOk(this.#process)) {
if (typeof args[0] === 'number') {
this.#process.exitCode = args[0];
/* c8 ignore start */
}
/* c8 ignore start */
const ret = og.call(this.#process, ev, ...args);
/* c8 ignore start */
this.#emitter.emit('exit', this.#process.exitCode, null);
/* c8 ignore stop */
return ret;
}
else {
return og.call(this.#process, ev, ...args);
}
}
}
const process = globalThis.process;
// wrap so that we call the method on the actual handler, without
// exporting it directly.
_a = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback()),
/**
* Called when the process is exiting, whether via signal, explicit
* exit, or running out of stuff to do.
*
* If the global process object is not suitable for instrumentation,
* then this will be a no-op.
*
* Returns a function that may be used to unload signal-exit.
*/
exports.onExit = _a.onExit,
/**
* Load the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
exports.load = _a.load,
/**
* Unload the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
exports.unload = _a.unload;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
{
"type": "commonjs"
}

View File

@@ -0,0 +1,29 @@
/// <reference types="node" />
/**
* This is not the set of all possible signals.
*
* It IS, however, the set of all signals that trigger
* an exit on either Linux or BSD systems. Linux is a
* superset of the signal names supported on BSD, and
* the unknown signals just fail to register, so we can
* catch that easily enough.
*
* Windows signals are a different set, since there are
* signals that terminate Windows processes, but don't
* terminate (or don't even exist) on Posix systems.
*
* Don't bother with SIGKILL. It's uncatchable, which
* means that we can't fire any callbacks anyway.
*
* If a user does happen to register a handler on a non-
* fatal signal like SIGWINCH or something, and then
* exit, it'll end up firing `process.emit('exit')`, so
* the handler will be fired anyway.
*
* SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
* artificially, inherently leave the process in a
* state from which it is not safe to try and enter JS
* listeners.
*/
export declare const signals: NodeJS.Signals[];
//# sourceMappingURL=signals.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,OAAO,EAAO,CAAA"}

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signals = void 0;
/**
* This is not the set of all possible signals.
*
* It IS, however, the set of all signals that trigger
* an exit on either Linux or BSD systems. Linux is a
* superset of the signal names supported on BSD, and
* the unknown signals just fail to register, so we can
* catch that easily enough.
*
* Windows signals are a different set, since there are
* signals that terminate Windows processes, but don't
* terminate (or don't even exist) on Posix systems.
*
* Don't bother with SIGKILL. It's uncatchable, which
* means that we can't fire any callbacks anyway.
*
* If a user does happen to register a handler on a non-
* fatal signal like SIGWINCH or something, and then
* exit, it'll end up firing `process.emit('exit')`, so
* the handler will be fired anyway.
*
* SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
* artificially, inherently leave the process in a
* state from which it is not safe to try and enter JS
* listeners.
*/
exports.signals = [];
exports.signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
if (process.platform !== 'win32') {
exports.signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
);
}
if (process.platform === 'linux') {
exports.signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
}
//# sourceMappingURL=signals.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"signals.js","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACU,QAAA,OAAO,GAAqB,EAAE,CAAA;AAC3C,eAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAA;AAE3C,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,eAAO,CAAC,IAAI,CACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,EACT,QAAQ;IACR,yDAAyD;IACzD,UAAU;IACV,YAAY;KACb,CAAA;CACF;AAED,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,eAAO,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAA;CACxD","sourcesContent":["/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n signals.push(\n 'SIGALRM',\n 'SIGABRT',\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n"]}

View File

@@ -0,0 +1,12 @@
/**
* This is a browser shim that provides the same functional interface
* as the main node export, but it does nothing.
* @module
*/
import type { Handler } from './index.js';
export declare const onExit: (cb: Handler, opts: {
alwaysLast?: boolean;
}) => () => void;
export declare const load: () => void;
export declare const unload: () => void;
//# sourceMappingURL=browser.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACzC,eAAO,MAAM,MAAM,EAAE,CACnB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3B,MAAM,IAAqB,CAAA;AAChC,eAAO,MAAM,IAAI,YAAW,CAAA;AAC5B,eAAO,MAAM,MAAM,YAAW,CAAA"}

View File

@@ -0,0 +1,4 @@
export const onExit = () => () => { };
export const load = () => { };
export const unload = () => { };
//# sourceMappingURL=browser.js.map

Some files were not shown because too many files have changed in this diff Show More