#!/usr/bin/env node
import{a as A,b as B}from"./chunk-X77ZMKPA.js";import"./chunk-4OALHZXB.js";import"./chunk-MY5PY2PL.js";import{a as j,b as v}from"./chunk-WECK54LW.js";import"./chunk-LIYVQA3X.js";import{b as M}from"./chunk-SJDWSD6Z.js";import{a as W}from"./chunk-4PRVMER6.js";import{a as T}from"./chunk-4VDEBYW7.js";import{a as F,b as S}from"./chunk-RLNOQILG.js";import{b as P}from"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";import{AsyncLocalStorage as D}from"node:async_hooks";import{randomBytes as J}from"node:crypto";import{existsSync as N}from"node:fs";import{dirname as H,join as m}from"node:path";import{fileURLToPath as z}from"node:url";import{Worker as $}from"node:worker_threads";var V=1e4,Q=6e4,_=new D,q=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs

Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]

Options:
  -c CODE          Execute inline code
  -m, --module     Enable ES module mode (import/export)
  --strip-types    Strip TypeScript type annotations
  --version, -V    Show version
  --help           Show this help

Examples:
  js-exec -c "console.log(1 + 2)"
  js-exec script.js
  js-exec app.ts
  echo 'console.log("hello")' | js-exec

File Extension Auto-Detection:
  .js              script mode (module mode if top-level await detected)
  .mjs             ES module mode
  .ts, .mts        ES module mode + TypeScript stripping

Node.js Compatibility:
  Code written for Node.js largely works here. Both require and import
  are supported, the node: prefix works, and standard globals like process,
  console, and fetch are available. All I/O is synchronous.

  Available modules:
    fs, path, child_process, process, console,
    os, url, assert, util, events, buffer, stream,
    string_decoder, querystring

  fs (global, require('fs'), or import from 'node:fs'):
    readFileSync, writeFileSync, appendFileSync, copyFileSync, renameSync
    readdirSync, mkdirSync, rmSync, unlinkSync, rmdirSync
    statSync, lstatSync, existsSync, realpathSync, chmodSync
    symlinkSync, readlinkSync, readFileBuffer
    fs.promises.readFile, fs.promises.writeFile, fs.promises.access, ...

  path: join, resolve, dirname, basename, extname, normalize,
    relative, isAbsolute, parse, format, sep, delimiter

  child_process:
    execSync(cmd)       throws on non-zero exit, returns stdout
    spawnSync(cmd, args) returns { stdout, stderr, status }

  process (also global): argv, cwd(), exit(), env, platform, arch,
    version, versions

  os: platform(), arch(), homedir(), tmpdir(), type(), hostname(),
    EOL, cpus(), endianness()

  url: URL, URLSearchParams, parse(), format()

  assert: ok(), equal(), strictEqual(), deepEqual(), throws(),
    doesNotThrow(), fail()

  util: format(), inspect(), promisify(), types, inherits()

  events: EventEmitter (on, once, emit, off, removeListener, ...)

  buffer: Buffer.from(), Buffer.alloc(), Buffer.concat(),
    Buffer.isBuffer(), toString(), slice(), equals()

  stream: Readable, Writable, Duplex, Transform, PassThrough, pipeline

  string_decoder: StringDecoder (write, end)

  querystring: parse(), stringify(), escape(), unescape()

Other Globals:
  console            log (stdout), error/warn (stderr)
  fetch(url, opts)   HTTP; returns Promise<Response> (Web Fetch API)
  URL, URLSearchParams, Headers, Request, Response
  Buffer             Buffer.from(), Buffer.alloc(), etc.

Not Available:
  http, https, net, tls, crypto, zlib, dns, cluster, worker_threads,
  vm, v8, readline, and other Node.js built-in modules that require
  native bindings. Use fetch() for HTTP requests.

Limits:
  Memory: 64 MB per execution
  Timeout: 10 s (60 s with network; configurable via maxJsTimeoutMs)
  Engine: QuickJS (compiled to WebAssembly)
`;function G(t){let r={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1,sessionId:null};if(t.length===0)return r;for(let e=0;e<t.length;e++){let s=t[e];if(s==="-m"||s==="--module"){r.isModule=!0;continue}if(s==="--strip-types"){r.stripTypes=!0;continue}if(s==="-c")return e+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
`,exitCode:2}:(r.code=t[e+1],r.scriptArgs=t.slice(e+2),r);if(s==="--version"||s==="-V")return r.showVersion=!0,r;if(s.startsWith("-")&&s!=="-"&&s!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${s}'
`,exitCode:2};if(s==="--")return e+1<t.length&&(r.scriptFile=t[e+1],r.scriptArgs=t.slice(e+2)),r;if(s==="--session"){if(e+1>=t.length)return{stdout:"",stderr:`js-exec: option requires an argument -- 'session'
`,exitCode:2};r.sessionId=t[e+1],e++;continue}if(!s.startsWith("-"))return r.scriptFile=s,r.scriptArgs=t.slice(e+1),r}return r}var i=null,k=null,l=[],n=null;function K(){let t="worker.js",r=typeof process<"u";if(typeof import.meta<"u"&&import.meta.url)try{let s=new URL(import.meta.url);if(s.protocol==="file:"){let o=H(z(s)),c=m(o,"worker.js");if(r){let d=[c,m(o,"js-worker.js"),m(o,"chunks","js-worker.js"),m(o,"..","commands","js-exec","worker.js"),m(o,"../../../dist/commands/js-exec/worker.js")];for(let a of d)if(N(a))return a}t=c}}catch{}return t}var X=K();function h(){for(;l.length>0&&l[0].canceled;)l.shift();if(n||l.length===0)return;let t=l.shift();if(!t)return;n=t,Z(n.input.sessionId,n.sessionManager).postMessage(n.input)}function Y(t,r){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let e=t;return typeof e.protocolToken!="string"||e.protocolToken!==r?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof e.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:e.success?{success:!0}:{success:!1,error:typeof e.error=="string"&&e.error.length>0?e.error:"Worker execution failed"}}function Z(t,r){if(k&&!t&&(v(k),k=null),t&&r){let s=r.getSession(t);if(s)return s.worker}if(i&&!t)return i;let e=M.runTrusted(()=>new $(X));return t&&r?r.createSession("javascript",e,t):i=e,e.on("message",s=>{if(i===e){if(n){let o=Y(s,n.input.protocolToken);n.resolve(o),n=null}l.length>0?h():ee()}}),e.on("error",s=>{if(i===e){if(n){let o=S(T(s));n.resolve({success:!1,error:o}),n=null}for(let o of l)o.resolve({success:!1,error:"Worker crashed"});l.length=0,i=null}}),e.on("exit",()=>{i===e&&(i=null,n&&(n.resolve({success:!1,error:"Worker exited unexpectedly"}),n=null),l.length>0&&h())}),e}function ee(){k=j(()=>{i&&!n&&l.length===0&&(i.terminate(),i=null)},5e3)}async function re(t,r,e,s=[],o,c,d,a){return _.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
`,exitCode:1}:te(t,r,e,s,o,c,d,a)}async function te(t,r,e,s=[],o,c,d,a){let f=A(),w=r.exec,O=w?(u,C)=>_.run(!0,()=>w(u,C)):void 0,L=new B(f,r.fs,r.cwd,"js-exec",r.fetch,r.limits?.maxOutputSize??0,O),E=r.limits?.maxJsTimeoutMs??V,y=r.fetch?Math.max(E,Q):E,R={protocolToken:J(16).toString("hex"),sharedBuffer:f,jsCode:t,cwd:r.cwd,env:W(r.env),args:s,scriptPath:e,bootstrapCode:o,isModule:c,stripTypes:d,timeoutMs:y,persistent:!!a,sessionId:a||void 0},b,I=new Promise(u=>{b=u}),p={input:R,resolve:()=>{},sessionManager:r.bash?.services?.sessionManager},U=j(()=>{if(n===p){let u=i;u&&(i=null,u.terminate()),n=null,h()}else p.canceled=!0,n||h();p.resolve({success:!1,error:`Execution timeout: exceeded ${y}ms limit`})},y);p.resolve=u=>{v(U),b(u)},l.push(p),h();let[x,g]=await Promise.all([L.run(y),I.catch(u=>({success:!1,error:S(T(u))}))]);return!g.success&&g.error?{stdout:x.stdout,stderr:`${x.stderr}js-exec: ${S(g.error)}
`,exitCode:x.exitCode||1}:x}var xe={name:"js-exec",async execute(t,r){if(P(t))return{stdout:q,stderr:"",exitCode:0};let e=G(t);if("exitCode"in e)return e;if(e.showVersion)return{stdout:`QuickJS (quickjs-emscripten)
`,stderr:"",exitCode:0};let s,o;if(e.code!==null)s=e.code,o="-c";else if(e.scriptFile!==null){let f=r.fs.resolvePath(r.cwd,e.scriptFile);if(!await r.fs.exists(f))return{stdout:"",stderr:`js-exec: can't open file '${e.scriptFile}': No such file or directory
`,exitCode:2};try{s=await r.fs.readFile(f),o=f}catch(w){return{stdout:"",stderr:`js-exec: can't open file '${e.scriptFile}': ${F(w.message)}
`,exitCode:2}}}else if(r.stdin.trim())s=r.stdin,o="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
`,exitCode:2};let c=e.isModule,d=e.stripTypes;o&&o!=="-c"&&o!=="<stdin>"&&((o.endsWith(".mjs")||o.endsWith(".mts")||o.endsWith(".ts"))&&(c=!0),(o.endsWith(".ts")||o.endsWith(".mts"))&&(d=!0)),!c&&/\bawait\s+[\w([`]/.test(s)&&(c=!0);let a=r.jsBootstrapCode;return re(s,r,o,e.scriptArgs,a,c,d,e.sessionId)}},Se={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node

${q}`,exitCode:1}}};export{xe as jsExecCommand,Se as nodeStubCommand};
