@wrnexus/compiler
Parser and code generators for the .wrn language.
bun add @wrnexus/compiler@0.2.15Compiler for the.wrnlanguage — tokenizes, parses, and lowers.wrnpage and component files to TypeScript.
Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.
Overview
@wrnexus/compiler turns .wrn source into TypeScript that targets the framework's runtime primitives. A .wrn file declares either a page (a route) or a component (a reusable, prop-driven fragment) with blocks for state, view (plain HTML), seo, style, functions, api, ssr/client data bindings, and realtime websocket handlers. The pipeline is source → Lexer → parse() → PageAst → generate() → TypeScript. It is a build/server-side library — the WRNexusJS dev loader calls it to compile .wrn files on the fly, surfacing ParseError as a readable error page.
Installation
bun add @wrnexus/compiler
Private package — the machine must be authenticated to the wrnexus npm org
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
API
All exports come from the package root (@wrnexus/compiler).
compileWireFile(source: string): string
Compile .wrn source to a TypeScript module string. Throws ParseError on invalid input. The output is prefixed with a // compiled from .wrn comment.
compile(source: string): CompileResult
Richer entry point that returns the generated code, the AST, and any diagnostics.
interface CompileResult {
code: string;
ast: PageAst;
diagnostics: string[];
}
On a ParseError it pushes the message into diagnostics and re-throws.
parse(source: string): PageAst
Run the lexer + recursive-descent parser and return the AST. Throws ParseError (lexer LexErrors are caught and rethrown as ParseError).
generate(ast: PageAst): string
Lower a PageAst to TypeScript. page ASTs become a default-export page component (plus meta, optional layout, __wrnexusApi/method handlers, websocket, and SSR/CSR data bindings); component ASTs become a module exporting render(props) and __wrnexusComponent.
Lexer
On-demand lexer for .wrn. Yields structural tokens and exposes raw-span readers for the parser.
class Lexer {
pos: number;
constructor(src: string);
next(): Token; // consume next structural token
peek(): Token; // look ahead without consuming
readPath(): string; // route path, e.g. /users/[id]
readToLineEnd(): string; // rest of line (state/prop initializers)
readBalancedBraces(): string; // inner text of a { ... } block, string-aware
}
Token is { type: TokenType; value: string; pos: number }, where TokenType is one of ident, string, lbrace, rbrace, lparen, rparen, at, eq, comma, eof.
Errors
| Class | Thrown by | Meaning |
|---|---|---|
ParseError | parse, compile, compileWireFile, generate | Invalid .wrn grammar or (rewrapped) lex failure. |
LexError | Lexer | Unexpected character / unterminated string / unbalanced braces. |
AST types
Exported type-only symbols describing the parsed tree:
| Type | Description | |
|---|---|---|
PageAst | Root node: kind (`"page" \ | "component"), name, optional layout, props, states, seo, view, styles, functions, dataApis, modeFunctions, apis, realtimes`. |
ViewNode | { type: "text"; value } or { type: "element"; tag; attrs; children }. | |
Attr | { name; value; event; boolean? } — event marks @event bindings. | |
StateDecl | { name; expr } — a state x = <expr> declaration. | |
SeoBlock | Record<string, string> from the seo { ... } block. | |
ApiBlock | { method; path; body } — a top-level api METHOD /path { ... }. | |
DataApiBlock | { mode; name; method; path; body } — an api inside an ssr/client block. | |
DataMode | `"ssr" \ | "client"`. |
ModeFunctionsBlock | { mode; body } — a functions { ... } inside an ssr/client block. | |
RealtimeBlock | { name; handlers } — a realtime <name> { on evt(args) { ... } } block. |
Usage
Compile a page:
import { compileWireFile } from "@wrnexus/compiler";
const ts = compileWireFile(`
page Home {
state count = 0
seo { title = "Home" description = "Welcome" }
view {
<button @click="count++">Clicked {count} times</button>
}
}
`);
// ts is a TypeScript module: exports `meta`, and a default page component
// returning an HTML string, wrapped in a data-scope for the reactive runtime.
Inspect the AST and diagnostics:
import { compile, ParseError } from "@wrnexus/compiler";
try {
const { code, ast, diagnostics } = compile(source);
console.log(ast.kind, ast.name, ast.states.length);
} catch (err) {
if (err instanceof ParseError) console.error(err.message);
}
Drive the parse/codegen stages directly:
import { parse, generate } from "@wrnexus/compiler";
const ast = parse(componentSource); // ast.kind === "component"
const module = generate(ast); // exports render(props) + __wrnexusComponent
Use the lexer standalone:
import { Lexer } from "@wrnexus/compiler";
const lx = new Lexer("page Home {");
lx.next(); // { type: "ident", value: "page", pos: 0 }
lx.next(); // { type: "ident", value: "Home", pos: 5 }
lx.next(); // { type: "lbrace", value: "{", pos: 10 }
The .wrn language (as parsed)
A file opens with page <Name> or component <Name> followed by a { ... } body containing zero or more members:
layout = "<name>"— selectsapp/layouts/<name>.wrn(pages only).props { name = <default> ... }— component props; each default's type drives coercion.state <ident> = <expr>— reactive state seeded from a raw JS expression.view { <html> }— plain HTML with{expr}interpolation, hyphenated attributes, boolean attributes,@event="..."client bindings, and<!-- comments -->.seo { key = "value" ... }— metadata merged into the generatedmeta.style { <raw css> }— inlined page/component stylesheet (repeatable).functions { <raw js> }— shared server-side helpers (repeatable).api <METHOD> <path> { <raw js> }— route handler, lowered to aMETHODexport (repeatable).ssr { ... }/client { ... }— data blocks holdingapi <name> <METHOD> <path> { ... }bindings and their ownfunctions { ... }.realtime <name> { on <evt>(<args>) { <raw js> } ... }— websocket handlers, lowered to awebsocketexport.
view markup is parsed by a lenient dedicated HTML parser (parseHtmlView); HTML void elements (<br>, <img>, …) take no closing tag. Line comments (//) are skipped by the lexer.
Requirements / Notes
- Pure TypeScript with no runtime dependencies; runs under Bun as part of the WRNexusJS toolchain (Node is not supported).
- Generated modules target WRNexusJS runtime primitives (
data-scope,data-text,data-on-*,data-for,data-component,__wrnexus*/__wire*helpers) — consume the output within a WRNexusJS app, e.g. via@wrnexus/core's dev loader.
Complete TypeScript API
This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.
/**
* Recursive-descent parser for `.wrn`, producing a small AST.
*
* Grammar (subset of the vision, but real):
*
* page <Name> {
* state <ident> = <expr> // zero or more
* view { <html> } // plain HTML (see parseHtmlView)
* seo { title = "Home" description = "..." }
* ssr { api <name> <METHOD> <path> { <render js> } functions { <raw js> } }
* client { api <name> <METHOD> <path> { <render js> } functions { <raw js> } }
* style { <raw css> } // zero or more, inlined with the page
* functions { <raw js> } // zero or more, shared helpers
* api <METHOD> <path> { <raw js> } // zero or more
* realtime <name> { on <evt>(<args>) { <raw js> } * } // zero or more
* }
*
* The `view` block is written as ordinary HTML — nothing new to learn. Text may
* contain `{expr}` interpolation, attributes may be hyphenated (`data-*`), and
* `@event="..."` declares a client event binding. See `parseHtmlView`.
*/
interface StateDecl {
name: string;
/** Raw JS initializer expression, e.g. `0` or `'x'`. */
expr: string;
}
interface Attr {
name: string;
value: string;
/** True for `@event` bindings (vs. plain HTML attributes). */
event: boolean;
/** True for a valueless boolean attribute, e.g. `<button disabled>`. */
boolean?: boolean;
}
type ViewNode = {
type: "text";
value: string;
} | {
type: "element";
tag: string;
attrs: Attr[];
children: ViewNode[];
}
/**
* A server-side loop: `{#each <list> as <item>[, <index>]} …body… {:empty} …empty… {/each}`.
* `list` is a JS expression (evaluated on the server, may reference an `ssr` data
* binding). The `body` is rendered once per item with `{item.field}` interpolation;
* `empty` renders when the list is empty. See codegen `compileEach`.
*/
| {
type: "each";
list: string;
item: string;
index?: string;
body: ViewNode[];
empty: ViewNode[];
}
/**
* A server-side conditional: `{#if <expr>} … {:else if <expr>} … {:else} … {/if}`.
* Rendered branches are chosen on the server. Each branch's `cond` is a JS expression
* (`null` for the final `{:else}`); the first truthy branch renders. See `compileIfExpr`.
*/
| {
type: "if";
branches: {
cond: string | null;
body: ViewNode[];
}[];
};
interface ApiBlock {
method: string;
path: string;
body: string;
}
type SeoBlock = Record<string, string>;
type DataMode = "ssr" | "client";
interface DataApiBlock {
mode: DataMode;
name: string;
method: string;
path: string;
body: string;
}
interface ModeFunctionsBlock {
mode: DataMode;
body: string;
}
interface RealtimeHandler {
event: string;
args: string[];
body: string;
}
interface RealtimeBlock {
name: string;
handlers: RealtimeHandler[];
}
interface PropDecl {
name: string;
/** Raw JS default expression, e.g. `0` or `'Count'`. Its type drives coercion. */
default: string;
}
interface PageAst {
type: "page";
/** `page` (a route) or `component` (a reusable, prop-driven fragment). */
kind: "page" | "component";
name: string;
/** Name of the page layout (`app/layouts/<layout>.wrn`), if the page sets one. */
layout?: string;
/** Declared component props (empty for pages). */
props: PropDecl[];
states: StateDecl[];
seo: SeoBlock;
view: ViewNode[];
styles: string[];
functions: string[];
dataApis: DataApiBlock[];
modeFunctions: ModeFunctionsBlock[];
apis: ApiBlock[];
realtimes: RealtimeBlock[];
}
declare class ParseError extends Error {
}
declare function parse(source: string): PageAst;
/**
* Code generation: lower a `.wrn` AST to TypeScript that targets the framework's
* existing primitives.
*
* state -> a `data-scope` declaration consumed by the runtime
* view -> an HTML string returned by a page component
* @event="..." -> data-on-<event>="..."
* "...{expr}..." -> text kept verbatim ({expr} is mustache for runtime)
* api="<name>" -> SSR/client data binding declared in a mode block
* ssrGet/ssrText -> legacy server-side API fetch + render
* csrGet/csrText -> legacy browser-side API fetch + render
* style -> an inline page stylesheet
* functions -> server-only helpers for API/realtime code
* api M /p {b} -> export const M = async (ctx) => { b }
* realtime {..} -> export const websocket = { evt(ws, ...args) { b } }
*/
declare function generate(ast: PageAst): string;
declare class NativeCompileError extends Error {
constructor(message: string);
}
/** Compile a parsed `.wrn` page to an Expo Router React Native screen. */
declare function generateNative(ast: PageAst): string;
/**
* Lexer for the `.wrn` language.
*
* `.wrn` mixes a small structural grammar (page/state/view/api/realtime) with
* raw JavaScript bodies. A pure token stream can't represent the raw JS, so the
* lexer is driven on demand by the parser: it yields structural tokens via
* `next()`/`peek()`, and exposes `readBalancedBraces()`, `readPath()` and
* `readToLineEnd()` for the parser to grab raw spans when grammar demands it.
*/
type TokenType = "ident" | "string" | "lbrace" | "rbrace" | "lparen" | "rparen" | "at" | "eq" | "comma" | "eof";
interface Token {
type: TokenType;
value: string;
pos: number;
}
declare class LexError extends Error {
}
declare class Lexer {
readonly src: string;
pos: number;
constructor(src: string);
/** Skip whitespace and `// line comments`. */
private skipTrivia;
/** Read and consume the next structural token. */
next(): Token;
/** Look at the next token without consuming it. */
peek(): Token;
private readString;
/** Read a route path like `/users/[id]` up to whitespace or `{`. */
readPath(): string;
/** Read the rest of the current line (used for `state x = <expr>`). */
readToLineEnd(): string;
/**
* Read a `{ ... }` block and return its INNER text (no outer braces), with
* brace counting that respects string and template literals so a `}` inside a
* string doesn't end the block early.
*/
readBalancedBraces(): string;
private lineAt;
}
/**
* @wrnexus/compiler — the `.wrn` language compiler.
*
* Pipeline: source ──▶ Lexer ──▶ parse() ──▶ AST ──▶ generate() ──▶ TypeScript
*
* See VISION.md for the language design. The MVP supports `page` with `state`,
* `view`, `api`, and `realtime` blocks, lowering to the framework's primitives.
*/
interface CompileResult {
code: string;
ast: PageAst;
diagnostics: string[];
}
/** Compile `.wrn` source into an Expo Router React Native screen. */
declare function compileNativeWireFile(source: string): string;
/**
* Compile `.wrn` source into TypeScript source. Throws `ParseError` on invalid
* input (the dev loader surfaces this as a readable error page).
*/
declare function compileWireFile(source: string): string;
/** Richer entry point returning the AST and diagnostics alongside the code. */
declare function compile(source: string): CompileResult;
export { type ApiBlock, type Attr, type CompileResult, type DataApiBlock, type DataMode, LexError, Lexer, type ModeFunctionsBlock, NativeCompileError, type PageAst, ParseError, type RealtimeBlock, type SeoBlock, type StateDecl, type ViewNode, compile, compileNativeWireFile, compileWireFile, generate, generateNative, parse };
Examples
Copy-ready examples taken from this package's published documentation.
Example 1
bun add @wrnexus/compilerExample 2
interface CompileResult {
code: string;
ast: PageAst;
diagnostics: string[];
}Example 3
class Lexer {
pos: number;
constructor(src: string);
next(): Token; // consume next structural token
peek(): Token; // look ahead without consuming
readPath(): string; // route path, e.g. /users/[id]
readToLineEnd(): string; // rest of line (state/prop initializers)
readBalancedBraces(): string; // inner text of a { ... } block, string-aware
}Example 4
import { compileWireFile } from "@wrnexus/compiler";
const ts = compileWireFile(`
page Home {
state count = 0
seo { title = "Home" description = "Welcome" }
view {
<button @click="count++">Clicked {count} times</button>
}
}
`);
// ts is a TypeScript module: exports `meta`, and a default page component
// returning an HTML string, wrapped in a data-scope for the reactive runtime.