### Install npm Packages Source: https://almostnode.dev/docs Fetch and install packages from the npm registry at runtime. ```javascript import { createContainer } from 'almostnode'; const { vfs, npm, runtime } = createContainer(); // Install Express from npm await npm.install('express'); vfs.writeFileSync('/app.js', ` const express = require('express'); const app = express(); app.get('/', (req, res) => { res.json({ message: 'Express in the browser!' }); }); app.listen(3000); `); runtime.runFile('/app.js'); ``` -------------------------------- ### Install and execute packages Source: https://almostnode.dev/docs/core-concepts.html Demonstrates installing packages, writing files to the virtual filesystem, and executing them with the runtime. ```javascript import { createContainer } from 'almostnode'; const { vfs, npm, runtime } = createContainer(); // Install lodash from npm await npm.install('lodash'); // Use it in your code vfs.writeFileSync('/app.js', ` const _ = require('lodash'); const data = [1, [2, [3, [4]]]]; console.log(_.flattenDeep(data)); // [1, 2, 3, 4] console.log(_.chunk([1,2,3,4,5,6], 2)); // [[1,2],[3,4],[5,6]] `); runtime.runFile('/app.js'); // Install a specific version await npm.install('dayjs@1.11.10'); // Scoped packages work too await npm.install('@hono/node-server'); ``` -------------------------------- ### Manual Sandbox HTML Page Setup Source: https://almostnode.dev/docs/security.html This script sets up the sandbox HTML page for manual setup on any platform. It handles initialization and execution messages from the parent application. ```html ``` -------------------------------- ### Track npm installation progress Source: https://almostnode.dev/docs/core-concepts.html Use the onProgress callback to monitor the installation status of a package and optionally save it to package.json. ```javascript // Track installation progress await npm.install('express', { onProgress: (msg) => console.log(msg), save: true, // Add to package.json dependencies }); ``` -------------------------------- ### Install almostnode Source: https://almostnode.dev/docs Use npm to add the library to your project. ```bash npm install almostnode ``` -------------------------------- ### Start Next.js Dev Server Source: https://almostnode.dev/docs/tutorial-editor.html Configures the dev server, initializes the Service Worker bridge, and registers the server to enable HMR. ```javascript import { NextDevServer } from 'almostnode/next'; import { getServerBridge } from 'almostnode'; // 1. Create the dev server const devServer = new NextDevServer(vfs, { port: 3000, root: '/' }); // 2. Initialize the Service Worker bridge const bridge = getServerBridge(); await bridge.initServiceWorker(); // 3. Register the server on a port bridge.registerServer(devServer, 3000); // 4. Start the server (enables file watching for HMR) devServer.start(); // 5. Get the URL to load in the iframe const serverUrl = bridge.getServerUrl(3000); // → "http://localhost:5173/__virtual__/3000" ``` -------------------------------- ### Initialize and Run Next.js Dev Server with AlmostNode Source: https://almostnode.dev/docs/tutorial-editor.html This script sets up a virtual file system, loads project files, and starts a Next.js development server. It configures the preview iframe to receive HMR updates. Ensure the HTML includes elements with IDs 'editor', 'preview-frame', and 'start-btn'. ```javascript ``` -------------------------------- ### Setup Vite Dev Server Source: https://almostnode.dev/docs/vite-guide.html Initialize the Vite dev server and register it with the ServerBridge. Ensure the service worker is initialized before registering the server. ```typescript import { VirtualFS, getServerBridge } from 'almostnode'; import { ViteDevServer } from 'almostnode/vite'; const vfs = new VirtualFS(); const server = new ViteDevServer(vfs); const bridge = getServerBridge(); await bridge.initServiceWorker(); bridge.registerServer(server, 5173); ``` -------------------------------- ### PackageManager Source: https://almostnode.dev/docs/api-reference.html Manages installation of npm packages into the virtual filesystem. ```APIDOC ## PackageManager ### Description Installs npm packages into the virtual filesystem. Fetches from the npm registry, resolves dependencies, and extracts tarballs. ### Methods - **install** (packageSpec: string, options?: InstallOptions) - Install a package. - **installFromPackageJson** (options?: InstallOptions) - Install all dependencies from package.json. - **list** () - Get installed packages and versions. ``` -------------------------------- ### Install npm Packages Source: https://almostnode.dev/docs/vite-guide.html Install npm packages like 'react' and 'react-dom' using the PackageManager. These packages can then be imported into your Vite app. ```typescript import { VirtualFS, PackageManager } from 'almostnode'; const vfs = new VirtualFS(); const npm = new PackageManager(vfs); // Install React await npm.install('react'); await npm.install('react-dom'); // Now your Vite app can import them // import React from 'react'; ``` -------------------------------- ### Create Same-Origin Main Thread Runtime Source: https://almostnode.dev/docs/security.html Use this to run code directly on the main thread. This is the simplest setup but provides no isolation. Only use with fully trusted code. ```javascript const runtime = await createRuntime(vfs, { dangerouslyAllowSameOrigin: true, }); ``` -------------------------------- ### PackageManager npm Package Installation Source: https://almostnode.dev/docs/core-concepts.html Install npm packages into the virtual filesystem using PackageManager. It fetches packages, resolves dependencies, and extracts files. Supports installing single packages, specific versions, or all dependencies from package.json. ```javascript import { VirtualFS, PackageManager } from 'almostnode'; const vfs = new VirtualFS(); const npm = new PackageManager(vfs); // Install a single package await npm.install('lodash'); // Install a specific version await npm.install('react@18.2.0'); // Install all deps from package.json vfs.writeFileSync('/package.json', JSON.stringify({ dependencies: { express: '^4.18.0' } })); await npm.installFromPackageJson(); // List installed packages console.log(npm.list()); // { express: '4.18.2', ... } ``` -------------------------------- ### Sandboxed Iframe Setup Source: https://almostnode.dev/docs/security.html Creating and registering a sandboxed iframe for HMR. ```javascript // Create sandboxed iframe for security const iframe = document.createElement('iframe'); iframe.src = '/__virtual__/3000/'; iframe.sandbox = 'allow-forms allow-scripts allow-same-origin allow-popups'; container.appendChild(iframe); // Register as HMR target after load iframe.onload = () => { if (iframe.contentWindow) { devServer.setHMRTarget(iframe.contentWindow); } }; ``` -------------------------------- ### Configure Hot Module Replacement Source: https://almostnode.dev/docs/nextjs-guide.html Enables HMR by starting the dev server and setting the HMR target to the iframe window. ```javascript const devServer = new NextDevServer(vfs, { port: 3000, root: '/' }); devServer.start(); // Required: enables file watching for HMR // After bridge setup and iframe load: devServer.setHMRTarget(iframe.contentWindow); // Required: HMR delivery target // Now updating a file triggers HMR automatically vfs.writeFileSync('/app/page.tsx', ` export default function Home() { return

Version 2

; } `); ``` -------------------------------- ### Vite Plugin Configuration Source: https://almostnode.dev/docs/security.html Setup for the almostnode Vite plugin to serve the service worker. ```typescript // vite.config.ts import { defineConfig } from 'vite'; import { almostnodePlugin } from 'almostnode/vite'; export default defineConfig({ plugins: [almostnodePlugin()] }); ``` ```typescript almostnodePlugin({ swPath: '/custom/__sw__.js' }) // Then in your app: await bridge.initServiceWorker({ swUrl: '/custom/__sw__.js' }); ``` -------------------------------- ### Initialize Virtual Filesystem Source: https://almostnode.dev/docs/tutorial-editor.html Sets up the in-memory filesystem and populates it with a basic Next.js App Router structure. ```javascript import { VirtualFS } from 'almostnode'; const vfs = new VirtualFS(); // Create directories vfs.mkdirSync('/app', { recursive: true }); vfs.mkdirSync('/app/about', { recursive: true }); // Root layout vfs.writeFileSync('/app/layout.tsx', ` export default function RootLayout({ children }) { return (
{children}
); } `); // Home page with client-side interactivity vfs.writeFileSync('/app/page.tsx', ` 'use client'; import { useState } from 'react'; export default function Home() { const [count, setCount] = useState(0); return (

Welcome!

Count: {count}

); } `); // About page vfs.writeFileSync('/app/about/page.tsx', ` export default function About() { return

About

; } `); ``` -------------------------------- ### Initialize a Container Source: https://almostnode.dev/docs Create a virtual environment and execute a file using the runtime. ```javascript import { createContainer } from 'almostnode'; const { vfs, runtime, npm } = createContainer(); // Write a file to the virtual filesystem vfs.writeFileSync('/hello.js', ` console.log('Hello from almostnode!'); `); // Execute it runtime.runFile('/hello.js'); ``` -------------------------------- ### Initialize Next.js Dev Server Source: https://almostnode.dev/docs/nextjs-guide.html Sets up the VirtualFS, NextDevServer, and ServerBridge to serve the application in an iframe. ```javascript import { VirtualFS } from 'almostnode'; import { NextDevServer } from 'almostnode/next'; import { getServerBridge } from 'almostnode'; const vfs = new VirtualFS(); const server = new NextDevServer(vfs); const bridge = getServerBridge(); // Initialize the service worker await bridge.initServiceWorker(); // Register the server on a port bridge.registerServer(server, 3000); // Point an iframe to the dev server iframe.src = bridge.getServerUrl(3000); ``` -------------------------------- ### Create React App Entry Point Source: https://almostnode.dev/docs/vite-guide.html Write the HTML entry point for the React application. This file sets up the basic HTML structure and includes the main TypeScript entry point. ```html
``` -------------------------------- ### Configure Next.js Options Source: https://almostnode.dev/docs/nextjs-guide.html Writes a next.config.js file to the VirtualFS for path aliases and experimental settings. ```javascript vfs.writeFileSync('/next.config.js', ` module.exports = { experimental: { paths: { '@/*': ['./src/*'], '@components/*': ['./src/components/*'] } } }; `); ``` -------------------------------- ### Integrate Convex CLI in the browser Source: https://almostnode.dev/docs/core-concepts.html Execute the Convex CLI within the almostnode Runtime by setting up the VirtualFS and executing the bundle directly. ```javascript import { VirtualFS, Runtime, PackageManager } from 'almostnode'; const vfs = new VirtualFS(); const npm = new PackageManager(vfs, { cwd: '/project' }); // Install Convex await npm.install('convex'); // Set up project structure vfs.writeFileSync('/project/convex.json', '{ "functions": "convex/" }'); // IMPORTANT: Both .ts AND .js config files are required const configSrc = `import { defineApp } from "convex/server"; const app = defineApp(); export default app;`; vfs.writeFileSync('/project/convex/convex.config.ts', configSrc); vfs.writeFileSync('/project/convex/convex.config.js', configSrc); // Write your Convex functions vfs.writeFileSync('/project/convex/tasks.ts', ` import { query } from './_generated/server'; export const list = query({ handler: async (ctx) => ctx.db.query('tasks').collect(), }); `); // CRITICAL: Create a fresh Runtime for each deployment const cliRuntime = new Runtime(vfs, { cwd: '/project' }); cliRuntime.execute(` process.env.CONVEX_DEPLOY_KEY = 'dev:your-deployment|token'; process.argv = ['node', 'convex', 'dev', '--once']; require('./node_modules/convex/dist/cli.bundle.cjs'); `); ``` -------------------------------- ### createContainer() Source: https://almostnode.dev/docs/api-reference.html Creates a complete container environment with a virtual filesystem, runtime, package manager, and server bridge. ```APIDOC ## createContainer() ### Description Creates a complete container environment with a virtual filesystem, runtime, package manager, and server bridge. ### Parameters #### Options - **cwd** (string) - Optional - Working directory (default: '/') - **env** (Record) - Optional - Environment variables for process.env - **onConsole** ((level, ...args) => void) - Optional - Callback for console output - **baseUrl** (string) - Optional - Base URL for the server bridge - **onServerReady** ((port) => void) - Optional - Called when a server starts listening ### Response - **vfs** (VirtualFS) - Virtual filesystem instance - **runtime** (Runtime) - Code execution runtime - **npm** (PackageManager) - Package manager for installing npm packages - **serverBridge** (ServerBridge) - Service worker bridge - **execute** ((code) => result) - Shorthand for runtime.execute() - **runFile** ((path) => result) - Shorthand for runtime.runFile() - **createREPL** (() => { eval: (code) => unknown }) - Create an interactive REPL context - **on** ((event, listener) => void) - Listen for events (e.g. 'server-ready') ``` -------------------------------- ### Create and use a REPL context Source: https://almostnode.dev/docs/api-reference.html Initializes an interactive REPL that persists variables and evaluates expressions. Use for interactive shells or notebook-style execution. ```javascript const repl = runtime.createREPL(); // Expression values are returned directly repl.eval('1 + 2'); // 3 repl.eval("require('path').join('/a', 'b')"); // '/a/b' // Variables persist across calls repl.eval('const x = 42'); repl.eval('x * 2'); // 84 // Full access to require, process, Buffer, console repl.eval("const fs = require('fs')"); repl.eval("fs.writeFileSync('/test.txt', 'hello')"); repl.eval("fs.readFileSync('/test.txt', 'utf8')"); // 'hello' ``` -------------------------------- ### Create React App Main Entry Point Source: https://almostnode.dev/docs/vite-guide.html Define the main entry point for the React application using TypeScript. This file renders the root React component into the DOM. ```typescript import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; ReactDOM.createRoot( document.getElementById('root') ).render(); ``` -------------------------------- ### Define App Router Pages Source: https://almostnode.dev/docs/nextjs-guide.html Creates layouts and pages within the /app directory using VirtualFS. ```javascript // Create a root layout vfs.writeFileSync('/app/layout.tsx', ` export default function RootLayout({ children }) { return ( {children} ); } `); // Create the home page vfs.writeFileSync('/app/page.tsx', ` export default function Home() { return

Welcome!

; } `); // Create a nested route: /about vfs.writeFileSync('/app/about/page.tsx', ` export default function About() { return

About us

; } `); ``` -------------------------------- ### Run an HTTP Server Source: https://almostnode.dev/docs Create an in-memory HTTP server accessible via the service worker bridge. ```javascript import { createContainer } from 'almostnode'; const { vfs, runtime } = createContainer(); vfs.writeFileSync('/server.js', ` const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('

Hello from the browser!

'); }); server.listen(3000, () => { console.log('Server running on port 3000'); }); `); runtime.runFile('/server.js'); ``` -------------------------------- ### Local Development Terminal Commands Source: https://almostnode.dev/docs/security.html Commands to run the main application and the sandbox server on different ports. ```bash # Terminal 1: Main app on port 5173 npm run dev # Terminal 2: Sandbox on port 3002 npm run sandbox ``` -------------------------------- ### Define Files for Editor Source: https://almostnode.dev/docs/tutorial-editor.html Sets up an array of file objects, each with a path and label, to manage files within the editor. ```javascript const files = [ { path: '/app/page.tsx', label: 'page.tsx' }, { path: '/app/layout.tsx', label: 'layout.tsx' }, { path: '/app/about/page.tsx', label: 'about/page.tsx' }, ]; let currentFile = files[0].path; function loadFile(path) { editor.value = vfs.readFileSync(path, 'utf8'); currentFile = path; } ``` -------------------------------- ### Utility Functions Source: https://almostnode.dev/docs/api-reference.html Helper functions for managing the server state. ```APIDOC ## resetServerBridge() ### Description Resets the global ServerBridge instance. Useful in tests to get a clean state. ### Signature `resetServerBridge(): void` ``` -------------------------------- ### runtime.createREPL() Source: https://almostnode.dev/docs/api-reference.html Creates an interactive REPL context that evaluates expressions and persists variables between calls. ```APIDOC ## createREPL() ### Description Creates an interactive REPL context that evaluates expressions and persists variables between calls. Unlike `execute()`, the REPL's `eval()` returns the value of the last expression. ### Method runtime.createREPL() ### Response - **eval** (function) - A function that takes a string of code and returns the result of the last expression. ``` -------------------------------- ### Generate Sandbox Files for Vercel Deployment Source: https://almostnode.dev/docs/security.html Use this helper function to generate all necessary files for deploying the cross-origin sandbox to Vercel. Deploy the generated 'sandbox' directory. ```javascript import { generateSandboxFiles } from 'almostnode'; import fs from 'fs'; const files = generateSandboxFiles(); fs.mkdirSync('sandbox', { recursive: true }); for (const [filename, content] of Object.entries(files)) { fs.writeFileSync(`sandbox/${filename}`, content); } // Deploy: cd sandbox && vercel --prod ``` -------------------------------- ### Create an Interactive REPL Source: https://almostnode.dev/docs Use the runtime REPL to evaluate code dynamically from a text editor. ```javascript import { createContainer } from 'almostnode'; const { vfs, runtime } = createContainer(); const repl = runtime.createREPL(); // Wire up to a text editor in your docs page runButton.addEventListener('click', () => { const result = repl.eval(editor.value); output.textContent = String(result); }); ``` -------------------------------- ### Create AlmostNode Container Source: https://almostnode.dev/docs/core-concepts.html Use the `createContainer` helper to instantiate all core AlmostNode components. This includes the virtual file system, runtime, package manager, and server bridge. ```javascript import { createContainer } from 'almostnode'; const { vfs, // VirtualFS instance runtime, // Runtime instance npm, // PackageManager instance serverBridge, // ServerBridge instance execute, // Shorthand for runtime.execute() runFile, // Shorthand for runtime.runFile() createREPL, // Create interactive REPL context } = createContainer(); ``` -------------------------------- ### Initialize ViteDevServer Source: https://almostnode.dev/docs/api-reference.html Creates a new virtual Vite dev server instance with React support and HMR capabilities. ```typescript new ViteDevServer(vfs: VirtualFS) ``` -------------------------------- ### Create Runtime with Sandbox Source: https://almostnode.dev/docs/tutorial-editor.html Initializes the AlmostNode runtime, pointing it to a deployed sandbox origin for secure code execution. ```javascript import { VirtualFS, createRuntime } from 'almostnode'; const vfs = new VirtualFS(); // Point to your deployed sandbox const runtime = await createRuntime(vfs, { sandbox: 'https://sandbox.myapp.com', }); // The runtime handles VFS sync and postMessage automatically const result = await runtime.execute(code); ``` -------------------------------- ### Run streaming commands with AbortSignal Source: https://almostnode.dev/docs/core-concepts.html Use container.run with streaming callbacks and an AbortController to manage long-running processes like watch mode. ```javascript const controller = new AbortController(); // Start vitest in watch mode with streaming output container.run('vitest', { onStdout: (data) => console.log(data), onStderr: (data) => console.error(data), signal: controller.signal, }); // Tests re-run automatically when VFS files change. // Stop watching: controller.abort(); ``` -------------------------------- ### Create Dynamic App Router Routes Source: https://almostnode.dev/docs/nextjs-guide.html Uses bracket notation to define dynamic segments in the App Router. ```javascript // /app/posts/[id]/page.tsx → matches /posts/123 vfs.writeFileSync('/app/posts/[id]/page.tsx', ` export default function Post({ params }) { return

Post {params.id}

; } `); ``` -------------------------------- ### Nginx Server Configuration Source: https://almostnode.dev/docs/security.html Nginx configuration to serve the sandbox with required CORS headers. ```nginx server { listen 3002; root /path/to/sandbox; location / { add_header Access-Control-Allow-Origin *; add_header Cross-Origin-Resource-Policy cross-origin; } } ``` -------------------------------- ### createRuntime() Source: https://almostnode.dev/docs/api-reference.html Creates a runtime with security isolation for sandboxed or worker-based execution. ```APIDOC ## createRuntime() ### Description Creates a runtime with security isolation. Use this when you need sandboxed or worker-based execution. ### Parameters #### Request Body - **vfs** (VirtualFS) - Required - The virtual filesystem instance. - **options** (CreateRuntimeOptions) - Optional - Configuration options including `sandbox` (string), `dangerouslyAllowSameOrigin` (boolean), and `useWorker` (boolean). ``` -------------------------------- ### VirtualFS Class Source: https://almostnode.dev/docs/api-reference.html In-memory POSIX-compatible filesystem operations. ```APIDOC ## VirtualFS ### Description In-memory POSIX-compatible filesystem. ### Methods - **writeFileSync** (path: string, data: string | Uint8Array) - Write file (creates parent dirs) - **readFileSync** (path: string, encoding?: 'utf8') - Read file contents - **existsSync** (path: string) - Check if path exists - **statSync** (path: string) - Get file metadata - **unlinkSync** (path: string) - Delete a file - **renameSync** (oldPath: string, newPath: string) - Move or rename a file - **copyFileSync** (src: string, dest: string) - Copy a file - **mkdirSync** (path: string, options?: {recursive?: boolean}) - Create directory - **readdirSync** (path: string) - List directory contents - **toSnapshot** () - Serialize entire filesystem ``` -------------------------------- ### Generate Sandbox Files Source: https://almostnode.dev/docs/tutorial-editor.html Uses `generateSandboxFiles` to create necessary files for a cross-origin sandbox environment and writes them to the 'sandbox' directory. ```javascript import { generateSandboxFiles } from 'almostnode'; import fs from 'fs'; const files = generateSandboxFiles(); fs.mkdirSync('sandbox', { recursive: true }); for (const [name, content] of Object.entries(files)) { fs.writeFileSync(`sandbox/${name}`, content); } // Deploy to a separate origin: // cd sandbox && vercel --prod ``` -------------------------------- ### Implement CSS Modules Source: https://almostnode.dev/docs/nextjs-guide.html Applies scoped CSS by writing a module file and importing it into a component. ```javascript vfs.writeFileSync('/app/styles.module.css', ` .title { color: blue; font-size: 2rem; } .subtitle { color: gray; } `); vfs.writeFileSync('/app/page.tsx', ` import styles from './styles.module.css'; export default function Home() { return (

Hello

World

); } `); ``` -------------------------------- ### Manual Service Worker Deployment Source: https://almostnode.dev/docs/security.html Methods for copying the service worker file to the public directory. ```bash cp node_modules/almostnode/dist/__sw__.js ./public/ ``` ```typescript import { getServiceWorkerPath } from 'almostnode/next'; import fs from 'fs'; fs.copyFileSync(getServiceWorkerPath(), './public/__sw__.js'); ``` -------------------------------- ### Execute shell commands with child_process Source: https://almostnode.dev/docs/core-concepts.html Run bash-compatible commands against the virtual filesystem, including support for pipes, redirects, and custom node execution. ```javascript const { exec } = require('child_process'); // Run shell commands against the VirtualFS exec('ls /src', (err, stdout) => { console.log(stdout); // Lists files in /src }); // Pipes and redirects work too exec('cat /data.csv | sort | head -5', (err, stdout) => { console.log(stdout); }); // Custom 'node' command runs JS via the Runtime exec('node /app.js', (err, stdout) => { console.log(stdout); }); ``` -------------------------------- ### HTML Scaffolding for Editor and Preview Source: https://almostnode.dev/docs/tutorial-editor.html Defines the two-column layout structure for the editor and the iframe preview panel. ```html
``` -------------------------------- ### Organize Routes with Route Groups Source: https://almostnode.dev/docs/nextjs-guide.html Uses parentheses in directory names to group routes without affecting the URL path. ```javascript // /app/(marketing)/pricing/page.tsx → /pricing vfs.writeFileSync('/app/(marketing)/pricing/page.tsx', ` export default function Pricing() { return

Plans

; } `); ``` -------------------------------- ### Runtime Class Source: https://almostnode.dev/docs/api-reference.html Executes JavaScript and TypeScript with CommonJS module resolution. ```APIDOC ## Runtime ### Description Executes JavaScript and TypeScript with CommonJS module resolution and 40+ shimmed Node.js modules. ### Constructor Options - **cwd** (string) - Optional - Working directory (default: '/') - **env** (Record) - Optional - Environment variables - **onConsole** ((level, ...args) => void) - Optional - Console output callback ### Methods - **execute** (code: string, filename?: string) - Execute code string as a module - **runFile** (path: string) - Execute a file from the VFS - **executeAsync** (code: string, filename?: string) - Execute code asynchronously - **runFileAsync** (path: string) - Execute a file asynchronously - **clearCache** () - Clear module cache (for HMR) ``` -------------------------------- ### Connect virtual servers with ServerBridge Source: https://almostnode.dev/docs/core-concepts.html Use ServerBridge to expose virtual servers to the browser via a service worker. ```javascript import { getServerBridge } from 'almostnode'; const bridge = getServerBridge(); // Initialize the service worker await bridge.initServiceWorker(); // Register a virtual server on port 3000 bridge.registerServer(myServer, 3000); // Now accessible at /__virtual__/3000/ in an iframe const url = bridge.getServerUrl(3000); iframe.src = url; ``` -------------------------------- ### Create Cross-Origin Sandbox Runtime Source: https://almostnode.dev/docs/security.html Use this to create a runtime in a cross-origin iframe for the highest security. Code runs fully isolated from your main application. Requires a deployed sandbox at a different origin. ```javascript import { createRuntime, VirtualFS } from 'almostnode'; const vfs = new VirtualFS(); const runtime = await createRuntime(vfs, { sandbox: 'https://your-sandbox.vercel.app', }); // Safe to run untrusted code const result = await runtime.execute(untrustedCode); ``` -------------------------------- ### NextDevServer Source: https://almostnode.dev/docs/api-reference.html A virtual Next.js dev server supporting App Router, Pages Router, and HMR. ```APIDOC ## NextDevServer ### Description A virtual Next.js dev server that supports both App Router and Pages Router, CSS Modules, API routes, dynamic routes, route groups, and HMR via React Refresh. ### Methods - **start** () - Start file watching for HMR. - **stop** () - Stop the server and clean up file watchers. - **setHMRTarget** (window: Window) - Set the iframe contentWindow as the HMR update target. - **handleRequest** (method, url, headers, body) - Handle an HTTP request. ``` -------------------------------- ### Configure Local Sandbox URL Source: https://almostnode.dev/docs/tutorial-editor.html Sets the sandbox URL for local development when the editor and sandbox are running on different ports. ```javascript const runtime = await createRuntime(vfs, { sandbox: 'http://localhost:3002/sandbox/', }); ``` -------------------------------- ### ServerBridge Source: https://almostnode.dev/docs/api-reference.html Connects virtual servers to real browser URLs via a service worker. ```APIDOC ## ServerBridge ### Description Get or create the global ServerBridge instance. Connects virtual servers to real browser URLs via a service worker. ### Methods - **initServiceWorker** (options?: { swUrl?: string }) - Register and activate the service worker. - **registerServer** (server, port: number, hostname?: string) - Register a virtual server on a port. - **unregisterServer** (port: number) - Unregister a server. - **getServerUrl** (port: number) - Get URL for the virtual server. - **handleRequest** (port, method, url, headers, body?) - Handle an incoming request directly. ``` -------------------------------- ### Create API Routes Source: https://almostnode.dev/docs/nextjs-guide.html Defines API endpoints for both Pages and App routers. ```javascript // Pages Router API route vfs.writeFileSync('/pages/api/hello.js', ` export default function handler(req, res) { res.status(200).json({ message: 'Hello!' }); } `); // App Router route handler vfs.writeFileSync('/app/api/hello/route.ts', ` export async function GET(request) { return Response.json({ message: 'Hello!' }); } `); ``` -------------------------------- ### Define Pages Router Routes Source: https://almostnode.dev/docs/nextjs-guide.html Creates routes using the /pages directory structure. ```javascript // /pages/index.jsx → / vfs.writeFileSync('/pages/index.jsx', ` export default function Home() { return

Pages Router home

; } `); // /pages/about.jsx → /about vfs.writeFileSync('/pages/about.jsx', ` export default function About() { return

About

; } `); ``` -------------------------------- ### Create Same-Origin Worker Runtime Source: https://almostnode.dev/docs/security.html Use this to run code in a Web Worker on the same origin. This offloads execution from the main thread but shares the origin with your app. Suitable for demos with trusted code. ```javascript const runtime = await createRuntime(vfs, { dangerouslyAllowSameOrigin: true, useWorker: true, }); ``` -------------------------------- ### Implement an AI Coding Agent Source: https://almostnode.dev/docs Execute AI-generated code and handle errors by feeding them back into the agent loop. ```javascript import { createContainer } from 'almostnode'; const { vfs, runtime, npm } = createContainer({ onConsole: (level, ...args) => logs.push({ level, args }) }); async function agentLoop(task) { let code = await askLLM(task); for (let i = 0; i < 5; i++) { vfs.writeFileSync('/agent/index.js', code); logs = []; try { runtime.runFile('/agent/index.js'); return { success: true, logs }; } catch (err) { // Send error back to LLM for a fix code = await askLLM( `Fix this error: ${err.message}\nCode:\n${code}` ); } } } ``` -------------------------------- ### VirtualFS File System Operations Source: https://almostnode.dev/docs/core-concepts.html Use VirtualFS to manage an in-memory filesystem. It supports directory creation, file writing/reading, listing contents, and watching for changes. Parent directories are created automatically when writing files. ```javascript import { VirtualFS } from 'almostnode'; const vfs = new VirtualFS(); // Create directories vfs.mkdirSync('/src', { recursive: true }); // Write files vfs.writeFileSync('/src/index.js', 'console.log("hello")'); // Read files const content = vfs.readFileSync('/src/index.js', 'utf8'); // List directory contents const files = vfs.readdirSync('/src'); // ['index.js'] // Watch for changes vfs.watch('/src', (event, filename) => { console.log(event, filename); }); ``` -------------------------------- ### Run npm scripts via container Source: https://almostnode.dev/docs/core-concepts.html Execute npm scripts and other shell commands directly using the container run method. ```javascript const container = createContainer(); // Run shell commands directly with container.run() const result = await container.run('npm run build'); console.log(result.stdout); await container.run('npm test'); await container.run('ls /'); ``` -------------------------------- ### Runtime Execution of Node.js Code Source: https://almostnode.dev/docs/core-concepts.html The Runtime executes JavaScript/TypeScript with Node.js module resolution, shimming over 40 built-in modules. It can execute code directly or run files from the VirtualFS. ```javascript import { VirtualFS, Runtime } from 'almostnode'; const vfs = new VirtualFS(); const runtime = new Runtime(vfs); // Execute code directly runtime.execute(" const path = require('path'); console.log(path.join('/foo', 'bar', 'baz.js')); "); // Or run a file from the VFS vfs.writeFileSync('/app.js', 'module.exports = { version: 1 }'); const result = runtime.runFile('/app.js'); console.log(result.exports); // { version: 1 } ``` -------------------------------- ### ViteDevServer Class Source: https://almostnode.dev/docs/api-reference.html The ViteDevServer class provides a virtual Vite development environment with support for React, JSX/TSX transforms, and HMR. ```APIDOC ## ViteDevServer ### Description A virtual Vite dev server with React support, JSX/TSX transforms, npm module resolution, and HMR via React Refresh. ### Constructor `new ViteDevServer(vfs: VirtualFS)` ### Methods - `start()`: Starts the server. - `stop()`: Stops the server. - `setHMRTarget()`: Sets the HMR target. - `handleRequest()`: Handles incoming requests. ``` -------------------------------- ### Register iframe as HMR Target Source: https://almostnode.dev/docs/tutorial-editor.html Connect the iframe to the dev server to receive HMR updates. Ensure `setHMRTarget` is called within the iframe's `onload` handler. ```javascript const iframe = document.getElementById('preview-frame'); // Connect HMR when iframe loads iframe.onload = () => { if (iframe.contentWindow) { devServer.setHMRTarget(iframe.contentWindow); } }; // Load the preview iframe.src = serverUrl + '/'; ``` -------------------------------- ### CORS Header Configuration Source: https://almostnode.dev/docs/security.html Required headers for cross-origin iframe embedding. ```text Access-Control-Allow-Origin: * Cross-Origin-Resource-Policy: cross-origin ``` -------------------------------- ### Express.js Server Configuration Source: https://almostnode.dev/docs/security.html Express middleware to inject CORS headers into the sandbox response. ```javascript app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); next(); }); app.use(express.static('sandbox')); ``` -------------------------------- ### Events Source: https://almostnode.dev/docs/api-reference.html Events emitted by the ViteDevServer instance during its lifecycle. ```APIDOC ## Events ### 'hmr-update' - **Payload**: `{ type: 'update' | 'full-reload', path: string, timestamp: number }` - **Description**: Fired when a VFS file changes. JS/CSS files trigger 'update', others trigger 'full-reload'. ### 'listening' - **Payload**: `port: number` - **Description**: Fired when `start()` is called. ``` -------------------------------- ### Manual HMR Triggering Source: https://almostnode.dev/docs/security.html Triggering HMR updates via postMessage after programmatic file changes. ```javascript function triggerHMR(path: string, iframe: HTMLIFrameElement) { if (iframe.contentWindow) { iframe.contentWindow.postMessage({ type: 'update', path, timestamp: Date.now(), channel: 'next-hmr', // Use 'vite-hmr' for Vite }, '*'); } } // After writing a file vfs.writeFileSync('/app/page.tsx', newContent); triggerHMR('/app/page.tsx', iframe); ``` -------------------------------- ### Create React App Component Source: https://almostnode.dev/docs/vite-guide.html Define a basic React functional component using TypeScript. This component includes state management for a counter. ```typescript import { useState } from 'react'; export default function App() { const [count, setCount] = useState(0); return (

Vite + React

); } ``` -------------------------------- ### Listen for HMR Events Source: https://almostnode.dev/docs/tutorial-editor.html Registers a listener for 'hmr-update' events from the dev server to provide user feedback, such as a toast notification. ```javascript devServer.on('hmr-update', (update) => { console.log('HMR update:', update.path); showToast('Updated!'); }); ``` -------------------------------- ### Save File and Trigger HMR Source: https://almostnode.dev/docs/tutorial-editor.html Saves the current editor content to the Virtual File System (VFS), which automatically triggers HMR updates. ```javascript function saveFile() { vfs.writeFileSync(currentFile, editor.value); // HMR triggers automatically — the dev server watches the VFS } // Keyboard shortcut editor.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); saveFile(); } }); ``` -------------------------------- ### Reset ServerBridge Source: https://almostnode.dev/docs/api-reference.html Clears the global ServerBridge instance, typically used to ensure a clean state during testing. ```typescript resetServerBridge(): void ``` -------------------------------- ### Next.js Service Worker Route Handlers Source: https://almostnode.dev/docs/security.html Route handlers for serving the service worker in Next.js App and Pages routers. ```typescript // app/__sw__.js/route.ts import { getServiceWorkerContent } from 'almostnode/next'; export async function GET() { return new Response(getServiceWorkerContent(), { headers: { 'Content-Type': 'application/javascript', 'Cache-Control': 'no-cache', }, }); } ``` ```typescript // pages/api/__sw__.ts import { getServiceWorkerContent } from 'almostnode/next'; import type { NextApiRequest, NextApiResponse } from 'next'; export default function handler(req: NextApiRequest, res: NextApiResponse) { res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Cache-Control', 'no-cache'); res.send(getServiceWorkerContent()); } ``` -------------------------------- ### Update React Component for HMR Source: https://almostnode.dev/docs/vite-guide.html Update an existing React component. The Vite dev server with React Refresh will apply these changes with Hot Module Replacement, preserving component state. ```typescript import { useState } from 'react'; export default function App() { const [count, setCount] = useState(0); return (

Updated App!

); } // The heading updates but the count state is preserved ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.