@dandre3000/sandbox
v0.2.0
Published
Run code with a temporary globalThis.
Downloads
29
Maintainers
Readme
@dandre3000/sandbox
Run code with a temporary globalThis.
Install
npm i @dandre3000/sandbox
Usage
import { isMainThread, runtime } from '@dandre3000/environment'
import { createRestrictedGlobalProxy, createSandboxFunction, SandboxPort } from '@dandre3000/sandbox'
if (isMainThread) {
const sandbox = createRestrictedGlobalProxy()
sandbox.foo = 'bar'
createSandboxFunction(
() => console.log(foo, window, process, userAgent, navigator), sandbox
)() // bar undefined undefined undefined undefined
const url = new URL(import.meta.url)
const worker = runtime === 'node' ?
new (await import('node:worker_threads')).Worker(url)
: new Worker(url, { type: 'module' })
const port = new SandboxPort(worker)
port.setRemoteFunction('test', () => test)
console.log(await port.callRemoteFunction('test')) // AYO
worker.terminate()
} else {
new SandboxPort(runtime === 'node' ?
(await import('node:worker_threads')).parentPort
: globalThis
).context.test = 'AYO'
}Exports
createRestrictedGlobalProxy: () => RestrictedGlobalProxy
Create a Proxy of the globalThis that only includes properties appropriate for use as an isolated context.
createSandboxFunction: createSandboxFunction: (fn: Function, context: any) => Function
Create a new function with the same code as fn but in a new, isolated closure where global property access is intercepted by the context.
Class SandboxPort
Create and call functions inside a sandboxed globalThis through a MessagePort or Worker .
constructor (port: Port)
context: RestrictedGlobalProxy
Functions added to this port with setLocalFunction or setRemoteFunction use this object as their sandbox.
setLocalFunction (id: string, fn: Function | null): void
Create sandboxed function on the current thread or remove it if fn is null.
setRemoteFunction (id: string, fn: Function | null): Promise<void>
Create a sandboxed function through the connected port or remove it if fn is null.
callRemoteFunction (id: string): Promise<void>
Call a sandboxed function through the connected port.
