Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/shadownrx/windows/llms.txt

Use this file to discover all available pages before exploring further.

AssemblyScript lets you write TypeScript-like code that compiles directly to WebAssembly — no Rust knowledge required. In NEX OS, the exported functions in assembly/index.ts power the Task Manager’s real-time CPU and memory metrics, running calculations at near-native speed while the React UI stays completely responsive. If you already know TypeScript, you can start writing WASM functions immediately.

Exported Functions

The assembly/index.ts file is the sole source of truth for the AssemblyScript module. The following two functions are exported and available to React components through the useWasmEngine hook and the wasmLoader utility.
// assembly/index.ts

export function calculateLoad(cpu: f64, mem: f64): f64 {
  // A simple formula to calculate "System Impact"
  // This runs in WASM for peak performance during rapid updates
  return (cpu * 0.7) + (mem * 0.3);
}

export function getRank(load: f64): i32 {
  if (load > 80) return 3; // Critical
  if (load > 40) return 2; // High
  if (load > 10) return 1; // Normal
  return 0;                // Low
}
calculateLoad takes two f64 arguments — cpu and mem as decimal fractions — and returns a weighted system-impact score. getRank takes that score and maps it to an integer rank (0–3) that the Task Manager uses to colour-code process rows.

AssemblyScript Type System

AssemblyScript is a strict subset of TypeScript with explicit numeric types. These map directly to WebAssembly value types, which is what makes the compilation possible and why the performance is so high.
CategoryTypesNotes
Signed integersi8, i16, i32, i64i32 is the default integer type
Unsigned integersu8, u16, u32, u64Use for counts and indices
Floatsf32, f64f64 matches JavaScript number
ArraysFloat64Array, i32[]Typed arrays cross the WASM boundary
StringsstringLimited support — avoid for exported functions
Prefer i32 for counters and ranks, and f64 for percentages and load values. f64 has the same precision as a JavaScript number, so results stay numerically consistent on both sides of the bridge.

Compilation Workflow

1

Edit assembly/index.ts

Open assembly/index.ts and add or modify exported functions. Use AssemblyScript types (f64, i32, Float64Array) for all parameters and return values.
// assembly/index.ts
export function calculateLoad(cpu: f64, mem: f64): f64 {
  return (cpu * 0.7) + (mem * 0.3);
}
2

Run the build command

Compile the AssemblyScript source to WebAssembly using the project’s npm script:
npm run build:as
This internally calls asc assembly/index.ts --target release using the configuration in asconfig.json.
3

Verify the output files

After a successful build, the following files are updated in public/:
public/
├── process_utils.wasm      ← Compiled WebAssembly binary
├── process_utils.wasm.map  ← Source map for DevTools debugging
└── process_utils.js        ← ESM wrapper (bindings: "esm")
4

Test in the browser

Start the dev server and open the Task Manager application. The useWasmEngine hook will automatically load the new binary. Use the isWasm flag to confirm WASM is active.
npm run dev

asconfig.json Configuration

The asconfig.json file at the project root controls how AssemblyScript compiles the module. NEX OS ships with the following configuration:
{
  "targets": {
    "debug": {
      "outFile": "public/process_utils.wasm",
      "sourceMap": true,
      "debug": true
    },
    "release": {
      "outFile": "public/process_utils.wasm",
      "sourceMap": true,
      "optimizeLevel": 3,
      "shrinkLevel": 0,
      "converge": false,
      "noAssert": false
    }
  },
  "options": {
    "bindings": "esm"
  }
}
KeyValueEffect
outFilepublic/process_utils.wasmWhere the binary is written (both targets)
optimizeLevel3Maximum LLVM-level optimizations (release only)
shrinkLevel0Size shrinking disabled — preserves readable output
sourceMaptrueEmits .wasm.map for source-mapped debugging in DevTools
bindings"esm"Emits an ES module wrapper (process_utils.js) for easy import
The pre-compiled public/process_utils.wasm is committed to the repository. You only need to run npm run build:as if you modify assembly/index.ts.

Consuming the Module in React

The wasmLoader Utility

The low-level loader in src/utils/wasmLoader.ts fetches and instantiates the binary once, then caches the result for all subsequent calls:
// src/utils/wasmLoader.ts
let wasmModule: any = null;

export async function initWasm() {
  const response = await fetch('/process_utils.wasm');
  const buffer = await response.arrayBuffer();
  const result = await WebAssembly.instantiate(buffer);
  return result.instance.exports;
}

export async function getWasm() {
  if (!wasmModule) wasmModule = await initWasm();
  return wasmModule;
}
For React components, the useWasmEngine hook at src/utils/useWasmEngine.ts is the preferred integration point. It wraps wasmLoader, manages loading state, and provides a transparent JavaScript fallback:
import { useWasmEngine } from '../utils/useWasmEngine';

export const TaskManager: React.FC = () => {
  const { isReady, isWasm, calculateLoad, getRank } = useWasmEngine();

  if (!isReady) return <div>Loading WASM engine...</div>;

  const load = calculateLoad(0.7, 0.4);
  const rank = getRank(load);

  return (
    <div>
      <p>System Load: {load.toFixed(2)}%</p>
      <p>Rank: {rank}</p>
      <p>Engine: {isWasm ? 'WASM ⚡' : 'JS Fallback'}</p>
    </div>
  );
};

Limitations

Not all TypeScript patterns are valid in AssemblyScript. The compiler enforces strict constraints that map to WebAssembly’s type system.
PatternSupportedNotes
Float64Array parametersEfficient cross-boundary transfer
i32 / f64 return valuesMap directly to WASM value types
Primitive types (i32, f64)First-class citizens
Callbacks (() => void)Function references not exportable
Complex return objects ({ x, y })Structs cannot cross the JS boundary
Dynamic any typesAssemblyScript is strictly typed
// ❌ NOT supported — callbacks
export function takesCallback(cb: () => void): void {
  cb(); // will not compile
}

// ❌ NOT supported — object returns
export function returnsObject(): { x: i32; y: i32 } {
  return { x: 1, y: 2 }; // structs cannot cross the boundary
}

// ✅ Supported — typed array return
export function returnsArray(): Float64Array {
  return new Float64Array([1.0, 2.0, 3.0]);
}

// ✅ Supported — primitive return
export function add(a: i32, b: i32): i32 {
  return a + b;
}

Performance Tips

Getting the best out of WASM requires minimising the cost of crossing the JS ↔ WASM boundary. Use precise numeric types:
// ✅ i32 for integer ranks — maps to a 32-bit int natively
export function getRank(load: f64): i32 { ... }

// ❌ Avoid f64 for values that are always integers
export function getRank(load: f64): f64 { ... } // unnecessary precision
Batch operations — don’t call WASM in a loop:
// ❌ Expensive: many individual WASM calls
for (let i = 0; i < samples.length; i++) {
  ranks.push(wasm.getRank(wasm.calculateLoad(cpu[i], mem[i])));
}

// ✅ Cheap: accumulate data in JS, make one WASM call per metric
const load = wasm.calculateLoad(avgCpu, avgMem);
const rank = wasm.getRank(load);
Minimise data copying: Pass Float64Array views of existing buffers rather than creating new arrays just for a WASM call.

Debugging

Timing WASM vs JavaScript

// src/utils/debug.ts
import { getWasm } from './wasmLoader';

export const benchmarkWasm = async () => {
  const wasm = await getWasm();

  console.time('WASM calculateLoad');
  const wasmResult = wasm.calculateLoad(0.85, 0.40);
  console.timeEnd('WASM calculateLoad');

  console.time('JS calculateLoad');
  const jsResult = (0.85 * 0.7) + (0.40 * 0.3);
  console.timeEnd('JS calculateLoad');

  console.log('WASM:', wasmResult, '| JS:', jsResult);
  console.log('Match:', Math.abs(wasmResult - jsResult) < 0.0001);
};

Inspecting the Binary

# Convert the WASM binary to human-readable WAT format
wasm2wat public/process_utils.wasm > public/process_utils.wat

# Peek at the raw binary header
hexdump -C public/process_utils.wasm | head
Chrome DevTools also renders WASM call frames in the Performance tab — record a profile while the Task Manager is open to see calculateLoad and getRank appearing as native frames in the flame chart.

Build docs developers (and LLMs) love