{"_id":"@tootallnate/quickjs-emscripten","name":"@tootallnate/quickjs-emscripten","dist-tags":{"latest":"0.23.0"},"versions":{"0.23.0":{"name":"@tootallnate/quickjs-emscripten","version":"0.23.0","main":"dist/index.js","sideEffects":false,"license":"MIT","keywords":["eval","quickjs","vm","interpreter","runtime","safe","emscripten","wasm"],"repository":{"type":"git","url":"git+https://github.com/justjake/quickjs-emscripten.git"},"scripts":{"tarball":"make build/quickjs-emscripten.tgz","clean":"make clean","tsc":"tsc","build":"make dist","doc":"typedoc","test":"TS_NODE_TRANSPILE_ONLY=true mocha 'ts/**/*.test.ts'","test-dist":"cd dist && TS_NODE_TRANSPILE_ONLY=true mocha --require source-map-support/register *.test.js","test-fast":"TEST_NO_ASYNC=true yarn test 'ts/**/*.test.ts'","test-all":"TEST_LEAK=1 yarn test && TEST_LEAK=1 yarn test-dist","prettier":"prettier --write .","prettier-check":"prettier --check .","update-quickjs":"git subtree pull --prefix=quickjs --squash git@github.com:bellard/quickjs.git master","smoketest-node":"yarn tarball && ./scripts/smoketest-node.sh","smoketest-cra":"yarn tarball && ./scripts/smoketest-website.sh"},"devDependencies":{"@types/emscripten":"^1.38.0","@types/fs-extra":"^9.0.13","@types/mocha":"^5.2.7","@types/node":"^13.1.4","fs-extra":"^10.0.1","markserv":"^1.17.4","mocha":"7.2.0","node-fetch-commonjs":"^3.1.1","prettier":"2.8.4","source-map-support":"^0.5.21","ts-node":"^10.9.1","typedoc":"^0.22.0","typedoc-plugin-inline-sources":"^1.0.1","typedoc-plugin-markdown":"^3.11.12","typescript":"^4.9.5"},"types":"./dist/index.d.ts","gitHead":"891a55e8df93a667e5980863f2995e8bfef54872","description":"Javascript/Typescript bindings for QuickJS, a modern Javascript interpreter, compiled to WebAssembly.","bugs":{"url":"https://github.com/justjake/quickjs-emscripten/issues"},"homepage":"https://github.com/justjake/quickjs-emscripten#readme","_id":"@tootallnate/quickjs-emscripten@0.23.0","_nodeVersion":"16.20.1","_npmVersion":"8.19.4","dist":{"integrity":"sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==","shasum":"db4ecfd499a9765ab24002c3b696d02e6d32a12c","tarball":"https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz","fileCount":70,"unpackedSize":1732565,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICaS1RkzFQpKEX1A/QCh7FGPvcrkKByF/lxn1smAso9bAiEA6NMr164orrOY8keHcGWEJblrwYTs1wGyMfCM5MwAuO0="}]},"_npmUser":{"name":"tootallnate","email":"nathan@tootallnate.net"},"directories":{},"maintainers":[{"name":"tootallnate","email":"nathan@tootallnate.net"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/quickjs-emscripten_0.23.0_1689668807300_0.47508671517826206"},"_hasShrinkwrap":false}},"time":{"created":"2023-07-18T08:26:47.197Z","0.23.0":"2023-07-18T08:26:47.468Z","modified":"2023-07-18T08:26:47.729Z"},"maintainers":[{"name":"tootallnate","email":"nathan@tootallnate.net"}],"description":"Javascript/Typescript bindings for QuickJS, a modern Javascript interpreter, compiled to WebAssembly.","homepage":"https://github.com/justjake/quickjs-emscripten#readme","keywords":["eval","quickjs","vm","interpreter","runtime","safe","emscripten","wasm"],"repository":{"type":"git","url":"git+https://github.com/justjake/quickjs-emscripten.git"},"bugs":{"url":"https://github.com/justjake/quickjs-emscripten/issues"},"license":"MIT","readme":"# quickjs-emscripten\n\nJavascript/Typescript bindings for QuickJS, a modern Javascript interpreter,\ncompiled to WebAssembly.\n\n- Safely evaluate untrusted Javascript (up to ES2020).\n- Create and manipulate values inside the QuickJS runtime ([more][values]).\n- Expose host functions to the QuickJS runtime ([more][functions]).\n- Execute synchronous code that uses asynchronous functions, with [asyncify][asyncify].\n\n[Github] | [NPM] | [API Documentation][api] | [Examples][tests]\n\n```typescript\nimport { getQuickJS } from \"quickjs-emscripten\"\n\nasync function main() {\n const QuickJS = await getQuickJS()\n const vm = QuickJS.newContext()\n\n const world = vm.newString(\"world\")\n vm.setProp(vm.global, \"NAME\", world)\n world.dispose()\n\n const result = vm.evalCode(`\"Hello \" + NAME + \"!\"`)\n if (result.error) {\n console.log(\"Execution failed:\", vm.dump(result.error))\n result.error.dispose()\n } else {\n console.log(\"Success:\", vm.dump(result.value))\n result.value.dispose()\n }\n\n vm.dispose()\n}\n\nmain()\n```\n\n[github]: https://github.com/justjake/quickjs-emscripten\n[npm]: https://www.npmjs.com/package/quickjs-emscripten\n[api]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md\n[tests]: https://github.com/justjake/quickjs-emscripten/blob/main/ts/quickjs.test.ts\n[values]: #interfacing-with-the-interpreter\n[asyncify]: #asyncify\n[functions]: #exposing-apis\n\n## Usage\n\nInstall from `npm`: `npm install --save quickjs-emscripten` or `yarn add quickjs-emscripten`.\n\nThe root entrypoint of this library is the `getQuickJS` function, which returns\na promise that resolves to a [QuickJS singleton](./doc/classes/quickjs.md) when\nthe QuickJS WASM module is ready.\n\nOnce `getQuickJS` has been awaited at least once, you also can use the `getQuickJSSync`\nfunction to directly access the singleton engine in your synchronous code.\n\n### Safely evaluate Javascript code\n\nSee [QuickJS.evalCode](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/quickjs.md#evalcode)\n\n```typescript\nimport { getQuickJS, shouldInterruptAfterDeadline } from \"quickjs-emscripten\"\n\ngetQuickJS().then((QuickJS) => {\n const result = QuickJS.evalCode(\"1 + 1\", {\n shouldInterrupt: shouldInterruptAfterDeadline(Date.now() + 1000),\n memoryLimitBytes: 1024 * 1024,\n })\n console.log(result)\n})\n```\n\n### Interfacing with the interpreter\n\nYou can use [QuickJSContext](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/QuickJSContext.md)\nto build a scripting environment by modifying globals and exposing functions\ninto the QuickJS interpreter.\n\nEach `QuickJSContext` instance has its own environment -- globals, built-in\nclasses -- and actions from one context won't leak into other contexts or\nruntimes (with one exception, see [Asyncify][asyncify]).\n\nEvery context is created inside a\n[QuickJSRuntime](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/QuickJSRuntime.md).\nA runtime represents a Javascript heap, and you can even share values between\ncontexts in the same runtime.\n\n```typescript\nconst vm = QuickJS.newContext()\nlet state = 0\n\nconst fnHandle = vm.newFunction(\"nextId\", () => {\n return vm.newNumber(++state)\n})\n\nvm.setProp(vm.global, \"nextId\", fnHandle)\nfnHandle.dispose()\n\nconst nextId = vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`))\nconsole.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n\nnextId.dispose()\nvm.dispose()\n```\n\nWhen you create a context from a top-level API like in the example above,\ninstead of by calling `runtime.newContext()`, a runtime is automatically created\nfor the lifetime of the context, and disposed of when you dispose the context.\n\n#### Runtime\n\nThe runtime has APIs for CPU and memory limits that apply to all contexts within\nthe runtime in aggregate. You can also use the runtime to configure EcmaScript\nmodule loading.\n\n```typescript\nconst runtime = QuickJS.newRuntime()\n// \"Should be enough for everyone\" -- attributed to B. Gates\nruntime.setMemoryLimit(1024 * 640)\n// Limit stack size\nruntime.setMaxStackSize(1024 * 320)\n// Interrupt computation after 1024 calls to the interrupt handler\nlet interruptCycles = 0\nruntime.setInterruptHandler(() => ++interruptCycles > 1024)\n// Toy module system that always returns the module name\n// as the default export\nruntime.setModuleLoader((moduleName) => `export default '${moduleName}'`)\nconst context = runtime.newContext()\nconst ok = context.evalCode(`\nimport fooName from './foo.js'\nglobalThis.result = fooName\n`)\ncontext.unwrapResult(ok).dispose()\n// logs \"foo.js\"\nconsole.log(context.getProp(context.global, \"result\").consume(context.dump))\ncontext.dispose()\nruntime.dispose()\n```\n\n### Memory Management\n\nMany methods in this library return handles to memory allocated inside the\nWebAssembly heap. These types cannot be garbage-collected as usual in\nJavascript. Instead, you must manually manage their memory by calling a\n`.dispose()` method to free the underlying resources. Once a handle has been\ndisposed, it cannot be used anymore. Note that in the example above, we call\n`.dispose()` on each handle once it is no longer needed.\n\nCalling `QuickJSContext.dispose()` will throw a RuntimeError if you've forgotten to\ndispose any handles associated with that VM, so it's good practice to create a\nnew VM instance for each of your tests, and to call `vm.dispose()` at the end\nof every test.\n\n```typescript\nconst vm = QuickJS.newContext()\nconst numberHandle = vm.newNumber(42)\n// Note: numberHandle not disposed, so it leaks memory.\nvm.dispose()\n// throws RuntimeError: abort(Assertion failed: list_empty(&rt->gc_obj_list), at: quickjs/quickjs.c,1963,JS_FreeRuntime)\n```\n\nHere are some strategies to reduce the toil of calling `.dispose()` on each\nhandle you create:\n\n#### Scope\n\nA\n[`Scope`](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/scope.md#class-scope)\ninstance manages a set of disposables and calls their `.dispose()`\nmethod in the reverse order in which they're added to the scope. Here's the\n\"Interfacing with the interpreter\" example re-written using `Scope`:\n\n```typescript\nScope.withScope((scope) => {\n const vm = scope.manage(QuickJS.newContext())\n let state = 0\n\n const fnHandle = scope.manage(\n vm.newFunction(\"nextId\", () => {\n return vm.newNumber(++state)\n })\n )\n\n vm.setProp(vm.global, \"nextId\", fnHandle)\n\n const nextId = scope.manage(vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)))\n console.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n\n // When the withScope block exits, it calls scope.dispose(), which in turn calls\n // the .dispose() methods of all the disposables managed by the scope.\n})\n```\n\nYou can also create `Scope` instances with `new Scope()` if you want to manage\ncalling `scope.dispose()` yourself.\n\n#### `Lifetime.consume(fn)`\n\n[`Lifetime.consume`](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/lifetime.md#consume)\nis sugar for the common pattern of using a handle and then\nimmediately disposing of it. `Lifetime.consume` takes a `map` function that\nproduces a result of any type. The `map` fuction is called with the handle,\nthen the handle is disposed, then the result is returned.\n\nHere's the \"Interfacing with interpreter\" example re-written using `.consume()`:\n\n```typescript\nconst vm = QuickJS.newContext()\nlet state = 0\n\nvm.newFunction(\"nextId\", () => {\n return vm.newNumber(++state)\n}).consume((fnHandle) => vm.setProp(vm.global, \"nextId\", fnHandle))\n\nvm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)).consume((nextId) =>\n console.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n)\n\nvm.dispose()\n```\n\nGenerally working with `Scope` leads to more straight-forward code, but\n`Lifetime.consume` can be handy sugar as part of a method call chain.\n\n### Exposing APIs\n\nTo add APIs inside the QuickJS environment, you'll need to create objects to\ndefine the shape of your API, and add properties and functions to those objects\nto allow code inside QuickJS to call code on the host.\n\nBy default, no host functionality is exposed to code running inside QuickJS.\n\n```typescript\nconst vm = QuickJS.newContext()\n// `console.log`\nconst logHandle = vm.newFunction(\"log\", (...args) => {\n const nativeArgs = args.map(vm.dump)\n console.log(\"QuickJS:\", ...nativeArgs)\n})\n// Partially implement `console` object\nconst consoleHandle = vm.newObject()\nvm.setProp(consoleHandle, \"log\", logHandle)\nvm.setProp(vm.global, \"console\", consoleHandle)\nconsoleHandle.dispose()\nlogHandle.dispose()\n\nvm.unwrapResult(vm.evalCode(`console.log(\"Hello from QuickJS!\")`)).dispose()\n```\n\n#### Promises\n\nTo expose an asynchronous function that _returns a promise_ to callers within\nQuickJS, your function can return the handle of a `QuickJSDeferredPromise`\ncreated via `context.newPromise()`.\n\nWhen you resolve a `QuickJSDeferredPromise` -- and generally whenever async\nbehavior completes for the VM -- pending listeners inside QuickJS may not\nexecute immediately. Your code needs to explicitly call\n`runtime.executePendingJobs()` to resume execution inside QuickJS. This API\ngives your code maximum control to _schedule_ when QuickJS will block the host's\nevent loop by resuming execution.\n\nTo work with QuickJS handles that contain a promise inside the environment, you\ncan convert the QuickJSHandle into a native promise using\n`context.resolvePromise()`. Take care with this API to avoid 'deadlocks' where\nthe host awaits a guest promise, but the guest cannot make progress until the\nhost calls `runtime.executePendingJobs()`. The simplest way to avoid this kind\nof deadlock is to always schedule `executePendingJobs` after any promise is\nsettled.\n\n```typescript\nconst vm = QuickJS.newContext()\nconst fakeFileSystem = new Map([[\"example.txt\", \"Example file content\"]])\n\n// Function that simulates reading data asynchronously\nconst readFileHandle = vm.newFunction(\"readFile\", (pathHandle) => {\n const path = vm.getString(pathHandle)\n const promise = vm.newPromise()\n setTimeout(() => {\n const content = fakeFileSystem.get(path)\n promise.resolve(vm.newString(content || \"\"))\n }, 100)\n // IMPORTANT: Once you resolve an async action inside QuickJS,\n // call runtime.executePendingJobs() to run any code that was\n // waiting on the promise or callback.\n promise.settled.then(vm.runtime.executePendingJobs)\n return promise.handle\n})\nreadFileHandle.consume((handle) => vm.setProp(vm.global, \"readFile\", handle))\n\n// Evaluate code that uses `readFile`, which returns a promise\nconst result = vm.evalCode(`(async () => {\n const content = await readFile('example.txt')\n return content.toUpperCase()\n})()`)\nconst promiseHandle = vm.unwrapResult(result)\n\n// Convert the promise handle into a native promise and await it.\n// If code like this deadlocks, make sure you are calling\n// runtime.executePendingJobs appropriately.\nconst resolvedResult = await vm.resolvePromise(promiseHandle)\npromiseHandle.dispose()\nconst resolvedHandle = vm.unwrapResult(resolvedResult)\nconsole.log(\"Result:\", vm.getString(resolvedHandle))\nresolvedHandle.dispose()\n```\n\n#### Asyncify\n\nSometimes, we want to create a function that's synchronous from the perspective\nof QuickJS, but prefer to implement that function _asynchronously_ in your host\ncode. The most obvious use-case is for EcmaScript module loading. The underlying\nQuickJS C library expects the module loader function to return synchronously,\nbut loading data synchronously in the browser or server is somewhere between \"a\nbad idea\" and \"impossible\". QuickJS also doesn't expose an API to \"pause\" the\nexecution of a runtime, and adding such an API is tricky due to the VM's\nimplementation.\n\nAs a work-around, we provide an alternate build of QuickJS processed by\nEmscripten/Binaryen's [ASYNCIFY](https://emscripten.org/docs/porting/asyncify.html)\ncompiler transform. Here's how Emscripten's documentation describes Asyncify:\n\n> Asyncify lets synchronous C or C++ code interact with asynchronous \\[host] JavaScript. This allows things like:\n>\n> - A synchronous call in C that yields to the event loop, which allows browser events to be handled.\n>\n> - A synchronous call in C that waits for an asynchronous operation in \\[host] JS to complete.\n>\n> Asyncify automatically transforms ... code into a form that can be paused and\n> resumed ..., so that it is asynchronous (hence the name “Asyncify”) even though\n> \\[it is written] in a normal synchronous way.\n\nThis means we can suspend an _entire WebAssembly module_ (which could contain\nmultiple runtimes and contexts) while our host Javascript loads data\nasynchronously, and then resume execution once the data load completes. This is\na very handy superpower, but it comes with a couple of major limitations:\n\n1. _An asyncified WebAssembly module can only suspend to wait for a single\n asynchronous call at a time_. You may call back into a suspended WebAssembly\n module eg. to create a QuickJS value to return a result, but the system will\n crash if this call tries to suspend again. Take a look at Emscripten's documentation\n on [reentrancy](https://emscripten.org/docs/porting/asyncify.html#reentrancy).\n\n2. _Asyncified code is bigger and runs slower_. The asyncified build of\n Quickjs-emscripten library is 1M, 2x larger than the 500K of the default\n version. There may be room for further\n [optimization](https://emscripten.org/docs/porting/asyncify.html#optimizing)\n Of our build in the future.\n\nTo use asyncify features, use the following functions:\n\n- [newAsyncRuntime][]: create a runtime inside a new WebAssembly module.\n- [newAsyncContext][]: create runtime and context together inside a new\n WebAssembly module.\n- [newQuickJSAsyncWASMModule][]: create an empty WebAssembly module.\n\n[newasyncruntime]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newasyncruntime\n[newasynccontext]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newasynccontext\n[newquickjsasyncwasmmodule]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newquickjsasyncwasmmodule\n\nThese functions are asynchronous because they always create a new underlying\nWebAssembly module so that each instance can suspend and resume independently,\nand instantiating a WebAssembly module is an async operation. This also adds\nsubstantial overhead compared to creating a runtime or context inside an\nexisting module; if you only need to wait for a single async action at a time,\nyou can create a single top-level module and create runtimes or contexts inside\nof it.\n\n##### Async module loader\n\nHere's an example of valuating a script that loads React asynchronously as an ES\nmodule. In our example, we're loading from the filesystem for reproducibility,\nbut you can use this technique to load using `fetch`.\n\n```typescript\nconst module = await newQuickJSAsyncWASMModule()\nconst runtime = module.newRuntime()\nconst path = await import(\"path\")\nconst { promises: fs } = await import(\"fs\")\n\nconst importsPath = path.join(__dirname, \"../examples/imports\") + \"/\"\n// Module loaders can return promises.\n// Execution will suspend until the promise resolves.\nruntime.setModuleLoader((moduleName) => {\n const modulePath = path.join(importsPath, moduleName)\n if (!modulePath.startsWith(importsPath)) {\n throw new Error(\"out of bounds\")\n }\n console.log(\"loading\", moduleName, \"from\", modulePath)\n return fs.readFile(modulePath, \"utf-8\")\n})\n\n// evalCodeAsync is required when execution may suspend.\nconst context = runtime.newContext()\nconst result = await context.evalCodeAsync(`\nimport * as React from 'esm.sh/react@17'\nimport * as ReactDOMServer from 'esm.sh/react-dom@17/server'\nconst e = React.createElement\nglobalThis.html = ReactDOMServer.renderToStaticMarkup(\n e('div', null, e('strong', null, 'Hello world!'))\n)\n`)\ncontext.unwrapResult(result).dispose()\nconst html = context.getProp(context.global, \"html\").consume(context.getString)\nconsole.log(html) //