nexus-env
v0.2.1
Published
A lightweight, dynamic environment system for JavaScript — everything is content, envs hold it, folders organize it.
Maintainers
Readme
Nexus-Env
The Single-File Application Engine for JavaScript. Build, structure, and scale multi-modular applications inside a single physical
index.jsfile — eliminating physical sub-files on disk.
Version: 0.2.1
Nexus-Env is a lightweight, zero-dependency virtual file system and environment engine for JavaScript. It allows you to organize, structure, and execute complex, multi-modular codebases within a single physical file on disk by replacing physical directory trees and ES module imports with an in-memory virtual hierarchy (Folder → Env → Content).
import Nexus from "nexus-env";
// 1. Build an in-memory virtual directory hierarchy in a single index.js file
const src = Nexus.createFolder("src");
const auth = Nexus.createEnv("auth");
const utils = Nexus.createEnv("utils");
src.addEnv(auth);
src.addEnv(utils);
// 2. Define modular content (functions) without physical sub-files
auth.add(function login(user) {
return `User ${user} authenticated via virtual module!`;
});
utils.add(function formatDate(date) {
return date.toISOString().split("T")[0];
});
// 3. Resolve and call across virtual modules using logical paths
const loginFn = Nexus.get("src/auth/login");
console.log(loginFn("Omid")); // → "User Omid authenticated via virtual module!"
const fmtFn = Nexus.get("src/utils/formatDate");
console.log(fmtFn(new Date())); // → "2026-07-25"Table of Contents
- The Core Goal & Vision
- The Four Pillars
- Why Nexus-Env?
- Core Philosophy
- Core Concepts
- Installation
- Quick Start
- API Reference
- Usage Examples
- Where Nexus-Env Shines
- Comparison with Existing Patterns
- Architecture & Data Model
- V1 → V2 Migration
- Known Trade-offs
- Roadmap
- Contributing
- License
The Core Goal & Vision
The primary mission behind nexus-env is the elimination of physical sub-files on disk.
As projects grow, physical file management introduces friction: creating nested folders on OS directory trees, managing long lists of physical sub-files (./../../utils/formatDate.js), managing build tool bundles, and wrangling complex module resolution chains.
Nexus-Env solves this by shifting modular application architecture entirely into memory.
The Four Pillars
1. Single-File Physical Footprint
Build, structure, and scale a complete multi-modular application inside a single physical index.js file on your hard drive, avoiding the overhead of creating and maintaining dozens of physical files and subdirectories on disk.
2. In-Memory Virtual File System
Instead of relying on OS filesystems and directory trees, Nexus-Env creates a virtualized in-memory hierarchy (Folder $\rightarrow$ Env $\rightarrow$ Content) that mimics a folder structure purely inside JavaScript memory.
3. Path-Based Virtual Resolution
By using logical string paths like Nexus.get("src/utils/formatDate"), virtual modules inside the single script reference, execute, and share functions seamlessly without needing relative physical imports (import ... from "./../../utils").
4. Specialized Purpose
Nexus-Env is not a generic replacement for standard ES modules or bundlers in traditional multi-file web apps. It is a specialized engine engineered for virtualized single-file applications, in-browser sandboxes, zero-infrastructure scripts, micro-runtimes, and dynamic plugin engines.
Why Nexus-Env?
Standard JavaScript tooling forces modularity to equal physical files:
- 1 Module = 1 File on disk.
- 50 Functions = 10 to 50 physical
.jsfiles on your file system. - Cross-referencing requires relative file system paths like
import { formatDate } from "../../utils/date.js".
Nexus-Env decouples modularity from physical files:
| Traditional Approach | Nexus-Env Virtual Approach |
|----------------------|---------------------------|
| Dozens of physical .js files on hard drive | 1 single index.js file on hard drive |
| OS directory trees (fs.readdir) | In-memory Virtual Hierarchy (Folder $\rightarrow$ Env $\rightarrow$ Content) |
| Relative file paths (import ... from "./../../utils") | Logical String Paths (Nexus.get("src/utils/formatDate")) |
| Static build steps & bundlers | Zero infrastructure, runtime virtual resolution |
Core Philosophy
1. Functions Are Just Content
Code is not bound to a physical file path. In Nexus-Env, functions are portable content — lines of code that live inside virtual environments and can be added, moved, and executed on demand.
2. Envs Are Virtual Containers
An Env doesn't exist on your hard drive. It is a lightweight memory container that holds related virtual content (functions, helpers, handlers).
3. Folders Group Environments
Folder objects organize multiple Env containers into logical directories.
The entire hierarchy has three intuitive layers:
$$\text{Folder} \longrightarrow \text{Env} \longrightarrow \text{Content}$$
Core Concepts
| Concept | What It Is | How It's Created | Example Path |
|---------|-----------|------------------|--------------|
| Content | A JavaScript function (virtual module unit) | env.add(fn) | "src/auth/login" |
| Env | A virtual container holding content | Nexus.createEnv("auth") | "src/auth" |
| Folder | A virtual directory grouping environments | Nexus.createFolder("src") | "src" |
| Path | A slash-separated logical string locator | Passed to Nexus.get() | "src/utils/formatDate" |
| Registry | The internal in-memory map tracking everything | Managed automatically | — |
Visual Architecture
┌─────────────────────────────────────────────────────────────────────────────┐
│ Single physical index.js │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Nexus In-Memory Registry │ │
│ │ │ │
│ │ ┌──────────────────────────────────────┐ │ │
│ │ │ Folder: "src" │ │ │
│ │ │ │ │ │
│ │ │ ┌──────────────┐ ┌─────────────┐ │ ┌─────────────┐ │ │
│ │ │ │ Env: "auth" │ │ Env: "users"│ │ │ Env: "utils" │ │ │
│ │ │ │ │ │ │ │ │ (root env) │ │ │
│ │ │ │ • login │ │ • create │ │ │ │ │ │
│ │ │ │ • logout │ │ • delete │ │ │ • formatDate│ │ │
│ │ │ └──────────────┘ └─────────────┘ │ └─────────────┘ │ │
│ │ └──────────────────────────────────────┘ │ │
│ │ │ │
│ │ Nexus.get("src/auth/login") → returns login function │ │
│ │ Nexus.get("utils/formatDate") → returns formatDate function │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘Installation
npm install nexus-envOr include directly in HTML (browser sandbox):
<script src="https://unpkg.com/nexus-env/dist/nexus-env.min.js"></script>
<script>
const app = NexusEnv.createEnv("app");
app.add(function greet(name) { return `Hello ${name}`; });
NexusEnv.get("app/greet")("World");
</script>Quick Start
import Nexus from "nexus-env";
// 1. Create a virtual folder and env
const src = Nexus.createFolder("src");
const math = Nexus.createEnv("math");
src.addEnv(math);
// 2. Add functions as content
math.add(function add(a, b) { return a + b; });
math.add(function multiply(a, b) { return a * b; });
// 3. Resolve & run by path
const sum = Nexus.get("src/math/add")(10, 20); // → 30
console.log(sum);API Reference
Nexus (Top-Level API)
The Nexus global singleton is the primary gateway to managing virtual folders, envs, and path resolution.
Nexus.createEnv(name)
Creates a root-level virtual environment.
- Parameters:
name(string) — Unique name. - Returns:
Envinstance. - Throws:
EnvironmentExistsErrorif name is already taken.
const auth = Nexus.createEnv("auth");Nexus.createFolder(name)
Creates a top-level virtual folder.
- Parameters:
name(string) — Unique folder name. - Returns:
Folderinstance. - Throws:
FolderExistsErrorif name is already taken.
const src = Nexus.createFolder("src");Nexus.deleteEnv(name)
Deletes a virtual environment and all contained content.
- Throws:
EnvironmentNotFoundErrorif non-existent.
Nexus.deleteEnv("auth");Nexus.deleteFolder(name)
Deletes a virtual folder and all environments contained within it.
- Throws:
FolderNotFoundErrorif non-existent.
Nexus.deleteFolder("src");Nexus.get(path)
Resolves any virtual item (Folder, Env, or Content function) using a slash-separated string path.
- Parameters:
path(string) — e.g."src","src/auth","src/auth/login". - Returns:
Folder|Env|Function - Throws:
InvalidPathErrorif path cannot be resolved.
// Resolve folder
const srcFolder = Nexus.get("src");
// Resolve env in folder
const authEnv = Nexus.get("src/auth");
// Resolve function content in env
const loginFn = Nexus.get("src/auth/login");
loginFn("Omid");| Path Pattern | Example | Resolves To |
|--------------|---------|-------------|
| "folder" | "src" | Folder instance |
| "env" | "utils" | Root-level Env instance |
| "folder/env" | "src/auth" | Env inside Folder |
| "folder/env/content" | "src/auth/login" | Function inside Env inside Folder |
| "env/content" | "utils/formatDate" | Function inside root-level Env |
Nexus.list()
Returns an overview of top-level virtual items.
- Returns:
{ folders: string[], envs: string[] }
Nexus.list();
// → { folders: ["src"], envs: ["utils"] }Nexus.compose(name, envs)
Merges multiple Env containers into a new composite Env. Conflicts resolve with last-write-wins behavior.
- Parameters:
name(string),envs(Env[]) - Returns: New
Envinstance.
const fullApp = Nexus.compose("fullApp", [auth, users, utils]);Env (Environment Container)
An Env is an in-memory virtual container for JavaScript functions (content).
env.add(fn, key?)
Adds a function to the virtual environment.
- Parameters:
fn(Function),key(string, optional — required for anonymous functions) - Throws:
FunctionExistsErrorif key exists;AnonymousFunctionErrorif fn is anonymous and key is omitted.
function login(user) { return `User ${user}`; }
auth.add(login); // Key derived from function name
auth.add((x) => x * 2, "double"); // Explicit key for anonymous fnenv.remove(name)
Removes content by name.
- Parameters:
name(string)
auth.remove("login");env.use(name)
Retrieves a function directly from the environment.
- Parameters:
name(string) - Returns:
Function - Throws:
FunctionNotFoundErrorif not found.
const login = auth.use("login");
login("Omid");env.move(contentName, targetEnv)
Atomically transfers a function from this env to targetEnv.
- Parameters:
contentName(string),targetEnv(Env)
devEnv.move("calculate", prodEnv);env.has(name)
Checks if function exists in this env.
- Returns:
boolean
auth.has("login"); // → trueenv.list()
Lists all content function names in this env.
- Returns:
string[]
auth.list(); // → ["login", "logout"]env.snapshot(name)
Creates an immutable, frozen snapshot copy of the environment.
- Parameters:
name(string) - Returns: Frozen
Envinstance.
const snapshotV1 = auth.snapshot("auth_v1");Folder (Virtual Directory)
A Folder groups related Env instances into virtual directory structures.
folder.addEnv(env)
Adds an existing Env to the folder.
src.addEnv(auth);folder.removeEnv(name)
Removes an Env from the folder.
src.removeEnv("auth");folder.getEnv(name)
Retrieves an Env from the folder by name.
const auth = src.getEnv("auth");folder.hasEnv(name)
Checks if an Env exists in the folder.
src.hasEnv("auth"); // → truefolder.list()
Lists all contained Env names.
src.list(); // → ["auth", "users"]Usage Examples
Single-File App Architecture
Structure an entire multi-layered backend or utility library inside a single physical index.js file:
import Nexus from "nexus-env";
// --- VIRTUAL DIRECTORY LAYOUT ---
const src = Nexus.createFolder("src");
// 1. Virtual Module: Auth
const auth = Nexus.createEnv("auth");
auth.add(function login(credentials) {
return { status: 200, token: `token_${credentials.user}` };
});
auth.add(function validateToken(token) {
return token.startsWith("token_");
});
src.addEnv(auth);
// 2. Virtual Module: Database
const db = Nexus.createEnv("db");
db.add(function findUser(id) {
return { id, name: "Omid", role: "admin" };
});
src.addEnv(db);
// --- APP EXECUTION (Zero physical imports needed) ---
function handleApiRequest(user, credentials) {
const login = Nexus.get("src/auth/login");
const findUser = Nexus.get("src/db/findUser");
const authRes = login(credentials);
if (authRes.status === 200) {
return findUser(user);
}
throw new Error("Unauthorized");
}
console.log(handleApiRequest("user_101", { user: "Omid" }));Path-Based Virtual Resolution
Clean locator strings eliminate physical directory traversal syntax (../../):
import Nexus from "nexus-env";
const system = Nexus.createFolder("system");
const logger = Nexus.createEnv("logger");
system.addEnv(logger);
logger.add(function info(msg) { console.log(`[INFO] ${msg}`); });
// Virtual Resolution from anywhere in your single script
Nexus.get("system/logger/info")("System initialized.");Dynamic Module Promotion (move)
Promote or reassign functions between environments dynamically at runtime:
import Nexus from "nexus-env";
const staging = Nexus.createEnv("staging");
const production = Nexus.createEnv("production");
staging.add(function processPayment(amount) {
return `[PROD READY] Processed $${amount}`;
});
// Transfer ownership from staging to production virtual env
staging.move("processPayment", production);
console.log(production.has("processPayment")); // → true
console.log(staging.has("processPayment")); // → falseVirtual Environment Composition
Combine disparate virtual modules into unified functional suites:
import Nexus from "nexus-env";
const mathUtils = Nexus.createEnv("math");
mathUtils.add(function square(n) { return n * n; });
const strUtils = Nexus.createEnv("string");
strUtils.add(function trim(s) { return s.trim(); });
// Merge into single runtime module
const coreUtils = Nexus.compose("coreUtils", [mathUtils, strUtils]);
console.log(coreUtils.use("square")(4)); // → 16
console.log(coreUtils.use("trim")(" hello ")); // → "hello"Snapshots & State Rollback
Protect known good states of virtual modules during hot updates:
import Nexus from "nexus-env";
const auth = Nexus.createEnv("auth");
auth.add(function verify() { return "v1_stable"; });
// Create snapshot copy in memory
const v1Backup = auth.snapshot("auth_v1_backup");
// Hot-swap live code
auth.remove("verify");
auth.add(function verify() { return "v2_experimental"; });
console.log(auth.use("verify")()); // → "v2_experimental"
console.log(v1Backup.use("verify")()); // → "v1_stable" (guaranteed unchanged)In-Browser Sandbox / Plugin Engine
Execute dynamic user script modules inside an isolated virtual hierarchy:
import Nexus from "nexus-env";
const sandbox = Nexus.createFolder("sandbox");
const userPlugins = Nexus.createEnv("plugins");
sandbox.addEnv(userPlugins);
// Dynamically register user-provided function content
function registerUserPlugin(pluginName, fn) {
userPlugins.add(fn, pluginName);
}
registerUserPlugin("customFormatter", (str) => str.toUpperCase());
// Execute dynamically registered user code
const pluginFn = Nexus.get("sandbox/plugins/customFormatter");
console.log(pluginFn("hello sandbox")); // → "HELLO SANDBOX"Where Nexus-Env Shines
| Specialized Target | Why Nexus-Env Fits Perfectly | |--------------------|-----------------------------| | Single-File Applications | Structure complex multi-module apps inside 1 physical file without physical file proliferation | | In-Browser Sandboxes | Build web playgrounds, online IDEs, and code runners without filesystem APIs | | Zero-Infrastructure Scripts | Write self-contained CLI tools or automations without build bundlers or package structures | | Dynamic Plugin Engines | Add, remove, and hot-swap executable plugins dynamically at runtime | | Live Coding & Interactive Runtimes | Move and snapshot execution contexts in memory while the app runs |
Comparison with Existing Patterns
| Capability | Physical ES Modules | CommonJS | Nexus-Env (Virtual) |
|------------|---------------------|----------|----------------------|
| Physical File Requirement | 1 file per module on disk | 1 file per module on disk | 0 sub-files (1 single index.js) |
| Filesystem Dependency | Required (OS directory tree) | Required (OS directory tree) | Pure In-Memory Virtual FS |
| Path Resolution | Relative disk path (../../) | Relative disk path (../../) | Logical Virtual String Paths |
| Runtime Swapping / Move | Impossible | Hacky / Cached | Native First-Class (env.move) |
| In-Memory Snapshots | Not supported | Not supported | Native (env.snapshot) |
| Build Step / Bundler | Required for single file | Required for single file | Zero build step required |
Architecture & Data Model
Internal Memory Structure
// Content — wraps function with metadata
class Content {
name; // Key identifier
fn; // Target function
createdAt; // Date timestamp
}
// Env — virtual container holding contents
class Env {
name; // Env name
_contents; // Map<string, Content>
_frozen; // Immutable snapshot boolean
_folder; // Parent folder name reference
}
// Folder — virtual directory holding envs
class Folder {
name; // Folder name
_envs; // Map<string, Env>
}
// Global Registry — root tracker
_folders; // Map<string, Folder>
_envs; // Map<string, Env> (root-level)Path Resolution Protocol
When resolving Nexus.get("src/auth/login"):
Path String: "src/auth/login"
│ │ │
│ │ └─── 3. Match "login" in Env's _contents Map
│ └──────── 2. Match "auth" in Folder's _envs Map
└──────────── 1. Match "src" in Registry's _folders MapResolution rules:
- 1 segment: Resolves to
Folderor rootEnv. - 2 segments: Resolves to
EnvinsideFolderorContentinside rootEnv. - 3 segments: Resolves to
ContentinsideEnvinsideFolder.
Error Handling
| Error Class | Trigger Condition |
|-------------|-------------------|
| EnvironmentExistsError | Attempted to create duplicate env name |
| FolderExistsError | Attempted to create duplicate folder name |
| EnvironmentNotFoundError | Referenced env does not exist in registry/folder |
| FolderNotFoundError | Referenced folder does not exist in registry |
| FunctionExistsError | Function key already exists in target env |
| AnonymousFunctionError | Function is anonymous and no key parameter was provided |
| FunctionNotFoundError | Function key not found in env |
| FrozenEnvironmentError | Attempted modification of snapshot env |
| InvalidPathError | Path string cannot be resolved |
V1 → V2 Migration
| V1 API | V2 API | Changes & Upgrades |
|--------|--------|-------------------|
| Create("app") | Nexus.createEnv("app") | Explicit namespace |
| Delete("app") | Nexus.deleteEnv("app") | Explicit namespace |
| app.Add(fn) | app.add(fn) | Standard camelCase |
| app.Remove(fn) | app.remove(name) | Standard camelCase |
| app.Use("fn") | app.use("name") | Standard camelCase |
| Move(fn, src, tgt) | src.move("name", tgt) | Method on source Env |
| ❌ No Folders | Nexus.createFolder("src") | V2 In-Memory Virtual Folders |
| ❌ No Path Resolution | Nexus.get("src/auth/login") | V2 Path-Based Resolution |
Known Trade-offs
- Static Analysis & IDE Auto-Import: Because paths like
Nexus.get("src/math/add")resolve dynamically in memory at runtime, standard IDE static type jump-to-definition won't trace into string paths automatically. Use explicit TypeScript generics if typing call sites:const login = auth.use<(user: string) => string>("login"); - Lookup Performance:
env.use()performs an $O(1)$Map.get()lookup. Path resolution viaNexus.get()performs 1 to 3Map.get()lookups. For intense computational inner loops, cache the returned function reference:const fn = Nexus.get("src/math/add"); for (let i = 0; i < 1_000_000; i++) fn(i, 1);
Roadmap
v0.2.1 — Current Release
- [x] In-memory
Folder→Env→Contentvirtual hierarchy - [x] Path-based virtual resolution (
Nexus.get) - [x] Dynamic module transfers (
env.move) - [x] Environment snapshot frozen copies
- [x] Environment composition (
Nexus.compose)
v0.3.0 — Developer Experience
- [ ] Chainable API (
Nexus.createEnv("app").add(fn1).add(fn2)) - [ ] Lifecycle event hooks (
onAdd,onRemove,onMove) - [ ] TypeScript declaration generation
v0.4.0 — Advanced Virtual Features
- [ ] Deep nested virtual folders (
FolderinsideFolder) - [ ] Serialized virtual state export/import (
toJSON/fromJSON) - [ ] Virtual middleware interceptors on
get/use
Contributing
Contributions, bug reports, and discussion on single-file virtual architecture patterns are welcome! Please check the GitHub Issues page to participate.
License
MIT © Omid
