just-bash 2.14.0 → 2.15.1-executor.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/Bash.d.ts +88 -0
  2. package/dist/bin/chunks/chunk-MNMRGJJM.js +11 -0
  3. package/dist/bin/chunks/js-exec-RGKNWHHL.js +100 -0
  4. package/dist/bin/chunks/js-exec-worker.js +233 -1
  5. package/dist/bin/chunks/{python3-VCIXXAXF.js → python3-QOJU2POC.js} +1 -1
  6. package/dist/bin/chunks/worker.js +15 -1
  7. package/dist/bin/just-bash.js +238 -238
  8. package/dist/bin/shell/chunks/chunk-MNMRGJJM.js +11 -0
  9. package/dist/bin/shell/chunks/js-exec-DUGJM6RL.js +100 -0
  10. package/dist/bin/shell/chunks/{python3-KFZH67GD.js → python3-O4VTP6TD.js} +1 -1
  11. package/dist/bin/shell/shell.js +113 -113
  12. package/dist/bundle/browser.js +6 -6
  13. package/dist/bundle/chunks/chunk-B6O2PIY4.js +10 -0
  14. package/dist/bundle/chunks/js-exec-LSIPMWTQ.js +99 -0
  15. package/dist/bundle/chunks/js-exec-worker.js +233 -1
  16. package/dist/bundle/chunks/{python3-SG3DOKBZ.js → python3-5F2XPEW4.js} +1 -1
  17. package/dist/bundle/chunks/worker.js +15 -1
  18. package/dist/bundle/index.cjs +666 -663
  19. package/dist/bundle/index.js +49 -49
  20. package/dist/commands/js-exec/executor-adapter.d.ts +66 -0
  21. package/dist/commands/js-exec/js-exec.d.ts +19 -1
  22. package/dist/commands/js-exec/worker.d.ts +8 -0
  23. package/dist/commands/worker-bridge/bridge-handler.d.ts +3 -1
  24. package/dist/commands/worker-bridge/protocol.d.ts +1 -0
  25. package/dist/commands/worker-bridge/sync-backend.d.ts +5 -0
  26. package/dist/executor-init.d.ts +19 -0
  27. package/dist/interpreter/interpreter.d.ts +7 -0
  28. package/dist/interpreter/types.d.ts +10 -0
  29. package/dist/types.d.ts +17 -0
  30. package/package.json +37 -34
  31. package/vendor/cpython-emscripten/python.wasm +0 -0
  32. package/vendor/executor/executor-sdk-bundle.d.mts +18 -0
  33. package/vendor/executor/executor-sdk-bundle.mjs +512 -0
  34. package/vendor/executor/openapi-extractor-wasm/openapi_extractor_bg.wasm +0 -0
  35. package/dist/bin/chunks/chunk-3KAVXQP4.js +0 -11
  36. package/dist/bin/chunks/js-exec-BDQGEAU6.js +0 -97
  37. package/dist/bin/shell/chunks/chunk-3KAVXQP4.js +0 -11
  38. package/dist/bin/shell/chunks/js-exec-HPXZV7UJ.js +0 -97
  39. package/dist/bundle/chunks/chunk-S4EYC6T6.js +0 -10
  40. package/dist/bundle/chunks/js-exec-4CW5N6RM.js +0 -96
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as F}from"./chunk-4OALHZXB.js";import{a as w,b as n}from"./chunk-LIYVQA3X.js";import{a as T,b as g}from"./chunk-OOJCYVYF.js";import{a as m}from"./chunk-RLNOQILG.js";var h={NOOP:0,READ_FILE:1,WRITE_FILE:2,STAT:3,READDIR:4,MKDIR:5,RM:6,EXISTS:7,APPEND_FILE:8,SYMLINK:9,READLINK:10,LSTAT:11,CHMOD:12,REALPATH:13,RENAME:14,COPY_FILE:15,WRITE_STDOUT:100,WRITE_STDERR:101,EXIT:102,HTTP_REQUEST:200,EXEC_COMMAND:300},a={PENDING:0,READY:1,SUCCESS:2,ERROR:3},u={NONE:0,NOT_FOUND:1,IS_DIRECTORY:2,NOT_DIRECTORY:3,EXISTS:4,PERMISSION_DENIED:5,INVALID_PATH:6,IO_ERROR:7,TIMEOUT:8,NETWORK_ERROR:9,NETWORK_NOT_CONFIGURED:10},s={OP_CODE:0,STATUS:4,PATH_LENGTH:8,DATA_LENGTH:12,RESULT_LENGTH:16,ERROR_CODE:20,FLAGS:24,MODE:28,PATH_BUFFER:32,DATA_BUFFER:4128},E={CONTROL_REGION:32,PATH_BUFFER:4096,DATA_BUFFER:1048576,TOTAL:1052704},S={NONE:0,RECURSIVE:1,FORCE:2,MKDIR_RECURSIVE:1},l={IS_FILE:0,IS_DIRECTORY:1,IS_SYMLINK:2,MODE:4,SIZE:8,MTIME:16,TOTAL:24};function _(){return new w(E.TOTAL)}var R=class{int32View;uint8View;dataView;constructor(t){this.int32View=new Int32Array(t),this.uint8View=new Uint8Array(t),this.dataView=new DataView(t)}getOpCode(){return n.load(this.int32View,s.OP_CODE/4)}setOpCode(t){n.store(this.int32View,s.OP_CODE/4,t)}getStatus(){return n.load(this.int32View,s.STATUS/4)}setStatus(t){n.store(this.int32View,s.STATUS/4,t)}getPathLength(){return n.load(this.int32View,s.PATH_LENGTH/4)}setPathLength(t){n.store(this.int32View,s.PATH_LENGTH/4,t)}getDataLength(){return n.load(this.int32View,s.DATA_LENGTH/4)}setDataLength(t){n.store(this.int32View,s.DATA_LENGTH/4,t)}getResultLength(){return n.load(this.int32View,s.RESULT_LENGTH/4)}setResultLength(t){n.store(this.int32View,s.RESULT_LENGTH/4,t)}getErrorCode(){return n.load(this.int32View,s.ERROR_CODE/4)}setErrorCode(t){n.store(this.int32View,s.ERROR_CODE/4,t)}getFlags(){return n.load(this.int32View,s.FLAGS/4)}setFlags(t){n.store(this.int32View,s.FLAGS/4,t)}getMode(){return n.load(this.int32View,s.MODE/4)}setMode(t){n.store(this.int32View,s.MODE/4,t)}getPath(){let t=this.getPathLength(),e=this.uint8View.slice(s.PATH_BUFFER,s.PATH_BUFFER+t);return new TextDecoder().decode(e)}setPath(t){let e=new TextEncoder().encode(t);if(e.length>E.PATH_BUFFER)throw new Error(`Path too long: ${e.length} > ${E.PATH_BUFFER}`);this.uint8View.set(e,s.PATH_BUFFER),this.setPathLength(e.length)}getData(){let t=this.getDataLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setData(t){if(t.length>E.DATA_BUFFER)throw new Error(`Data too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setDataLength(t.length)}getDataAsString(){let t=this.getData();return new TextDecoder().decode(t)}setDataFromString(t){let e=new TextEncoder().encode(t);this.setData(e)}getResult(){let t=this.getResultLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setResult(t){if(t.length>E.DATA_BUFFER)throw new Error(`Result too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setResultLength(t.length)}getResultAsString(){let t=this.getResult();return new TextDecoder().decode(t)}setResultFromString(t){let e=new TextEncoder().encode(t);this.setResult(e)}encodeStat(t){this.uint8View[s.DATA_BUFFER+l.IS_FILE]=t.isFile?1:0,this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]=t.isDirectory?1:0,this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]=t.isSymbolicLink?1:0,this.dataView.setInt32(s.DATA_BUFFER+l.MODE,t.mode,!0);let e=Math.min(t.size,Number.MAX_SAFE_INTEGER);this.dataView.setFloat64(s.DATA_BUFFER+l.SIZE,e,!0),this.dataView.setFloat64(s.DATA_BUFFER+l.MTIME,t.mtime.getTime(),!0),this.setResultLength(l.TOTAL)}decodeStat(){return{isFile:this.uint8View[s.DATA_BUFFER+l.IS_FILE]===1,isDirectory:this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]===1,isSymbolicLink:this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]===1,mode:this.dataView.getInt32(s.DATA_BUFFER+l.MODE,!0),size:this.dataView.getFloat64(s.DATA_BUFFER+l.SIZE,!0),mtime:new Date(this.dataView.getFloat64(s.DATA_BUFFER+l.MTIME,!0))}}waitForReady(t){return n.wait(this.int32View,s.STATUS/4,a.PENDING,t)}waitForReadyAsync(t){return n.waitAsync(this.int32View,s.STATUS/4,a.PENDING,t)}async waitUntilReady(t){let e=Date.now();for(;;){let r=this.getStatus();if(r===a.READY)return!0;let o=Date.now()-e;if(o>=t)return!1;let i=t-o,c=n.waitAsync(this.int32View,s.STATUS/4,r,i);if(c.async&&await c.value==="timed-out")return!1}}waitForResult(t){return n.wait(this.int32View,s.STATUS/4,a.READY,t)}notify(){return n.notify(this.int32View,s.STATUS/4)}reset(){this.setOpCode(h.NOOP),this.setStatus(a.PENDING),this.setPathLength(0),this.setDataLength(0),this.setResultLength(0),this.setErrorCode(u.NONE),this.setFlags(S.NONE),this.setMode(0)}};var A=class{fs;cwd;commandName;secureFetch;maxOutputSize;exec;protocol;running=!1;output={stdout:"",stderr:"",exitCode:0};outputLimitExceeded=!1;startTime=0;timeoutMs=0;constructor(t,e,r,o,i=void 0,c=0,d=void 0){this.fs=e,this.cwd=r,this.commandName=o,this.secureFetch=i,this.maxOutputSize=c,this.exec=d,this.protocol=new R(t)}remainingMs(){return Math.max(0,this.timeoutMs-(Date.now()-this.startTime))}raceDeadline(t){let e=this.remainingMs();if(e<=0)return this.running=!1,this.output.exitCode=124,this.output.stderr+=`
3
- ${this.commandName}: execution timeout exceeded
4
- `,Promise.reject(new Error("Operation timed out"));let r=t();return new Promise((o,i)=>{let c=T(()=>{this.running=!1,this.output.exitCode=124,this.output.stderr+=`
5
- ${this.commandName}: execution timeout exceeded
6
- `,i(new Error("Operation timed out"))},e);r.then(d=>{g(c),o(d)},d=>{g(c),i(d)})})}async run(t){for(this.running=!0,this.startTime=Date.now(),this.timeoutMs=t;this.running;){if(Date.now()-this.startTime>=t){this.output.stderr+=`
7
- ${this.commandName}: execution timeout exceeded
8
- `,this.output.exitCode=124;break}let r=this.remainingMs();if(!await this.protocol.waitUntilReady(r)){this.output.stderr+=`
9
- ${this.commandName}: execution timeout exceeded
10
- `,this.output.exitCode=124;break}let i=this.protocol.getOpCode();await this.handleOperation(i),this.protocol.notify()}return this.output}stop(){this.running=!1}async handleOperation(t){try{switch(t){case h.READ_FILE:await this.handleReadFile();break;case h.WRITE_FILE:await this.handleWriteFile();break;case h.STAT:await this.handleStat();break;case h.LSTAT:await this.handleLstat();break;case h.READDIR:await this.handleReaddir();break;case h.MKDIR:await this.handleMkdir();break;case h.RM:await this.handleRm();break;case h.EXISTS:await this.handleExists();break;case h.APPEND_FILE:await this.handleAppendFile();break;case h.SYMLINK:await this.handleSymlink();break;case h.READLINK:await this.handleReadlink();break;case h.CHMOD:await this.handleChmod();break;case h.REALPATH:await this.handleRealpath();break;case h.RENAME:await this.handleRename();break;case h.COPY_FILE:await this.handleCopyFile();break;case h.WRITE_STDOUT:this.handleWriteStdout();break;case h.WRITE_STDERR:this.handleWriteStderr();break;case h.EXIT:this.handleExit();break;case h.HTTP_REQUEST:await this.handleHttpRequest();break;case h.EXEC_COMMAND:await this.handleExecCommand();break;default:this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setStatus(a.ERROR)}}catch(e){this.setErrorFromException(e)}}resolvePath(t){return this.fs.resolvePath(this.cwd,t)}async handleReadFile(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readFileBuffer(t);this.protocol.setResult(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleWriteFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.writeFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleStat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.stat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleLstat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.lstat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleReaddir(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readdir(t);this.protocol.setResultFromString(JSON.stringify(e)),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleMkdir(){let t=this.resolvePath(this.protocol.getPath()),r=(this.protocol.getFlags()&S.MKDIR_RECURSIVE)!==0;try{await this.fs.mkdir(t,{recursive:r}),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleRm(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getFlags(),r=(e&S.RECURSIVE)!==0,o=(e&S.FORCE)!==0;try{await this.fs.rm(t,{recursive:r,force:o}),this.protocol.setStatus(a.SUCCESS)}catch(i){this.setErrorFromException(i)}}async handleExists(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.exists(t);this.protocol.setResult(new Uint8Array([e?1:0])),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleAppendFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.appendFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleSymlink(){let t=this.protocol.getPath(),e=this.protocol.getDataAsString(),r=this.resolvePath(t);try{await this.fs.symlink(e,r),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleReadlink(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readlink(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleChmod(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getMode();try{await this.fs.chmod(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleRealpath(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.realpath(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleRename(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.mv(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleCopyFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.cp(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}handleWriteStdout(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stdout",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleWriteStderr(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stderr",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleExit(){let t=this.protocol.getFlags();this.outputLimitExceeded?this.output.exitCode===0&&(this.output.exitCode=1):this.output.exitCode=t,this.protocol.setStatus(a.SUCCESS),this.running=!1}tryAppendOutput(t,e){return this.outputLimitExceeded?!1:this.maxOutputSize<=0?(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0):this.output.stdout.length+this.output.stderr.length+e.length>this.maxOutputSize?!1:(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0)}appendOutputLimitError(){if(this.maxOutputSize<=0)return;let t=`${this.commandName}: total output size exceeded (>${this.maxOutputSize} bytes), increase executionLimits.maxOutputSize
11
- `,e=t.length>this.maxOutputSize?t.slice(0,this.maxOutputSize):t;if(this.output.stderr.includes("total output size exceeded"))return;let o=this.output.stdout.length+this.output.stderr.length+e.length-this.maxOutputSize;if(o>0)if(this.output.stdout.length>=o)this.output.stdout=this.output.stdout.slice(0,this.output.stdout.length-o);else{let i=o-this.output.stdout.length;this.output.stdout="",i>=this.output.stderr.length?this.output.stderr="":this.output.stderr=this.output.stderr.slice(0,this.output.stderr.length-i)}this.output.stderr+=e}async handleHttpRequest(){let t=this.secureFetch;if(!t){this.protocol.setErrorCode(u.NETWORK_NOT_CONFIGURED),this.protocol.setResultFromString("Network access not configured. Enable network in Bash options."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let o=r?JSON.parse(r):{},i=this.remainingMs(),c=await this.raceDeadline(()=>t(e,{method:o.method,headers:o.headers,body:o.body,timeoutMs:i})),d=JSON.stringify({status:c.status,statusText:c.statusText,headers:c.headers,body:c.body,url:c.url});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(o){let i=m(o instanceof Error?o.message:String(o));this.protocol.setErrorCode(u.NETWORK_ERROR),this.protocol.setResultFromString(i),this.protocol.setStatus(a.ERROR)}}async handleExecCommand(){let t=this.exec;if(!t){this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Command execution not available in this context."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString(),o=new AbortController;try{let i={cwd:this.cwd,signal:o.signal};if(r){let p=JSON.parse(r);p.stdin&&(i.stdin=p.stdin),p.args&&Array.isArray(p.args)&&(i.args=p.args.map(D=>String(D)),e=F([e]))}let c=await this.raceDeadline(()=>t(e,i)),d=JSON.stringify({stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(i){o.abort();let c=i instanceof Error?i.message:String(i);this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString(c),this.protocol.setStatus(a.ERROR)}}setErrorFromException(t){let e=t instanceof Error?t.message:String(t),r=m(e),o=u.IO_ERROR,i=e.toLowerCase();i.includes("no such file")||i.includes("not found")||i.includes("enoent")?o=u.NOT_FOUND:i.includes("is a directory")||i.includes("eisdir")?o=u.IS_DIRECTORY:i.includes("not a directory")||i.includes("enotdir")?o=u.NOT_DIRECTORY:i.includes("already exists")||i.includes("eexist")?o=u.EXISTS:(i.includes("permission")||i.includes("eperm")||i.includes("eacces"))&&(o=u.PERMISSION_DENIED),this.protocol.setErrorCode(o),this.protocol.setResultFromString(r),this.protocol.setStatus(a.ERROR)}};export{_ as a,A as b};
@@ -1,97 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as A,b as P}from"./chunk-3KAVXQP4.js";import"./chunk-4OALHZXB.js";import"./chunk-MY5PY2PL.js";import"./chunk-LIYVQA3X.js";import{a as k,b as T}from"./chunk-OOJCYVYF.js";import{a as W}from"./chunk-4PRVMER6.js";import{b as C}from"./chunk-YU6OGPZR.js";import{a as M,b as x}from"./chunk-RLNOQILG.js";import{a as v}from"./chunk-4VDEBYW7.js";import{b as F}from"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";import{AsyncLocalStorage as U}from"node:async_hooks";import{randomBytes as I}from"node:crypto";import{fileURLToPath as J}from"node:url";import{Worker as D}from"node:worker_threads";var N=1e4,H=6e4,B=new U,_=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
3
-
4
- Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]
5
-
6
- Options:
7
- -c CODE Execute inline code
8
- -m, --module Enable ES module mode (import/export)
9
- --strip-types Strip TypeScript type annotations
10
- --version, -V Show version
11
- --help Show this help
12
-
13
- Examples:
14
- js-exec -c "console.log(1 + 2)"
15
- js-exec script.js
16
- js-exec app.ts
17
- echo 'console.log("hello")' | js-exec
18
-
19
- File Extension Auto-Detection:
20
- .js script mode (module mode if top-level await detected)
21
- .mjs ES module mode
22
- .ts, .mts ES module mode + TypeScript stripping
23
-
24
- Node.js Compatibility:
25
- Code written for Node.js largely works here. Both require and import
26
- are supported, the node: prefix works, and standard globals like process,
27
- console, and fetch are available. All I/O is synchronous.
28
-
29
- Available modules:
30
- fs, path, child_process, process, console,
31
- os, url, assert, util, events, buffer, stream,
32
- string_decoder, querystring
33
-
34
- fs (global, require('fs'), or import from 'node:fs'):
35
- readFileSync, writeFileSync, appendFileSync, copyFileSync, renameSync
36
- readdirSync, mkdirSync, rmSync, unlinkSync, rmdirSync
37
- statSync, lstatSync, existsSync, realpathSync, chmodSync
38
- symlinkSync, readlinkSync, readFileBuffer
39
- fs.promises.readFile, fs.promises.writeFile, fs.promises.access, ...
40
-
41
- path: join, resolve, dirname, basename, extname, normalize,
42
- relative, isAbsolute, parse, format, sep, delimiter
43
-
44
- child_process:
45
- execSync(cmd) throws on non-zero exit, returns stdout
46
- spawnSync(cmd, args) returns { stdout, stderr, status }
47
-
48
- process (also global): argv, cwd(), exit(), env, platform, arch,
49
- version, versions
50
-
51
- os: platform(), arch(), homedir(), tmpdir(), type(), hostname(),
52
- EOL, cpus(), endianness()
53
-
54
- url: URL, URLSearchParams, parse(), format()
55
-
56
- assert: ok(), equal(), strictEqual(), deepEqual(), throws(),
57
- doesNotThrow(), fail()
58
-
59
- util: format(), inspect(), promisify(), types, inherits()
60
-
61
- events: EventEmitter (on, once, emit, off, removeListener, ...)
62
-
63
- buffer: Buffer.from(), Buffer.alloc(), Buffer.concat(),
64
- Buffer.isBuffer(), toString(), slice(), equals()
65
-
66
- stream: Readable, Writable, Duplex, Transform, PassThrough, pipeline
67
-
68
- string_decoder: StringDecoder (write, end)
69
-
70
- querystring: parse(), stringify(), escape(), unescape()
71
-
72
- Other Globals:
73
- console log (stdout), error/warn (stderr)
74
- fetch(url, opts) HTTP; returns Promise<Response> (Web Fetch API)
75
- URL, URLSearchParams, Headers, Request, Response
76
- Buffer Buffer.from(), Buffer.alloc(), etc.
77
-
78
- Not Available:
79
- http, https, net, tls, crypto, zlib, dns, cluster, worker_threads,
80
- vm, v8, readline, and other Node.js built-in modules that require
81
- native bindings. Use fetch() for HTTP requests.
82
-
83
- Limits:
84
- Memory: 64 MB per execution
85
- Timeout: 10 s (60 s with network; configurable via maxJsTimeoutMs)
86
- Engine: QuickJS (compiled to WebAssembly)
87
- `;function z(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let r=0;r<t.length;r++){let s=t[r];if(s==="-m"||s==="--module"){e.isModule=!0;continue}if(s==="--strip-types"){e.stripTypes=!0;continue}if(s==="-c")return r+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
88
- `,exitCode:2}:(e.code=t[r+1],e.scriptArgs=t.slice(r+2),e);if(s==="--version"||s==="-V")return e.showVersion=!0,e;if(s.startsWith("-")&&s!=="-"&&s!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${s}'
89
- `,exitCode:2};if(s==="--")return r+1<t.length&&(e.scriptFile=t[r+1],e.scriptArgs=t.slice(r+2)),e;if(!s.startsWith("-"))return e.scriptFile=s,e.scriptArgs=t.slice(r+1),e}return e}var i=null,w=null,c=[],o=null,$=J(new URL("./worker.js",import.meta.url));function p(){for(;c.length>0&&c[0].canceled;)c.shift();if(o||c.length===0)return;let t=c.shift();if(!t)return;o=t,Q().postMessage(o.input)}function V(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let r=t;return typeof r.protocolToken!="string"||r.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?{success:!0}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}function Q(){if(w&&(T(w),w=null),i)return i;let t=C.runTrusted(()=>new D($));return i=t,t.on("message",e=>{if(i===t){if(o){let r=V(e,o.input.protocolToken);o.resolve(r),o=null}c.length>0?p():G()}}),t.on("error",e=>{if(i===t){if(o){let r=x(v(e));o.resolve({success:!1,error:r}),o=null}for(let r of c)r.resolve({success:!1,error:"Worker crashed"});c.length=0,i=null}}),t.on("exit",()=>{i===t&&(i=null,o&&(o.resolve({success:!1,error:"Worker exited unexpectedly"}),o=null),c.length>0&&p())}),t}function G(){w=k(()=>{i&&!o&&c.length===0&&(i.terminate(),i=null)},5e3)}async function K(t,e,r,s=[],n,u,a){return B.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
90
- `,exitCode:1}:X(t,e,r,s,n,u,a)}async function X(t,e,r,s=[],n,u,a){let m=A(),d=e.exec,g=d?(l,j)=>B.run(!0,()=>d(l,j)):void 0,q=new P(m,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,g),E=e.limits?.maxJsTimeoutMs??N,h=e.fetch?Math.max(E,H):E,O={protocolToken:I(16).toString("hex"),sharedBuffer:m,jsCode:t,cwd:e.cwd,env:W(e.env),args:s,scriptPath:r,bootstrapCode:n,isModule:u,stripTypes:a,timeoutMs:h},b,L=new Promise(l=>{b=l}),f={input:O,resolve:()=>{}},R=k(()=>{if(o===f){let l=i;l&&(i=null,l.terminate()),o=null,p()}else f.canceled=!0,o||p();f.resolve({success:!1,error:`Execution timeout: exceeded ${h}ms limit`})},h);f.resolve=l=>{T(R),b(l)},c.push(f),p();let[y,S]=await Promise.all([q.run(h),L.catch(l=>({success:!1,error:x(v(l))}))]);return!S.success&&S.error?{stdout:y.stdout,stderr:`${y.stderr}js-exec: ${x(S.error)}
91
- `,exitCode:y.exitCode||1}:y}var de={name:"js-exec",async execute(t,e){if(F(t))return{stdout:_,stderr:"",exitCode:0};let r=z(t);if("exitCode"in r)return r;if(r.showVersion)return{stdout:`QuickJS (quickjs-emscripten)
92
- `,stderr:"",exitCode:0};let s,n;if(r.code!==null)s=r.code,n="-c";else if(r.scriptFile!==null){let d=e.fs.resolvePath(e.cwd,r.scriptFile);if(!await e.fs.exists(d))return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': No such file or directory
93
- `,exitCode:2};try{s=await e.fs.readFile(d),n=d}catch(g){return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': ${M(g.message)}
94
- `,exitCode:2}}}else if(e.stdin.trim())s=e.stdin,n="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
95
- `,exitCode:2};let u=r.isModule,a=r.stripTypes;n&&n!=="-c"&&n!=="<stdin>"&&((n.endsWith(".mjs")||n.endsWith(".mts")||n.endsWith(".ts"))&&(u=!0),(n.endsWith(".ts")||n.endsWith(".mts"))&&(a=!0)),!u&&/\bawait\s+[\w([`]/.test(s)&&(u=!0);let m=e.jsBootstrapCode;return K(s,e,n,r.scriptArgs,m,u,a)}},fe={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
96
-
97
- ${_}`,exitCode:1}}};export{de as jsExecCommand,fe as nodeStubCommand};
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as F}from"./chunk-4OALHZXB.js";import{a as w,b as n}from"./chunk-LIYVQA3X.js";import{a as T,b as g}from"./chunk-OOJCYVYF.js";import{a as m}from"./chunk-RLNOQILG.js";var h={NOOP:0,READ_FILE:1,WRITE_FILE:2,STAT:3,READDIR:4,MKDIR:5,RM:6,EXISTS:7,APPEND_FILE:8,SYMLINK:9,READLINK:10,LSTAT:11,CHMOD:12,REALPATH:13,RENAME:14,COPY_FILE:15,WRITE_STDOUT:100,WRITE_STDERR:101,EXIT:102,HTTP_REQUEST:200,EXEC_COMMAND:300},a={PENDING:0,READY:1,SUCCESS:2,ERROR:3},u={NONE:0,NOT_FOUND:1,IS_DIRECTORY:2,NOT_DIRECTORY:3,EXISTS:4,PERMISSION_DENIED:5,INVALID_PATH:6,IO_ERROR:7,TIMEOUT:8,NETWORK_ERROR:9,NETWORK_NOT_CONFIGURED:10},s={OP_CODE:0,STATUS:4,PATH_LENGTH:8,DATA_LENGTH:12,RESULT_LENGTH:16,ERROR_CODE:20,FLAGS:24,MODE:28,PATH_BUFFER:32,DATA_BUFFER:4128},E={CONTROL_REGION:32,PATH_BUFFER:4096,DATA_BUFFER:1048576,TOTAL:1052704},S={NONE:0,RECURSIVE:1,FORCE:2,MKDIR_RECURSIVE:1},l={IS_FILE:0,IS_DIRECTORY:1,IS_SYMLINK:2,MODE:4,SIZE:8,MTIME:16,TOTAL:24};function _(){return new w(E.TOTAL)}var R=class{int32View;uint8View;dataView;constructor(t){this.int32View=new Int32Array(t),this.uint8View=new Uint8Array(t),this.dataView=new DataView(t)}getOpCode(){return n.load(this.int32View,s.OP_CODE/4)}setOpCode(t){n.store(this.int32View,s.OP_CODE/4,t)}getStatus(){return n.load(this.int32View,s.STATUS/4)}setStatus(t){n.store(this.int32View,s.STATUS/4,t)}getPathLength(){return n.load(this.int32View,s.PATH_LENGTH/4)}setPathLength(t){n.store(this.int32View,s.PATH_LENGTH/4,t)}getDataLength(){return n.load(this.int32View,s.DATA_LENGTH/4)}setDataLength(t){n.store(this.int32View,s.DATA_LENGTH/4,t)}getResultLength(){return n.load(this.int32View,s.RESULT_LENGTH/4)}setResultLength(t){n.store(this.int32View,s.RESULT_LENGTH/4,t)}getErrorCode(){return n.load(this.int32View,s.ERROR_CODE/4)}setErrorCode(t){n.store(this.int32View,s.ERROR_CODE/4,t)}getFlags(){return n.load(this.int32View,s.FLAGS/4)}setFlags(t){n.store(this.int32View,s.FLAGS/4,t)}getMode(){return n.load(this.int32View,s.MODE/4)}setMode(t){n.store(this.int32View,s.MODE/4,t)}getPath(){let t=this.getPathLength(),e=this.uint8View.slice(s.PATH_BUFFER,s.PATH_BUFFER+t);return new TextDecoder().decode(e)}setPath(t){let e=new TextEncoder().encode(t);if(e.length>E.PATH_BUFFER)throw new Error(`Path too long: ${e.length} > ${E.PATH_BUFFER}`);this.uint8View.set(e,s.PATH_BUFFER),this.setPathLength(e.length)}getData(){let t=this.getDataLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setData(t){if(t.length>E.DATA_BUFFER)throw new Error(`Data too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setDataLength(t.length)}getDataAsString(){let t=this.getData();return new TextDecoder().decode(t)}setDataFromString(t){let e=new TextEncoder().encode(t);this.setData(e)}getResult(){let t=this.getResultLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setResult(t){if(t.length>E.DATA_BUFFER)throw new Error(`Result too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setResultLength(t.length)}getResultAsString(){let t=this.getResult();return new TextDecoder().decode(t)}setResultFromString(t){let e=new TextEncoder().encode(t);this.setResult(e)}encodeStat(t){this.uint8View[s.DATA_BUFFER+l.IS_FILE]=t.isFile?1:0,this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]=t.isDirectory?1:0,this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]=t.isSymbolicLink?1:0,this.dataView.setInt32(s.DATA_BUFFER+l.MODE,t.mode,!0);let e=Math.min(t.size,Number.MAX_SAFE_INTEGER);this.dataView.setFloat64(s.DATA_BUFFER+l.SIZE,e,!0),this.dataView.setFloat64(s.DATA_BUFFER+l.MTIME,t.mtime.getTime(),!0),this.setResultLength(l.TOTAL)}decodeStat(){return{isFile:this.uint8View[s.DATA_BUFFER+l.IS_FILE]===1,isDirectory:this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]===1,isSymbolicLink:this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]===1,mode:this.dataView.getInt32(s.DATA_BUFFER+l.MODE,!0),size:this.dataView.getFloat64(s.DATA_BUFFER+l.SIZE,!0),mtime:new Date(this.dataView.getFloat64(s.DATA_BUFFER+l.MTIME,!0))}}waitForReady(t){return n.wait(this.int32View,s.STATUS/4,a.PENDING,t)}waitForReadyAsync(t){return n.waitAsync(this.int32View,s.STATUS/4,a.PENDING,t)}async waitUntilReady(t){let e=Date.now();for(;;){let r=this.getStatus();if(r===a.READY)return!0;let o=Date.now()-e;if(o>=t)return!1;let i=t-o,c=n.waitAsync(this.int32View,s.STATUS/4,r,i);if(c.async&&await c.value==="timed-out")return!1}}waitForResult(t){return n.wait(this.int32View,s.STATUS/4,a.READY,t)}notify(){return n.notify(this.int32View,s.STATUS/4)}reset(){this.setOpCode(h.NOOP),this.setStatus(a.PENDING),this.setPathLength(0),this.setDataLength(0),this.setResultLength(0),this.setErrorCode(u.NONE),this.setFlags(S.NONE),this.setMode(0)}};var A=class{fs;cwd;commandName;secureFetch;maxOutputSize;exec;protocol;running=!1;output={stdout:"",stderr:"",exitCode:0};outputLimitExceeded=!1;startTime=0;timeoutMs=0;constructor(t,e,r,o,i=void 0,c=0,d=void 0){this.fs=e,this.cwd=r,this.commandName=o,this.secureFetch=i,this.maxOutputSize=c,this.exec=d,this.protocol=new R(t)}remainingMs(){return Math.max(0,this.timeoutMs-(Date.now()-this.startTime))}raceDeadline(t){let e=this.remainingMs();if(e<=0)return this.running=!1,this.output.exitCode=124,this.output.stderr+=`
3
- ${this.commandName}: execution timeout exceeded
4
- `,Promise.reject(new Error("Operation timed out"));let r=t();return new Promise((o,i)=>{let c=T(()=>{this.running=!1,this.output.exitCode=124,this.output.stderr+=`
5
- ${this.commandName}: execution timeout exceeded
6
- `,i(new Error("Operation timed out"))},e);r.then(d=>{g(c),o(d)},d=>{g(c),i(d)})})}async run(t){for(this.running=!0,this.startTime=Date.now(),this.timeoutMs=t;this.running;){if(Date.now()-this.startTime>=t){this.output.stderr+=`
7
- ${this.commandName}: execution timeout exceeded
8
- `,this.output.exitCode=124;break}let r=this.remainingMs();if(!await this.protocol.waitUntilReady(r)){this.output.stderr+=`
9
- ${this.commandName}: execution timeout exceeded
10
- `,this.output.exitCode=124;break}let i=this.protocol.getOpCode();await this.handleOperation(i),this.protocol.notify()}return this.output}stop(){this.running=!1}async handleOperation(t){try{switch(t){case h.READ_FILE:await this.handleReadFile();break;case h.WRITE_FILE:await this.handleWriteFile();break;case h.STAT:await this.handleStat();break;case h.LSTAT:await this.handleLstat();break;case h.READDIR:await this.handleReaddir();break;case h.MKDIR:await this.handleMkdir();break;case h.RM:await this.handleRm();break;case h.EXISTS:await this.handleExists();break;case h.APPEND_FILE:await this.handleAppendFile();break;case h.SYMLINK:await this.handleSymlink();break;case h.READLINK:await this.handleReadlink();break;case h.CHMOD:await this.handleChmod();break;case h.REALPATH:await this.handleRealpath();break;case h.RENAME:await this.handleRename();break;case h.COPY_FILE:await this.handleCopyFile();break;case h.WRITE_STDOUT:this.handleWriteStdout();break;case h.WRITE_STDERR:this.handleWriteStderr();break;case h.EXIT:this.handleExit();break;case h.HTTP_REQUEST:await this.handleHttpRequest();break;case h.EXEC_COMMAND:await this.handleExecCommand();break;default:this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setStatus(a.ERROR)}}catch(e){this.setErrorFromException(e)}}resolvePath(t){return this.fs.resolvePath(this.cwd,t)}async handleReadFile(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readFileBuffer(t);this.protocol.setResult(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleWriteFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.writeFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleStat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.stat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleLstat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.lstat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleReaddir(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readdir(t);this.protocol.setResultFromString(JSON.stringify(e)),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleMkdir(){let t=this.resolvePath(this.protocol.getPath()),r=(this.protocol.getFlags()&S.MKDIR_RECURSIVE)!==0;try{await this.fs.mkdir(t,{recursive:r}),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleRm(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getFlags(),r=(e&S.RECURSIVE)!==0,o=(e&S.FORCE)!==0;try{await this.fs.rm(t,{recursive:r,force:o}),this.protocol.setStatus(a.SUCCESS)}catch(i){this.setErrorFromException(i)}}async handleExists(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.exists(t);this.protocol.setResult(new Uint8Array([e?1:0])),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleAppendFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.appendFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleSymlink(){let t=this.protocol.getPath(),e=this.protocol.getDataAsString(),r=this.resolvePath(t);try{await this.fs.symlink(e,r),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleReadlink(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readlink(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleChmod(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getMode();try{await this.fs.chmod(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleRealpath(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.realpath(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleRename(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.mv(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleCopyFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.cp(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}handleWriteStdout(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stdout",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleWriteStderr(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stderr",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleExit(){let t=this.protocol.getFlags();this.outputLimitExceeded?this.output.exitCode===0&&(this.output.exitCode=1):this.output.exitCode=t,this.protocol.setStatus(a.SUCCESS),this.running=!1}tryAppendOutput(t,e){return this.outputLimitExceeded?!1:this.maxOutputSize<=0?(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0):this.output.stdout.length+this.output.stderr.length+e.length>this.maxOutputSize?!1:(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0)}appendOutputLimitError(){if(this.maxOutputSize<=0)return;let t=`${this.commandName}: total output size exceeded (>${this.maxOutputSize} bytes), increase executionLimits.maxOutputSize
11
- `,e=t.length>this.maxOutputSize?t.slice(0,this.maxOutputSize):t;if(this.output.stderr.includes("total output size exceeded"))return;let o=this.output.stdout.length+this.output.stderr.length+e.length-this.maxOutputSize;if(o>0)if(this.output.stdout.length>=o)this.output.stdout=this.output.stdout.slice(0,this.output.stdout.length-o);else{let i=o-this.output.stdout.length;this.output.stdout="",i>=this.output.stderr.length?this.output.stderr="":this.output.stderr=this.output.stderr.slice(0,this.output.stderr.length-i)}this.output.stderr+=e}async handleHttpRequest(){let t=this.secureFetch;if(!t){this.protocol.setErrorCode(u.NETWORK_NOT_CONFIGURED),this.protocol.setResultFromString("Network access not configured. Enable network in Bash options."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let o=r?JSON.parse(r):{},i=this.remainingMs(),c=await this.raceDeadline(()=>t(e,{method:o.method,headers:o.headers,body:o.body,timeoutMs:i})),d=JSON.stringify({status:c.status,statusText:c.statusText,headers:c.headers,body:c.body,url:c.url});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(o){let i=m(o instanceof Error?o.message:String(o));this.protocol.setErrorCode(u.NETWORK_ERROR),this.protocol.setResultFromString(i),this.protocol.setStatus(a.ERROR)}}async handleExecCommand(){let t=this.exec;if(!t){this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Command execution not available in this context."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString(),o=new AbortController;try{let i={cwd:this.cwd,signal:o.signal};if(r){let p=JSON.parse(r);p.stdin&&(i.stdin=p.stdin),p.args&&Array.isArray(p.args)&&(i.args=p.args.map(D=>String(D)),e=F([e]))}let c=await this.raceDeadline(()=>t(e,i)),d=JSON.stringify({stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(i){o.abort();let c=i instanceof Error?i.message:String(i);this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString(c),this.protocol.setStatus(a.ERROR)}}setErrorFromException(t){let e=t instanceof Error?t.message:String(t),r=m(e),o=u.IO_ERROR,i=e.toLowerCase();i.includes("no such file")||i.includes("not found")||i.includes("enoent")?o=u.NOT_FOUND:i.includes("is a directory")||i.includes("eisdir")?o=u.IS_DIRECTORY:i.includes("not a directory")||i.includes("enotdir")?o=u.NOT_DIRECTORY:i.includes("already exists")||i.includes("eexist")?o=u.EXISTS:(i.includes("permission")||i.includes("eperm")||i.includes("eacces"))&&(o=u.PERMISSION_DENIED),this.protocol.setErrorCode(o),this.protocol.setResultFromString(r),this.protocol.setStatus(a.ERROR)}};export{_ as a,A as b};
@@ -1,97 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as A,b as P}from"./chunk-3KAVXQP4.js";import"./chunk-4OALHZXB.js";import"./chunk-D64U2VGQ.js";import"./chunk-LIYVQA3X.js";import{a as k,b as T}from"./chunk-OOJCYVYF.js";import{a as W}from"./chunk-4PRVMER6.js";import{b as C}from"./chunk-YU6OGPZR.js";import{a as M,b as x}from"./chunk-RLNOQILG.js";import{a as v}from"./chunk-4VDEBYW7.js";import{b as F}from"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";import{AsyncLocalStorage as U}from"node:async_hooks";import{randomBytes as I}from"node:crypto";import{fileURLToPath as J}from"node:url";import{Worker as D}from"node:worker_threads";var N=1e4,H=6e4,B=new U,_=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
3
-
4
- Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]
5
-
6
- Options:
7
- -c CODE Execute inline code
8
- -m, --module Enable ES module mode (import/export)
9
- --strip-types Strip TypeScript type annotations
10
- --version, -V Show version
11
- --help Show this help
12
-
13
- Examples:
14
- js-exec -c "console.log(1 + 2)"
15
- js-exec script.js
16
- js-exec app.ts
17
- echo 'console.log("hello")' | js-exec
18
-
19
- File Extension Auto-Detection:
20
- .js script mode (module mode if top-level await detected)
21
- .mjs ES module mode
22
- .ts, .mts ES module mode + TypeScript stripping
23
-
24
- Node.js Compatibility:
25
- Code written for Node.js largely works here. Both require and import
26
- are supported, the node: prefix works, and standard globals like process,
27
- console, and fetch are available. All I/O is synchronous.
28
-
29
- Available modules:
30
- fs, path, child_process, process, console,
31
- os, url, assert, util, events, buffer, stream,
32
- string_decoder, querystring
33
-
34
- fs (global, require('fs'), or import from 'node:fs'):
35
- readFileSync, writeFileSync, appendFileSync, copyFileSync, renameSync
36
- readdirSync, mkdirSync, rmSync, unlinkSync, rmdirSync
37
- statSync, lstatSync, existsSync, realpathSync, chmodSync
38
- symlinkSync, readlinkSync, readFileBuffer
39
- fs.promises.readFile, fs.promises.writeFile, fs.promises.access, ...
40
-
41
- path: join, resolve, dirname, basename, extname, normalize,
42
- relative, isAbsolute, parse, format, sep, delimiter
43
-
44
- child_process:
45
- execSync(cmd) throws on non-zero exit, returns stdout
46
- spawnSync(cmd, args) returns { stdout, stderr, status }
47
-
48
- process (also global): argv, cwd(), exit(), env, platform, arch,
49
- version, versions
50
-
51
- os: platform(), arch(), homedir(), tmpdir(), type(), hostname(),
52
- EOL, cpus(), endianness()
53
-
54
- url: URL, URLSearchParams, parse(), format()
55
-
56
- assert: ok(), equal(), strictEqual(), deepEqual(), throws(),
57
- doesNotThrow(), fail()
58
-
59
- util: format(), inspect(), promisify(), types, inherits()
60
-
61
- events: EventEmitter (on, once, emit, off, removeListener, ...)
62
-
63
- buffer: Buffer.from(), Buffer.alloc(), Buffer.concat(),
64
- Buffer.isBuffer(), toString(), slice(), equals()
65
-
66
- stream: Readable, Writable, Duplex, Transform, PassThrough, pipeline
67
-
68
- string_decoder: StringDecoder (write, end)
69
-
70
- querystring: parse(), stringify(), escape(), unescape()
71
-
72
- Other Globals:
73
- console log (stdout), error/warn (stderr)
74
- fetch(url, opts) HTTP; returns Promise<Response> (Web Fetch API)
75
- URL, URLSearchParams, Headers, Request, Response
76
- Buffer Buffer.from(), Buffer.alloc(), etc.
77
-
78
- Not Available:
79
- http, https, net, tls, crypto, zlib, dns, cluster, worker_threads,
80
- vm, v8, readline, and other Node.js built-in modules that require
81
- native bindings. Use fetch() for HTTP requests.
82
-
83
- Limits:
84
- Memory: 64 MB per execution
85
- Timeout: 10 s (60 s with network; configurable via maxJsTimeoutMs)
86
- Engine: QuickJS (compiled to WebAssembly)
87
- `;function z(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let r=0;r<t.length;r++){let s=t[r];if(s==="-m"||s==="--module"){e.isModule=!0;continue}if(s==="--strip-types"){e.stripTypes=!0;continue}if(s==="-c")return r+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
88
- `,exitCode:2}:(e.code=t[r+1],e.scriptArgs=t.slice(r+2),e);if(s==="--version"||s==="-V")return e.showVersion=!0,e;if(s.startsWith("-")&&s!=="-"&&s!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${s}'
89
- `,exitCode:2};if(s==="--")return r+1<t.length&&(e.scriptFile=t[r+1],e.scriptArgs=t.slice(r+2)),e;if(!s.startsWith("-"))return e.scriptFile=s,e.scriptArgs=t.slice(r+1),e}return e}var i=null,w=null,c=[],o=null,$=J(new URL("./worker.js",import.meta.url));function p(){for(;c.length>0&&c[0].canceled;)c.shift();if(o||c.length===0)return;let t=c.shift();if(!t)return;o=t,Q().postMessage(o.input)}function V(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let r=t;return typeof r.protocolToken!="string"||r.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?{success:!0}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}function Q(){if(w&&(T(w),w=null),i)return i;let t=C.runTrusted(()=>new D($));return i=t,t.on("message",e=>{if(i===t){if(o){let r=V(e,o.input.protocolToken);o.resolve(r),o=null}c.length>0?p():G()}}),t.on("error",e=>{if(i===t){if(o){let r=x(v(e));o.resolve({success:!1,error:r}),o=null}for(let r of c)r.resolve({success:!1,error:"Worker crashed"});c.length=0,i=null}}),t.on("exit",()=>{i===t&&(i=null,o&&(o.resolve({success:!1,error:"Worker exited unexpectedly"}),o=null),c.length>0&&p())}),t}function G(){w=k(()=>{i&&!o&&c.length===0&&(i.terminate(),i=null)},5e3)}async function K(t,e,r,s=[],n,u,a){return B.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
90
- `,exitCode:1}:X(t,e,r,s,n,u,a)}async function X(t,e,r,s=[],n,u,a){let m=A(),d=e.exec,g=d?(l,j)=>B.run(!0,()=>d(l,j)):void 0,q=new P(m,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,g),E=e.limits?.maxJsTimeoutMs??N,h=e.fetch?Math.max(E,H):E,O={protocolToken:I(16).toString("hex"),sharedBuffer:m,jsCode:t,cwd:e.cwd,env:W(e.env),args:s,scriptPath:r,bootstrapCode:n,isModule:u,stripTypes:a,timeoutMs:h},b,L=new Promise(l=>{b=l}),f={input:O,resolve:()=>{}},R=k(()=>{if(o===f){let l=i;l&&(i=null,l.terminate()),o=null,p()}else f.canceled=!0,o||p();f.resolve({success:!1,error:`Execution timeout: exceeded ${h}ms limit`})},h);f.resolve=l=>{T(R),b(l)},c.push(f),p();let[y,S]=await Promise.all([q.run(h),L.catch(l=>({success:!1,error:x(v(l))}))]);return!S.success&&S.error?{stdout:y.stdout,stderr:`${y.stderr}js-exec: ${x(S.error)}
91
- `,exitCode:y.exitCode||1}:y}var de={name:"js-exec",async execute(t,e){if(F(t))return{stdout:_,stderr:"",exitCode:0};let r=z(t);if("exitCode"in r)return r;if(r.showVersion)return{stdout:`QuickJS (quickjs-emscripten)
92
- `,stderr:"",exitCode:0};let s,n;if(r.code!==null)s=r.code,n="-c";else if(r.scriptFile!==null){let d=e.fs.resolvePath(e.cwd,r.scriptFile);if(!await e.fs.exists(d))return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': No such file or directory
93
- `,exitCode:2};try{s=await e.fs.readFile(d),n=d}catch(g){return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': ${M(g.message)}
94
- `,exitCode:2}}}else if(e.stdin.trim())s=e.stdin,n="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
95
- `,exitCode:2};let u=r.isModule,a=r.stripTypes;n&&n!=="-c"&&n!=="<stdin>"&&((n.endsWith(".mjs")||n.endsWith(".mts")||n.endsWith(".ts"))&&(u=!0),(n.endsWith(".ts")||n.endsWith(".mts"))&&(a=!0)),!u&&/\bawait\s+[\w([`]/.test(s)&&(u=!0);let m=e.jsBootstrapCode;return K(s,e,n,r.scriptArgs,m,u,a)}},fe={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
96
-
97
- ${_}`,exitCode:1}}};export{de as jsExecCommand,fe as nodeStubCommand};
@@ -1,10 +0,0 @@
1
- import{a as w,b as n}from"./chunk-CWQS3NFK.js";import{a as T,b as g}from"./chunk-A5O5YHGN.js";import{a as F}from"./chunk-IPJHKYVM.js";import{a as m}from"./chunk-3THT3N7L.js";var h={NOOP:0,READ_FILE:1,WRITE_FILE:2,STAT:3,READDIR:4,MKDIR:5,RM:6,EXISTS:7,APPEND_FILE:8,SYMLINK:9,READLINK:10,LSTAT:11,CHMOD:12,REALPATH:13,RENAME:14,COPY_FILE:15,WRITE_STDOUT:100,WRITE_STDERR:101,EXIT:102,HTTP_REQUEST:200,EXEC_COMMAND:300},a={PENDING:0,READY:1,SUCCESS:2,ERROR:3},u={NONE:0,NOT_FOUND:1,IS_DIRECTORY:2,NOT_DIRECTORY:3,EXISTS:4,PERMISSION_DENIED:5,INVALID_PATH:6,IO_ERROR:7,TIMEOUT:8,NETWORK_ERROR:9,NETWORK_NOT_CONFIGURED:10},s={OP_CODE:0,STATUS:4,PATH_LENGTH:8,DATA_LENGTH:12,RESULT_LENGTH:16,ERROR_CODE:20,FLAGS:24,MODE:28,PATH_BUFFER:32,DATA_BUFFER:4128},E={CONTROL_REGION:32,PATH_BUFFER:4096,DATA_BUFFER:1048576,TOTAL:1052704},S={NONE:0,RECURSIVE:1,FORCE:2,MKDIR_RECURSIVE:1},l={IS_FILE:0,IS_DIRECTORY:1,IS_SYMLINK:2,MODE:4,SIZE:8,MTIME:16,TOTAL:24};function _(){return new w(E.TOTAL)}var R=class{int32View;uint8View;dataView;constructor(t){this.int32View=new Int32Array(t),this.uint8View=new Uint8Array(t),this.dataView=new DataView(t)}getOpCode(){return n.load(this.int32View,s.OP_CODE/4)}setOpCode(t){n.store(this.int32View,s.OP_CODE/4,t)}getStatus(){return n.load(this.int32View,s.STATUS/4)}setStatus(t){n.store(this.int32View,s.STATUS/4,t)}getPathLength(){return n.load(this.int32View,s.PATH_LENGTH/4)}setPathLength(t){n.store(this.int32View,s.PATH_LENGTH/4,t)}getDataLength(){return n.load(this.int32View,s.DATA_LENGTH/4)}setDataLength(t){n.store(this.int32View,s.DATA_LENGTH/4,t)}getResultLength(){return n.load(this.int32View,s.RESULT_LENGTH/4)}setResultLength(t){n.store(this.int32View,s.RESULT_LENGTH/4,t)}getErrorCode(){return n.load(this.int32View,s.ERROR_CODE/4)}setErrorCode(t){n.store(this.int32View,s.ERROR_CODE/4,t)}getFlags(){return n.load(this.int32View,s.FLAGS/4)}setFlags(t){n.store(this.int32View,s.FLAGS/4,t)}getMode(){return n.load(this.int32View,s.MODE/4)}setMode(t){n.store(this.int32View,s.MODE/4,t)}getPath(){let t=this.getPathLength(),e=this.uint8View.slice(s.PATH_BUFFER,s.PATH_BUFFER+t);return new TextDecoder().decode(e)}setPath(t){let e=new TextEncoder().encode(t);if(e.length>E.PATH_BUFFER)throw new Error(`Path too long: ${e.length} > ${E.PATH_BUFFER}`);this.uint8View.set(e,s.PATH_BUFFER),this.setPathLength(e.length)}getData(){let t=this.getDataLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setData(t){if(t.length>E.DATA_BUFFER)throw new Error(`Data too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setDataLength(t.length)}getDataAsString(){let t=this.getData();return new TextDecoder().decode(t)}setDataFromString(t){let e=new TextEncoder().encode(t);this.setData(e)}getResult(){let t=this.getResultLength();return this.uint8View.slice(s.DATA_BUFFER,s.DATA_BUFFER+t)}setResult(t){if(t.length>E.DATA_BUFFER)throw new Error(`Result too large: ${t.length} > ${E.DATA_BUFFER}`);this.uint8View.set(t,s.DATA_BUFFER),this.setResultLength(t.length)}getResultAsString(){let t=this.getResult();return new TextDecoder().decode(t)}setResultFromString(t){let e=new TextEncoder().encode(t);this.setResult(e)}encodeStat(t){this.uint8View[s.DATA_BUFFER+l.IS_FILE]=t.isFile?1:0,this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]=t.isDirectory?1:0,this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]=t.isSymbolicLink?1:0,this.dataView.setInt32(s.DATA_BUFFER+l.MODE,t.mode,!0);let e=Math.min(t.size,Number.MAX_SAFE_INTEGER);this.dataView.setFloat64(s.DATA_BUFFER+l.SIZE,e,!0),this.dataView.setFloat64(s.DATA_BUFFER+l.MTIME,t.mtime.getTime(),!0),this.setResultLength(l.TOTAL)}decodeStat(){return{isFile:this.uint8View[s.DATA_BUFFER+l.IS_FILE]===1,isDirectory:this.uint8View[s.DATA_BUFFER+l.IS_DIRECTORY]===1,isSymbolicLink:this.uint8View[s.DATA_BUFFER+l.IS_SYMLINK]===1,mode:this.dataView.getInt32(s.DATA_BUFFER+l.MODE,!0),size:this.dataView.getFloat64(s.DATA_BUFFER+l.SIZE,!0),mtime:new Date(this.dataView.getFloat64(s.DATA_BUFFER+l.MTIME,!0))}}waitForReady(t){return n.wait(this.int32View,s.STATUS/4,a.PENDING,t)}waitForReadyAsync(t){return n.waitAsync(this.int32View,s.STATUS/4,a.PENDING,t)}async waitUntilReady(t){let e=Date.now();for(;;){let r=this.getStatus();if(r===a.READY)return!0;let o=Date.now()-e;if(o>=t)return!1;let i=t-o,c=n.waitAsync(this.int32View,s.STATUS/4,r,i);if(c.async&&await c.value==="timed-out")return!1}}waitForResult(t){return n.wait(this.int32View,s.STATUS/4,a.READY,t)}notify(){return n.notify(this.int32View,s.STATUS/4)}reset(){this.setOpCode(h.NOOP),this.setStatus(a.PENDING),this.setPathLength(0),this.setDataLength(0),this.setResultLength(0),this.setErrorCode(u.NONE),this.setFlags(S.NONE),this.setMode(0)}};var A=class{fs;cwd;commandName;secureFetch;maxOutputSize;exec;protocol;running=!1;output={stdout:"",stderr:"",exitCode:0};outputLimitExceeded=!1;startTime=0;timeoutMs=0;constructor(t,e,r,o,i=void 0,c=0,d=void 0){this.fs=e,this.cwd=r,this.commandName=o,this.secureFetch=i,this.maxOutputSize=c,this.exec=d,this.protocol=new R(t)}remainingMs(){return Math.max(0,this.timeoutMs-(Date.now()-this.startTime))}raceDeadline(t){let e=this.remainingMs();if(e<=0)return this.running=!1,this.output.exitCode=124,this.output.stderr+=`
2
- ${this.commandName}: execution timeout exceeded
3
- `,Promise.reject(new Error("Operation timed out"));let r=t();return new Promise((o,i)=>{let c=T(()=>{this.running=!1,this.output.exitCode=124,this.output.stderr+=`
4
- ${this.commandName}: execution timeout exceeded
5
- `,i(new Error("Operation timed out"))},e);r.then(d=>{g(c),o(d)},d=>{g(c),i(d)})})}async run(t){for(this.running=!0,this.startTime=Date.now(),this.timeoutMs=t;this.running;){if(Date.now()-this.startTime>=t){this.output.stderr+=`
6
- ${this.commandName}: execution timeout exceeded
7
- `,this.output.exitCode=124;break}let r=this.remainingMs();if(!await this.protocol.waitUntilReady(r)){this.output.stderr+=`
8
- ${this.commandName}: execution timeout exceeded
9
- `,this.output.exitCode=124;break}let i=this.protocol.getOpCode();await this.handleOperation(i),this.protocol.notify()}return this.output}stop(){this.running=!1}async handleOperation(t){try{switch(t){case h.READ_FILE:await this.handleReadFile();break;case h.WRITE_FILE:await this.handleWriteFile();break;case h.STAT:await this.handleStat();break;case h.LSTAT:await this.handleLstat();break;case h.READDIR:await this.handleReaddir();break;case h.MKDIR:await this.handleMkdir();break;case h.RM:await this.handleRm();break;case h.EXISTS:await this.handleExists();break;case h.APPEND_FILE:await this.handleAppendFile();break;case h.SYMLINK:await this.handleSymlink();break;case h.READLINK:await this.handleReadlink();break;case h.CHMOD:await this.handleChmod();break;case h.REALPATH:await this.handleRealpath();break;case h.RENAME:await this.handleRename();break;case h.COPY_FILE:await this.handleCopyFile();break;case h.WRITE_STDOUT:this.handleWriteStdout();break;case h.WRITE_STDERR:this.handleWriteStderr();break;case h.EXIT:this.handleExit();break;case h.HTTP_REQUEST:await this.handleHttpRequest();break;case h.EXEC_COMMAND:await this.handleExecCommand();break;default:this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setStatus(a.ERROR)}}catch(e){this.setErrorFromException(e)}}resolvePath(t){return this.fs.resolvePath(this.cwd,t)}async handleReadFile(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readFileBuffer(t);this.protocol.setResult(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleWriteFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.writeFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleStat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.stat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleLstat(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.lstat(t);this.protocol.encodeStat(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleReaddir(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readdir(t);this.protocol.setResultFromString(JSON.stringify(e)),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleMkdir(){let t=this.resolvePath(this.protocol.getPath()),r=(this.protocol.getFlags()&S.MKDIR_RECURSIVE)!==0;try{await this.fs.mkdir(t,{recursive:r}),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleRm(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getFlags(),r=(e&S.RECURSIVE)!==0,o=(e&S.FORCE)!==0;try{await this.fs.rm(t,{recursive:r,force:o}),this.protocol.setStatus(a.SUCCESS)}catch(i){this.setErrorFromException(i)}}async handleExists(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.exists(t);this.protocol.setResult(new Uint8Array([e?1:0])),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleAppendFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getData();try{await this.fs.appendFile(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleSymlink(){let t=this.protocol.getPath(),e=this.protocol.getDataAsString(),r=this.resolvePath(t);try{await this.fs.symlink(e,r),this.protocol.setStatus(a.SUCCESS)}catch(o){this.setErrorFromException(o)}}async handleReadlink(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.readlink(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleChmod(){let t=this.resolvePath(this.protocol.getPath()),e=this.protocol.getMode();try{await this.fs.chmod(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleRealpath(){let t=this.resolvePath(this.protocol.getPath());try{let e=await this.fs.realpath(t);this.protocol.setResultFromString(e),this.protocol.setStatus(a.SUCCESS)}catch(e){this.setErrorFromException(e)}}async handleRename(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.mv(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}async handleCopyFile(){let t=this.resolvePath(this.protocol.getPath()),e=this.resolvePath(this.protocol.getDataAsString());try{await this.fs.cp(t,e),this.protocol.setStatus(a.SUCCESS)}catch(r){this.setErrorFromException(r)}}handleWriteStdout(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stdout",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleWriteStderr(){let t=this.protocol.getDataAsString();if(!this.tryAppendOutput("stderr",t)){this.outputLimitExceeded=!0,this.output.exitCode=1,this.appendOutputLimitError(),this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Output size limit exceeded"),this.protocol.setStatus(a.ERROR);return}this.protocol.setStatus(a.SUCCESS)}handleExit(){let t=this.protocol.getFlags();this.outputLimitExceeded?this.output.exitCode===0&&(this.output.exitCode=1):this.output.exitCode=t,this.protocol.setStatus(a.SUCCESS),this.running=!1}tryAppendOutput(t,e){return this.outputLimitExceeded?!1:this.maxOutputSize<=0?(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0):this.output.stdout.length+this.output.stderr.length+e.length>this.maxOutputSize?!1:(t==="stdout"?this.output.stdout+=e:this.output.stderr+=e,!0)}appendOutputLimitError(){if(this.maxOutputSize<=0)return;let t=`${this.commandName}: total output size exceeded (>${this.maxOutputSize} bytes), increase executionLimits.maxOutputSize
10
- `,e=t.length>this.maxOutputSize?t.slice(0,this.maxOutputSize):t;if(this.output.stderr.includes("total output size exceeded"))return;let o=this.output.stdout.length+this.output.stderr.length+e.length-this.maxOutputSize;if(o>0)if(this.output.stdout.length>=o)this.output.stdout=this.output.stdout.slice(0,this.output.stdout.length-o);else{let i=o-this.output.stdout.length;this.output.stdout="",i>=this.output.stderr.length?this.output.stderr="":this.output.stderr=this.output.stderr.slice(0,this.output.stderr.length-i)}this.output.stderr+=e}async handleHttpRequest(){let t=this.secureFetch;if(!t){this.protocol.setErrorCode(u.NETWORK_NOT_CONFIGURED),this.protocol.setResultFromString("Network access not configured. Enable network in Bash options."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString();try{let o=r?JSON.parse(r):{},i=this.remainingMs(),c=await this.raceDeadline(()=>t(e,{method:o.method,headers:o.headers,body:o.body,timeoutMs:i})),d=JSON.stringify({status:c.status,statusText:c.statusText,headers:c.headers,body:c.body,url:c.url});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(o){let i=m(o instanceof Error?o.message:String(o));this.protocol.setErrorCode(u.NETWORK_ERROR),this.protocol.setResultFromString(i),this.protocol.setStatus(a.ERROR)}}async handleExecCommand(){let t=this.exec;if(!t){this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString("Command execution not available in this context."),this.protocol.setStatus(a.ERROR);return}let e=this.protocol.getPath(),r=this.protocol.getDataAsString(),o=new AbortController;try{let i={cwd:this.cwd,signal:o.signal};if(r){let p=JSON.parse(r);p.stdin&&(i.stdin=p.stdin),p.args&&Array.isArray(p.args)&&(i.args=p.args.map(D=>String(D)),e=F([e]))}let c=await this.raceDeadline(()=>t(e,i)),d=JSON.stringify({stdout:c.stdout,stderr:c.stderr,exitCode:c.exitCode});this.protocol.setResultFromString(d),this.protocol.setStatus(a.SUCCESS)}catch(i){o.abort();let c=i instanceof Error?i.message:String(i);this.protocol.setErrorCode(u.IO_ERROR),this.protocol.setResultFromString(c),this.protocol.setStatus(a.ERROR)}}setErrorFromException(t){let e=t instanceof Error?t.message:String(t),r=m(e),o=u.IO_ERROR,i=e.toLowerCase();i.includes("no such file")||i.includes("not found")||i.includes("enoent")?o=u.NOT_FOUND:i.includes("is a directory")||i.includes("eisdir")?o=u.IS_DIRECTORY:i.includes("not a directory")||i.includes("enotdir")?o=u.NOT_DIRECTORY:i.includes("already exists")||i.includes("eexist")?o=u.EXISTS:(i.includes("permission")||i.includes("eperm")||i.includes("eacces"))&&(o=u.PERMISSION_DENIED),this.protocol.setErrorCode(o),this.protocol.setResultFromString(r),this.protocol.setStatus(a.ERROR)}};export{_ as a,A as b};
@@ -1,96 +0,0 @@
1
- import{a as A,b as P}from"./chunk-S4EYC6T6.js";import"./chunk-XHM67O4N.js";import"./chunk-CWQS3NFK.js";import{a as k,b as T}from"./chunk-A5O5YHGN.js";import"./chunk-IPJHKYVM.js";import{a as W}from"./chunk-OJDRYQWQ.js";import{b as C}from"./chunk-5QMZ5MUS.js";import{a as M,b as x}from"./chunk-3THT3N7L.js";import{a as v}from"./chunk-44UOCSGV.js";import{b as F}from"./chunk-74CEPOFO.js";import"./chunk-DXB73IDG.js";import{AsyncLocalStorage as U}from"node:async_hooks";import{randomBytes as I}from"node:crypto";import{fileURLToPath as J}from"node:url";import{Worker as D}from"node:worker_threads";var N=1e4,H=6e4,B=new U,_=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
2
-
3
- Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]
4
-
5
- Options:
6
- -c CODE Execute inline code
7
- -m, --module Enable ES module mode (import/export)
8
- --strip-types Strip TypeScript type annotations
9
- --version, -V Show version
10
- --help Show this help
11
-
12
- Examples:
13
- js-exec -c "console.log(1 + 2)"
14
- js-exec script.js
15
- js-exec app.ts
16
- echo 'console.log("hello")' | js-exec
17
-
18
- File Extension Auto-Detection:
19
- .js script mode (module mode if top-level await detected)
20
- .mjs ES module mode
21
- .ts, .mts ES module mode + TypeScript stripping
22
-
23
- Node.js Compatibility:
24
- Code written for Node.js largely works here. Both require and import
25
- are supported, the node: prefix works, and standard globals like process,
26
- console, and fetch are available. All I/O is synchronous.
27
-
28
- Available modules:
29
- fs, path, child_process, process, console,
30
- os, url, assert, util, events, buffer, stream,
31
- string_decoder, querystring
32
-
33
- fs (global, require('fs'), or import from 'node:fs'):
34
- readFileSync, writeFileSync, appendFileSync, copyFileSync, renameSync
35
- readdirSync, mkdirSync, rmSync, unlinkSync, rmdirSync
36
- statSync, lstatSync, existsSync, realpathSync, chmodSync
37
- symlinkSync, readlinkSync, readFileBuffer
38
- fs.promises.readFile, fs.promises.writeFile, fs.promises.access, ...
39
-
40
- path: join, resolve, dirname, basename, extname, normalize,
41
- relative, isAbsolute, parse, format, sep, delimiter
42
-
43
- child_process:
44
- execSync(cmd) throws on non-zero exit, returns stdout
45
- spawnSync(cmd, args) returns { stdout, stderr, status }
46
-
47
- process (also global): argv, cwd(), exit(), env, platform, arch,
48
- version, versions
49
-
50
- os: platform(), arch(), homedir(), tmpdir(), type(), hostname(),
51
- EOL, cpus(), endianness()
52
-
53
- url: URL, URLSearchParams, parse(), format()
54
-
55
- assert: ok(), equal(), strictEqual(), deepEqual(), throws(),
56
- doesNotThrow(), fail()
57
-
58
- util: format(), inspect(), promisify(), types, inherits()
59
-
60
- events: EventEmitter (on, once, emit, off, removeListener, ...)
61
-
62
- buffer: Buffer.from(), Buffer.alloc(), Buffer.concat(),
63
- Buffer.isBuffer(), toString(), slice(), equals()
64
-
65
- stream: Readable, Writable, Duplex, Transform, PassThrough, pipeline
66
-
67
- string_decoder: StringDecoder (write, end)
68
-
69
- querystring: parse(), stringify(), escape(), unescape()
70
-
71
- Other Globals:
72
- console log (stdout), error/warn (stderr)
73
- fetch(url, opts) HTTP; returns Promise<Response> (Web Fetch API)
74
- URL, URLSearchParams, Headers, Request, Response
75
- Buffer Buffer.from(), Buffer.alloc(), etc.
76
-
77
- Not Available:
78
- http, https, net, tls, crypto, zlib, dns, cluster, worker_threads,
79
- vm, v8, readline, and other Node.js built-in modules that require
80
- native bindings. Use fetch() for HTTP requests.
81
-
82
- Limits:
83
- Memory: 64 MB per execution
84
- Timeout: 10 s (60 s with network; configurable via maxJsTimeoutMs)
85
- Engine: QuickJS (compiled to WebAssembly)
86
- `;function z(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let r=0;r<t.length;r++){let s=t[r];if(s==="-m"||s==="--module"){e.isModule=!0;continue}if(s==="--strip-types"){e.stripTypes=!0;continue}if(s==="-c")return r+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
87
- `,exitCode:2}:(e.code=t[r+1],e.scriptArgs=t.slice(r+2),e);if(s==="--version"||s==="-V")return e.showVersion=!0,e;if(s.startsWith("-")&&s!=="-"&&s!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${s}'
88
- `,exitCode:2};if(s==="--")return r+1<t.length&&(e.scriptFile=t[r+1],e.scriptArgs=t.slice(r+2)),e;if(!s.startsWith("-"))return e.scriptFile=s,e.scriptArgs=t.slice(r+1),e}return e}var i=null,w=null,c=[],o=null,$=J(new URL("./worker.js",import.meta.url));function p(){for(;c.length>0&&c[0].canceled;)c.shift();if(o||c.length===0)return;let t=c.shift();if(!t)return;o=t,Q().postMessage(o.input)}function V(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let r=t;return typeof r.protocolToken!="string"||r.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof r.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:r.success?{success:!0}:{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}function Q(){if(w&&(T(w),w=null),i)return i;let t=C.runTrusted(()=>new D($));return i=t,t.on("message",e=>{if(i===t){if(o){let r=V(e,o.input.protocolToken);o.resolve(r),o=null}c.length>0?p():G()}}),t.on("error",e=>{if(i===t){if(o){let r=x(v(e));o.resolve({success:!1,error:r}),o=null}for(let r of c)r.resolve({success:!1,error:"Worker crashed"});c.length=0,i=null}}),t.on("exit",()=>{i===t&&(i=null,o&&(o.resolve({success:!1,error:"Worker exited unexpectedly"}),o=null),c.length>0&&p())}),t}function G(){w=k(()=>{i&&!o&&c.length===0&&(i.terminate(),i=null)},5e3)}async function K(t,e,r,s=[],n,u,a){return B.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
89
- `,exitCode:1}:X(t,e,r,s,n,u,a)}async function X(t,e,r,s=[],n,u,a){let m=A(),d=e.exec,g=d?(l,j)=>B.run(!0,()=>d(l,j)):void 0,q=new P(m,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,g),E=e.limits?.maxJsTimeoutMs??N,h=e.fetch?Math.max(E,H):E,O={protocolToken:I(16).toString("hex"),sharedBuffer:m,jsCode:t,cwd:e.cwd,env:W(e.env),args:s,scriptPath:r,bootstrapCode:n,isModule:u,stripTypes:a,timeoutMs:h},b,L=new Promise(l=>{b=l}),f={input:O,resolve:()=>{}},R=k(()=>{if(o===f){let l=i;l&&(i=null,l.terminate()),o=null,p()}else f.canceled=!0,o||p();f.resolve({success:!1,error:`Execution timeout: exceeded ${h}ms limit`})},h);f.resolve=l=>{T(R),b(l)},c.push(f),p();let[y,S]=await Promise.all([q.run(h),L.catch(l=>({success:!1,error:x(v(l))}))]);return!S.success&&S.error?{stdout:y.stdout,stderr:`${y.stderr}js-exec: ${x(S.error)}
90
- `,exitCode:y.exitCode||1}:y}var de={name:"js-exec",async execute(t,e){if(F(t))return{stdout:_,stderr:"",exitCode:0};let r=z(t);if("exitCode"in r)return r;if(r.showVersion)return{stdout:`QuickJS (quickjs-emscripten)
91
- `,stderr:"",exitCode:0};let s,n;if(r.code!==null)s=r.code,n="-c";else if(r.scriptFile!==null){let d=e.fs.resolvePath(e.cwd,r.scriptFile);if(!await e.fs.exists(d))return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': No such file or directory
92
- `,exitCode:2};try{s=await e.fs.readFile(d),n=d}catch(g){return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': ${M(g.message)}
93
- `,exitCode:2}}}else if(e.stdin.trim())s=e.stdin,n="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
94
- `,exitCode:2};let u=r.isModule,a=r.stripTypes;n&&n!=="-c"&&n!=="<stdin>"&&((n.endsWith(".mjs")||n.endsWith(".mts")||n.endsWith(".ts"))&&(u=!0),(n.endsWith(".ts")||n.endsWith(".mts"))&&(a=!0)),!u&&/\bawait\s+[\w([`]/.test(s)&&(u=!0);let m=e.jsBootstrapCode;return K(s,e,n,r.scriptArgs,m,u,a)}},fe={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
95
-
96
- ${_}`,exitCode:1}}};export{de as jsExecCommand,fe as nodeStubCommand};