v6
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import { AsyncLocalStorage } from 'node:async_hooks'
16import { spawn } from 'node:child_process'
17
18export interface Options {
19 verbose: boolean | number
20 cwd: string
21 env: NodeJS.ProcessEnv
22 prefix: string
23 shell: string | boolean
24 maxBuffer: number
25 quote: (v: string) => string
26 spawn: typeof spawn
27 logOutput?: 'stdout' | 'stderr'
28 logFormat?: (...msg: any[]) => string | string[]
29 logPrint?: (data: any, err?: any) => void
30 logIgnore?: string | string[]
31}
32
33export interface Context extends Options {
34 nothrow?: boolean
35 cmd: string
36 __from: string
37 resolve: any
38 reject: any
39}
40
41let root: Options
42
43const storage = new AsyncLocalStorage<Options>()
44
45export function getCtx() {
46 return (storage.getStore() as Context) || getRootCtx()
47}
48
49export function setRootCtx(ctx: Options) {
50 root = ctx
51}
52
53export function getRootCtx() {
54 return root
55}
56
57export const runInCtx = <R, TArgs extends any[]>(
58 ctx: Options = root,
59 cb: (...args: TArgs) => R,
60 ...args: TArgs
61): R => storage.run(ctx, cb, ...args)