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,GAC7B,MAAM,EAAqB,IAAI,IAAI,UACnC,IAAK,MAAO,EAAK,KAAY,OAAO,QAAQ,GACxC,EAAmB,IAAI,EAAK,GAElB,OAAV,IACA,EAAQ,IAAI,SAAS,aACf,MAEV,MAAM,EAAM,UAAU,WAAW,GAGjC,IAAK,mBAAmB,IAAQ,EAAI,OAAS,GAAK,EAAK,OAAS,EAAG,CAC/D,IAAI,EAAU,EAAI,EAAI,OAAS,GAC/B,KAAO,EAAQ,MACX,EAAU,EAAQ,KAAK,KAC3B,IAAI,EAAQ,EAAQ,MACpB,KAAO,EAAM,MACT,EAAQ,EAAM,KAAK,MACJ,YAAf,EAAM,OACN,EAAM,KAAO,EAAM,KAAK,OAAO,EAAK,KAAI,IAC7B,CACH,KAAM,WACN,SAAU,CAAC,CACH,KAAM,OACN,KAAM,SAK9B,CACA,aAAa,iBAAiB,EAAK,CAC/B,OACA,SAAU,EACV,aAAc,EACd,cAAe,EACf,cAAe,GAChB,CACC,MACA,YAAa,EACb,SAAU,KACV,QACA,SACA,SACA,UAAW,OAAO,OAAO,OAAO,OAAO,GAAY,CAC/C,IAAO,KAGnB,CACA,QAAQ,QAAU","file":"/npm/@berry/shell@0.1.0/lib/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@berry/shell@0.1.0/lib/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fslib_1 = require(\"@berry/fslib\");\nconst parsers_1 = require(\"@berry/parsers\");\nconst stream_1 = require(\"stream\");\nconst pipe_1 = require(\"./pipe\");\nconst pipe_2 = require(\"./pipe\");\nfunction cloneState(state, mergeWith = {}) {\n    const newState = Object.assign({}, state, mergeWith);\n    newState.environment = Object.assign({}, state.environment, mergeWith.environment);\n    newState.variables = Object.assign({}, state.variables, mergeWith.variables);\n    return newState;\n}\nconst BUILTINS = new Map([\n    [`cd`, async ([target, ...rest], opts, state) => {\n            const resolvedTarget = fslib_1.ppath.resolve(state.cwd, fslib_1.NodeFS.toPortablePath(target));\n            const stat = await fslib_1.xfs.statPromise(resolvedTarget);\n            if (!stat.isDirectory()) {\n                state.stderr.write(`cd: not a directory\\n`);\n                return 1;\n            }\n            else {\n                state.cwd = resolvedTarget;\n                return 0;\n            }\n        }],\n    [`pwd`, async (args, opts, state) => {\n            state.stdout.write(`${fslib_1.NodeFS.fromPortablePath(state.cwd)}\\n`);\n            return 0;\n        }],\n    [`true`, async (args, opts, state) => {\n            return 0;\n        }],\n    [`false`, async (args, opts, state) => {\n            return 1;\n        }],\n    [`exit`, async ([code, ...rest], opts, state) => {\n            return state.exitCode = parseInt(code, 10);\n        }],\n    [`echo`, async (args, opts, state) => {\n            state.stdout.write(`${args.join(` `)}\\n`);\n            return 0;\n        }],\n    [`setredirects`, async (args, opts, state) => {\n            let stdin = state.stdin;\n            let stdout = state.stdout;\n            let stderr = state.stderr;\n            const inputs = [];\n            const outputs = [];\n            let t = 0;\n            while (args[t] !== `--`) {\n                const type = args[t++];\n                const count = Number(args[t++]);\n                const last = t + count;\n                for (let u = t; u < last; ++t, ++u) {\n                    switch (type) {\n                        case `<`:\n                            {\n                                inputs.push(() => {\n                                    return fslib_1.xfs.createReadStream(fslib_1.ppath.resolve(state.cwd, fslib_1.NodeFS.toPortablePath(args[u])));\n                                });\n                            }\n                            break;\n                        case `<<<`:\n                            {\n                                inputs.push(() => {\n                                    const input = new stream_1.PassThrough();\n                                    process.nextTick(() => {\n                                        input.write(`${args[u]}\\n`);\n                                        input.end();\n                                    });\n                                    return input;\n                                });\n                            }\n                            break;\n                        case `>`:\n                            {\n                                outputs.push(fslib_1.xfs.createWriteStream(fslib_1.ppath.resolve(state.cwd, fslib_1.NodeFS.toPortablePath(args[u]))));\n                            }\n                            break;\n                        case `>>`:\n                            {\n                                outputs.push(fslib_1.xfs.createWriteStream(fslib_1.ppath.resolve(state.cwd, fslib_1.NodeFS.toPortablePath(args[u])), { flags: `a` }));\n                            }\n                            break;\n                    }\n                }\n            }\n            if (inputs.length > 0) {\n                const pipe = new stream_1.PassThrough();\n                stdin = pipe;\n                const bindInput = (n) => {\n                    if (n === inputs.length) {\n                        pipe.end();\n                    }\n                    else {\n                        const input = inputs[n]();\n                        input.pipe(pipe, { end: false });\n                        input.on(`end`, () => {\n                            bindInput(n + 1);\n                        });\n                    }\n                };\n                bindInput(0);\n            }\n            if (outputs.length > 0) {\n                const pipe = new stream_1.PassThrough();\n                stdout = pipe;\n                for (const output of outputs) {\n                    pipe.pipe(output);\n                }\n            }\n            const exitCode = await pipe_1.start(makeCommandAction(args.slice(t + 1), opts, state), {\n                stdin: new pipe_1.ProtectedStream(stdin),\n                stdout: new pipe_1.ProtectedStream(stdout),\n                stderr: new pipe_1.ProtectedStream(stderr),\n            }).run();\n            // Close all the outputs (since the shell never closes the output stream)\n            await Promise.all(outputs.map(output => {\n                output.end();\n                // Wait until the output got flushed to the disk\n                return new Promise(resolve => {\n                    output.on(`close`, () => {\n                        resolve();\n                    });\n                });\n            }));\n            return exitCode;\n        }],\n]);\nasync function executeBufferedSubshell(ast, opts, state) {\n    const chunks = [];\n    const stdout = new stream_1.PassThrough();\n    stdout.on(`data`, chunk => chunks.push(chunk));\n    await executeShellLine(ast, opts, cloneState(state, { stdout }));\n    return Buffer.concat(chunks).toString().replace(/[\\r\\n]+$/, ``);\n}\nasync function applyEnvVariables(environmentSegments, opts, state) {\n    const envPromises = environmentSegments.map(async (envSegment) => {\n        const interpolatedArgs = await interpolateArguments(envSegment.args, opts, state);\n        return {\n            name: envSegment.name,\n            value: interpolatedArgs.join(` `),\n        };\n    });\n    const interpolatedEnvs = await Promise.all(envPromises);\n    return interpolatedEnvs.reduce((envs, env) => {\n        envs[env.name] = env.value;\n        return envs;\n    }, {});\n}\nasync function interpolateArguments(commandArgs, opts, state) {\n    const redirections = new Map();\n    const interpolated = [];\n    let interpolatedSegments = [];\n    const split = (raw) => {\n        return raw.match(/[^ \\r\\n\\t]+/g) || [];\n    };\n    const push = (segment) => {\n        interpolatedSegments.push(segment);\n    };\n    const close = () => {\n        if (interpolatedSegments.length > 0)\n            interpolated.push(interpolatedSegments.join(``));\n        interpolatedSegments = [];\n    };\n    const pushAndClose = (segment) => {\n        push(segment);\n        close();\n    };\n    const redirect = (type, target) => {\n        let targets = redirections.get(type);\n        if (typeof targets === `undefined`)\n            redirections.set(type, targets = []);\n        targets.push(target);\n    };\n    for (const commandArg of commandArgs) {\n        switch (commandArg.type) {\n            case `redirection`:\n                {\n                    const interpolatedArgs = await interpolateArguments(commandArg.args, opts, state);\n                    for (const interpolatedArg of interpolatedArgs) {\n                        redirect(commandArg.subtype, interpolatedArg);\n                    }\n                }\n                break;\n            case `argument`:\n                {\n                    for (const segment of commandArg.segments) {\n                        switch (segment.type) {\n                            case `text`:\n                                {\n                                    push(segment.text);\n                                }\n                                break;\n                            case `shell`:\n                                {\n                                    const raw = await executeBufferedSubshell(segment.shell, opts, state);\n                                    if (segment.quoted) {\n                                        push(raw);\n                                    }\n                                    else {\n                                        for (const part of split(raw)) {\n                                            pushAndClose(part);\n                                        }\n                                    }\n                                }\n                                break;\n                            case `variable`:\n                                {\n                                    switch (segment.name) {\n                                        case `#`:\n                                            {\n                                                push(String(opts.args.length));\n                                            }\n                                            break;\n                                        case `@`:\n                                            {\n                                                if (segment.quoted) {\n                                                    for (const raw of opts.args) {\n                                                        pushAndClose(raw);\n                                                    }\n                                                }\n                                                else {\n                                                    for (const raw of opts.args) {\n                                                        for (const part of split(raw)) {\n                                                            pushAndClose(part);\n                                                        }\n                                                    }\n                                                }\n                                            }\n                                            break;\n                                        case `*`:\n                                            {\n                                                const raw = opts.args.join(` `);\n                                                if (segment.quoted) {\n                                                    push(raw);\n                                                }\n                                                else {\n                                                    for (const part of split(raw)) {\n                                                        pushAndClose(part);\n                                                    }\n                                                }\n                                            }\n                                            break;\n                                        default:\n                                            {\n                                                const argIndex = parseInt(segment.name, 10);\n                                                if (Number.isFinite(argIndex)) {\n                                                    if (!(argIndex >= 0 && argIndex < opts.args.length)) {\n                                                        throw new Error(`Unbound argument #${argIndex}`);\n                                                    }\n                                                    else {\n                                                        push(opts.args[argIndex]);\n                                                    }\n                                                }\n                                                else {\n                                                    if (Object.prototype.hasOwnProperty.call(state.variables, segment.name)) {\n                                                        push(state.variables[segment.name]);\n                                                    }\n                                                    else if (Object.prototype.hasOwnProperty.call(state.environment, segment.name)) {\n                                                        push(state.environment[segment.name]);\n                                                    }\n                                                    else if (segment.defaultValue) {\n                                                        push((await interpolateArguments(segment.defaultValue, opts, state)).join(` `));\n                                                    }\n                                                    else {\n                                                        throw new Error(`Unbound variable \"${segment.name}\"`);\n                                                    }\n                                                }\n                                            }\n                                            break;\n                                    }\n                                }\n                                break;\n                        }\n                    }\n                }\n                break;\n        }\n        close();\n    }\n    if (redirections.size > 0) {\n        const redirectionArgs = [];\n        for (const [subtype, targets] of redirections.entries())\n            redirectionArgs.splice(redirectionArgs.length, 0, subtype, String(targets.length), ...targets);\n        interpolated.splice(0, 0, `setredirects`, ...redirectionArgs, `--`);\n    }\n    return interpolated;\n}\n/**\n * Executes a command chain. A command chain is a list of commands linked\n * together thanks to the use of either of the `|` or `|&` operators:\n *\n * $ cat hello | grep world | grep -v foobar\n */\nfunction makeCommandAction(args, opts, state) {\n    if (!opts.builtins.has(args[0]))\n        args = [`command`, ...args];\n    const [name, ...rest] = args;\n    if (name === `command`) {\n        return pipe_2.makeProcess(rest[0], rest.slice(1), opts, {\n            cwd: fslib_1.NodeFS.fromPortablePath(state.cwd),\n            env: state.environment,\n        });\n    }\n    const builtin = opts.builtins.get(name);\n    if (typeof builtin === `undefined`)\n        throw new Error(`Assertion failed: A builtin should exist for \"${name}\"`);\n    return pipe_2.makeBuiltin(async ({ stdin, stdout, stderr }) => {\n        state.stdin = stdin;\n        state.stdout = stdout;\n        state.stderr = stderr;\n        return await builtin(rest, opts, state);\n    });\n}\nfunction makeSubshellAction(ast, opts, state) {\n    return (stdio) => {\n        const stdin = new stream_1.PassThrough();\n        const promise = executeShellLine(ast, opts, cloneState(state, { stdin }));\n        return { stdin, promise };\n    };\n}\nasync function executeCommandChain(node, opts, state) {\n    let current = node;\n    let pipeType = null;\n    let execution = null;\n    while (current) {\n        // Only the final segment is allowed to modify the shell state; all the\n        // other ones are isolated\n        const activeState = current.then\n            ? Object.assign({}, state) : state;\n        let action;\n        switch (current.type) {\n            case `command`:\n                {\n                    const args = await interpolateArguments(current.args, opts, state);\n                    const environment = await applyEnvVariables(current.envs, opts, state);\n                    action = current.envs.length\n                        ? makeCommandAction(args, opts, cloneState(activeState, { environment }))\n                        : makeCommandAction(args, opts, activeState);\n                }\n                break;\n            case `subshell`:\n                {\n                    // We don't interpolate the subshell because it will be recursively\n                    // interpolated within its own context\n                    action = makeSubshellAction(current.subshell, opts, activeState);\n                }\n                break;\n            case `envs`:\n                {\n                    const environment = await applyEnvVariables(current.envs, opts, state);\n                    activeState.environment = Object.assign({}, activeState.environment, environment);\n                    action = makeCommandAction([`true`], opts, activeState);\n                }\n                break;\n        }\n        if (typeof action === `undefined`)\n            throw new Error(`Assertion failed: An action should have been generated`);\n        if (pipeType === null) {\n            // If we're processing the left-most segment of the command, we start a\n            // new execution pipeline\n            execution = pipe_1.start(action, {\n                stdin: new pipe_1.ProtectedStream(activeState.stdin),\n                stdout: new pipe_1.ProtectedStream(activeState.stdout),\n                stderr: new pipe_1.ProtectedStream(activeState.stderr),\n            });\n        }\n        else {\n            if (execution === null)\n                throw new Error(`The execution pipeline should have been setup`);\n            // Otherwise, depending on the exaxct pipe type, we either pipe stdout\n            // only or stdout and stderr\n            switch (pipeType) {\n                case `|`:\n                    {\n                        execution = execution.pipeTo(action);\n                    }\n                    break;\n                case `|&`:\n                    {\n                        execution = execution.pipeTo(action);\n                    }\n                    break;\n            }\n        }\n        if (current.then) {\n            pipeType = current.then.type;\n            current = current.then.chain;\n        }\n        else {\n            current = null;\n        }\n    }\n    if (execution === null)\n        throw new Error(`Assertion failed: The execution pipeline should have been setup`);\n    return await execution.run();\n}\n/**\n * Execute a command line. A command line is a list of command shells linked\n * together thanks to the use of either of the `||` or `&&` operators.\n */\nasync function executeCommandLine(node, opts, state) {\n    if (!node.then)\n        return await executeCommandChain(node.chain, opts, state);\n    const code = await executeCommandChain(node.chain, opts, state);\n    // If the execution aborted (usually through \"exit\"), we must bailout\n    if (state.exitCode !== null)\n        return state.exitCode;\n    // We must update $?, which always contains the exit code from\n    // the right-most command\n    state.variables[`?`] = String(code);\n    switch (node.then.type) {\n        case `&&`:\n            {\n                if (code === 0) {\n                    return await executeCommandLine(node.then.line, opts, state);\n                }\n                else {\n                    return code;\n                }\n            }\n            break;\n        case `||`:\n            {\n                if (code !== 0) {\n                    return await executeCommandLine(node.then.line, opts, state);\n                }\n                else {\n                    return code;\n                }\n            }\n            break;\n        default:\n            {\n                throw new Error(`Unsupported command type: \"${node.then.type}\"`);\n            }\n            break;\n    }\n}\nasync function executeShellLine(node, opts, state) {\n    let rightMostExitCode = 0;\n    for (const command of node) {\n        rightMostExitCode = await executeCommandLine(command, opts, state);\n        // If the execution aborted (usually through \"exit\"), we must bailout\n        if (state.exitCode !== null)\n            return state.exitCode;\n        // We must update $?, which always contains the exit code from\n        // the right-most command\n        state.variables[`?`] = String(rightMostExitCode);\n    }\n    return rightMostExitCode;\n}\nfunction locateArgsVariableInSegment(segment) {\n    switch (segment.type) {\n        case `variable`:\n            {\n                return segment.name === `@` || segment.name === `#` || segment.name === `*` || Number.isFinite(parseInt(segment.name, 10)) || (!!segment.defaultValue && segment.defaultValue.some(arg => locateArgsVariableInArgument(arg)));\n            }\n            break;\n        case `shell`:\n            {\n                return locateArgsVariable(segment.shell);\n            }\n            break;\n        default:\n            {\n                return false;\n            }\n            break;\n    }\n}\nfunction locateArgsVariableInArgument(arg) {\n    switch (arg.type) {\n        case `redirection`:\n            {\n                return arg.args.some(arg => locateArgsVariableInArgument(arg));\n            }\n            break;\n        case `argument`:\n            {\n                return arg.segments.some(segment => locateArgsVariableInSegment(segment));\n            }\n            break;\n    }\n}\nfunction locateArgsVariable(node) {\n    return node.some(command => {\n        while (command) {\n            let chain = command.chain;\n            while (chain) {\n                let hasArgs;\n                switch (chain.type) {\n                    case `subshell`:\n                        {\n                            hasArgs = locateArgsVariable(chain.subshell);\n                        }\n                        break;\n                    case `command`:\n                        {\n                            hasArgs = chain.envs.some(env => env.args.some(arg => {\n                                return locateArgsVariableInArgument(arg);\n                            })) || chain.args.some(arg => {\n                                return locateArgsVariableInArgument(arg);\n                            });\n                        }\n                        break;\n                }\n                if (hasArgs)\n                    return true;\n                if (!chain.then)\n                    break;\n                chain = chain.then.chain;\n            }\n            if (!command.then)\n                break;\n            command = command.then.line;\n        }\n        return false;\n    });\n}\nasync function execute(command, args = [], { builtins = {}, cwd = fslib_1.NodeFS.toPortablePath(process.cwd()), env = process.env, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, variables = {}, } = {}) {\n    const normalizedEnv = {};\n    for (const [key, value] of Object.entries(env))\n        if (typeof value !== `undefined`)\n            normalizedEnv[key] = value;\n    const normalizedBuiltins = new Map(BUILTINS);\n    for (const [key, builtin] of Object.entries(builtins))\n        normalizedBuiltins.set(key, builtin);\n    // This is meant to be the equivalent of /dev/null\n    if (stdin === null) {\n        stdin = new stream_1.PassThrough();\n        stdin.end();\n    }\n    const ast = parsers_1.parseShell(command);\n    // If the shell line doesn't use the args, inject it at the end of the\n    // right-most command\n    if (!locateArgsVariable(ast) && ast.length > 0 && args.length > 0) {\n        let command = ast[ast.length - 1];\n        while (command.then)\n            command = command.then.line;\n        let chain = command.chain;\n        while (chain.then)\n            chain = chain.then.chain;\n        if (chain.type === `command`) {\n            chain.args = chain.args.concat(args.map(arg => {\n                return {\n                    type: `argument`,\n                    segments: [{\n                            type: `text`,\n                            text: arg,\n                        }],\n                };\n            }));\n        }\n    }\n    return await executeShellLine(ast, {\n        args,\n        builtins: normalizedBuiltins,\n        initialStdin: stdin,\n        initialStdout: stdout,\n        initialStderr: stderr,\n    }, {\n        cwd,\n        environment: normalizedEnv,\n        exitCode: null,\n        stdin,\n        stdout,\n        stderr,\n        variables: Object.assign(Object.create(variables), {\n            [`?`]: 0,\n        }),\n    });\n}\nexports.execute = execute;\n"]}