diff --git a/AGENTS.md b/AGENTS.md index a0139af..eb14c02 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ their facts are verified against the CLI, so trust them over stale prose. ## Project Structure & Module Organization - Source: Next.js + Nextra docs site using TypeScript. -- Content: MDX pages under `pages/` (route = file path). Example: `pages/sdk/wasmer-js/how-to/use-filesystem.mdx`. +- Content: MDX pages under `content/` (route = file path). Example: `content/runtime/js.mdx`. - UI: React components in `components/` and `theme/src/components/`; site config in `theme.config.tsx` and `next.config.mjs`. - Styling & assets: Tailwind config in `tailwind.config.js`, global styles in `styles/`, static files in `public/`, additional images in `assets/`. @@ -50,7 +50,7 @@ their facts are verified against the CLI, so trust them over stale prose. ## Commit & Pull Request Guidelines - Commits: Write clear, scoped messages in present tense (e.g., `docs: add wasm fs how-to`). -- PRs: Include a concise description, affected pages/components, screenshots or local URLs (e.g., `http://localhost:3000/sdk/...`) when visual changes apply, and link related issues. +- PRs: Include a concise description, affected pages/components, screenshots or local URLs (e.g., `http://localhost:3000/runtime/js`) when visual changes apply, and link related issues. - CI: GitHub Actions build must pass (`.github/workflows/ci.yaml`). For deploys, main builds publish via Wasmer. ## Security & Deployment Notes diff --git a/app/layout.tsx b/app/layout.tsx index eecd17f..e4a2a97 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -19,12 +19,11 @@ export default async function RootLayout({ }: Readonly<{ children: ReactNode }>) { - const [rootPageMap, edgePageMap, registryPageMap, sdkPageMap, runtimePageMap] = + const [rootPageMap, edgePageMap, registryPageMap, runtimePageMap] = await Promise.all([ getPageMap('/'), getPageMap('/edge'), getPageMap('/registry'), - getPageMap('/sdk'), getPageMap('/runtime'), ]) @@ -37,7 +36,6 @@ export default async function RootLayout({ root: rootPageMap, edge: edgePageMap, registry: registryPageMap, - sdk: sdkPageMap, runtime: runtimePageMap, }} > diff --git a/components/DocsNavbarLinks.tsx b/components/DocsNavbarLinks.tsx index 14694a3..542366c 100644 --- a/components/DocsNavbarLinks.tsx +++ b/components/DocsNavbarLinks.tsx @@ -10,7 +10,6 @@ const sections = [ { href: '/runtime', label: 'Runtime' }, { href: '/registry', label: 'Registry' }, { href: '/edge', label: 'Edge' }, - { href: '/sdk/wasmer-js', label: 'SDKs' }, ] function XLogoIcon() { diff --git a/components/DocsShell.tsx b/components/DocsShell.tsx index 0a54693..d34bb87 100644 --- a/components/DocsShell.tsx +++ b/components/DocsShell.tsx @@ -13,7 +13,6 @@ type DocsShellProps = { root: PageMapItem[] edge: PageMapItem[] registry: PageMapItem[] - sdk: PageMapItem[] runtime: PageMapItem[] } } @@ -21,7 +20,6 @@ type DocsShellProps = { function getSection(pathname: string) { if (pathname === '/edge' || pathname.startsWith('/edge/')) return 'edge' if (pathname === '/registry' || pathname.startsWith('/registry/')) return 'registry' - if (pathname === '/sdk' || pathname.startsWith('/sdk/')) return 'sdk' if (pathname === '/runtime' || pathname.startsWith('/runtime/')) return 'runtime' return 'root' } diff --git a/content/_meta.js b/content/_meta.js index 48dff9b..5880709 100644 --- a/content/_meta.js +++ b/content/_meta.js @@ -18,10 +18,6 @@ export default { "title": "Edge", "display": "hidden" }, - "sdk": { - "title": "SDKs", - "display": "hidden" - }, "-- Developers": { "type": "separator", "title": "Developers" diff --git a/content/index.mdx b/content/index.mdx index 0a17e68..8e59a48 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -21,11 +21,11 @@ Welcome to the Wasmer Documentation! 👋 ## SDKs -Wasmer is available in multiple programming languages and operating systems in the shape of SDKs. -Using these SDKs, it's possible to embed Wasmer modules compiled from other languages into your application. -We have set up the SDKs to allow using Wasmer easily anywhere: +Embed the Wasmer Runtime directly in your application and run packages in +local, capability-based sandboxes: -* [Wasmer JavaScript SDK](/sdk/wasmer-js): run your Wasmer packages in JavaScript +* [JavaScript SDK](/runtime/js): run Wasmer packages in Node.js or a browser +* [Python SDK](/runtime/python): run Wasmer packages inside a Python application ## Social diff --git a/content/install.mdx b/content/install.mdx index d14e10c..4a7b5e9 100644 --- a/content/install.mdx +++ b/content/install.mdx @@ -1,11 +1,11 @@ # Install Wasmer -import { Callout } from '@components/nextra-theme'; -import { Tabs, Tab } from '@components/nextra-theme'; +import { Callout, Tab, Tabs } from '@components/nextra-theme'; -Wasmer allows you to run applications either **standalone** (_via the CLI_) or **embedded** in [other languages](/sdk), such as Rust, C/C++, and JavaScript. +Run Wasmer as a standalone CLI or embed the Runtime in a JavaScript or Python +application with an SDK. - + **Unix** (macOS, Linux): @@ -65,22 +65,28 @@ Wasmer allows you to run applications either **standalone** (_via the CLI_) or * - **NPM**: + **npm**: - ```bash /@wasmer/ /sdk/ copy - npm install @wasmer/sdk --save + ```bash copy + npm install @wasmer/sdk ``` - Bun: + **pnpm**: - ```bash /@wasmer/ /sdk/ copy - bun install @wasmer/sdk --save + ```bash copy + pnpm add @wasmer/sdk ``` - - Read the [Wasmer-JS SDK docs](/sdk/wasmer-js). + + Import `@wasmer/sdk/node` in Node.js or `@wasmer/sdk/browser` in a + browser. Continue with the [JavaScript SDK guide](/runtime/js). + + ```bash copy + python -m pip install wasmer-sdk + ``` -{/* `bash npm install wasmer` ```bash pip install wasmer ``` */} + Continue with the [Python SDK guide](/runtime/python). + diff --git a/content/runtime.mdx b/content/runtime.mdx index 62beff1..e5f32df 100644 --- a/content/runtime.mdx +++ b/content/runtime.mdx @@ -1,39 +1,53 @@ import { Cards, Card } from '@components/nextra-theme' import { RunIcon } from '@components/icons/ProductIcons' -# Runtime Introduction +# Wasmer Runtime -The Wasmer Runtime is the engine that allows running WebAssembly modules and Wasmer packages anywhere. +The Wasmer Runtime runs WebAssembly modules and packages from the +[Wasmer Registry](/registry) in lightweight, capability-based sandboxes. +Use it as a command-line tool or embed it directly in a JavaScript or Python +application. -Wasmer can be used as a library from any programming language, or as a standalone runtime via the [`Wasmer CLI`](/runtime/cli). +| Interface | Best for | Install | +| --- | --- | --- | +| [Wasmer CLI](/runtime/cli) | Running packages from a terminal or script | `curl https://get.wasmer.io -sSfL \| sh` | +| [JavaScript SDK](/runtime/js) | Node.js and browser applications | `npm install @wasmer/sdk` | +| [Python SDK](/runtime/python) | Python applications and AI agents | `python -m pip install wasmer-sdk` | +All three interfaces use the same Wasmer packages and WASIX runtime. The SDKs +also expose a shared sandbox model for composing packages, files, environment +variables, networking, and long-running processes inside a host application. -## đŸĨ First Steps +## First steps -To run a package, check out the [Getting Started](/runtime/get-started/) guide. +Start with one package, then choose the interface that fits your host +application. -} title="Run your first package" href="/runtime/get-started" /> + } title="Run your first package" href="/runtime/get-started" /> + } title="JavaScript SDK" href="/runtime/js" /> + } title="Python SDK" href="/runtime/python" /> ## Features - **Secure** by default. No file, network, or environment access, unless explicitly enabled. - **Fast**. Run WebAssembly at near-native speeds. -- **Pluggable**. Embeddable in multiple programming languages. +- **Embeddable**. Run sandboxes in JavaScript, Python, Rust, and other host + applications without a separate daemon. - Compliant with the latest WebAssembly proposals (SIMD, Reference Types, Threads, ...) ## Backends The Wasmer Runtime supports multiple backends, depending on your needs: -### Wasmer backends: +### Wasmer backends - **Singlepass**: A single-pass compiler for fast compilation times and low memory usage. - **Cranelift**: A fast compiler backend with a focus on compile times, and runtime performance. - **LLVM**: A compiler backend that uses LLVM for optimization and code generation. -### Integration backends: +### Integration backends - **Browser**: it allows running Wasmer fully in the browser (via `wasm-bindgen`). - **V8**: it allows running Wasmer using the WebAssembly engine inside V8 (can run in interpreter mode or with JIT) diff --git a/content/runtime/_meta.js b/content/runtime/_meta.js index c9332c7..c3351d2 100644 --- a/content/runtime/_meta.js +++ b/content/runtime/_meta.js @@ -1,5 +1,7 @@ export default { "get-started": "Getting Started", + "js": "JavaScript SDK", + "python": "Python SDK", "cli": "CLI", "features": "Features", "wasix": "WASIX", diff --git a/content/runtime/cli.mdx b/content/runtime/cli.mdx index 041ee38..17f06f0 100644 --- a/content/runtime/cli.mdx +++ b/content/runtime/cli.mdx @@ -4,6 +4,12 @@ import { Callout } from '@components/nextra-theme'; Run a WebAssembly file or Wasmer container. + + To embed the same packages and WASIX runtime in an application, use the + [JavaScript SDK](/runtime/js) or + [Python SDK](/runtime/python). + + ## Usage ### Run a Wasmer package diff --git a/content/runtime/features.mdx b/content/runtime/features.mdx index 50ecb29..9cd4359 100644 --- a/content/runtime/features.mdx +++ b/content/runtime/features.mdx @@ -4,6 +4,12 @@ import { Callout } from '@components/nextra-theme'; Wasmer is powered by [WebAssembly](https://webassembly.org). +The native CLI and Python SDK use Wasmer's native compiler backends. The +[JavaScript SDK](/runtime/js) targets the host JavaScript engine: +Node.js and browsers compile and execute WebAssembly while Wasmer supplies the +package, sandbox, filesystem, process, and WASIX layers. See the +[Python SDK guide](/runtime/python) for native embedding from Python. + Wasmer runs WebAssembly through a **backend**, and ships several depending on your needs. They fall into two groups by *how* they execute your code: * Compiler backends: Wasmer compiles your WebAssembly to native machine code itself, then runs it directly on the CPU: diff --git a/content/runtime/get-started.mdx b/content/runtime/get-started.mdx index 5029f44..c03c49e 100644 --- a/content/runtime/get-started.mdx +++ b/content/runtime/get-started.mdx @@ -1,59 +1,106 @@ -import { Steps } from "@components/nextra-theme"; -import { Callout } from "@components/nextra-theme"; -import { Tab, Tabs } from "@components/nextra-theme"; -import Install from "../../components/install.mdx"; +import { Callout, Steps, Tab, Tabs } from '@components/nextra-theme'; # Run your first package -This page will guide you through installing Wasmer, and running a package from the Wasmer Registry. - -The runtime can run any package published to the Wasmer Registry. +Wasmer packages run from the CLI or inside JavaScript and Python applications. +This guide uses the [`python/python`](https://wasmer.io/python/python) package +to calculate `1 + 1`; no system Python installation is used inside the +sandbox. - - -### Run a package +### Install Wasmer -Let's say you want to run version `3.12` of the Wasmer package [`python/python`](https://wasmer.io/python/python) and execute the `-c "print(1+1)"` argument to print a result. +Choose the interface used by your host application: - + - ```bash copy /python/ - wasmer run python/python@3.12 -- -c "print(1+1)" + On macOS or Linux: + + ```bash copy + curl https://get.wasmer.io -sSfL | sh ``` + + See [Install Wasmer](/install) for Windows and other installation methods. + ```bash copy + npm install @wasmer/sdk + ``` - ```js copy /python/ - import { init, Wasmer } from "@wasmer/sdk"; - - await init(); - let python = await Wasmer.fromRegistry("python/python@3.12"); - let instance = await python.entrypoint.run({ - args: ["-c", "print(1+1)"] - }); - let output = await instance.wait(); + Node.js and browser applications use the same package with different + entrypoints. This example uses Node.js. + + + ```bash copy + python -m pip install wasmer-sdk ``` + Published wheels support macOS and Linux on arm64 and x86_64. -{/* + + +### Run the package + + + ```bash copy + wasmer run python/python@=3.13.18 -- -c "print(1+1)" + ``` + - ```python copy - from wasmer import Wasmer + ```javascript copy filename="index.mjs" + import { Wasmer } from '@wasmer/sdk/node'; - python = Wasmer("python/python") - runner = python.entrypoint.run('-c "print(1+1)"') - print(python.stdout) + const wasmer = new Wasmer(); + const sandbox = await wasmer.sandboxes.create({ + packages: ['python/python@=3.13.18'], + }); + + const output = await sandbox + .command('python', ['-c', 'print(1+1)']) + .run(); + + console.log(output.text()); + await sandbox.close(); + await wasmer.close(); ``` + + + ```python copy filename="main.py" + import asyncio + + from wasmer_sdk import Wasmer + - */} + async def main() -> None: + async with Wasmer() as wasmer: + sandbox = await wasmer.sandboxes.create( + packages=['python/python@=3.13.18'], + ) + async with sandbox: + output = await sandbox.command( + 'python', ['-c', 'print(1+1)'] + ).run() + print(output.text()) + + + asyncio.run(main()) + ``` + +Each example prints `2`. The `@=` syntax pins the exact registry package +version so every run resolves the same artifact. + - - You can also publish your packages to the Wasmer registry, so it can be used - everywhere. [Learn how](/registry/get-started). + + A sandbox can combine multiple packages and expose files, streams, + networking, and long-running processes. Continue with the + [JavaScript SDK](/runtime/js) or + [Python SDK](/runtime/python) guide. + +You can also [publish your own package](/registry/get-started) to run it through +the CLI and every SDK. diff --git a/content/runtime/js.mdx b/content/runtime/js.mdx new file mode 100644 index 0000000..740a179 --- /dev/null +++ b/content/runtime/js.mdx @@ -0,0 +1,242 @@ +import { Callout, Tab, Tabs } from '@components/nextra-theme'; + +# JavaScript SDK + +`@wasmer/sdk` embeds Wasmer and WASIX in Node.js or a browser. It runs +packages locally through the host's WebAssembly engine; it does not contact a +remote sandbox service and Node.js does not load a native addon. + +## Install + +Node.js 20 or newer is required for the Node.js entrypoint. + + + + ```bash copy + npm install @wasmer/sdk + ``` + + + ```bash copy + pnpm add @wasmer/sdk + ``` + + + ```bash copy + yarn add @wasmer/sdk + ``` + + + +## Run a package in Node.js + +Create a client, compose a sandbox from registry packages and files, then run +a command inside it: + +```javascript copy filename="index.mjs" +import { Wasmer } from '@wasmer/sdk/node'; + +const wasmer = new Wasmer(); +const sandbox = await wasmer.sandboxes.create({ + packages: ['python/python@=3.13.18'], + files: { + 'main.py': 'print(sum(number * number for number in range(10)))', + }, +}); + +const output = await sandbox + .command('python', ['/workspace/main.py']) + .run(); + +console.log(output.text()); + +await sandbox.close(); +await wasmer.close(); +``` + +`new Wasmer()` is synchronous. Package resolution, sandbox creation, command +execution, and shutdown are asynchronous. Reuse one client for multiple +sandboxes and close long-lived clients and sandboxes when they are no longer +needed. + +`run()` captures a finite command and throws when it exits unsuccessfully. +Use `spawn()` when the process needs live stdin, stdout, stderr, termination, +or terminal resizing. + +## Compose software in one sandbox + +A sandbox can combine packages that export different commands: + +```javascript copy +const sandbox = await wasmer.sandboxes.create({ + packages: [ + 'python/python@=3.13.18', + 'wasmer/edgejs@0.2.0', + 'php/php-32', + ], +}); + +console.log( + (await sandbox.command('python', ['-c', "print('Python')"]).run()).text(), +); +console.log( + (await sandbox.command('node', ['-e', "console.log('Edge.js')"]).run()).text(), +); +console.log( + (await sandbox.command('php', ['-r', "echo 'PHP\\n';"]).run()).text(), +); +``` + +Files passed to `sandboxes.create()` are written under `/workspace`. Use +`sandbox.fs` to read, write, rename, list, and remove files while the sandbox +is alive. Use `sandbox.installPackage()` to add another package later. + +## Work with files + +Create initial files with the sandbox, then use `sandbox.fs` to exchange data +with commands while the sandbox is alive: + +```javascript copy +const sandbox = await wasmer.sandboxes.create({ + packages: ['python/python@=3.13.18'], + files: { + 'input.txt': 'hello from JavaScript', + }, +}); + +await sandbox.fs.mkdir('results', { recursive: true }); +await sandbox.fs.writeText('results/message.txt', 'hello from the sandbox'); + +const output = await sandbox + .command('python', [ + '-c', + "print(open('/workspace/input.txt').read().upper())", + ]) + .run(); + +console.log(output.text()); +console.log(await sandbox.fs.readText('results/message.txt')); +console.log(await sandbox.fs.readDir('results')); +``` + +The filesystem API also provides `readFile()`, `writeFile()`, `stat()`, +`rename()`, and `remove()`. Paths are relative to `/workspace` unless an +absolute path is supplied. + +## Stream an interactive process + +Use `spawn()` for commands that need streaming output, stdin, or terminal +resizing: + +```javascript copy +const process = await sandbox.command('python', ['-u', '-i']).spawn({ + terminal: { columns: 80, rows: 24 }, +}); + +await process.stdin.write("print('hello from Python')\n"); +await process.stdin.write('exit()\n'); +await process.stdin.close(); + +for await (const line of process.stdout.lines()) { + console.log(line); +} + +await process.wait({ check: true }); +``` + +Attaching a terminal enables piped stdin, stdout, and stderr. Connect those +streams to a terminal component such as xterm.js for a browser shell. Call +`process.resizeTerminal(columns, rows)` when the terminal size changes. + +## Networking in Node.js + +Network access is disabled unless the sandbox is given a network capability: + +```javascript copy +const sandbox = await wasmer.sandboxes.create({ + packages: ['curl/curl'], + network: { mode: 'host' }, +}); +``` + +The Node.js SDK maps WASIX TCP and DNS operations to Node's networking APIs. + +## Run in a browser + +Use the browser entrypoint: + +```javascript copy +import { Wasmer } from '@wasmer/sdk/browser'; + +const wasmer = new Wasmer(); +const sandbox = await wasmer.sandboxes.create({ + packages: ['python/python@=3.13.18'], +}); + +const output = await sandbox + .command('python', ['-c', "print('Hello from the browser')"]) + .run(); + +console.log(output.text()); +``` + +Browser execution uses Web Workers and `SharedArrayBuffer`. Serve the page with +these headers so it is [cross-origin isolated](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated): + +```http +Cross-Origin-Opener-Policy: same-origin +Cross-Origin-Embedder-Policy: require-corp +``` + +Check `window.crossOriginIsolated` before creating a sandbox. On static hosts +that cannot set response headers, a service worker such as +[`coi-serviceworker`](https://github.com/gzuidhof/coi-serviceworker) can add +cross-origin isolation, but serving the headers directly is preferred. + +Browsers cannot open TCP sockets directly. For outbound TCP and DNS, configure +a [WISP](https://github.com/MercuryWorkshop/wisp-protocol) endpoint: + +```javascript copy +const sandbox = await wasmer.sandboxes.create({ + packages: ['curl/curl'], + network: { + mode: 'wisp', + url: 'wss://proxy.example/wisp/', + }, +}); +``` + +Browser applications can expose a guest HTTP listener with +`sandbox.ports.expose(port)`. The SDK uses Wasmer's managed HTTP host by +default. + + + Package downloads are cached in `.wasmer` by default in Node.js and in + browser storage in a browser. The first run downloads the selected package; + later sandboxes can reuse it. + + +## Troubleshooting + +### `SharedArrayBuffer` is unavailable + +The browser entrypoint requires a secure, cross-origin-isolated page. Confirm +the page is served over HTTPS or localhost, both COOP and COEP headers are +present on the document response, and `window.crossOriginIsolated` is `true`. + +### Browser APIs are missing in Node.js + +Import `@wasmer/sdk/node` in Node.js. Importing the browser entrypoint under +Node.js can fail because browser-only facilities such as Web Workers are not +available there. + +### A package is slow on its first run + +The first sandbox resolves and downloads its registry packages. Later +sandboxes reuse the local `.wasmer` cache in Node.js or browser storage in a +browser. Pin package versions with `@=` when builds must resolve the same +artifact every time. + +See the +[`@wasmer/sdk` source and complete examples](https://github.com/wasmerio/wasmer-sdk/tree/main/js) +for streaming, interactive terminals, browser servers, and custom caches. diff --git a/content/runtime/python.mdx b/content/runtime/python.mdx new file mode 100644 index 0000000..a19a85b --- /dev/null +++ b/content/runtime/python.mdx @@ -0,0 +1,107 @@ +import { Callout } from '@components/nextra-theme'; + +# Python SDK + +`wasmer-sdk` embeds Wasmer and WASIX in a Python application. Sandboxes run +locally in the application process without Docker, a VM, or a remote sandbox +service. + +## Install + +```bash copy +python -m pip install wasmer-sdk +``` + +Published wheels support macOS and Linux on arm64 and x86_64. A wheel works +across supported Python 3 versions on the same platform because the native +boundary does not depend on the CPython ABI. + +## Run a package + +```python copy filename="main.py" +import asyncio + +from wasmer_sdk import Wasmer + + +async def main() -> None: + async with Wasmer() as wasmer: + sandbox = await wasmer.sandboxes.create( + packages=['python/python@=3.13.18'], + files={ + 'main.py': 'print(sum(n * n for n in range(10)))', + }, + ) + async with sandbox: + output = await sandbox.command( + 'python', ['/workspace/main.py'] + ).run() + print(output.text()) + + +asyncio.run(main()) +``` + +Constructing `Wasmer()` is synchronous. Operations that resolve packages, +create sandboxes, or run commands are asynchronous. Reuse one client for +multiple sandboxes. The async context managers close workers and runtime +resources deterministically. + +`run()` captures a finite command and raises `ProcessExitError` when it exits +unsuccessfully. Use `spawn()` for a long-running or interactive process with +live asynchronous streams. + +## Compose software in one sandbox + +The Python and JavaScript SDKs share the same package, sandbox, command, +filesystem, and process model: + +```python copy +sandbox = await wasmer.sandboxes.create( + packages=[ + 'python/python@=3.13.18', + 'wasmer/edgejs@0.2.0', + 'php/php-32', + ], +) + +python = await sandbox.command( + 'python', ['-c', "print('Python')"] +).run() +edgejs = await sandbox.command( + 'node', ['-e', "console.log('Edge.js')"] +).run() +php = await sandbox.command( + 'php', ['-r', "echo 'PHP\\n';"] +).run() + +print(python.text(), edgejs.text(), php.text(), sep='') +``` + +Files passed to `sandboxes.create()` are written under `/workspace`. Use +`sandbox.fs` to modify the filesystem while the sandbox is alive, or +`sandbox.install_package()` to add software after creation. + +## Networking + +Network access is disabled unless it is explicitly enabled: + +```python copy +sandbox = await wasmer.sandboxes.create( + packages=['curl/curl'], + network='host', +) +``` + +The native SDK gives WASIX sockets access to the host network. Only enable it +for sandboxes that need networking. + + + Registry metadata, downloaded packages, and compiled artifacts are cached in + `.wasmer` by default. Pass `cache_root='.cache/wasmer'` to `Wasmer()` to use + another location. + + +See the +[`wasmer-sdk` source and complete Python examples](https://github.com/wasmerio/wasmer-sdk/tree/main/python) +for process streams, Edge.js servers, and PostgreSQL. diff --git a/content/runtime/runners.mdx b/content/runtime/runners.mdx index d41ad24..631b8e8 100644 --- a/content/runtime/runners.mdx +++ b/content/runtime/runners.mdx @@ -6,3 +6,7 @@ The Wasmer runtime supports the following runner: - [WASIX](/runtime/wasix) (including plain WASI) [WCGI](/runtime/runners/wcgi) packages use the same packaging workflow, and run on [Wasmer Edge](/edge). + +Runner metadata belongs to the package, so the same WASI(X) command can run +through the CLI, the [JavaScript SDK](/runtime/js), or the +[Python SDK](/runtime/python). diff --git a/content/runtime/wasix.mdx b/content/runtime/wasix.mdx index 87fb64f..0b73c15 100644 --- a/content/runtime/wasix.mdx +++ b/content/runtime/wasix.mdx @@ -20,7 +20,7 @@ Wasmer. | Rust (plain WASI) | `rustup target add wasm32-wasip1`, then `cargo build --target wasm32-wasip1` | | C / C++ (WASIX) | Install `wasixcc`, run `wasixcc --download-all` once, then `wasixcc main.c -o app.wasm` | | Go | Go >= 1.21: `GOOS=wasip1 GOARCH=wasm go build -o app.wasm .` TinyGo: `tinygo build -target=wasi -o app.wasm .` | -| Python, PHP, JS | Do not compile. Run the prebuilt runtimes: `python/python`, `php/php`, `wasmer/winterjs`. Find more with `wasmer package search` | +| Python, PHP, JS | Do not compile. Run the prebuilt runtimes: `python/python`, `php/php-32`, `wasmer/edgejs`. Find more with `wasmer package search` | Go's `wasip1` port is single-threaded WASI, not WASIX. Programs that need sockets or subprocesses in Go need a different design or language. @@ -30,6 +30,10 @@ read the import namespaces: `wasi_snapshot_preview1` means WASI, `wasix_32v1` means WASIX. A "missing import" error usually means the module targets a different ABI or a newer WASIX than the runtime. +These runtime packages can be launched with `wasmer run` or composed inside a +sandbox through the [JavaScript SDK](/runtime/js) and +[Python SDK](/runtime/python). + ## Usage To use the WASIX runner, you need to specify the runner for your package in your `wasmer.toml` file: diff --git a/content/sdk.mdx b/content/sdk.mdx deleted file mode 100644 index d4d92a7..0000000 --- a/content/sdk.mdx +++ /dev/null @@ -1,8 +0,0 @@ -import { Cards, Card } from '@components/nextra-theme' -import { RunIcon } from '@components/icons/ProductIcons' - -# Introduction to Wasmer SDKs - -Wasmer currently supports the following SDKs: - -- [Wasmer JavaScript SDK](/sdk/wasmer-js) diff --git a/content/sdk/wasmer-js.mdx b/content/sdk/wasmer-js.mdx deleted file mode 100644 index dfa99cd..0000000 --- a/content/sdk/wasmer-js.mdx +++ /dev/null @@ -1,96 +0,0 @@ -import { Cards, Card } from '@components/nextra-theme'; -import { Tabs, Tab } from '@components/nextra-theme'; -import GitHubLogo from "@components/GitHubLogo.tsx"; - -# Introduction - -The `@wasmer/sdk` package is Wasmer's SDK for JavaScript. - -Some functionality supported by `@wasmer/sdk`: - -- Executing WebAssembly modules compiled to [WASIX][wasix] -- Includes **full** WASI support (filesystem access, environment variables, - command-line arguments, etc.) -- Running packages from [the Wasmer registry](/registry) -- Mounting directories into a WASIX instance and communicating with it while the - instance is running -- Running multi-threaded WASIX programs -- Spawning sub-processes using commands from the same package, side-loaded - packages (`uses`), or arbitrary packages from the Wasmer registry using the - virtual `wasmer run` command - -## Quickstart - -First, add the [`@wasmer/sdk`][wasmer-sdk] to your project. - - - - ```sh copy - npm install -S @wasmer/sdk - ``` - - - ```sh copy - yarn add @wasmer/sdk - ``` - - - ```sh copy - pnpm add @wasmer/sdk - ``` - - - -We'll be running version `3.12` of the `python/python` - -```ts copy showLineNumbers filename="index.ts" -import { init, Wasmer } from "@wasmer/sdk"; - -await init(); - -const pkg = await Wasmer.fromRegistry("python/python@3.12"); -const instance = await pkg.entrypoint.run({ - args: ["-c", "print('Hello, World!')"], -}); - -const { code, stdout } = await instance.wait(); -console.log(`Python exited with ${code}: ${stdout}`); -``` - -Breaking this down line-by-line... - -Line 1 - imports the `Wasmer` class and `init()` function from the `@wasmer/sdk` -package. - -Line 3 - here, the `init()` function is called and awaited. This function must -be called once before using any functionality from `@wasmer/sdk` It sets up the -necessary environment for running WebAssembly modules and instantiates the -WebAssembly runtime. - -Line 5 - uses `Wasmer.fromRegistry()` to fetch the `python/python@3.12` package -from the Wasmer registry and load it into memory, alongside any dependencies it -may have. - -Line 6 - runs the `python/python@3.12` package's entrypoint (the `python` -command) with the arguments `-c "print('Hello, World!")` and gets an `Instance` -which can be used to communicate with the running process. - -Line 10 - waits until the python interpreter has exited, then extracts the -`code` and `stdout` values from the output so they can be printed to the console -on line 11. - -## What Next? - - - - } - title="wasmerio/wasmer-js" - href="https://github.com/wasmerio/wasmer-js" - target="_blank" - /> - - - -[wasmer-sdk]: https://www.npmjs.com/package/@wasmer/sdk -[wasix]: https://wasix.org/ diff --git a/content/sdk/wasmer-js/_meta.js b/content/sdk/wasmer-js/_meta.js deleted file mode 100644 index eb3dc09..0000000 --- a/content/sdk/wasmer-js/_meta.js +++ /dev/null @@ -1,9 +0,0 @@ -export default { - "tutorials": "Tutorials", - "how-to": "How-To Guides", - "explainers": "Explainers", - "api-docs": { - "title": "API Docs ↗", - "href": "https://wasmerio.github.io/wasmer-js" - } -} diff --git a/content/sdk/wasmer-js/explainers/troubleshooting.mdx b/content/sdk/wasmer-js/explainers/troubleshooting.mdx deleted file mode 100644 index 02d3038..0000000 --- a/content/sdk/wasmer-js/explainers/troubleshooting.mdx +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: Troubleshooting Common Problems ---- - -import { Callout, Steps } from '@components/nextra-theme'; - -# Troubleshooting Common Problems - -This page contains several common problems that may be encountered while using -the `@wasmer/sdk` package. - -## `SharedArrayBuffer` and Cross-Origin Isolation - -If you encounter the following warning in your console while using the -`@wasmer/sdk` package, it indicates an issue with Cross-Origin Isolation: - -``` -WARN wasmer_js::tasks::scheduler: An error occurred while handling a message - error=Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer - requires self.crossOriginIsolated. -``` - -### Root Cause - -This issue arises due to security measures implemented in browsers following the -Spectre and Meltdown vulnerabilities. These measures restrict the sharing of -`SharedArrayBuffer` objects with Web Workers unless the execution context is -deemed secure. - -The `@wasmer/sdk` uses a threadpool built on Web Workers and requires sharing -the same `SharedArrayBuffer` across multiple workers to enable WASIX threads to -access the same address space. This requirement is crucial even for running -single-threaded WASIX programs because the SDK internals rely on -`SharedArrayBuffer` for communication with Web Workers. - -### Solution - -To resolve this issue, your application must run in a secure context with -Cross-Origin Isolation. This is achieved by setting specific HTTP response -headers: - -1. **Set 'Cross-Origin-Opener-Policy' to 'same-origin'**: This header ensures - that your document does not share a browsing context group with cross-origin - documents. -2. **Set 'Cross-Origin-Embedder-Policy' to 'require-corp'**: This header - requires all resources to be loaded with explicit CORS policies, enabling a - secure environment for `SharedArrayBuffer`. - -After setting these headers, reload your application and verify if the issue is -resolved. - -If you are deploying your app to a server that doesn't allow setting the COOP -and COEP headers directly (e.g. GitHub Pages) you may be able to use -`coi-serviceworker` as a workaround. Check out [*Patching COOP/COEP headers for -GitHub Pages Deployment*](/sdk/wasmer-js/how-to/coop-coep-headers) for more. - -## Instantiation Failed Due to Memory Import Mismatch - -If you encounter an error message similar to the one below when running -WebAssembly modules with the `@wasmer/sdk`, it indicates an issue with memory -imports: - -``` -ERROR wasmer_wasix::state::env: Instantiation failed - pid=1 - error=RuntimeError: js: WebAssembly.Instance(): - Import #54 module="env" function="memory": - memory import has 1 page which is smaller than the declared initial of 179 -``` - -This error typically appears when attempting to run a package like `ffmpeg` in -the following manner: - -```typescript -import { init, runWasix, Wasmer } from "@wasmer/sdk"; - -await init(); - -const pkg = await Wasmer.fromRegistry("wasmer/ffmpeg@1.0.5"); -const ffmpeg = pkg.commands["ffmpeg"].binary(); -const module = await WebAssembly.compile(ffmpeg); - -let instance = await runWasix(module, { - program: "ffmpeg", - args: ["-i", "input.mp4", "-vf", `"transpose=2"`, "output.mp4"], -}); -let result = await instance.wait(); -``` - -### Root Cause - -The issue stems from how memory is allocated for the WebAssembly module. When -using `WebAssembly.compile()` and `runWasix()` directly, the browser doesn't provide -detailed information about the memory requirements of the module, such as the -number of pages needed. - -Wasmer has no way of knowing how much memory the WebAssembly module is importing -(the `env.memory` import), so [it guesses][guesses] a minimum of 1 page and -hopes for the best. - -Most of the time this works out fine, but some WebAssembly modules (like -`ffmpeg`) are statically defined to require significantly more (in this case, at -least 179 pages). - -### Solution - -To work around this, Wasmer has [a `wasm-types-polyfill` -feature][wasm-types-polyfill], which parses the original `*.wasm` file to -determine the correct amount of memory required. To utilize this workaround, you -should pass the original `*.wasm` file's contents as a `Uint8Array` to the -`runWasix()` function. - -```typescript /ffmpeg,/ -import { init, runWasix, Wasmer } from "@wasmer/sdk"; - -await init(); - -const pkg = await Wasmer.fromRegistry("wasmer/ffmpeg@1.0.5"); -const ffmpeg = pkg.commands["ffmpeg"].binary(); - -let instance = await runWasix(ffmpeg, { - program: "ffmpeg", - args: ["-i", "input.mp4", "-vf", `"transpose=2"`, "output.mp4"], -}); -let result = await instance.wait(); -``` - -A more straightforward and effective approach is to use the package's -`entrypoint.run()` method, which automatically handles memory allocation -correctly. - -Here is the recommended way to run a package's command: - -```typescript -const pkg = await Wasmer.fromRegistry("wasmer/ffmpeg@1.0.5"); -const instance = await pkg.entrypoint.run({ args: [...] }); -const output = await instance.wait(); -``` - -Using this approach ensures that the necessary memory is allocated for the -WebAssembly module, thereby avoiding the instantiation error. - -## Undefined `__wbindgen_*` Reference - -When working with the `@wasmer/sdk` package, you might encounter the following -JavaScript error: - -``` -Uncaught TypeError: Cannot read properties of undefined (reading '__wbindgen_add_to_stack_pointer') -``` - -This error typically occurs when trying to access `@wasmer/sdk` functionalities -without properly initializing the SDK. - -### Root Cause - -The root cause of this issue is the premature usage of the `@wasmer/sdk` -package's functions or methods before calling the `init()` function. - -The `init()` function is crucial as it loads the WebAssembly code that -constitutes the core logic of the `@wasmer/sdk` and initializes internal states -necessary for the package, including those set up by -[`wasm-bindgen`][wasm-bindgen]. - -### Solution - -To resolve this issue, ensure that `init()` is called and awaited at the -beginning of your script or module where you intend to use the `@wasmer/sdk`. - -This setup should be done before any other interaction with the SDK's -functionalities. - -```typescript -import { init, Wasmer } from "@wasmer/sdk"; - -async function main() { - // Ensure to await the initialization before using any SDK functionality - await init(); - - // After initialization, you can safely use the SDK's features - const pkg = await Wasmer.fromRegistry("some-package"); - // ... rest of your code -} - -main(); -``` - -## Unable to Determine Hardware Concurrency - -When attempting to use the `@wasmer/sdk` package, you might encounter the -following error: - -``` -Error: Unable to determine the hardware concurrency - at A.wbg.__wbg_new_ab87fd305ed9004b (/path/to/node_modules/@wasmer/sdk/dist/Library.cjs:11:44038) - ... [additional stack trace] ... - detailedMessage: 'Unable to determine the hardware concurrency', - causes: [] -``` - -This error typically arises when executing the browser build of `@wasmer/sdk` -within a Node.js environment. - -### Root Cause - -The default `@wasmer/sdk` entry point targets browsers and relies on -browser-specific features, such as `navigator.hardwareConcurrency`, which -Node.js does not provide. - -### Solution - -Node.js is supported through the dedicated `@wasmer/sdk/node` entry point. -Import the SDK from there when running under Node.js: - -```typescript -import { init, runWasix } from "@wasmer/sdk/node"; -``` - -## ReferenceError: `document is not defined` - -When making a production build of your app, you might encounter an issue where -worker threads fail to start up due to a `ReferenceError` exception. - -``` -Uncaught (in promise) ReferenceError: document is not defined - at index-bnmRepzq.js:1:21 - at index-bnmRepzq.js:1:708 -``` - -### Root Cause - -This issue arises because Web Workers do not have access to the DOM, and any -attempt by the worker threads to access DOM elements will result in a crash. - -Something to be aware of is that each Web Worker in the threadpool will import -`@wasmer/sdk` on startup to bring in the rest of its business logic. - -In production mode, a bundle often includes all dependencies, causing the -`@wasmer/sdk` import to also execute top-level code from your dependencies. Some -dependencies, like `xterm.js`, will [interact with the DOM][create-element] and -inadvertently crash the worker. - -### Solution - -To resolve this issue, `@wasmer/sdk` should be dynamically imported, ensuring -that the bundler puts it in a separate chunk from `xterm.js`. This approach -prevents the worker from executing the DOM-related code in `xterm.js` and allows -it to start up successfully. - -Here's how you can implement the fix: - - - -### Modify your import statement - -Change the static import of `@wasmer/sdk` to a dynamic one. This tells the -bundler to separate it into its own chunk, avoiding the unintentional execution -of DOM-related code. - -```typescript -// Before -import { Wasmer, init, initializeLogger, Instance } from "@wasmer/sdk/wasm-inlined"; - -// After -const { Wasmer, init, initializeLogger } = await import("@wasmer/sdk/wasm-inlined"); -``` - -### Update your `vite.config.js` - -Ensure your Vite configuration doesn't add its own code top-level which might -trigger a similar error. - -```js filename="vite.config.js" copy -build: { - modulePreload: { - polyfill: false, - }, -}, -``` - -### Rebuild and redeploy - -After making these changes, rebuild your app in production mode and redeploy it. - - - -For a real-world example of this, check out the diff for -[`wasmerio/wasmer-js#374`][pr-374] on GitHub. - - -[create-element]: https://github.com/xtermjs/xterm.js/blob/b3737d6ff0821b08ee791c6d261e35a3cf5cd317/src/common/Color.ts#L117 -[guesses]: https://github.com/wasmerio/wasmer/blob/e6438738d884d6fb4297ca2af90ab04459ddbbfb/lib/api/src/js/module.rs#L323-L328 -[pr-374]: https://github.com/wasmerio/wasmer-js/pull/374 -[wasm-bindgen]: https://github.com/rustwasm/wasm-bindgen -[wasm-types-polyfill]: https://github.com/wasmerio/wasmer/blob/e6438738d884d6fb4297ca2af90ab04459ddbbfb/lib/api/src/js/module.rs#L91-L110 diff --git a/content/sdk/wasmer-js/how-to/_meta.js b/content/sdk/wasmer-js/how-to/_meta.js deleted file mode 100644 index 5e47ccc..0000000 --- a/content/sdk/wasmer-js/how-to/_meta.js +++ /dev/null @@ -1,4 +0,0 @@ -export default { - "coop-coep-headers": "COOP & COEP Headers", - "use-filesystem": "Interacting with the Filesystem" -} diff --git a/content/sdk/wasmer-js/how-to/coop-coep-headers.mdx b/content/sdk/wasmer-js/how-to/coop-coep-headers.mdx deleted file mode 100644 index efa4bd6..0000000 --- a/content/sdk/wasmer-js/how-to/coop-coep-headers.mdx +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Patching COOP & COEP headers for GitHub Pages Deployment ---- - -# Patching COOP/COEP Headers for GitHub Pages Deployment - -## Introduction - -Deploying web applications on GitHub Pages that require Cross-Origin Isolation -can be challenging due to lack of control over HTTP headers. This guide -demonstrates using [`coi-serviceworker`][coi-gh] to patch -[`Cross-Origin-Opener-Policy`][coop] (COOP) and -[`Cross-Origin-Embedder-Policy`][coep] (COEP) headers, enabling features like -`SharedArrayBuffer`. - -## Step 1: Prepare coi-serviceworker - -1. **Download**: Obtain `coi-serviceworker.js` from its [GitHub - repository][coi-gh] or via npm (`npm i --save coi-serviceworker`). -2. **Place File**: Ensure `coi-serviceworker.js` is located next to your - project's index file or in a parent directory. - -## Step 2: Integrate with HTML - -- **Add Script Tag**: In your HTML file, include: - ```html - - ``` -- **First Load Behavior**: This script reloads the page on the first user visit, - registering a service worker that emulates COOP and COEP headers. - -## Step 3: Customization (Optional) - -- **Customize Behavior**: You can define a `window.coi` object to customize the - service worker's behavior. Options include `shouldRegister`, `shouldDeregister`, - `coepCredentialless`, `doReload`, and `quiet`. Check out the project's README - for more. - -## Step 4: Deploy to GitHub Pages - -- **Commit and Push**: Upload your changes to GitHub and enable GitHub Pages in - your repository settings. -- **Test**: Verify that your application works correctly on GitHub Pages with - the required cross-origin isolation. - -## Notes - -- **HTTPS Requirement**: Your page must be served over HTTPS or localhost. -- **Separate File**: `coi-serviceworker.js` must not be bundled with your app - and should be served from your origin. - - -[coi-gh]: https://github.com/kairi003/coi-serviceworker/ -[coop]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy -[coep]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy diff --git a/content/sdk/wasmer-js/how-to/use-filesystem.mdx b/content/sdk/wasmer-js/how-to/use-filesystem.mdx deleted file mode 100644 index 253b69f..0000000 --- a/content/sdk/wasmer-js/how-to/use-filesystem.mdx +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: Interacting with the Filesystem ---- - -import { Callout } from '@components/nextra-theme'; - -# Interacting with the Filesystem - - -The `@wasmer/sdk` package provides users with the ability to mount directories -inside a running WASIX instance. This allows both the WASIX instance and a -JavaScript user to communicate via a shared folder. - -Let's say you're using the FFmpeg WebAssembly module to convert a video file -from one format to another. You will need to store your input file somewhere so -that the WASIX program can use it. This is where a shared `Directory` comes in. -You'll store your input file in the shared directory, and then the WASIX program -will be able to read it and process it. When the processing is done, the output -file can be written back to the shared directory so the JavaScript host can -access it. - -## Instantiating a `Directory` - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -``` - -The `Directory` class is used to create a directory that can be mounted inside a -WASIX instance's file system. You can create as many `Directory` instances as -you want. - -## Adding Files to a `Directory` - -The `writeFile()` method creates a new file in the specified directory, setting -its content to the provided data. The first argument is the path of the file, -and the second argument is the content of the file. - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -await dir.writeFile("/file.txt", "Hello, World!"); -``` - - -The content of the file may be a `string` or `Uint8Array`. - - -## Creating Sub-Directories - -The `createDir` method is used to create a directory in the virtual file system. -The argument is the path of the directory. - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -await dir.createDir("/pictures"); -``` - -Now you can place files in the directory you just created like this: - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -// reading an image file as a blob and converting it to an Uint8Array -const response = await fetch("https://example.com/image.png"); -const blob = await response.blob(); -const image = await blob.arrayBuffer(); - -const dir = new Directory(); -await dir.createDir("/pictures"); -await dir.writeFile("/pictures/image.png", new Uint8Array(image)); -``` - -## Reading Files from a `Directory` - -There are two ways to read files from a directory. - -### 1. The `readFile` Method - -The `readFile()` method will read the file's bytes back as a `Uint8Array`. - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -const bytes = await dir.readFile("/file.bin"); -``` - -### 2. The `readTextFile` Method - -The `readTextFile()` method will read a file from the `Directory` and parse it as -a UTF-8 string. The argument is the path of the file. - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -const text = await dir.readTextFile("/output.txt"); -``` - -## Listing a Directory's Contents - -The `readDir()` method is analogous to the `ls` command in Linux. The argument -is the path of the directory. - -```typescript copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -await dir.createDir("/mydir"); -await dir.writeFile("/mydir/file.txt", new Uint8Array()); -await dir.createDir("/mydir/pictures"); -await dir.writeFile("/mydir/pictures/image.png", new Uint8Array()); -await dir.createDir("/mydir/videos"); -await dir.writeFile("/mydir/videos/video.mp4", new Uint8Array()); - -const entries = await dir.readDir("/mydir"); -console.log(entries); -``` - -The output of the above code will be: - -```json -[ - { - "name": "file.txt", - "type": "file" - }, - { - "name": "pictures", - "type": "directory" - }, - { - "name": "videos", - "type": "directory" - } -] -``` - -## Mounting a Directory - -The primary way to use `Directory` is by mounting it in a Wasmer package or -WASIX instance. - -Both `Command.run()` and `runWasix()` accept a `mount` option which accepts -a mapping from paths to the `Directory` that should be mounted to that path. - -For example, this is how you can mount a `Directory` to `/app` and use the -`cat` command from `sharrattj/coreutils` to print its contents. - -```typescript -import { Wasmer, Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -await dir.writeFile("/file.txt", "Hello, World!"); - -const pkg = await Wasmer.fromRegistry("sharrattj/coreutils"); -const cat = pkg.commands["cat"]; -const instance = await cat.run({ - args: ["/app/file.txt"], - mount: { "/app": dir }, -}); -let output = await instance.wait(); - -console.log(output.stdout); // Hello, World! -``` - -The same can also be done for a WebAssembly module instantiated from the user -instead of the registry. - -```typescript -import { runWasix, Directory } from "@wasmer/sdk"; - -const python = await WebAssembly.compile(fs.readFileSync("./python.wasm")); - -const instance = await runWasix(python, { - program: "python", - args: ["/app/main.py"], - mount: { - "/app": { - "main.py": "print('Hello, World!')", - }, - }, -}); -``` - -## `DirectoryInit` Shorthand - -As a shortcut for initializing a `Directory` when all contents are known -up-front, you may provide the `new Directory()` constructor with a mapping from -file paths to their contents. The TypeScript type definitions use the -`DirectoryInit` type alias to represent this mapping. - -```ts copy -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory({ - "/file.txt": "Hello, World!", - "/path/to/nested/file.bin": new Uint8Array(), -}); -``` - - -As well as a `Directory` instance, both `Command.run()` and `runWasix()` accept -the `DirectoryInit` shorthand when specifying mounts. - -This is useful when you don't need to hang on to the `Directory` handle or -access the `Directory` while the WASIX instance is running. - - -## Removing Files and Directories from a `Directory` - -The `removeFile` method is used to remove a file from the `Directory`. The -argument is the path of the file. - -The `removeDir` method is used to remove a directory from the `Directory`. The -argument is the path of the directory. - -```typescript -import { Directory } from "@wasmer/sdk"; - -const dir = new Directory(); -await dir.createDir("/mydir"); -await dir.writeFile("/mydir/file.txt", new Uint8Array()); - -await dir.removeFile("/mydir/file.txt"); -await dir.removeDir("/mydir"); -``` - - -The `removeDir` method will only remove empty directories. If you want to -remove a directory that has files in it, then you'll have to remove the files -first. Its behavior is analogous to the `rmdir` command in Linux. - - -## Kitchen Sink - -Here is a comprehensive example of the `Directory` API. - -It includes: - -- Creating an empty `Directory` -- Mounting directories inside the newly spawned `python` instance -- Using the `DirectoryInit` shorthand to simplify passing in the `/src/main.py` -- Reading back the generated `/out/version.txt` - -```typescript copy -import { init, Directory, Wasmer } from "@wasmer/sdk"; - -// Initialize the Wasmer SDK -await init(); - -// Download the Python package -const python = await Wasmer.fromRegistry("python/python"); - -// The script to be executed -const script = ` -import sys - -with open("/out/version.txt", "w") as f: - f.write(sys.version) -`; -// A shared directory where the output will be written -const out = new Directory(); - -// Running the Python script -const instance = await python.entrypoint!.run({ - args: ["/src/main.py"], - mount: { - "/out": out, - "/src": { - "main.py": script, - } - }, -}); -const output = await instance.wait(); - -if (!output.ok) { - throw new Error(`Python failed with exit code ${output.code}: ${output.stderr}`); -} - -// Read the version string back -const pythonVersion = await out.readTextFile("/version.txt"); -console.log(pythonVersion) // 3.11.6 (main, Oct 2 2023, 13:45:54) [Clang 15.0.0 (clang-1500.0.40.1)] -``` - diff --git a/content/sdk/wasmer-js/tutorials/_meta.js b/content/sdk/wasmer-js/tutorials/_meta.js deleted file mode 100644 index 927e98d..0000000 --- a/content/sdk/wasmer-js/tutorials/_meta.js +++ /dev/null @@ -1,5 +0,0 @@ -export default { - "run": "Building a Web-Based Markdown Editor with WASIX and WebAssembly", - "package": "Migrating the Editor to a Wasmer Package", - "xterm-js": "Creating an Interactive Terminal with XTerm.js" -} diff --git a/content/sdk/wasmer-js/tutorials/package.mdx b/content/sdk/wasmer-js/tutorials/package.mdx deleted file mode 100644 index 43902ea..0000000 --- a/content/sdk/wasmer-js/tutorials/package.mdx +++ /dev/null @@ -1,231 +0,0 @@ -import { Card, Callout, Steps, FileTree } from '@components/nextra-theme'; -import Install from "@components/install.mdx"; -import GitHubLogo from "@components/GitHubLogo"; -import ImageLoader from "@components/ImageLoader"; -import previewUrl from "@assets/javascript-sdk/markdown-editor-preview.png"; - -# Migrating the Editor to a Wasmer Package - -In [the previous tutorial][run], we created a basic Markdown editor by wiring a -` - - - - - -``` - -Here's some CSS for `style.css`: - -```css filename="style.css" copy -body { - font-family: Arial, sans-serif; - margin: 0; - padding: 0; - display: flex; - justify-content: center; - align-items: center; - height: 100vh; - background-color: #f4f4f4; -} - -.editor-container { - display: grid; - grid-template-columns: repeat(2, 1fr); - gap: 20px; - width: 80%; - max-width: 1200px; - margin: auto; - box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); - padding: 20px; - background: white; - border-radius: 8px; -} - -#markdown-input, #html-output { - border: 1px solid #ddd; - padding: 10px; - height: 400px; - overflow: auto; -} - -#markdown-input { - resize: none; -} - -#html-output { - background-color: #fff; - width: 100%; - border: none; -} -``` - -### Creating a Markdown Renderer in Rust - -To render the Markdown to HTML, we'll use a powerful crate from the Rust -ecosystem called [`pulldown-cmark`][pulldown-cmark]. - -First, create a new Rust project: - -```sh -$ cargo new --bin markdown-renderer -$ cd markdown-renderer -$ cargo add pulldown-cmark -``` - -And add the following code to `src/main.rs`: - -```rs filename="markdown-renderer/src/main.rs" copy -use pulldown_cmark::{Options, Parser}; -use std::io::Read; - -fn main() -> std::io::Result<()> { - let mut markdown_input = String::new(); - std::io::stdin().read_to_string(&mut markdown_input)?; - let parser = Parser::new_ext(&markdown_input, Options::all()); - - pulldown_cmark::html::write_html(std::io::stdout(), parser)?; - Ok(()) -} -``` - -This program will read its STDIN into `markdown_input`, interpreting it as a -UTF-8 string. The `markdown_input` is then parsed by the parser and rendered to -STDOUT with `pulldown_cmark::html::write_html()`. - -### Compile the Markdown Renderer to WebAssembly - -The next step is to compile this Rust program to WebAssembly. This will give us -an executable that can be run anywhere Wasmer runs, although for our use case we -are mostly concerned about running it in the browser. - - -If you haven't already, you may need to [install Rust][rust] and use `rustup` to -add the `wasm32-wasip1` target: - -```sh copy -rustup target add wasm32-wasip1 -``` - - -```sh copy -cargo build --release --target=wasm32-wasip1 -``` - -This should create a `markdown-renderer.wasm` file under `target/`: - -```sh -$ file target/wasm32-wasip1/release/*.wasm -target/wasm32-wasip1/release/markdown-renderer.wasm: WebAssembly (wasm) binary module version 0x1 (MVP) -``` - -### TypeScript Setup & Initialization - -Now we've got a `*.wasm` binary, let's start implementing the app's logic. - -The first thing we need to do is initialize `@wasmer/sdk` and load our -`markdown-renderer.wasm` module. - -```ts filename="index.ts" copy -import { init, runWasix } from "@wasmer/sdk"; -import markdownRendererUrl from "./markdown-renderer/target/wasm32-wasip1/release/markdown-renderer.wasm?url"; - -async function initialize() { - await init(); - return WebAssembly.compileStreaming(fetch(markdownRendererUrl)); -} -``` - - -This uses `vite`'s [explicit URL imports][explicit-url-imports] functionality to -get a URL that will load our -`./markdown-renderer/target/wasm32-wasip1/release/markdown-renderer.wasm` file. - -If you aren't using `vite`, you will need to explicitly copy -`markdown-renderer.wasm` to some sort of `public/` directory and make sure it -is distributed with the rest of your app's files. - - -### Debounce Function - -Create a utility function that we can use to debounce render calls. This will -help avoid flashes and jank as the `