From 1dbdb4f4d565160bc71f9789cab07dcf8f267835 Mon Sep 17 00:00:00 2001 From: Ajay Ghanwat Date: Sun, 12 Jul 2026 16:14:06 +0530 Subject: [PATCH] first commit --- .editorconfig | 9 + .gitignore | 3 + .prettierignore | 5 + .prettierrc.json | 9 + CLAUDE.md | 278 +++ README.md | 23 + app/docs.test.ts | 122 ++ app/pages/architecture.wrn | 18 + app/pages/getting-started.wrn | 31 + app/pages/index.wrn | 25 + app/pages/language.wrn | 90 + app/pages/packages.wrn | 94 + app/pages/packages/ai.wrn | 181 ++ app/pages/packages/authz.wrn | 232 +++ app/pages/packages/cli.wrn | 114 ++ app/pages/packages/compiler.wrn | 361 ++++ app/pages/packages/core.wrn | 966 +++++++++++ app/pages/packages/csr.wrn | 234 +++ app/pages/packages/db.wrn | 321 ++++ app/pages/packages/dev-server.wrn | 727 ++++++++ app/pages/packages/encryption.wrn | 113 ++ app/pages/packages/i18n.wrn | 215 +++ app/pages/packages/jwt.wrn | 151 ++ app/pages/packages/mobile.wrn | 76 + app/pages/packages/native.wrn | 55 + app/pages/packages/oauth.wrn | 269 +++ app/pages/packages/pubsub.wrn | 137 ++ app/pages/packages/queue.wrn | 177 ++ app/pages/packages/reactive.wrn | 139 ++ app/pages/packages/router.wrn | 266 +++ app/pages/packages/ssr.wrn | 171 ++ app/pages/packages/styles.wrn | 562 ++++++ app/pages/packages/test.wrn | 176 ++ app/pages/packages/tracking.wrn | 157 ++ app/pages/packages/ui.wrn | 117 ++ app/pages/packages/uploader.wrn | 419 +++++ app/pages/packages/validation.wrn | 316 ++++ app/routes.gen.ts | 53 + app/styles/global.css | 757 ++++++++ bun.lock | 463 +++++ eslint.config.js | 44 + llms.txt | 259 +++ package-lock.json | 2667 +++++++++++++++++++++++++++++ package.json | 55 + public/robots.txt | 2 + public/theme-navigation.js | 9 + scripts/generate-docs.ts | 397 +++++ tsconfig.json | 34 + wrnexus.config.ts | 73 + 49 files changed, 12172 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 .prettierignore create mode 100644 .prettierrc.json create mode 100644 CLAUDE.md create mode 100644 README.md create mode 100644 app/docs.test.ts create mode 100644 app/pages/architecture.wrn create mode 100644 app/pages/getting-started.wrn create mode 100644 app/pages/index.wrn create mode 100644 app/pages/language.wrn create mode 100644 app/pages/packages.wrn create mode 100644 app/pages/packages/ai.wrn create mode 100644 app/pages/packages/authz.wrn create mode 100644 app/pages/packages/cli.wrn create mode 100644 app/pages/packages/compiler.wrn create mode 100644 app/pages/packages/core.wrn create mode 100644 app/pages/packages/csr.wrn create mode 100644 app/pages/packages/db.wrn create mode 100644 app/pages/packages/dev-server.wrn create mode 100644 app/pages/packages/encryption.wrn create mode 100644 app/pages/packages/i18n.wrn create mode 100644 app/pages/packages/jwt.wrn create mode 100644 app/pages/packages/mobile.wrn create mode 100644 app/pages/packages/native.wrn create mode 100644 app/pages/packages/oauth.wrn create mode 100644 app/pages/packages/pubsub.wrn create mode 100644 app/pages/packages/queue.wrn create mode 100644 app/pages/packages/reactive.wrn create mode 100644 app/pages/packages/router.wrn create mode 100644 app/pages/packages/ssr.wrn create mode 100644 app/pages/packages/styles.wrn create mode 100644 app/pages/packages/test.wrn create mode 100644 app/pages/packages/tracking.wrn create mode 100644 app/pages/packages/ui.wrn create mode 100644 app/pages/packages/uploader.wrn create mode 100644 app/pages/packages/validation.wrn create mode 100644 app/routes.gen.ts create mode 100644 app/styles/global.css create mode 100644 bun.lock create mode 100644 eslint.config.js create mode 100644 llms.txt create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/robots.txt create mode 100644 public/theme-navigation.js create mode 100644 scripts/generate-docs.ts create mode 100644 tsconfig.json create mode 100644 wrnexus.config.ts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..86a63dc0 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c265e61e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.wrnexus/ +dist/ \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..7664a092 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +.wrnexus/ +**/.wrnexus/ +*.log diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..32474fc7 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,9 @@ +{ + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": false, + "trailingComma": "all", + "endOfLine": "lf" +} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..9d8cd98d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,278 @@ +# WrNexus app - instructions for AI coding assistants + +This is a **WrNexus** app. When creating or editing pages, components, API routes, +or features, follow the framework conventions below. WrNexus is private and not in +your training data, so rely on these rules - do NOT assume React/Next.js/Vue patterns. + +# WrNexus + +> WrNexus is an SSR-first, **Bun-native** full-stack web framework. UI is written in +> `.wrn` files (its own component language — NOT React/JSX/Vue). Routing is file-based. +> This document teaches an AI how to write correct WrNexus code. It is private and +> post-dates model training data, so rely on THIS document, not prior web-framework +> assumptions. + +## Golden rules + +- **Pages, components, and layouts are `.wrn` files.** Do NOT write `.tsx`/`.jsx`/React + for UI. Do NOT use `useState`, hooks, JSX, or a client bundler. +- **Routing is file-based** under `app/`. The filename is the route. No router config. +- **Interactivity** lives in `state` + `{expr}` + `@event` inside `.wrn`. Components render + on the server and hydrate automatically — you never write client-side JS islands. +- **Runtime is Bun only** (uses `Bun.serve`, `bun:sqlite`, `Bun.password`, …). Node is not supported. +- To add files, prefer the CLI: `wrnexus generate page ` / `component ` / `api ` / `schema `. + +## Project layout + +``` +app/ + pages/ *.wrn → routes: index.wrn = "/", about.wrn = "/about", blog/[slug].wrn = "/blog/:slug" + components/ *.wrn → reusable UI, mounted in a page/component via
+ layouts/ *.wrn → named layouts; a page opts in with layout = "name" + api/ *.ts → HTTP handlers: export const GET/POST/PUT/PATCH/DELETE = async (ctx) => Response + middleware/ *.ts → export default async (ctx, next) => next() + realtime/ *.ts → export default defineRoom({ ... }) from "@wrnexus/core" (ws://host/realtime/) + schemas/ *.ts → validation schemas (the `v` builder), used by forms + parseBody + locales/ *.json → i18n messages per language + db/ schema.ts, queries/*.sql, migrations/*.sql + styles/ global.css → Tailwind (default) or plain CSS +wrnexus.config.ts → app config (AppConfig from "@wrnexus/styles") +public/ → static assets served at / +``` + +## `.wrn` page + +```wrn +page Home { + layout = "public" // optional: a component in app/layouts/.wrn ("none" to skip) + + state count = 0 // optional: seeds client-reactive state (omit for pure SSR) + + seo { + title = "Home" + description = "..." + canonical = "/" + } + + view { +

Hello

+

Count is {count}, doubled is {count * 2}.

+ +
+ } + + style { + h1 { color: var(--wire-color-text); } + } +} +``` + +## `.wrn` component + +```wrn +component Counter { + props { // props come from mount attributes; each is coerced to the + start = 0 // TYPE of its default (so start="5" arrives as the number 5) + label = "Count" + } + state count = start // state may reference props + view { + + } +} +``` + +Mount it from any page/component: `
`. +Components render on the server with their props, then hydrate — no per-component JS. + +## The `view { }` block (plain HTML + a few directives) + +- `{expr}` — interpolate a JS expression. Reactive if it references `state`: `{count}`, `{count * 2}`, `{user.name}`. +- `@event="expr"` — bind a DOM event; the expression runs in the reactive scope: `@click="count++"`, `@input="name = event.target.value"`. +- `
` — mount a component (attrs become string props, coerced). +- `` / `` — component/layout slots; fill with `
`. +- **Server loop (DB/list/table):** `{#each as [, ]} …rows… {:empty} …fallback… {/each}` — iterates SSR data on the server and renders markup per item. `{item.field}` interpolates (HTML-escaped, XSS-safe). `` is a JS expression, usually an `ssr` data binding (see "Data-driven tables" below). This is how you render a database table in `.wrn`. +- **Server conditional:** `{#if } … {:else if } … {:else} … {/if}` — renders the first truthy branch on the server. `` can reference `ssr` data, or the `item`/`index` of an enclosing `{#each}`. Works at page level and inside loops (e.g. `{#if r.active}{:else}{/if}` per row). For client-side show/hide based on reactive `state`, use `data-show="expr"` instead. +- i18n: `{t:home.title}` in text, `t:placeholder="form.name"` on attributes — resolved per request from `app/locales/`. +- Theme: any element with `data-wire-theme-toggle` toggles light/dark; `data-wire-theme-set="dark"` sets it. +- Void/self-closing tags are fine: `
`, ``. +- Only `{` and `}` are special (interpolation). Don't use a bare `}` in view text. + +## Data-driven tables / lists (server-rendered `.wrn`) + +Use an `ssr` data binding to fetch rows on the server, then `{#each}` to render them. +This renders on the **server** (SSR-first) and is HTML-escaped by default. + +```wrn +page Admin { + layout = "dashboard" + + // Fetch on the server. The api handler at /api/contacts returns { contacts: [...] }; + // this block's `return contacts` exposes that array (via `$data`) as the binding `rows`. + ssr { + api rows GET /api/contacts { return contacts } + } + + view { + + + {#each rows as r, i} + + + + + + {:empty} + + {/each} + +
#{i}{r.name}{r.email}
No submissions yet.
+ } +} +``` + +The matching API returns the array under a key the `ssr` block reads: + +```ts +// app/api/contacts.ts → GET /api/contacts +import { getDb } from "@wrnexus/db"; +export const GET = async () => { + const contacts = await getDb().all("SELECT id, name, email FROM contacts ORDER BY id DESC"); + return Response.json({ contacts }); // ssr block does `return contacts` +}; +``` + +**Prefer this `.wrn` + `{#each}` approach for DB-backed tables and lists.** (`.ts`/`.tsx` +pages returning an HTML string are also supported for fully-custom programmatic rendering, +but a `.wrn` page with `ssr` data + `{#each}` is the idiomatic, SSR-first way.) + +## API routes (`app/api/*.ts`) + +```ts +// app/api/users/list.ts → GET /api/users/list +import { getDb } from "@wrnexus/db"; + +export const GET = async (ctx) => { + return Response.json({ users: await ListUsers(getDb()) }); +}; + +export const POST = async (ctx) => { + const body = await ctx.req.json(); + return Response.json({ ok: true, body }, { status: 201 }); +}; +``` + +`ctx` (the `Context` from `@wrnexus/core`) has: +`req: Request`, `url: URL`, `params: Record` (dynamic route params, e.g. `/users/[id]` → `ctx.params.id`), +`lang: string`, `t(key, params?)` (i18n), `cookies` (get/set), `session` (get/set). Auth: `getUser(ctx)` after `sessionAuth`/`logIn`. + +## Middleware & realtime + +```ts +// app/middleware/logger.ts +export default async function logger(ctx, next) { + console.log(ctx.req.method, ctx.url.pathname); + return next(); // return a Response WITHOUT calling next() to short-circuit +} +``` + +```ts +// app/realtime/chat.ts → ws://host/realtime/chat +import { defineRoom } from "@wrnexus/core"; +export default defineRoom({ + onConnect(client) { + client.send({ type: "system", text: "connected" }); + }, + onMessage(client, msg) { + client.room.broadcast({ type: "message", data: msg }); + }, +}); +``` + +Client side: a page opts in with `data-room="chat"` (handled by the realtime runtime). + +## Config (`wrnexus.config.ts`) + +```ts +import type { AppConfig } from "@wrnexus/styles"; +const config: AppConfig = { + seo: { title: "App", titleTemplate: "%s | App", description: "..." }, + styles: { + entry: "app/styles/global.css", + process: async ({ entryPath, mode }) => /* Tailwind */ "", + }, + fonts: { + sans: '"Inter", system-ui, sans-serif', + google: [{ family: "Inter", weights: [400, 600] }], + }, + theme: { default: "dark", themes: { light: { "color-primary": "#2563eb" } } }, + i18n: { default: "en", locales: ["en", "es"] }, + db: { driver: "sqlite", url: "file:./dev.db" }, + security: { cors: { enabled: true, origin: ["http://localhost:5173"] } }, + // profiles: { production: { db: { driver: "postgres", url: process.env.DATABASE_URL } } }, +}; +export default config; +``` + +## Database (`@wrnexus/db`) + +```ts +// app/db/schema.ts +import { v, table } from "@wrnexus/db"; +export const users = table("users", { + id: v.id(), + name: v.string(), + email: v.string().unique(), + createdAt: v.timestamp(), +}); +``` + +- Queries: write `app/db/queries/*.sql` with `-- name: ListUsers :many` blocks; `wrnexus db generate` emits typed functions. +- Access at runtime: `import { getDb } from "@wrnexus/db"; const rows = await ListUsers(getDb());` +- Migrations in `app/db/migrations/`; run `wrnexus db migrate` (dev auto-migrates sqlite). + +## Validation (`@wrnexus/validation`) + +```ts +// app/schemas/login.ts +import { v } from "@wrnexus/validation"; +export default v.object({ + email: v.string().email(), + password: v.string().min(8), +}); +``` + +In an API route: `import s from "../schemas/login"; import { parseBody } from "@wrnexus/validation"; const r = await parseBody(s, ctx.req);` → `r.ok ? r.value : r.response`. +In a form: `
` + `` (client + server validation wired automatically). + +## AI / LLM (`@wrnexus/ai`) + +```ts +// app/api/ai.ts +import { createAI } from "@wrnexus/ai"; +const ai = createAI(); // reads ANTHROPIC_API_KEY; default model claude-opus-4-8 +export const POST = async (ctx) => { + const { prompt } = await ctx.req.json(); + return ai.streamResponse(prompt); // or: return Response.json({ text: await ai.generate(prompt) }) +}; +``` + +## CLI + +``` +wrnexus dev . # dev server + HMR +wrnexus build . # production build → dist/server.js +wrnexus create # scaffold a new app +wrnexus generate page # scaffold a page (aliases: g p) +wrnexus generate component | api | schema +wrnexus db migrate | rollback | status | new [--from-models] | generate | seed +wrnexus eject # copy a Wire UI component's .wrn into app/components to customize +``` + +## When asked to "create a page/component/feature" + +1. Create the `.wrn` file under `app/pages/` (or `app/components/`) with a `page`/`component` block — or run `wrnexus generate page `. +2. Put markup in `view { }`, interactive bits in `state` + `{expr}` + `@event`, reusable UI as components mounted via `data-component`. +3. For data, add an `app/api/*.ts` route and `getDb()`; for forms, add an `app/schemas/*.ts` and `data-schema`. +4. Style with Tailwind utility classes in the view, or theme tokens (`var(--wire-*)`), or `style { }`. +5. Never emit React/JSX, a manual router, or client-side island JS — the framework handles hydration. diff --git a/README.md b/README.md new file mode 100644 index 00000000..363e50d0 --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# WRNexusJS Documentation + +Standalone documentation site for all 25 private `@wrnexus/*` packages at version `0.2.12`. + +## Development + +```bash +bun install +bun run docs:generate +bun run dev +``` + +Package pages are generated from the installed package README and TypeScript declarations, so the documentation stays aligned with the published release. + +## Verification and production + +```bash +bun run check +bun run build +bun dist/server.js +``` + +The site includes searchable package discovery, complete API declarations, installation commands, usage guides, responsive styling, dark mode, SEO metadata, PWA configuration, and WRNexusJS production security headers. diff --git a/app/docs.test.ts b/app/docs.test.ts new file mode 100644 index 00000000..0e2af42c --- /dev/null +++ b/app/docs.test.ts @@ -0,0 +1,122 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { compileWireFile } from "@wrnexus/compiler"; +import { mountHtml } from "@wrnexus/test"; + +const root = join(import.meta.dir, ".."); +const packagePages = join(root, "app", "pages", "packages"); +const expected = [ + "ai", + "authz", + "cli", + "compiler", + "core", + "csr", + "db", + "dev-server", + "encryption", + "i18n", + "jwt", + "mobile", + "native", + "oauth", + "pubsub", + "queue", + "reactive", + "router", + "ssr", + "styles", + "test", + "tracking", + "ui", + "uploader", + "validation", +]; + +test("generates one detailed page for every published package", () => { + const generated = readdirSync(packagePages) + .filter((file) => file.endsWith(".wrn")) + .map((file) => file.replace(/\.wrn$/, "")) + .sort(); + expect(generated).toEqual([...expected].sort()); +}); + +test("every package page contains installation, guide, and complete API sections", () => { + for (const name of expected) { + const source = readFileSync(join(packagePages, `${name}.wrn`), "utf8"); + expect(source).toContain(`bun add @wrnexus/${name}@0.2.12`); + expect(source).toContain('id="guide"'); + expect(source).toContain('id="api"'); + expect(source).toContain("Complete TypeScript API"); + expect(source).toContain('class="on-this-page"'); + expect(source).toContain('id="examples"'); + expect(source).toContain('class="example-card"'); + } +}); + +test("site includes core guides and production configuration", () => { + for (const route of [ + "index.wrn", + "packages.wrn", + "getting-started.wrn", + "language.wrn", + "architecture.wrn", + ]) { + expect(existsSync(join(root, "app", "pages", route))).toBe(true); + } + expect(readFileSync(join(root, "wrnexus.config.ts"), "utf8")).toContain( + "WRNexusJS Documentation", + ); +}); + +test("language reference covers directives, events, loops, and conditionals", () => { + const source = readFileSync(join(root, "app", "pages", "language.wrn"), "utf8"); + for (const section of [ + "events", + "directives", + "conditionals", + "loops", + "components", + "forms", + "realtime", + "native", + ]) { + expect(source).toContain(`id="${section}"`); + } + expect(source).toContain("data-show"); + expect(source).toContain("@mobile-click"); +}); + +test("package index includes searchable category filters", () => { + const source = readFileSync(join(root, "app", "pages", "packages.wrn"), "utf8"); + expect(source).toContain('state category = "All"'); + expect(source).toContain("category = 'Security'"); + expect(source).toContain("category = 'Native'"); + expect(source).toContain("category === 'All'"); + expect(source).not.toContain("category === 'All' ||"); + expect(source).not.toContain(") && (query"); + expect(source.match(/class="package-card"/g)).toHaveLength(25); +}); + +test("clicking a category hides packages from other categories", async () => { + const source = readFileSync(join(root, "app", "pages", "packages.wrn"), "utf8"); + const directory = join(tmpdir(), "wrnexus-doc-tests"); + mkdirSync(directory, { recursive: true }); + const modulePath = join(directory, `packages-${Date.now()}.ts`); + writeFileSync(modulePath, compileWireFile(source)); + const page = (await import(pathToFileURL(modulePath).href)).default as () => string; + const mounted = mountHtml(page()); + const dataButton = mounted + .querySelectorAll(".category-row button") + .find((button) => button.textContent?.startsWith("Data")); + expect(dataButton).toBeDefined(); + (dataButton as HTMLElement).click(); + const visible = mounted + .querySelectorAll(".package-card") + .filter((card) => (card as HTMLElement).style.display !== "none") + .map((card) => card.getAttribute("href")); + expect(visible).toEqual(["/packages/db", "/packages/queue", "/packages/uploader"]); +}); diff --git a/app/pages/architecture.wrn b/app/pages/architecture.wrn new file mode 100644 index 00000000..890cc0cb --- /dev/null +++ b/app/pages/architecture.wrn @@ -0,0 +1,18 @@ +page Architecture { + seo { + title = "Architecture" + description = "Understand the WRNexusJS SSR, compiler, runtime, and package architecture." + } + + view { +
+
+ W WRNexusJS + + +
+
Concepts

Architecture

WRNexusJS separates server work, generated markup, and browser behavior so applications stay understandable and efficient.

Request path

Request → Router → Middleware → Page/API → SSR document → Browser runtime

Compiler

The compiler parses .wrn files and lowers state, events, interpolation, loops, conditionals, data bindings, components, and styles into server modules and small declarative browser directives.

Runtime

The server owns routing, data, secrets, sessions, validation, uploads, and rendering. The browser owns reactive scopes, navigation, forms, realtime clients, and native capability dispatch.

Package boundaries

Each package is independently installable. Start with the CLI and core, then add database, security, realtime, native, UI, and operational packages as required.

+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/getting-started.wrn b/app/pages/getting-started.wrn new file mode 100644 index 00000000..0fe789d8 --- /dev/null +++ b/app/pages/getting-started.wrn @@ -0,0 +1,31 @@ +page Gettingstarted { + seo { + title = "Getting started" + description = "Getting started with WRNexusJS" + } + + view { +
+
+ W WRNexusJS + + +
+
Guide

Getting started

Create a production-ready WRNexusJS application with Bun.

1. Create the project

bunx @wrnexus/cli create my-app
+cd my-app
+bun install
+bun run dev

2. Add a page

page Dashboard {
+  state count = 0
+  view {
+    <main>
+      <h1>Dashboard</h1>
+      <button @click="count++">{count}</button>
+    </main>
+  }
+}

3. Verify and build

wrnexus doctor
+wrnexus test
+wrnexus build

Where things live

  • app/pages contains routes.
  • app/components contains reusable .wrn components.
  • app/api contains server API handlers.
  • app/layouts contains shared shells.
  • app/middleware contains request middleware.
  • wrnexus.config.ts configures security, styles, data, mobile, and deployment.
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/index.wrn b/app/pages/index.wrn new file mode 100644 index 00000000..45d3de2a --- /dev/null +++ b/app/pages/index.wrn @@ -0,0 +1,25 @@ +page Home { + seo { + title = "Home" + description = "WRNexusJS documentation: build secure, server-rendered, reactive applications with Bun." + } + + view { +
+
+ W WRNexusJS + + +
+
WRNexusJS 0.2.12

Build from the server.
Ship only what matters.

An SSR-first, Bun-native framework with reactive .wrn components, typed data, realtime rooms, mobile capabilities, and production security built in.

app/pages/counter.wrn
page Counter {
+  state count = 0
+  view {
+    <button @click="count++">
+      Count {count}
+    </button>
+  }
+}

SSR by default

Useful HTML reaches the browser immediately. Interactive pages hydrate only the runtime they use.

Secure foundations

CSP, Trusted Types, CSRF, sessions, validation, authorization, encryption, and safe rendering are integrated.

Web to native

Share markup through Capacitor or compile portable pages into Expo and React Native routes.

+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/language.wrn b/app/pages/language.wrn new file mode 100644 index 00000000..2f0b4e92 --- /dev/null +++ b/app/pages/language.wrn @@ -0,0 +1,90 @@ +page Languageanddirectives { + seo { + title = "Language and directives" + description = "Complete WRNexusJS language reference for events, directives, loops, conditionals, data, components, forms, realtime, and native behavior." + } + + view { +
+
+ W WRNexusJS + + +
+
Complete reference

Language and directives

This page documents the .wrn language and declarative browser features that span multiple packages.

+

File anatomy

A file declares a page or component and can contain metadata, props, state, data, view, style, server functions, APIs, and realtime handlers.

page Dashboard {
+  layout = "default"
+  seo { title = "Dashboard" }
+  state count = 0
+  view { <button @click="count++">{count}</button> }
+  style { button { padding: 12px; } }
+}
+

State and interpolation

State is scoped to the nearest generated data-scope. Text expressions update reactively after hydration.

state count = 0
+state user = { name: "Ada" }
+
+view {
+  <p>Count: {count}</p>
+  <p>{user.name}</p>
+}
+

Events

Any DOM event can use @event="statement". The compiler emits data-on-event. The expression receives event and can mutate state.

SyntaxPurpose
@clickPointer or keyboard activation.
@inputRead live field values.
@changeReact to committed field changes.
@submitHandle form submission behavior.
@browser-clickRun only in a browser target.
@mobile-clickRun only in a native/mobile target.
<input @input="name = event.target.value">
+<button @click="count++">Add</button>
+<form @submit="submitted = true">...</form>
+

Reactive data attributes

DirectiveBehavior
data-scopeDeclares reactive state for a subtree.
data-textSynchronizes textContent with an expression.
data-showShows or hides an element by truthiness.
data-forRepeats an element for a client-side list.
data-on-<event>Compiled form of an event binding.
data-componentMounts a server-rendered component.
data-slotFills a named component or layout slot.
data-wrnexus-csrConnects generated client data fetching.
+

Conditional rendering

Server conditionals

Server blocks render only the selected branch into the response.

{#if user.isAdmin}
+  <a href="/admin">Admin</a>
+{:else if user}
+  <p>Welcome {user.name}</p>
+{:else}
+  <a href="/login">Sign in</a>
+{/if}

Client visibility

<section data-show="open">Visible while open is true</section>
+

Loops and lists

Server each block

{#each users as user, i}
+  <p>{i + 1}. {user.name}</p>
+{:empty}
+  <p>No users</p>
+{/each}

Reactive client loop

<li data-for="item, i in items">
+  <span data-text="item.name"></span>
+  <button data-on-click="items = items.filter(x => x !== item)">Remove</button>
+</li>
+

Components, props, and slots

component Card {
+  props { title = "Card" }
+  view {
+    <article><h2>{title}</h2><slot></slot></article>
+  }
+}
+
+<div data-component="card" title="Profile">
+  <p>Card content</p>
+</div>
+

Server and client data

Use named data bindings for SSR data or client hydration. Secrets and database work stay on the server.

data users {
+  ssr GET "/api/users"
+}
+
+view {
+  {#each users as user}<p>{user.name}</p>{/each}
+}
+

Forms and validation

Schema-backed forms validate in the browser and on the server with the same descriptor.

<form data-schema="login" method="post" action="/api/login" data-redirect="/dashboard">
+  <input name="email" type="email">
+  <span data-error="email"></span>
+  <button>Sign in</button>
+  <p data-success="Signed in" hidden></p>
+</form>
+

Internationalization and themes

<h1>{t:home.title}</h1>
+<button data-wire-lang-set="fr">Français</button>
+<button data-wire-theme-toggle>Toggle theme</button>
+<button data-wire-theme-set="dark">Dark</button>
+

Realtime rooms

<div data-room="chat" data-room-user="Ada">
+  <span data-room-status></span>
+  <div data-room-log></div>
+  <template data-room-item="message"><p>%user%: %text%</p></template>
+  <form data-room-send><input name="text" data-room-reset></form>
+</div>
+

Browser and native directives

<button data-native-browser="share" data-native-mobile="share"
+        data-native-options='{"title":"WRNexusJS"}'>Share</button>
+<nav data-native-only="mobile">Mobile navigation</nav>
+<p data-native-only="browser">Browser instructions</p>
+<button data-native-requires="haptics">Haptic action</button>
+

Other framework attributes

AttributePurpose
data-errorField validation error destination.
data-successSuccessful form message.
data-redirectNavigation after form success.
data-room-*Realtime status, templates, sending, and reset behavior.
data-uploaderConfig-driven upload widget.
data-wire-theme-*Theme selection and toggling.
data-wire-lang*Language selection.
data-native-*Cross-platform capability and visibility behavior.
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages.wrn b/app/pages/packages.wrn new file mode 100644 index 00000000..611196a3 --- /dev/null +++ b/app/pages/packages.wrn @@ -0,0 +1,94 @@ +page Packages { + seo { + title = "Packages" + description = "Explore every WRNexusJS package, API, function, and copy-ready usage example." + } + state query = "" + state category = "All" + + view { +
+
+ W WRNexusJS + + +
+
25 focused packages

Package reference

Everything in the framework, organized by responsibility and documented from the published 0.2.12 APIs.

Showing {category} packages

+ AI

@wrnexus/ai

Server-side Anthropic client with generation and streaming.

Open documentation → +
+ + Security

@wrnexus/authz

Role, permission, policy, and authorization guards.

Open documentation → +
+ + Tooling

@wrnexus/cli

Create, develop, build, generate, test, and maintain WRNexusJS apps.

Open documentation → +
+ + Core

@wrnexus/compiler

Parser and code generators for the .wrn language.

Open documentation → +
+ + Core

@wrnexus/core

Contexts, middleware, security, sessions, caching, JSX, and realtime.

Open documentation → +
+ + Frontend

@wrnexus/csr

Reactive, navigation, and realtime browser runtimes.

Open documentation → +
+ + Data

@wrnexus/db

Database adapters, typed queries, models, migrations, and sessions.

Open documentation → +
+ + Runtime

@wrnexus/dev-server

Development and production servers, HMR, assets, and gateways.

Open documentation → +
+ + Security

@wrnexus/encryption

Hashing, HMAC, authenticated encryption, and key derivation.

Open documentation → +
+ + Frontend

@wrnexus/i18n

Translation loading, locale resolution, and Intl formatting.

Open documentation → +
+ + Security

@wrnexus/jwt

HS256 JWT signing, verification, and bearer authentication.

Open documentation → +
+ + Native

@wrnexus/mobile

SSR-safe compatibility access to Capacitor plugins.

Open documentation → +
+ + Native

@wrnexus/native

Cross-platform browser and Capacitor capability registry.

Open documentation → +
+ + Security

@wrnexus/oauth

OAuth 2.0, PKCE, provider presets, and profile mapping.

Open documentation → +
+ + Realtime

@wrnexus/pubsub

In-process and Redis-backed publish/subscribe.

Open documentation → +
+ + Data

@wrnexus/queue

Background jobs with delay, concurrency, retry, and repetition.

Open documentation → +
+ + Frontend

@wrnexus/reactive

Small type-safe reactive signal primitives.

Open documentation → +
+ + Core

@wrnexus/router

Filesystem discovery, route matching, and typed route generation.

Open documentation → +
+ + Runtime

@wrnexus/ssr

Secure HTML document rendering and SEO metadata.

Open documentation → +
+ + Frontend

@wrnexus/styles

CSS pipeline, themes, fonts, profiles, and application config.

Open documentation → +
+ + Tooling

@wrnexus/test

WRNexusJS-aware component, route, and browser testing utilities.

Open documentation → +
+ + Runtime

@wrnexus/tracking

Error/event capture, middleware, filtering, and sinks.

Open documentation → +
+ + Frontend

@wrnexus/ui

Themeable server-rendered UI components and CSS.

Open documentation → +
+ + Data

@wrnexus/uploader

Validated local/S3 uploads and secure file serving.

Open documentation → +
+ + Security

@wrnexus/validation

Typed schemas, coercion, validation, and browser descriptors.

Open documentation → +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/ai.wrn b/app/pages/packages/ai.wrn new file mode 100644 index 00000000..530f1170 --- /dev/null +++ b/app/pages/packages/ai.wrn @@ -0,0 +1,181 @@ +page wrnexusai { + seo { + title = "@wrnexus/ai" + description = "Server-side Anthropic client with generation and streaming." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
AI

@wrnexus/ai

Server-side Anthropic client with generation and streaming.

bun add @wrnexus/ai@0.2.12
A tiny, zero-dependency Claude (Anthropic) client for WRNexusJS apps — generate and stream text with Claude from any server-side code.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/ai is a thin, dependency-free wrapper over the Anthropic Messages API, built on fetch (Bun-native, no SDK). Use it in API routes, jobs, or middleware to call Claude. It defaults to the most capable model, claude-opus-4-8, reads your key from ANTHROPIC_API_KEY, and supports both one-shot generation and streaming.

+

Installation

+
bun add @wrnexus/ai
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

Set your key in the environment (e.g. .env):

+
ANTHROPIC_API_KEY=sk-ant-...
+

API

+

createAI(config?)

+

Creates a client. The key is read at call time, so it's safe to create at import.

+
import { createAI } from "@wrnexus/ai";
+const ai = createAI(); // or createAI({ apiKey, model, maxTokens, baseURL, version })
+

AIConfig fields (all optional):

+
+ +
FieldDefaultDescription
apiKeyANTHROPIC_API_KEYAnthropic API key
model"claude-opus-4-8"Model id
maxTokens4096Default max output tokens
baseURLhttps://api.anthropic.comAPI base URL
version"2023-06-01"anthropic-version header
+

ai.generate(prompt, opts?): Promise<string>

+

One-shot text generation. prompt is a string or a Message[] history.

+
const text = await ai.generate("Write a haiku about Bun.");
+
+const reply = await ai.generate(
+  [
+    { role: "user", content: "My name is Ada." },
+    { role: "assistant", content: "Hi Ada!" },
+    { role: "user", content: "What's my name?" },
+  ],
+  { system: "You are concise." },
+);
+

ai.stream(prompt, opts?): AsyncGenerator<string>

+

Yields text deltas as they arrive.

+
for await (const chunk of ai.stream("Tell me a story.")) {
+  process.stdout.write(chunk);
+}
+

ai.streamResponse(prompt, opts?): Response

+

Returns a streaming text/plain Response — drop it straight into an API route.

+
// app/api/chat.ts
+import { createAI } from "@wrnexus/ai";
+const ai = createAI();
+
+export const POST = async (ctx) => {
+  const { prompt } = await ctx.req.json();
+  return ai.streamResponse(prompt);
+};
+

GenerateOptions

+
+ +
OptionTypeDescription
systemstringSystem prompt
modelstringOverride the model for this call
maxTokensnumberOverride max output tokens
thinkingbooleanEnable adaptive extended thinking (deeper reasoning)
effort`"low" \"medium" \"high" \"xhigh" \"max"`Reasoning effort / token spend
messagesMessage[]Full history — supersedes prompt
signalAbortSignalCancel the request
+
temperature / top_p are intentionally not exposed — the current Claude
+
models reject them (400). Steer output with prompting instead.
+

AIError

+

Thrown on non-2xx responses or a model refusal. Carries .status and .type (e.g. "authentication_error", "rate_limit_error", "refusal").

+
import { AIError } from "@wrnexus/ai";
+try {
+  await ai.generate("...");
+} catch (e) {
+  if (e instanceof AIError && e.type === "rate_limit_error") {
+    /* back off */
+  }
+}
+

Usage

+
// app/api/summarize.ts — summarize posted text
+import { createAI } from "@wrnexus/ai";
+const ai = createAI();
+
+export const POST = async (ctx) => {
+  const { text } = await ctx.req.json().catch(() => ({}));
+  if (!text) return Response.json({ error: "Provide 'text'." }, { status: 400 });
+  const summary = await ai.generate(`Summarize in one sentence:\n\n${text}`, {
+    system: "You are a precise summarizer.",
+  });
+  return Response.json({ summary });
+};
+

Requirements / Notes

+
    +
  • Bun-only. Uses fetch, ReadableStream, TextDecoder/TextEncoder, and
  • +

    reads ANTHROPIC_API_KEY from Bun.env (falls back to process.env).

    +
  • Zero dependencies — no @anthropic-ai/sdk; talks to the Messages API directly.
  • +
  • Defaults to claude-opus-4-8. Pass { model } for a different model (e.g.
  • +

    "claude-sonnet-5" for speed/cost, "claude-haiku-4-5" for the fastest).

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/ai — a tiny, zero-dependency Claude (Anthropic) client for WRNexusJS apps.
+ *
+ * Use it in API routes, jobs, or anywhere server-side to generate text with Claude.
+ * It talks to the Anthropic Messages API over `fetch` (no SDK dependency, Bun-native),
+ * and defaults to the most capable model, `claude-opus-4-8`.
+ *
+ *   import { createAI } from "@wrnexus/ai";
+ *   const ai = createAI();                       // reads ANTHROPIC_API_KEY
+ *   const text = await ai.generate("Write a haiku about Bun.");
+ *
+ * Streaming (great for API routes):
+ *   export const POST = async (ctx) => ai.streamResponse(await ctx.req.text());
+ */
+type Role = "user" | "assistant";
+interface Message {
+    role: Role;
+    content: string;
+}
+/** Reasoning effort — higher means deeper thinking + more tokens. */
+type Effort = "low" | "medium" | "high" | "xhigh" | "max";
+interface AIConfig {
+    /** Anthropic API key. Default: `ANTHROPIC_API_KEY` from the environment. */
+    apiKey?: string;
+    /** Model id. Default: `claude-opus-4-8` (the most capable Claude model). */
+    model?: string;
+    /** Default max output tokens. Default: 4096. */
+    maxTokens?: number;
+    /** API base URL. Default: `https://api.anthropic.com`. */
+    baseURL?: string;
+    /** `anthropic-version` header. Default: `2023-06-01`. */
+    version?: string;
+}
+interface GenerateOptions {
+    /** System prompt — sets the assistant's role/behavior. */
+    system?: string;
+    /** Override the model for this call. */
+    model?: string;
+    /** Override max output tokens for this call. */
+    maxTokens?: number;
+    /** Enable adaptive extended thinking (slower, deeper reasoning). */
+    thinking?: boolean;
+    /** Reasoning effort / token spend (`output_config.effort`). */
+    effort?: Effort;
+    /** Full message history — supersedes the `prompt` argument when provided. */
+    messages?: Message[];
+    /** Abort the request. */
+    signal?: AbortSignal;
+}
+/** Thrown when the API returns a non-2xx response or refuses the request. */
+declare class AIError extends Error {
+    readonly status: number;
+    readonly type: string;
+    constructor(message: string, status?: number, type?: string);
+}
+interface AI {
+    /** Generate a full text response (non-streaming). */
+    generate(prompt: string | Message[], opts?: GenerateOptions): Promise<string>;
+    /** Stream the response as text deltas, as they arrive. */
+    stream(prompt: string | Message[], opts?: GenerateOptions): AsyncGenerator<string, void, unknown>;
+    /** Stream straight to a `Response` (text/plain) — drop-in for an API route return. */
+    streamResponse(prompt: string | Message[], opts?: GenerateOptions): Response;
+}
+/** Create a Claude client. Reads `ANTHROPIC_API_KEY` from the environment by default. */
+declare function createAI(config?: AIConfig): AI;
+
+export { type AI, type AIConfig, AIError, type Effort, type GenerateOptions, type Message, type Role, createAI };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/ai

Example 2

ANTHROPIC_API_KEY=sk-ant-...

Example 3

import { createAI } from "@wrnexus/ai";
+const ai = createAI(); // or createAI({ apiKey, model, maxTokens, baseURL, version })

Example 4

const text = await ai.generate("Write a haiku about Bun.");
+
+const reply = await ai.generate(
+  [
+    { role: "user", content: "My name is Ada." },
+    { role: "assistant", content: "Hi Ada!" },
+    { role: "user", content: "What's my name?" },
+  ],
+  { system: "You are concise." },
+);
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/authz.wrn b/app/pages/packages/authz.wrn new file mode 100644 index 00000000..e49ab3b4 --- /dev/null +++ b/app/pages/packages/authz.wrn @@ -0,0 +1,232 @@ +page wrnexusauthz { + seo { + title = "@wrnexus/authz" + description = "Role, permission, policy, and authorization guards." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Security

@wrnexus/authz

Role, permission, policy, and authorization guards.

bun add @wrnexus/authz@0.2.12
Composable authorization for WRNexusJS — role-based (RBAC), policy-based (PBAC), and attribute-based (ABAC) access control that reduces to a boolean check plus an authorize() guard.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/authz is a small, server-side authorization toolkit. It gives you three interchangeable models — RBAC (roles → permissions), PBAC (policy predicates), and ABAC (attribute matchers) — that all collapse to a boolean | Promise<boolean> decision. Wrap any decision in a Middleware guard (authorize, requireRole, requirePermission) to protect WRNexusJS routes. Reach for it whenever a route or action needs to be gated on who the user is, what roles they hold, or attributes of the user and the resource. It plugs into @wrnexus/core by reading ctx.user as the authorization subject.

+

Installation

+
bun add @wrnexus/authz
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The package has a single entry point (@wrnexus/authz) exporting the following.

+

Types

+
+ +
SymbolDescription
SubjectThe authorized principal: { id?: string; roles?: string[]; [attribute: string]: unknown }.
RbacAn RBAC checker: { can(subject, permission): boolean; permissionsFor(roles): Set<string> }.
Policy<S = Subject, R = unknown>A predicate `(subject: S, resource?: R) => boolean \Promise<boolean>`.
+

RBAC

+

defineRbac(roles: Record<string, string[]>): Rbac

+

Builds an RBAC checker from a role → permissions map. Supported permission forms:

+
    +
  • "*" — grants every permission.
  • +
  • "ns:*" — namespace wildcard (e.g. "post:*" grants "post:write").
  • +
  • "role:<name>" — inherits all permissions of another role (resolved recursively, cycle-safe).
  • +
+

The returned Rbac provides:

+
    +
  • can(subject, permission)true if any of subject.roles grants permission (honouring * and namespace wildcards). Returns false when the subject has no roles.
  • +
  • permissionsFor(roles) — the resolved Set<string> of all permissions granted to a set of roles.
  • +
+

hasRole(subject: Subject | undefined, ...required: string[]): boolean

+

true if the subject holds all of the given roles.

+

PBAC / ABAC combinators

+
    +
  • any<S, R>(...policies: Policy<S, R>[]): Policy<S, R> — allow if any policy passes (OR); awaits async policies.
  • +
  • all<S, R>(...policies: Policy<S, R>[]): Policy<S, R> — allow only if all policies pass (AND); awaits async policies.
  • +
  • attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S> — ABAC helper that allows when subject[name] equals match, or when match is a function, when match(value) is truthy.
  • +
+

Guards (middleware)

+

Each guard returns a @wrnexus/core Middleware. A denied request short-circuits with Response.json({ ok: false, error: "Forbidden" }, { status: 403 }).

+
    +
  • authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware — runs policy against the request Context; calls next() when it resolves truthy, otherwise returns 403.
  • +
  • requireRole(...roles: string[]): Middleware — allows when ctx.user holds any of the listed roles.
  • +
  • requirePermission(rbac: Rbac, permission: string): Middleware — allows when rbac.can(ctx.user, permission) is true.
  • +
+

Usage

+

RBAC

+
import { defineRbac, hasRole } from "@wrnexus/authz";
+
+const rbac = defineRbac({
+  admin: ["*"],
+  editor: ["post:read", "post:write"],
+  viewer: ["post:read"],
+  // role inheritance: lead gets everything an editor has, plus post:publish
+  lead: ["role:editor", "post:publish"],
+});
+
+const user = { id: "u1", roles: ["editor"] };
+
+rbac.can(user, "post:write"); // true
+rbac.can(user, "post:delete"); // false
+rbac.permissionsFor(["lead"]); // Set { "post:read", "post:write", "post:publish" }
+hasRole(user, "editor"); // true
+

Guarding routes

+
import { authorize, requireRole, requirePermission, defineRbac } from "@wrnexus/authz";
+
+const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
+
+// Only admins or editors
+app.get("/dashboard", requireRole("admin", "editor"), handler);
+
+// Requires a specific permission
+app.post("/posts", requirePermission(rbac, "post:write"), handler);
+
+// Arbitrary policy over the request context
+app.delete(
+  "/posts/:id",
+  authorize((ctx) => hasRole(ctx.user, "admin")),
+  handler,
+);
+

PBAC / ABAC policies

+
import { any, all, attr, authorize, type Policy } from "@wrnexus/authz";
+
+interface User {
+  id: string;
+  department?: string;
+  roles?: string[];
+}
+interface Post {
+  authorId: string;
+}
+
+// Ownership policy (subject + resource)
+const ownsPost: Policy<User, Post> = (u, post) => u.id === post?.authorId;
+
+// ABAC: attribute equality, or a predicate
+const inEngineering = attr<User>("department", "engineering");
+const isVerified = attr<User>("verified", (v) => v === true);
+
+// Compose: allow if the user owns the post OR is in engineering AND verified
+const canEdit = any(ownsPost, all(inEngineering, isVerified));
+
+app.put(
+  "/posts/:id",
+  authorize((ctx) => canEdit(ctx.user as User, loadPost(ctx))),
+  handler,
+);
+

Requirements / Notes

+
    +
  • Bun-only — like the rest of WRNexusJS, this package targets the Bun runtime; Node is not supported.
  • +
  • Works with [@wrnexus/core](../core) — the guards return Middleware and read the subject from ctx.user on the request Context. Both types are imported from @wrnexus/core.
  • +
  • Policy combinators (any, all) and authorize are async-aware, so policies may return a Promise<boolean> (e.g. for a database ownership check).
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Context, Middleware } from '@wrnexus/core';
+
+/**
+ * @wrnexus/authz — authorization: role-based (RBAC), policy-based (PBAC), and
+ * attribute-based (ABAC). Compose freely; all three reduce to a boolean check
+ * plus an `authorize()` guard middleware.
+ *
+ *   const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
+ *   rbac.can(user, "post:write");
+ *
+ *   // PBAC/ABAC: a policy is a predicate over subject + resource + attributes
+ *   const ownsPost: Policy<User, Post> = (u, post) => u.id === post.authorId;
+ *   authorize((ctx) => ownsPost(ctx.user, resource))  // middleware
+ */
+
+interface Subject {
+    id?: string;
+    roles?: string[];
+    [attribute: string]: unknown;
+}
+interface Rbac {
+    /** True if any of the subject's roles grants `permission` (supports "*" and "ns:*"). */
+    can(subject: Subject | undefined, permission: string): boolean;
+    /** All permissions granted to a set of roles. */
+    permissionsFor(roles: string[]): Set<string>;
+}
+/** Build an RBAC checker from a role → permissions map. */
+declare function defineRbac(roles: Record<string, string[]>): Rbac;
+/** True if the subject has ALL of the given roles. */
+declare function hasRole(subject: Subject | undefined, ...required: string[]): boolean;
+/** A policy predicate: subject (+ optional resource/attributes) → allowed. */
+type Policy<S = Subject, R = unknown> = (subject: S, resource?: R) => boolean | Promise<boolean>;
+/** Combine policies: allow if ANY passes (OR). */
+declare function any<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
+/** Combine policies: allow only if ALL pass (AND). */
+declare function all<S, R>(...policies: Policy<S, R>[]): Policy<S, R>;
+/** ABAC helper: allow when an attribute matches (equality or predicate). */
+declare function attr<S extends Subject>(name: string, match: unknown | ((value: unknown) => boolean)): Policy<S>;
+/** Guard a route with a policy over `ctx` (reads `ctx.user` as the subject). */
+declare function authorize(policy: (ctx: Context) => boolean | Promise<boolean>): Middleware;
+/** Guard requiring one of the given roles. */
+declare function requireRole(...roles: string[]): Middleware;
+/** Guard requiring an RBAC permission. */
+declare function requirePermission(rbac: Rbac, permission: string): Middleware;
+
+export { type Policy, type Rbac, type Subject, all, any, attr, authorize, defineRbac, hasRole, requirePermission, requireRole };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/authz

Example 2

import { defineRbac, hasRole } from "@wrnexus/authz";
+
+const rbac = defineRbac({
+  admin: ["*"],
+  editor: ["post:read", "post:write"],
+  viewer: ["post:read"],
+  // role inheritance: lead gets everything an editor has, plus post:publish
+  lead: ["role:editor", "post:publish"],
+});
+
+const user = { id: "u1", roles: ["editor"] };
+
+rbac.can(user, "post:write"); // true
+rbac.can(user, "post:delete"); // false
+rbac.permissionsFor(["lead"]); // Set { "post:read", "post:write", "post:publish" }
+hasRole(user, "editor"); // true

Example 3

import { authorize, requireRole, requirePermission, defineRbac } from "@wrnexus/authz";
+
+const rbac = defineRbac({ admin: ["*"], editor: ["post:read", "post:write"] });
+
+// Only admins or editors
+app.get("/dashboard", requireRole("admin", "editor"), handler);
+
+// Requires a specific permission
+app.post("/posts", requirePermission(rbac, "post:write"), handler);
+
+// Arbitrary policy over the request context
+app.delete(
+  "/posts/:id",
+  authorize((ctx) => hasRole(ctx.user, "admin")),
+  handler,
+);

Example 4

import { any, all, attr, authorize, type Policy } from "@wrnexus/authz";
+
+interface User {
+  id: string;
+  department?: string;
+  roles?: string[];
+}
+interface Post {
+  authorId: string;
+}
+
+// Ownership policy (subject + resource)
+const ownsPost: Policy<User, Post> = (u, post) => u.id === post?.authorId;
+
+// ABAC: attribute equality, or a predicate
+const inEngineering = attr<User>("department", "engineering");
+const isVerified = attr<User>("verified", (v) => v === true);
+
+// Compose: allow if the user owns the post OR is in engineering AND verified
+const canEdit = any(ownsPost, all(inEngineering, isVerified));
+
+app.put(
+  "/posts/:id",
+  authorize((ctx) => canEdit(ctx.user as User, loadPost(ctx))),
+  handler,
+);
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/cli.wrn b/app/pages/packages/cli.wrn new file mode 100644 index 00000000..155376d8 --- /dev/null +++ b/app/pages/packages/cli.wrn @@ -0,0 +1,114 @@ +page wrnexuscli { + seo { + title = "@wrnexus/cli" + description = "Create, develop, build, generate, test, and maintain WRNexusJS apps." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Tooling

@wrnexus/cli

Create, develop, build, generate, test, and maintain WRNexusJS apps.

bun add @wrnexus/cli@0.2.12
The wrnexus command-line tool that scaffolds, runs, builds, tests, and manages WRNexusJS apps.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/cli provides the wrnexus executable — the single entry point for developing a WRNexusJS app. It runs the HMR dev server, produces a self-contained production build, scaffolds apps/pages/components, drives database migrations, regenerates typed routes and queries, runs tests, and manages configuration profiles. It also scaffolds multi-app monorepos and serves them behind a domain-routing gateway. This is a CLI/build-time package (it shells out to the Bun binary for the dev child and tests) and it also exports the workspace config types via a subpath.

+

Installation

+
bun add @wrnexus/cli
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

Once installed, invoke it from an app directory:

+
bunx wrnexus dev
+# or add scripts: "dev": "wrnexus dev .", "build": "wrnexus build ."
+

Commands

+

Every command accepts an optional [app-dir] (defaults to .). Commands that read config or .env also accept --profile=<name> (see [Profiles](#profiles)).

+
+ +
CommandPurpose
wrnexus dev [app-dir] [--port=3000]Start the development server with live reload / HMR.
wrnexus build [app-dir]Build a self-contained production server bundle + assets into dist/.
wrnexus create <app-name>Scaffold a new single app from an inline template.
wrnexus workspace <name>Scaffold a monorepo (apps/* + shared packages/*).
wrnexus gateway [--port=3000]Serve every workspace app behind one port, routed by domain.
wrnexus generate <type> <name>Scaffold a page \component \api \schema.
wrnexus generate routesRegenerate the typed routes file (app/routes.gen.ts).
wrnexus generate dockerScaffold Dockerfile, .dockerignore, and docker-compose.yml.
wrnexus generate mobileScaffold a Capacitor shell for iOS and Android.
wrnexus mobile add <package...>Install Capacitor plugins and sync native projects.
wrnexus eject <name...>Copy Wire UI component .wrn sources into app/components/.
wrnexus db <cmd>Database migrations and tooling (see [db](#wrnexus-db)).
wrnexus test [app-dir] [--watch]Run the app's tests via bun test (defaults to the test profile).
wrnexus profiles [app-dir]List config profiles and their .env files, marking the active one.
wrnexus helpPrint usage.
+

wrnexus g is an alias for wrnexus generate.

+

wrnexus dev

+

Supervises a child dev-server process (from @wrnexus/dev-server). The child owns file watching and HMR: CSS and client-island edits update the live page over a WebSocket with no restart; when a server module changes, the child exits with a restart code and the supervisor respawns it (the browser reconnects and morphs in the new HTML). On startup it regenerates typed DB queries and typed routes (best effort). Use --port= to change the port (default 3000).

+
wrnexus dev . --port=8080
+

wrnexus build

+

Emits into <app-dir>/dist/:

+
    +
  • server.js — a single, minified, self-contained Bun server with a static manifest of every page / api / realtime / middleware / component / layout module (no runtime filesystem scan or on-the-fly bundling).
  • +
  • reactive.js, theme.css, theme.js, ui.css, and (if present) styles.css — hashed, minified browser assets.
  • +
  • public/ — copied verbatim.
  • +
+

Before bundling, it regenerates typed queries for the default and every named database. Run the output with:

+
bun dist/server.js   # PORT env var optional
+

wrnexus create

+

Scaffolds a new app from an inline (dependency-free) template — package.json, config, and starter app/ files. Run wrnexus dev in the new directory to start.

+
wrnexus create my-app
+

wrnexus generate

+

Scaffolds a single file from a template, refusing to overwrite an existing file. Types (with aliases): page/p, component/c, api/a, schema/s. Nested names create nested paths.

+
wrnexus generate page about          # app/pages/about.wrn
+wrnexus generate component user-card # app/components/user-card.wrn
+wrnexus generate api users/list      # app/api/users/list.ts
+wrnexus generate schema signup       # app/schemas/signup.ts
+wrnexus generate routes              # regenerate app/routes.gen.ts
+wrnexus generate docker              # Dockerfile + compose + .dockerignore
+wrnexus generate mobile --mode=webview --app-id=com.example.app --app-name="Example" --url=https://app.example.com
+wrnexus generate mobile --mode=native
+

The mobile generator creates a separate mobile/ package and reads config.mobile.mode. webview creates a Capacitor shell that renders the hosted WRNexusJS application. native creates a WebView-free Expo/React Native app whose screens call the shared backend through mobile/src/wrnexus.ts. Native screens do not render .wrn HTML. In either mode, run bun install in mobile/; iOS device builds require macOS and Xcode.

+

Install official or community Capacitor plugins through the root CLI:

+
wrnexus mobile add @capacitor/camera @capacitor/haptics
+wrnexus mobile sync
+wrnexus mobile assets # generate native icons from config.mobile.icon
+

In native mode, mobile add runs expo install and mobile sync runs Expo prebuild. In WebView mode they retain the Capacitor install/sync behavior. wrnexus mobile compile maps portable app/pages/**/*.wrn pages to Expo Router TSX routes. Native bun run start invokes this compilation automatically.

+

Browser code can access installed plugins through the SSR-safe @wrnexus/mobile bridge. The command adds each plugin to both the WRNexusJS app (JavaScript proxy) and mobile/ (native synchronization).

+

wrnexus mobile sync also configures Android so only true network failures use the local connection-error screen. HTTP errors such as 404 and 500 keep their WRNexusJS response pages.

+

wrnexus eject

+

Copies a Wire UI component's .wrn source out of @wrnexus/ui into app/components/, so the app owns and can edit it (the app copy shadows the library one by name). Run with no names to list available components. It skips components that already exist in the app.

+
wrnexus eject button card modal
+

wrnexus db

+

Database migrations and tooling. Without a flag, commands target the default database (db in wrnexus.config.ts, files under app/db/). Pass --db=<name> to target a named database (databases.<name>, files under app/db/<name>/).

+
+ +
SubcommandPurpose
db new <name> [--from-models]Scaffold a migration; --from-models derives it from the TS models in schema.ts.
db migrateApply all pending migrations.
db rollbackRevert the last applied migration.
db statusList applied / pending migrations.
db generateRegenerate typed queries (queries/*.sqlqueries.gen.ts).
db seedRun the database's seed.ts (default export / seed function).
db studio [table]Inspect tables — list row counts, or dump the first 50 rows of one table.
+
wrnexus db new create_users --from-models
+wrnexus db migrate
+wrnexus db studio users
+wrnexus db status --db=analytics
+

wrnexus workspace and wrnexus gateway

+

workspace <name> scaffolds a monorepo: several WRNexusJS apps under apps/* and shared libraries under packages/*, plus a wrnexus.workspace.ts that maps each app to the domains it serves. gateway runs every app behind one port and routes by Host header, with optional per-app auth and gateway-wide security (trusted hosts, rate limit, security headers, access log).

+
wrnexus workspace acme
+wrnexus gateway --port=3000
+

wrnexus test

+

Runs the app's tests with bun test. Defaults to the test profile (config + .env.test). Pass --watch to re-run on change; extra flags pass straight through to bun test.

+
wrnexus test . --watch
+

Profiles

+

Pass --profile=<name> to dev, build, db (or set WRNEXUS_PROFILE) to select a config profile. The CLI publishes WRNEXUS_PROFILE so config loaders and the dev child pick it up, and loads that profile's .env cascade (.env, .env.local, .env.<profile>, .env.<profile>.local) into process.env.

+
wrnexus dev --profile=uat
+wrnexus profiles          # ● development  (config, .env.development)
+                          # ○ production
+                          # ○ uat          (config, .env.uat)
+

Subpath exports

+

@wrnexus/cli/workspace exposes the workspace configuration types used by wrnexus.workspace.ts:

+
import type { WorkspaceConfig, WorkspaceApp } from "@wrnexus/cli/workspace";
+
+const config: WorkspaceConfig = {
+  security: { trustedHostsOnly: true, headers: true, accessLog: true },
+  apps: [{ name: "web", dir: "apps/web", domains: ["localhost", "web.localhost"] }],
+};
+
+export default config;
+

Requirements / Notes

+
    +
  • Bun-only. The CLI runs on Bun, spawns the Bun binary for the dev child and bun test, and the production build uses Bun.build. Node is not supported.
  • +
  • Orchestrates the rest of the framework: @wrnexus/dev-server (dev/prod server + gateway), @wrnexus/router (route + typed-routes codegen), @wrnexus/compiler (.wrn.ts), @wrnexus/db (migrations, typed queries), @wrnexus/styles (config, profiles, .env, themes, styles), @wrnexus/ui (ejectable Wire UI components), @wrnexus/validation, @wrnexus/csr, and @wrnexus/i18n.
  • +
  • Reads wrnexus.config.ts for db / databases, theme, styles, seo, security, i18n, and profiles, and wrnexus.workspace.ts for the gateway.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

#!/usr/bin/env bun
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/cli

Example 2

bunx wrnexus dev
+# or add scripts: "dev": "wrnexus dev .", "build": "wrnexus build ."

Example 3

wrnexus dev . --port=8080

Example 4

bun dist/server.js   # PORT env var optional
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/compiler.wrn b/app/pages/packages/compiler.wrn new file mode 100644 index 00000000..5fd8751b --- /dev/null +++ b/app/pages/packages/compiler.wrn @@ -0,0 +1,361 @@ +page wrnexuscompiler { + seo { + title = "@wrnexus/compiler" + description = "Parser and code generators for the .wrn language." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Core

@wrnexus/compiler

Parser and code generators for the .wrn language.

bun add @wrnexus/compiler@0.2.12
Compiler for the .wrn language — tokenizes, parses, and lowers .wrn page 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

+
+ +
ClassThrown byMeaning
ParseErrorparse, compile, compileWireFile, generateInvalid .wrn grammar or (rewrapped) lex failure.
LexErrorLexerUnexpected character / unterminated string / unbalanced braces.
+

AST types

+

Exported type-only symbols describing the parsed tree:

+
+ +
TypeDescription
PageAstRoot 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.
SeoBlockRecord<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>" — selects app/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 generated meta.
  • +
  • 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 a METHOD export (repeatable).
  • +
  • ssr { ... } / client { ... } — data blocks holding api <name> <METHOD> <path> { ... } bindings and their own functions { ... }.
  • +
  • realtime <name> { on <evt>(<args>) { <raw js> } ... } — websocket handlers, lowered to a websocket export.
  • +
+

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/compiler

Example 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.
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/core.wrn b/app/pages/packages/core.wrn new file mode 100644 index 00000000..14d83917 --- /dev/null +++ b/app/pages/packages/core.wrn @@ -0,0 +1,966 @@ +page wrnexuscore { + seo { + title = "@wrnexus/core" + description = "Contexts, middleware, security, sessions, caching, JSX, and realtime." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Core

@wrnexus/core

Contexts, middleware, security, sessions, caching, JSX, and realtime.

bun add @wrnexus/core@0.2.12
The framework core: the request Context, middleware contract, and the security, session, caching, streaming, realtime, and JSX primitives every other WRNexusJS package builds on.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/core is the shared foundation of WRNexusJS. It defines the Context object that flows through every middleware, page, and API route, plus the Middleware/Next contract they implement. On top of that it ships the building blocks a real app needs: cookie-backed sessions, password auth, CSRF protection, rate limiting, request logging, HTTP + in-memory caching, file uploads, streaming/SSE responses, WebSocket "rooms", security headers/CORS, and a server-side JSX runtime that renders to HTML strings. Everything here is server-side and Bun-native (it uses Bun.password, Bun.write, the web-standard Request/Response, and crypto). You depend on it directly and transitively through the rest of the framework.

+

Installation

+
bun add @wrnexus/core
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Context & middleware — @wrnexus/core

+

The Context (ctx) is the single value passed to middleware and handlers.

+
+ +
ExportKindDescription
ContexttypePer-request object: req, url, lang, t, params, locals, user?, ip?, cookies, session, localStorage.
Nexttype`() => Promise<Response> \Response` — invokes the next middleware/handler.
Middlewaretype`(ctx, next) => Promise<Response> \Response. Return next() to continue, or a Response` to short-circuit.
createContext(req, url)fnBuild a fresh Context for an incoming request (wires up cookies, session, localStorage snapshot).
withContextHeaders(ctx, res)fnApply accumulated headers (e.g. Set-Cookie) from the context onto a response.
PageComponenttype`(ctx) => string \Promise<string>` — a page module's default export.
PageMeta / SeoConfigtype<head> metadata: title, description, canonical, robots, image, twitterCard, themeColor, …
TFunctiontype(key, params?) => string — translate a key for ctx.lang, interpolating {param} placeholders.
+

Key Context fields:

+
    +
  • ctx.locals — per-request scratch space for passing values between middleware.
  • +
  • ctx.user — the authenticated user (populated by sessionAuth/logIn), or null.
  • +
  • ctx.ip — the direct socket peer IP (not spoofable via headers).
  • +
  • ctx.cookies / ctx.session / ctx.localStorage — see Storage below.
  • +
+

Authentication — @wrnexus/core

+

Passwords are hashed with argon2id via Bun.password; sessions ride the cookie-backed SessionStore.

+
+ +
ExportSignatureNotes
hashPassword(password)(string) => Promise<string>argon2id hash to store.
verifyPassword(password, hash)(string, string) => Promise<boolean>Constant-safe; returns false on bad/empty hash.
logIn(ctx, user)(Context, U) => voidRegenerates the session id (fixation defense), stores the user, sets ctx.user.
logOut(ctx)(Context) => voidClears the session and ctx.user.
getUser(ctx)`(Context) => U \null`Current user from ctx.user, falling back to the session.
sessionAuth()() => MiddlewareHydrates ctx.user from the session each request. Register early.
requireAuth(options?)(RequireAuthOptions?) => MiddlewareGuard: API/fetch requests get 401 JSON, page navigations get 302 to loginPath (default /login) with ?next=.
SESSION_USER_KEY"user"Session key holding the user.
+

RequireAuthOptions: { loginPath?: string }.

+

CSRF — @wrnexus/core

+

Double-submit cookie pattern: a readable wire-csrf cookie is echoed in an x-csrf-token header on unsafe requests.

+
+ +
ExportSignatureNotes
csrfToken(ctx)(Context) => stringEnsures the CSRF cookie exists and returns its token.
verifyCsrf(ctx)(Context) => booleanSafe methods (GET/HEAD/OPTIONS) pass; otherwise header/ctx.locals._csrf must match the cookie (constant-time).
csrfProtection()() => Middleware403s unsafe requests with a missing/mismatched token.
CSRF_COOKIE / CSRF_HEADER"wire-csrf" / "x-csrf-token"Cookie & header names.
+

Rate limiting — @wrnexus/core

+

Fixed-window limiter that returns 429 with Retry-After and emits RateLimit-Limit/-Remaining/-Reset headers.

+
+ +
ExportSignatureNotes
rateLimit(options?)(RateLimitOptions?) => MiddlewareMain middleware.
peerKey(ctx)(Context) => stringNon-spoofable key from ctx.ip (default).
proxyKey(ctx)(Context) => stringTrusts x-forwarded-for/x-real-ip. Use only behind a trusted proxy.
defaultKeyDeprecated alias of proxyKey.
+

RateLimitOptions: windowMs (default 60_000), max (default 60), key, trustProxy (default false → keys on peerKey; trueproxyKey), message, headers (default true), store.

+

RateLimitStore is pluggable — implement hit(key, windowMs, now) => Bucket | Promise<Bucket> (a Bucket is { count, resetAt }) to back limits with Redis/SQL across instances. The default store is process-local memory.

+

Request logging — @wrnexus/core

+
+ +
ExportSignatureNotes
requestLogger(options?)(RequestLoggerOptions?) => MiddlewareOne record per request with a request id (stored on ctx.locals[requestIdKey]).
+

RequestLoggerOptions: format ("pretty" default \| "json"), sink(line, record) (default console.log), requestIdKey (default "requestId"), now. RequestRecord = { time, id, method, path, status, durationMs }.

+

Caching — @wrnexus/core

+
+ +
ExportKindNotes
TTLCache<V>classIn-memory TTL cache: get, set, getOrLoad(key, loader, ttlMs?), delete, clear, size. Constructor takes a default ttlMs (60s).
cacheControl(options)fnBuild a Cache-Control value from CacheControlOptions.
withCacheControl(res, options)fnApply Cache-Control to a response.
etag(body, weak?)fnStable quoted FNV-1a ETag (weak by default).
notModified(req, tag)fntrue when If-None-Match matches — send a 304.
+

CacheControlOptions: maxAge, sMaxAge, private, noStore, noCache, staleWhileRevalidate, immutable.

+

File uploads — @wrnexus/core

+

Bun parses multipart/form-data via Request.formData(); these helpers validate and persist the resulting Files.

+
+ +
ExportSignatureNotes
collectUploads(form)(FormData) => { field, file }[]Every non-empty File in a parsed form.
saveUpload(file, options)(File, SaveUploadOptions) => Promise<SavedUpload>Validates size/type, sanitizes the name, writes via Bun.write. Throws UploadError.
sanitizeFilename(name)(string) => stringStrips separators, traversal, control/illegal chars; caps at 255.
UploadErrorclassThrown on rejected uploads.
+

SaveUploadOptions: dir (required), maxBytes, allowedTypes (MIME types like "image/png" and/or extensions like ".png"), filename(file). SavedUpload = { path, filename, size, type }.

+

Streaming & SSE — @wrnexus/core

+
+ +
ExportSignatureNotes
streamResponse(source, init?)`(Iterable\AsyncIterable<string\Uint8Array>, StreamResponseInit?) => Response`Streaming Response from a chunk source (basis for streaming SSR).
sse(source)`(Iterable\AsyncIterable<ServerSentEvent>) => Response`text/event-stream response.
+

StreamResponseInit: status, headers, contentType (default "text/html; charset=utf-8"). ServerSentEvent: { data, event?, id?, retry? }.

+

Realtime rooms — @wrnexus/core

+

WebSocket rooms. A file in app/realtime/ exports default defineRoom({ ... }) and is served at ws://host/realtime/<name>.

+
+ +
ExportSignatureNotes
defineRoom(handlers)(RoomHandlers) => RoomDefinitionDefine a room. Export the result as default.
isRoomDefinition(value)(unknown) => booleanType guard for a room definition.
createRealtimeRegistry()() => RealtimeRegistryServer-side connection manager mapping sockets ↔ rooms.
bridgeRealtime(registry, bus, topic?)(RealtimeRegistry, RealtimeBus, string?) => () => voidBridge broadcasts/toUser sends across processes via a pub/sub bus.
+

RoomHandlers: authorize(info) => boolean (gate before accept — return false to reject with 403), onConnect(client), onMessage(client, message) (JSON auto-parsed), onLeave(client). A handler receives a RoomClient with id, user, query, data, room, and send / broadcast / to(id) / toUser(user) / close. The Room API adds state, clients(), count(), and broadcast. RealtimeBus is structurally satisfied by @wrnexus/pubsub. Legacy RealtimeHandler/RealtimeSocket raw handlers are still exported. Connection-targeted sends (send, to(id)) stay local; room broadcasts and toUser cross the bridge.

+

Error pages — @wrnexus/core

+
+ +
ExportSignatureNotes
renderError(err, mode)(unknown, Mode) => ResponseDev page (with stack) or generic prod page by mode.
renderDevError(err, status?)(unknown, number?) => ResponseReadable HTML error page including the stack trace.
renderProdError(status?)(number?) => ResponseGeneric page that never leaks file paths.
renderNotFound()() => ResponseSimple 404 page.
+

Mode = "development" | "production".

+

Security headers & CORS — @wrnexus/core

+
+ +
ExportSignatureNotes
withSecurityHeaders(req, res, mode, security?, nonce?)ResponseApplies CORS + CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, COOP, Trusted Types, and extraHeaders.
createCorsPreflightResponse(req, security?)→ `Response \null`Builds a 204/403 preflight response for CORS OPTIONS requests.
isWebSocketOriginAllowed(req, security?)booleanGuards WS upgrades against cross-site hijacking (allows same-origin, configured CORS origins, and non-browser clients).
+

Config types: SecurityConfig (top-level), CorsConfig/CorsOrigin, ContentSecurityPolicyConfig/CspDirectiveValue, HstsConfig, TrustedTypesConfig, PermissionsPolicyConfig. WRNexusJS applies sensible defaults (self-only CSP, frame-ancestors 'none', restrictive Permissions-Policy, HSTS in production, Trusted Types in production); each is individually overridable or disable-able via false.

+

Storage: cookies, sessions, localStorage — @wrnexus/core

+

These back the ctx.cookies, ctx.session, and ctx.localStorage fields.

+
+ +
ExportKindNotes
setSessionBackend(backend)fnSwap the sync session persistence backend (SessionBackend) — e.g. bun:sqlite. Default is process-local memory. Call once at startup.
loadSession(backend, options?)fn → MiddlewareBack ctx.session with an async store (AsyncSessionBackend: load/save/destroy) — loads before the request, saves after. options.ttlMs default 24h.
CookieStoretypeget/getAll/has/set(name, value, opts?)/delete/headers.
SessionStoretypeid/get/getAll/set/delete/regenerate/clear.
LocalStorageSnapshottypeRead-only view of the browser's localStorage sent via header for CSR bindings.
CookieOptionstypepath, domain, maxAge, expires, httpOnly, secure, sameSite.
SessionEntry / SessionBackend / AsyncSessionBackendtypesSession persistence contracts.
+

Low-level security helpers — @wrnexus/core

+
+ +
ExportSignatureNotes
escapeHtml(value)(string) => stringEscape for HTML text/attributes.
isSafeIslandName(name)(string) => booleanAllow only a conservative [A-Za-z0-9_-]+ charset.
isSafeRequestPath(pathname)(string) => booleanReject NULs, .. traversal, and backslashes.
+

JSX runtime — @wrnexus/core, @wrnexus/core/jsx-runtime, @wrnexus/core/jsx-dev-runtime

+

A server-side JSX runtime that renders to HTML strings (no virtual DOM). Point tsconfig's jsxImportSource at @wrnexus/core.

+
+ +
ExportKindNotes
jsx / jsxsfnThe runtime factory (TypeScript calls these automatically). Returns an Html instance.
FragmentsymbolJSX fragment marker.
HtmlclassWraps a raw, already-safe HTML string (toString() returns it).
mustache(expr)fnEmit a {{expr}} placeholder (tagged-template or string form) for the client binder.
JSXComponent / JSXProps / RenderabletypesComponent signature and renderable value types.
+

Values interpolated as children are HTML-escaped unless they are an Html instance; use dangerouslySetInnerHTML={{ __html }} for trusted markup. Void elements render without a closing tag; classNameclass, htmlForfor, and style objects are serialized to CSS text.

+

The subpath exports map to the runtime TypeScript's JSX transform expects:

+
// tsconfig.json
+{
+  "compilerOptions": {
+    "jsx": "react-jsx",
+    "jsxImportSource": "@wrnexus/core",
+  },
+}
+

Usage

+

A minimal middleware chain

+
import {
+  createContext,
+  withContextHeaders,
+  sessionAuth,
+  requireAuth,
+  requestLogger,
+  rateLimit,
+  csrfProtection,
+  type Middleware,
+} from "@wrnexus/core";
+
+const chain: Middleware[] = [
+  requestLogger({ format: "json" }),
+  rateLimit({ max: 100, windowMs: 60_000 }),
+  csrfProtection(),
+  sessionAuth(),
+  requireAuth({ loginPath: "/login" }),
+];
+

Password auth

+
import { hashPassword, verifyPassword, logIn, getUser } from "@wrnexus/core";
+
+// Registration
+const passwordHash = await hashPassword(form.password);
+
+// Login
+if (await verifyPassword(form.password, user.passwordHash)) {
+  logIn(ctx, { id: user.id, email: user.email });
+}
+
+const current = getUser<{ id: string }>(ctx); // or null
+

HTTP caching with ETags

+
import { etag, notModified, withCacheControl } from "@wrnexus/core";
+
+const body = JSON.stringify(data);
+const tag = etag(body);
+if (notModified(ctx.req, tag)) {
+  return new Response(null, { status: 304, headers: { ETag: tag } });
+}
+const res = new Response(body, { headers: { ETag: tag, "content-type": "application/json" } });
+return withCacheControl(res, { maxAge: 60, staleWhileRevalidate: 300 });
+

Streaming SSE

+
import { sse } from "@wrnexus/core";
+
+async function* ticks() {
+  for (let n = 0; ; n++) {
+    yield { event: "tick", data: String(n) };
+    await Bun.sleep(1000);
+  }
+}
+export default (ctx) => sse(ticks());
+

A realtime room

+
// app/realtime/chat.ts
+import { defineRoom } from "@wrnexus/core";
+
+export default defineRoom({
+  authorize: (info) => !!info.user, // require auth
+  onConnect(client) {
+    client.user = client.query.user;
+    client.room.broadcast({ type: "join", id: client.id });
+  },
+  onMessage(client, msg) {
+    client.broadcast({ type: "say", from: client.id, text: msg.text });
+  },
+});
+

Scale it across processes:

+
import { createRealtimeRegistry, bridgeRealtime } from "@wrnexus/core";
+import { createPubSub } from "@wrnexus/pubsub";
+import { redisDriver } from "@wrnexus/pubsub/redis";
+
+const registry = createRealtimeRegistry();
+bridgeRealtime(registry, createPubSub(redisDriver(process.env.REDIS_URL)));
+

JSX rendering

+
import { Html } from "@wrnexus/core";
+
+function Card({ title, body }: { title: string; body: string }) {
+  return (
+    <article class="card">
+      <h2>{title}</h2>
+      <p>{body}</p>
+    </article>
+  );
+}
+
+const html: Html = <Card title="Hi" body="<b>escaped</b> automatically" />;
+return new Response(html.toString(), { headers: { "content-type": "text/html" } });
+

Requirements / Notes

+
    +
  • Bun-only. Uses Bun.password (argon2id), Bun.write, web-standard
  • +

    Request/Response/FormData/ReadableStream, and the global crypto. Node is not supported.

    +
  • Session and rate-limit backends default to process-local memory. For
  • +

    multi-instance deployments, swap in a shared backend: setSessionBackend (sync, e.g. bun:sqlite) or loadSession (async, e.g. Redis) for sessions, a custom RateLimitStore for limits, and bridgeRealtime for realtime.

    +
  • Works with the rest of the framework: realtime bridging is structurally
  • +

    compatible with [@wrnexus/pubsub](../pubsub); the security, auth, and JSX primitives here are consumed by the WRNexusJS server/router packages.

    +
  • Subpath exports: @wrnexus/core/jsx-runtime and @wrnexus/core/jsx-dev-runtime
  • +

    for TypeScript's automatic JSX transform.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

export { Fragment, Html, Component as JSXComponent, Props as JSXProps, Renderable, jsx, jsxs, mustache } from './jsx-runtime.js';
+
+interface CookieOptions {
+    path?: string;
+    domain?: string;
+    maxAge?: number;
+    expires?: Date | string;
+    httpOnly?: boolean;
+    secure?: boolean;
+    sameSite?: "Strict" | "Lax" | "None" | "strict" | "lax" | "none";
+}
+interface CookieStore {
+    get(name: string): string | undefined;
+    getAll(): Record<string, string>;
+    has(name: string): boolean;
+    set(name: string, value: string, options?: CookieOptions): void;
+    delete(name: string, options?: CookieOptions): void;
+    headers(): string[];
+}
+interface SessionStore {
+    id(): string;
+    get<T = unknown>(key: string): T | undefined;
+    getAll(): Record<string, unknown>;
+    set(key: string, value: unknown): void;
+    delete(key: string): void;
+    /** Issue a fresh session id, keeping the data — defends against fixation. */
+    regenerate(): void;
+    clear(): void;
+}
+interface LocalStorageSnapshot {
+    get(key: string): string | undefined;
+    getAll(): Record<string, string>;
+    has(key: string): boolean;
+}
+/** A stored session: its data plus an absolute expiry timestamp (ms). */
+interface SessionEntry {
+    data: Record<string, unknown>;
+    expiresAt: number;
+}
+/**
+ * Pluggable session persistence. The default is process-local memory; swap in a
+ * shared backend (Redis, SQL, etc.) via `setSessionBackend` so sessions survive
+ * restarts and work across multiple instances. Methods are synchronous, so a
+ * backend must be sync (e.g. `bun:sqlite`); async stores need a load/save
+ * wrapper around the request (future work).
+ */
+interface SessionBackend {
+    get(id: string): SessionEntry | undefined;
+    set(id: string, entry: SessionEntry): void;
+    delete(id: string): void;
+    /** Optional: drop expired entries. Called periodically by the store. */
+    gc?(now: number): void;
+}
+/** Replace the session persistence backend (call once at startup). */
+declare function setSessionBackend(backend: SessionBackend): void;
+/**
+ * An ASYNC session store (Redis, a remote DB). Use it via the `loadSession`
+ * middleware, which loads the session before the request and saves it after —
+ * keeping the `ctx.session` API synchronous while persistence is shared across
+ * instances.
+ */
+interface AsyncSessionBackend {
+    load(id: string): Promise<SessionEntry | undefined>;
+    save(id: string, entry: SessionEntry): Promise<void>;
+    destroy(id: string): Promise<void>;
+}
+/**
+ * Back `ctx.session` with an async store. Register early (before anything reads
+ * `ctx.session`). Loads once at the start of the request and saves once at the
+ * end; regenerate/clear destroy the old id.
+ */
+declare function loadSession(backend: AsyncSessionBackend, options?: {
+    ttlMs?: number;
+}): Middleware;
+
+/**
+ * Core request context and middleware contracts.
+ *
+ * The `Context` object is the single value that flows through middleware,
+ * pages and API routes. It is intentionally small and framework-agnostic so
+ * it can later be reused by the `.wrn` compiler output.
+ */
+
+/** Translate a key for the active language, interpolating `{param}` placeholders. */
+type TFunction = (key: string, params?: Record<string, string | number>) => string;
+type Context = {
+    /** The raw incoming web-standard Request. */
+    req: Request;
+    /** Parsed URL of the request (pathname, query, etc.). */
+    url: URL;
+    /** Active language for this request (resolved by the runtime); "" if i18n is unused. */
+    lang: string;
+    /** Translate a key for the active language (identity until the runtime sets it). */
+    t: TFunction;
+    /** Dynamic route params, e.g. `/users/[id]` -> `{ id: "42" }`. */
+    params: Record<string, string>;
+    /**
+     * Per-request scratch space. Middleware can attach values here
+     * (e.g. the authenticated user) and downstream handlers can read them.
+     */
+    locals: Record<string, unknown>;
+    /**
+     * The authenticated user for this request, or null when anonymous. Populated
+     * by the `sessionAuth` middleware (or `logIn`); read via `getUser(ctx)`.
+     */
+    user?: unknown;
+    /**
+     * The direct socket peer IP, set by the server from `server.requestIP`. This
+     * is NOT spoofable by request headers — prefer it over `x-forwarded-for` for
+     * rate limiting unless you run behind a trusted proxy.
+     */
+    ip?: string;
+    /** Read/write HTTP cookies for the current response. */
+    cookies: CookieStore;
+    /** In-memory cookie-backed session store. */
+    session: SessionStore;
+    /** Read-only localStorage snapshot sent by the browser for CSR data bindings. */
+    localStorage: LocalStorageSnapshot;
+};
+/** Calls the next middleware in the chain (or the final route handler). */
+type Next = () => Promise<Response> | Response;
+/**
+ * Middleware runs before pages and API routes. It can:
+ *  - inspect/modify `ctx`
+ *  - short-circuit by returning a `Response` without calling `next()`
+ *  - continue by returning `await next()`
+ */
+type Middleware = (ctx: Context, next: Next) => Promise<Response> | Response;
+/** SEO metadata rendered into the document `<head>`. */
+type SeoConfig = {
+    title?: string;
+    titleTemplate?: string;
+    description?: string;
+    canonical?: string;
+    canonicalBase?: string;
+    robots?: string;
+    keywords?: string | string[];
+    image?: string;
+    siteName?: string;
+    type?: string;
+    locale?: string;
+    twitterCard?: string;
+    twitterSite?: string;
+    themeColor?: string;
+};
+/** Page metadata rendered into the document `<head>`. */
+type PageMeta = SeoConfig;
+/** A page module's default export. Returns an HTML string for the body. */
+type PageComponent = (ctx: Context) => string | Promise<string>;
+/** Create a fresh context for an incoming request. */
+declare function createContext(req: Request, url: URL): Context;
+/** Apply headers accumulated on the context, such as Set-Cookie. */
+declare function withContextHeaders(ctx: Context, res: Response): Response;
+
+/**
+ * Small, dependency-free security helpers shared across packages.
+ */
+/**
+ * Escape a string for safe interpolation into HTML text or attributes.
+ * Used for page metadata (title/description) so untrusted values can't
+ * break out of an attribute or inject markup.
+ */
+declare function escapeHtml(value: string): string;
+declare function isSafeIslandName(name: string): boolean;
+/**
+ * Reject obvious path-traversal in a request path before it is ever used to
+ * resolve a file. The router never builds file paths from request input
+ * (routes are resolved against a pre-scanned table), but this is a cheap
+ * defense-in-depth guard.
+ */
+declare function isSafeRequestPath(pathname: string): boolean;
+
+/**
+ * CSRF protection via the double-submit cookie pattern.
+ *
+ * The framework sets a readable `wire-csrf` cookie on page loads; the client
+ * echoes it in an `x-csrf-token` header on unsafe requests (the Wire UI form
+ * runtime does this automatically). The server checks header === cookie. A
+ * cross-site attacker can't read the cookie to forge the header, so the request
+ * is rejected — while same-origin requests pass.
+ */
+
+declare const CSRF_COOKIE = "wire-csrf";
+declare const CSRF_HEADER = "x-csrf-token";
+/** Ensure the CSRF cookie exists (readable by JS) and return its token. */
+declare function csrfToken(ctx: Context): string;
+/**
+ * Verify an unsafe request's CSRF token against the cookie. Safe methods
+ * (GET/HEAD/OPTIONS) always pass. The token may arrive in the `x-csrf-token`
+ * header or a `_csrf` field already parsed onto `ctx.locals`.
+ */
+declare function verifyCsrf(ctx: Context): boolean;
+/** Middleware that 403s unsafe requests with a missing/mismatched CSRF token. */
+declare function csrfProtection(): Middleware;
+
+/**
+ * Authentication primitives.
+ *
+ * Passwords are hashed with argon2id via `Bun.password`. Sessions ride on the
+ * existing cookie-backed `SessionStore`: logging a user in stores a serializable
+ * user object under the "user" key, and `sessionAuth` hydrates `ctx.user` from
+ * it on every request. `requireAuth` is a guard middleware for protected routes.
+ */
+
+/** Session key under which the authenticated user is stored. */
+declare const SESSION_USER_KEY = "user";
+/** Hash a plaintext password (argon2id). Store the returned string. */
+declare function hashPassword(password: string): Promise<string>;
+/** Verify a plaintext password against a stored hash. Safe against bad hashes. */
+declare function verifyPassword(password: string, hash: string): Promise<boolean>;
+/** Persist the authenticated user in the session and on the context. */
+declare function logIn<U = unknown>(ctx: Context, user: U): void;
+/** Clear the session and forget the current user. */
+declare function logOut(ctx: Context): void;
+/**
+ * The currently-authenticated user, or null. Reads `ctx.user` first (set by
+ * `sessionAuth`/`logIn`), falling back to the session store.
+ */
+declare function getUser<U = unknown>(ctx: Context): U | null;
+/**
+ * Hydrate `ctx.user` from the session for every request. Register this early in
+ * the middleware chain so downstream pages and API routes can read `ctx.user`.
+ */
+declare function sessionAuth(): Middleware;
+interface RequireAuthOptions {
+    /** Where to redirect unauthenticated page requests. Default "/login". */
+    loginPath?: string;
+}
+/**
+ * Guard that requires an authenticated user. Unauthenticated requests that look
+ * like an API/fetch call get a 401 JSON response; page navigations get a 302
+ * redirect to the login page with the original target preserved as `?next=`.
+ */
+declare function requireAuth(options?: RequireAuthOptions): Middleware;
+
+/**
+ * Fixed-window rate limiting middleware. Keeps an in-memory counter per key
+ * (client IP by default, read from `x-forwarded-for` / `x-real-ip`) and rejects
+ * requests over the limit with a 429 and a `Retry-After` header. Sets the
+ * `RateLimit-Limit` / `RateLimit-Remaining` / `RateLimit-Reset` headers.
+ *
+ * The store is process-local; behind multiple instances use a shared store
+ * (out of scope here). Suitable as-is for single-process apps and dev.
+ */
+
+interface RateLimitOptions {
+    /** Window length in milliseconds. Default 60_000 (1 minute). */
+    windowMs?: number;
+    /** Max requests allowed per key per window. Default 60. */
+    max?: number;
+    /** Derive the bucket key from the request. Default: client IP. */
+    key?: (ctx: Context) => string;
+    /**
+     * Trust `x-forwarded-for` / `x-real-ip` for the client IP. Default false —
+     * those headers are attacker-spoofable, so by default we key on the direct
+     * socket peer (`ctx.ip`). Enable ONLY when behind a proxy that overwrites
+     * these headers (nginx, a load balancer, Cloudflare).
+     */
+    trustProxy?: boolean;
+    /** Body returned on 429. Default "Too Many Requests". */
+    message?: string;
+    /** Emit RateLimit-* headers. Default true. */
+    headers?: boolean;
+    /** Persistence for the counters. Default: process-local memory. */
+    store?: RateLimitStore;
+    /** Maximum in-memory keys before oldest buckets are evicted. Ignored for custom stores. */
+    maxKeys?: number;
+}
+interface Bucket {
+    count: number;
+    resetAt: number;
+}
+/**
+ * Pluggable rate-limit counter store. The default is process-local memory; swap
+ * in a shared store (Redis/SQL) so limits hold across instances. `hit` records
+ * one request for `key` in the current window and returns the running bucket.
+ * It may be async (e.g. a Redis INCR + PEXPIRE) — the middleware awaits it.
+ */
+interface RateLimitStore {
+    hit(key: string, windowMs: number, now: number): Bucket | Promise<Bucket>;
+}
+declare function rateLimit(options?: RateLimitOptions): Middleware;
+/** Non-spoofable key: the direct socket peer IP (set by the server). */
+declare function peerKey(ctx: Context): string;
+/** Proxy-aware key: trusts `x-forwarded-for` / `x-real-ip`, else the peer IP. */
+declare function proxyKey(ctx: Context): string;
+/** @deprecated Use `peerKey` (default) or `proxyKey`. Kept for compatibility. */
+declare const defaultKey: typeof proxyKey;
+
+/**
+ * Structured request logging middleware. Emits one record per request with a
+ * request id, method, path, status, and duration — as pretty text (dev) or JSON
+ * (production/log aggregation). The request id is stored on `ctx.locals` so
+ * downstream handlers can correlate their own logs.
+ */
+
+interface RequestRecord {
+    time: string;
+    id: string;
+    method: string;
+    path: string;
+    status: number;
+    durationMs: number;
+}
+interface RequestLoggerOptions {
+    /** "pretty" (default) for humans, "json" for machines. */
+    format?: "pretty" | "json";
+    /** Where each finished record goes. Default console.log. */
+    sink?: (line: string, record: RequestRecord) => void;
+    /** ctx.locals key for the request id. Default "requestId". */
+    requestIdKey?: string;
+    /** Clock injection for tests. Default Date.now. */
+    now?: () => number;
+}
+declare function requestLogger(options?: RequestLoggerOptions): Middleware;
+
+/**
+ * Caching primitives:
+ *  - `TTLCache` — a small in-memory time-to-live cache with `getOrLoad`, for
+ *    memoising expensive data (query results, computed pages).
+ *  - HTTP helpers — `cacheControl` to build a directive, `withCacheControl` to
+ *    apply it, and `etag` / `notModified` for conditional requests (304s).
+ */
+declare class TTLCache<V = unknown> {
+    private readonly ttlMs;
+    private store;
+    private loading;
+    private revisions;
+    private generation;
+    constructor(ttlMs?: number);
+    get(key: string): V | undefined;
+    set(key: string, value: V, ttlMs?: number): void;
+    /** Return the cached value or compute, cache, and return it. */
+    getOrLoad(key: string, loader: () => Promise<V> | V, ttlMs?: number): Promise<V>;
+    delete(key: string): void;
+    clear(): void;
+    get size(): number;
+}
+interface CacheControlOptions {
+    /** max-age in seconds. */
+    maxAge?: number;
+    /** s-maxage (shared/CDN cache) in seconds. */
+    sMaxAge?: number;
+    /** Mark private (per-user) rather than public. */
+    private?: boolean;
+    /** no-store: never cache. Overrides other directives. */
+    noStore?: boolean;
+    /** no-cache: revalidate before use. */
+    noCache?: boolean;
+    /** stale-while-revalidate window in seconds. */
+    staleWhileRevalidate?: number;
+    immutable?: boolean;
+}
+/** Build a Cache-Control header value from options. */
+declare function cacheControl(options: CacheControlOptions): string;
+/** Apply a Cache-Control header to a response (returns the same response). */
+declare function withCacheControl(res: Response, options: CacheControlOptions): Response;
+/** A stable, quoted ETag for a string/bytes body (FNV-1a, weak by default). */
+declare function etag(body: string | ArrayBuffer | Uint8Array, weak?: boolean): string;
+/** True when the request's If-None-Match matches the given ETag (send a 304). */
+declare function notModified(req: Request, tag: string): boolean;
+
+/**
+ * File upload helpers. Bun parses `multipart/form-data` natively via
+ * `Request.formData()`, yielding web `File` objects; these helpers validate and
+ * persist them safely (size/type limits, filename sanitisation to prevent path
+ * traversal).
+ */
+declare class UploadError extends Error {
+    constructor(message: string);
+}
+interface SaveUploadOptions {
+    /** Destination directory. */
+    dir: string;
+    /** Reject files larger than this many bytes. */
+    maxBytes?: number;
+    /** Allowed MIME types (e.g. "image/png") and/or extensions (e.g. ".png"). */
+    allowedTypes?: string[];
+    /** Choose the stored filename. Default: the sanitised original name. */
+    filename?: (file: File) => string;
+}
+interface SavedUpload {
+    path: string;
+    filename: string;
+    size: number;
+    type: string;
+}
+/** All `File` values in a parsed form, with their field names. */
+declare function collectUploads(form: FormData): {
+    field: string;
+    file: File;
+}[];
+/** Validate and write one uploaded file to disk. Throws `UploadError` on reject. */
+declare function saveUpload(file: File, options: SaveUploadOptions): Promise<SavedUpload>;
+/** Strip directory separators, traversal, and control chars from a filename. */
+declare function sanitizeFilename(name: string): string;
+
+/**
+ * Streaming response primitives.
+ *
+ * `streamResponse` turns a (sync or async) iterable of strings/bytes into a
+ * streaming `Response` — the basis for streaming SSR (send the shell, then flush
+ * page chunks as they render) and any progressively-generated output. `sse`
+ * builds a Server-Sent Events stream from an async iterable of events.
+ *
+ * API routes and pages can already return a `Response` with a `ReadableStream`
+ * body and the framework streams it unbuffered; these helpers just make the
+ * common cases ergonomic.
+ */
+interface StreamResponseInit {
+    status?: number;
+    headers?: HeadersInit;
+    /** Content-Type; default "text/html; charset=utf-8". */
+    contentType?: string;
+}
+type Chunk = string | Uint8Array;
+type ChunkSource = Iterable<Chunk> | AsyncIterable<Chunk>;
+/** Build a streaming Response from an (async) iterable of chunks. */
+declare function streamResponse(source: ChunkSource, init?: StreamResponseInit): Response;
+interface ServerSentEvent {
+    data: string;
+    event?: string;
+    id?: string;
+    /** Client reconnection hint in milliseconds. */
+    retry?: number;
+}
+/** Build a Server-Sent Events (text/event-stream) Response from events. */
+declare function sse(source: Iterable<ServerSentEvent> | AsyncIterable<ServerSentEvent>): Response;
+
+/**
+ * Realtime rooms.
+ *
+ * A file in `app/realtime/` exports `default defineRoom({ onConnect, onMessage,
+ * onLeave })` and is served at `ws://host/realtime/<name>`. The framework's
+ * client runtime (`/__wrnexus/realtime.js`) handles the browser side, so pages
+ * ship NO hand-written WebSocket code.
+ *
+ * Handlers get a `RoomClient` with everything you need:
+ *   client.send(msg)                 → this connection
+ *   client.broadcast(msg)            → everyone else in the room
+ *   client.room.broadcast(msg)       → everyone (incl. sender)
+ *   client.to(id | ids).send(msg)    → specific connection(s)
+ *   client.toUser(u | users).send()  → a user / selected users (all their tabs)
+ *   client.user = "u1"               → identify a connection for targeting
+ *   client.data / client.room.state  → per-connection / shared room state
+ *
+ * The dynamic route `app/realtime/[room].ts` gives one handler many independent
+ * rooms — `/realtime/lobby` and `/realtime/game-7` are separate room instances.
+ */
+interface RawSocket {
+    send(data: string): unknown;
+    close(code?: number, reason?: string): void;
+}
+interface RealtimeSocket<Data = unknown> {
+    readonly data: Data;
+    send(data: string | Uint8Array): number;
+    subscribe(topic: string): void;
+    unsubscribe(topic: string): void;
+    publish(topic: string, data: string | Uint8Array): number;
+    isSubscribed(topic: string): boolean;
+    close(code?: number, reason?: string): void;
+}
+interface RealtimeHandler<Data = unknown> {
+    open?(ws: RealtimeSocket<Data>): void | Promise<void>;
+    message?(ws: RealtimeSocket<Data>, message: string | Uint8Array): void | Promise<void>;
+    close?(ws: RealtimeSocket<Data>, code?: number, reason?: string): void | Promise<void>;
+    drain?(ws: RealtimeSocket<Data>): void | Promise<void>;
+}
+interface Target {
+    /** Send a message (objects are JSON-serialized). */
+    send(message: unknown): void;
+}
+interface Room<TData = Record<string, unknown>> {
+    readonly name: string;
+    /** Shared, in-memory room state (lives while ≥1 client is connected). */
+    readonly state: Record<string, unknown>;
+    /** All connected clients. */
+    clients(): RoomClient<TData>[];
+    /** Number of connected clients. */
+    count(): number;
+    /** Send to everyone in the room, including the sender. */
+    broadcast(message: unknown): void;
+    /** Target specific connection id(s). */
+    to(id: string | string[]): Target;
+    /** Target a user / users by identity (reaches all their connections). */
+    toUser(user: string | string[]): Target;
+}
+interface RoomClient<TData = Record<string, unknown>> {
+    /** Unique per connection (a tab). */
+    readonly id: string;
+    /** App identity for targeting; assign it in `onConnect`. */
+    user: string | undefined;
+    /** Query params from the connection URL. */
+    readonly query: Record<string, string>;
+    /** Per-connection scratch state. */
+    readonly data: TData;
+    readonly room: Room<TData>;
+    /** Send to THIS connection. */
+    send(message: unknown): void;
+    /** Send to everyone else in the room. */
+    broadcast(message: unknown): void;
+    /** Target specific connection id(s). */
+    to(id: string | string[]): Target;
+    /** Target a user / users by identity. */
+    toUser(user: string | string[]): Target;
+    /** Close this connection. */
+    close(code?: number, reason?: string): void;
+}
+/** Info available when authorizing a connection, before it is accepted. */
+interface RoomAuthInfo {
+    /** Authenticated session user id, or `?user=` — undefined when anonymous. */
+    user?: string;
+    /** Connection URL query params. */
+    query: Record<string, string>;
+    /** The upgrade request's headers (cookies, etc.). */
+    headers: Headers;
+}
+interface RoomHandlers<TData = Record<string, unknown>> {
+    /**
+     * Gate the connection BEFORE it is accepted. Return false to reject the
+     * upgrade with 403 (e.g. `authorize: (info) => !!info.user` to require auth).
+     */
+    authorize?(info: RoomAuthInfo): boolean | Promise<boolean>;
+    /** A client connected (a new tab joined the room). */
+    onConnect?(client: RoomClient<TData>): void | Promise<void>;
+    /** A message arrived (JSON is parsed; non-JSON arrives as a string). */
+    onMessage?(client: RoomClient<TData>, message: any): void | Promise<void>;
+    /** A client disconnected. */
+    onLeave?(client: RoomClient<TData>): void | Promise<void>;
+}
+interface RoomDefinition<TData = Record<string, unknown>> {
+    readonly __wrnexusRoom: true;
+    readonly handlers: RoomHandlers<TData>;
+}
+/** Define a realtime room. Export the result as the `default` of a realtime file. */
+declare function defineRoom<TData = Record<string, unknown>>(handlers: RoomHandlers<TData>): RoomDefinition<TData>;
+declare function isRoomDefinition(value: unknown): value is RoomDefinition;
+interface RealtimeConnectMeta {
+    room: string;
+    def: RoomDefinition;
+    query?: Record<string, string>;
+    user?: string;
+}
+/** One cross-instance message: a room broadcast, or a targeted user send. */
+interface RealtimeEnvelope {
+    room: string;
+    /** If set, deliver only to these user identities; otherwise the whole room. */
+    users?: string[];
+    message: unknown;
+}
+/**
+ * A pub/sub bridge for horizontal scaling. Wire the registry to a shared bus
+ * (Redis pub/sub, NATS, …): local broadcasts/`toUser` sends are published to
+ * peers, and messages received from peers are delivered via `registry.deliver`.
+ * Connection-targeted sends (`send`, `to(id)`) stay local (ids are per-process).
+ */
+interface RealtimeBridge {
+    publish(envelope: RealtimeEnvelope): void;
+}
+interface RealtimeRegistry {
+    open(socket: RawSocket, meta: RealtimeConnectMeta): void | Promise<void>;
+    message(socket: RawSocket, raw: string | Uint8Array): void | Promise<void>;
+    close(socket: RawSocket): void | Promise<void>;
+    /** Attach a cross-instance bridge (call once at startup). */
+    setBridge(bridge: RealtimeBridge): void;
+    /** Deliver an envelope received from a peer to LOCAL connections only. */
+    deliver(envelope: RealtimeEnvelope): void;
+    /** Number of live connections (across all rooms) — for tests/metrics. */
+    size(): number;
+}
+/** Create the registry that maps sockets ↔ rooms and drives room handlers. */
+declare function createRealtimeRegistry(): RealtimeRegistry;
+/**
+ * A minimal pub/sub bus (structurally satisfied by `@wrnexus/pubsub`). Used to
+ * bridge realtime broadcasts across processes without a hard dependency.
+ */
+interface RealtimeBus {
+    publish(topic: string, message: unknown): void | Promise<void>;
+    subscribe(topic: string, handler: (message: unknown, topic: string) => void): () => void;
+}
+/**
+ * Bridge a realtime registry across processes/instances via a pub/sub bus (use
+ * the Redis driver so it crosses machines). After this, `client.room.broadcast`
+ * and `client.toUser(...)` reach connected clients on **every** app process/
+ * instance subscribed to the same bus — the foundation for realtime that works
+ * with multiple running apps behind the gateway. Connection-targeted sends
+ * (`send`, `to(id)`) stay local. Returns an unsubscribe function.
+ *
+ *   import { createRealtimeRegistry, bridgeRealtime } from "@wrnexus/core";
+ *   import { createPubSub } from "@wrnexus/pubsub";
+ *   import { redisDriver } from "@wrnexus/pubsub/redis";
+ *   bridgeRealtime(registry, createPubSub(redisDriver(process.env.REDIS_URL)));
+ */
+declare function bridgeRealtime(registry: RealtimeRegistry, bus: RealtimeBus, topic?: string): () => void;
+
+/**
+ * Error + status pages. Every page here is a self-contained HTML document —
+ * inline CSS only, no external stylesheet, no JavaScript (so it renders under the
+ * strict CSP, even when the app's assets are what failed). Theme-aware via
+ * `prefers-color-scheme`, styled in the WRNexusJS design language (ink-navy,
+ * azure, a faint blueprint grid + glow). Development shows the stack trace;
+ * production never leaks internal paths.
+ */
+type Mode = "development" | "production";
+/** A beautiful, self-contained HTML page for any 4xx/5xx status. */
+declare function renderStatusPage(status: number): Response;
+/** Readable, styled development error page — includes the stack trace. */
+declare function renderDevError(err: unknown, status?: number): Response;
+/** Generic production error page — no stack, no file paths. */
+declare function renderProdError(status?: number): Response;
+/** Pick the right error page for the current mode. */
+declare function renderError(err: unknown, mode: Mode): Response;
+/** Beautiful 404 page. */
+declare function renderNotFound(): Response;
+
+type CorsOrigin = "*" | string | string[];
+interface CorsConfig {
+    /** Enable CORS headers and preflight handling. Defaults to false. */
+    enabled?: boolean;
+    /** Allowed origins. Use "*" for public APIs. Defaults to "*". */
+    origin?: CorsOrigin;
+    /** Allowed methods for preflight responses. */
+    methods?: string[];
+    /** Allowed request headers. Defaults to the browser's requested headers. */
+    allowedHeaders?: string[];
+    /** Response headers exposed to browser JavaScript. */
+    exposedHeaders?: string[];
+    /** Whether to send Access-Control-Allow-Credentials. */
+    credentials?: boolean;
+    /** Access-Control-Max-Age, in seconds. */
+    maxAge?: number;
+}
+type CspDirectiveValue = string | string[] | false | null | undefined;
+interface ContentSecurityPolicyConfig {
+    /** Defaults to true. */
+    enabled?: boolean;
+    /** Use Content-Security-Policy-Report-Only instead of enforcing. */
+    reportOnly?: boolean;
+    /** Merge or remove directives. Set a directive to false/null to remove it. */
+    directives?: Record<string, CspDirectiveValue>;
+    /** Set false to start from an empty policy instead of WRNexusJS defaults. */
+    useDefaults?: boolean;
+}
+interface HstsConfig {
+    /** Defaults to true in production, false in development. */
+    enabled?: boolean;
+    /** Defaults to 31536000 seconds (1 year). */
+    maxAge?: number;
+    /** Defaults to true. */
+    includeSubDomains?: boolean;
+    /** Defaults to true. */
+    preload?: boolean;
+}
+interface TrustedTypesConfig {
+    /** Defaults to true in production, false in development. */
+    enabled?: boolean;
+    /**
+     * Defaults to ["*"] in production so browser extensions and dev tooling can
+     * create their own policies without noisy console errors. Set this to a
+     * concrete list, e.g. ["wrnexus", "default"], for stricter deployments.
+     */
+    policyNames?: string[];
+    /** Defaults to true. */
+    requireForScript?: boolean;
+    /** Adds "allow-duplicates" to the trusted-types directive. */
+    allowDuplicates?: boolean;
+}
+type PermissionsPolicyConfig = Record<string, string | string[] | false | null | undefined>;
+interface SecurityConfig {
+    /** Set false to skip all framework security headers except explicitly enabled CORS. */
+    headers?: boolean;
+    /**
+     * Trust `X-Forwarded-Proto` / `X-Forwarded-Host` when building `ctx.url` — set
+     * this when the app runs behind a TLS-terminating reverse proxy (nginx, the
+     * WRNexusJS gateway, a load balancer). Without it, a proxied app sees the internal
+     * `http://` request and marks cookies (e.g. CSRF/session) non-`Secure`. Default
+     * false; enable ONLY when a trusted proxy actually sets these headers.
+     */
+    trustProxy?: boolean;
+    cors?: boolean | CorsConfig;
+    contentSecurityPolicy?: false | ContentSecurityPolicyConfig;
+    hsts?: false | HstsConfig;
+    trustedTypes?: false | TrustedTypesConfig;
+    /** Defaults to "same-origin". */
+    crossOriginOpenerPolicy?: false | "same-origin" | "same-origin-allow-popups" | "unsafe-none";
+    /** Defaults to "DENY". */
+    frameOptions?: false | "DENY" | "SAMEORIGIN";
+    /** Defaults to "strict-origin-when-cross-origin". */
+    referrerPolicy?: false | string;
+    /** Defaults to a restrictive browser capability policy. */
+    permissionsPolicy?: false | PermissionsPolicyConfig;
+    /** Extra static headers applied last. */
+    extraHeaders?: Record<string, string>;
+}
+/**
+ * Guard a WebSocket upgrade against Cross-Site WebSocket Hijacking: browsers
+ * always send an `Origin` header on a WS handshake, and — unlike fetch — WS is
+ * NOT subject to CORS, so cookies would otherwise flow cross-site. We allow
+ * same-origin (Origin host === Host header), configured CORS origins, and
+ * non-browser clients (no Origin, which also carry no ambient cookies).
+ */
+declare function isWebSocketOriginAllowed(req: Request, security?: SecurityConfig): boolean;
+declare function createCorsPreflightResponse(req: Request, security?: SecurityConfig): Response | null;
+/**
+ * Build the request URL, honoring `X-Forwarded-Proto` / `X-Forwarded-Host` when
+ * `trustProxy` is set (app behind a TLS-terminating reverse proxy). This makes
+ * `ctx.url.protocol` reflect the EXTERNAL scheme, so protocol-dependent logic —
+ * `Secure` cookies, canonical URLs — is correct behind nginx / the gateway.
+ * Security checks that compare the raw `Host`/`Origin` headers don't use this URL,
+ * so they are unaffected. An invalid forwarded value is ignored by the URL setter.
+ */
+declare function resolveRequestUrl(req: Request, trustProxy?: boolean): URL;
+declare function withSecurityHeaders(req: Request, res: Response, mode: Mode, security?: SecurityConfig, nonce?: string): Response;
+
+export { type AsyncSessionBackend, type Bucket, CSRF_COOKIE, CSRF_HEADER, type CacheControlOptions, type ContentSecurityPolicyConfig, type Context, type CookieOptions, type CookieStore, type CorsConfig, type CorsOrigin, type CspDirectiveValue, type HstsConfig, type LocalStorageSnapshot, type Middleware, type Mode, type Next, type PageComponent, type PageMeta, type PermissionsPolicyConfig, type RateLimitOptions, type RateLimitStore, type RawSocket, type RealtimeBridge, type RealtimeBus, type RealtimeConnectMeta, type RealtimeEnvelope, type RealtimeHandler, type RealtimeRegistry, type RealtimeSocket, type RequestLoggerOptions, type RequestRecord, type RequireAuthOptions, type Room, type RoomAuthInfo, type RoomClient, type RoomDefinition, type RoomHandlers, SESSION_USER_KEY, type SaveUploadOptions, type SavedUpload, type SecurityConfig, type SeoConfig, type ServerSentEvent, type SessionBackend, type SessionEntry, type SessionStore, type StreamResponseInit, type TFunction, TTLCache, type Target, type TrustedTypesConfig, UploadError, bridgeRealtime, cacheControl, collectUploads, createContext, createCorsPreflightResponse, createRealtimeRegistry, csrfProtection, csrfToken, defaultKey, defineRoom, escapeHtml, etag, getUser, hashPassword, isRoomDefinition, isSafeIslandName, isSafeRequestPath, isWebSocketOriginAllowed, loadSession, logIn, logOut, notModified, peerKey, proxyKey, rateLimit, renderDevError, renderError, renderNotFound, renderProdError, renderStatusPage, requestLogger, requireAuth, resolveRequestUrl, sanitizeFilename, saveUpload, sessionAuth, setSessionBackend, sse, streamResponse, verifyCsrf, verifyPassword, withCacheControl, withContextHeaders, withSecurityHeaders };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/core

Example 2

// tsconfig.json
+{
+  "compilerOptions": {
+    "jsx": "react-jsx",
+    "jsxImportSource": "@wrnexus/core",
+  },
+}

Example 3

import {
+  createContext,
+  withContextHeaders,
+  sessionAuth,
+  requireAuth,
+  requestLogger,
+  rateLimit,
+  csrfProtection,
+  type Middleware,
+} from "@wrnexus/core";
+
+const chain: Middleware[] = [
+  requestLogger({ format: "json" }),
+  rateLimit({ max: 100, windowMs: 60_000 }),
+  csrfProtection(),
+  sessionAuth(),
+  requireAuth({ loginPath: "/login" }),
+];

Example 4

import { hashPassword, verifyPassword, logIn, getUser } from "@wrnexus/core";
+
+// Registration
+const passwordHash = await hashPassword(form.password);
+
+// Login
+if (await verifyPassword(form.password, user.passwordHash)) {
+  logIn(ctx, { id: user.id, email: user.email });
+}
+
+const current = getUser<{ id: string }>(ctx); // or null
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/csr.wrn b/app/pages/packages/csr.wrn new file mode 100644 index 00000000..d351a103 --- /dev/null +++ b/app/pages/packages/csr.wrn @@ -0,0 +1,234 @@ +page wrnexuscsr { + seo { + title = "@wrnexus/csr" + description = "Reactive, navigation, and realtime browser runtimes." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Frontend

@wrnexus/csr

Reactive, navigation, and realtime browser runtimes.

bun add @wrnexus/csr@0.2.12
The browser-side client runtime for WRNexusJS — generic, self-contained JS that hydrates server-rendered pages with reactivity, client-side navigation, and realtime rooms.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/csr holds the three client runtimes that WRNexusJS serves to the browser. Components are authored as .wrn files and rendered on the server; this package provides the single, generic runtime that hydrates that HTML in the browser — there are no per-component browser bundles. Each runtime is exported as a plain-JS string (no build step, no imports) intended to be served verbatim from a well-known URL:

+
    +
  • reactive at /__wrnexus/reactive.js — reactive directives (data-scope, data-text, data-for, …)
  • +
  • nav at /__wrnexus/nav.js — SPA-style client navigation with graceful fallback
  • +
  • realtime at /__wrnexus/realtime.js — WebSocket "rooms", declarative or programmatic
  • +
+

The package itself runs on the server (it just returns strings); the strings it returns run in the browser. A dev/prod server (see @wrnexus/core) is responsible for actually serving them.

+

Installation

+
bun add @wrnexus/csr
+
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/csr). The runtime source is delivered as strings, so the "API" on the server side is small; the real surface is the browser directives/globals each string installs.

+

Runtime strings

+
+ +
ExportTypeServed atContents
REACTIVE_RUNTIMEstring/__wrnexus/reactive.jsReactive directive runtime
NAV_RUNTIMEstring/__wrnexus/nav.jsClient-side navigation runtime
REALTIME_RUNTIMEstring/__wrnexus/realtime.jsRealtime rooms runtime
+

Accessor functions

+

Convenience getters that return the same strings.

+
getReactiveRuntime(): string   // → REACTIVE_RUNTIME
+getNavRuntime(): string        // → NAV_RUNTIME
+getRealtimeRuntime(): string   // → REALTIME_RUNTIME
+

Browser: reactive directives

+

Applied to any subtree containing data-scope. Expressions are parsed by a tiny eval-free evaluator, so a strict CSP with no unsafe-eval works.

+
+ +
DirectivePurpose
data-scope="count: 0, name: 'x'"Declare reactive state on a subtree
data-on-<event>="count++"Run a statement in scope on a DOM event
data-text="expr"Bind an element's textContent to an expression
data-show="expr"Toggle visibility (display) on truthiness
data-for="item in list" (opt. item, i in list)Per-item list rendering template
{{expr}} or {expr}Interpolation inside text nodes and attribute values
data-wrnexus-csr="id"Target for a generated CSR fetch binding (fetches /__wrnexus/csr?...)
+

Supported expression features: literals, identifiers, member access (a.b, a[b]), function/method calls, arrays, objects, arithmetic, comparison, equality, logical (&& ||), unary (! - +), and ternary. Statements support ++/--, assignment operators (= += -= *= /= %=), and bare expression/method calls. Rendering is dependency-tracked: a signal change only re-runs the renderers that actually read it.

+

Browser globals installed: window.__wrnexusHydrateScopes(root) and window.__wrnexusHydrateCsrFetches(root) — both idempotent, so re-running after a DOM swap or HMR morph is safe. Both run automatically on DOMContentLoaded.

+

Browser: navigation

+

Intercepts same-origin <a> clicks, fetches the target page, and swaps the #app container in place (via importNode — not innerHTML — so it works under a Trusted-Types CSP), updating history, title, and scroll, then re-hydrates. Cross-origin links, modified clicks, download/data-no-nav/rel="external"/target links, non-HTML responses, or a missing #app fall back to a full browser navigation.

+
    +
  • Programmatic navigation: window.__wrnexusNavigate(url)
  • +
  • Emits a wrnexus:navigated CustomEvent (detail.url) after each swap
  • +
  • Sends x-wrnexus-nav: 1 on fetches so the server can return the page fragment
  • +
  • Appends any /__wrnexus/* runtime scripts the incoming page needs but the current document lacks
  • +
+

Browser: realtime rooms

+

Connects to /realtime/<name> over WebSocket (ws/wss chosen from location.protocol). Two usage modes.

+

Programmatic API via window.wire:

+
wire.room(name): Room          // open (or reuse) a room connection
+wire.bindRooms(root?)          // (re)bind declarative [data-room] containers
+
+interface Room {
+  name: string;
+  send(obj: object | string): Room;         // JSON-stringifies objects; queues until open
+  on(type: string, cb): Room;               // filter by msg.type; "*" or a fn = all messages
+  on(cb): Room;
+  close(): Room;
+}
+

Internal lifecycle messages are emitted to listeners as { type }: __open, __close, __error, and __raw (non-JSON frames, with data). Reconnect uses exponential backoff capped at 5s; queued sends flush on reconnect.

+

Declarative binding (zero JS) on a data-room="<name>" container:

+
+ +
AttributeOnPurpose
data-room="<name>"containerConnect to room <name>
data-room-user="<id>"containerIdentify the connection (?user=<id>)
data-room-logelementWhere incoming messages are appended
<template data-room-item="<type>">templateRow template for messages of that type (empty = fallback)
%field%inside templatePlaceholder filled from the message field (text/attr only, HTML-escaped)
data-room-statuselementReflects connection state text (connected/disconnected/error)
data-room-status-classstatus elementBase class; a state variant (is-connected, …) is appended
<form data-room-send>formSubmits named fields as a JSON message
data-room-resetform fieldClears that field after send
+

Rebinds on wrnexus:navigated and closes rooms whose container has left the page.

+

Usage

+

Server side — serve the runtime strings from your router (example with Bun.serve):

+
import { getReactiveRuntime, getNavRuntime, getRealtimeRuntime } from "@wrnexus/csr";
+
+const routes: Record<string, string> = {
+  "/__wrnexus/reactive.js": getReactiveRuntime(),
+  "/__wrnexus/nav.js": getNavRuntime(),
+  "/__wrnexus/realtime.js": getRealtimeRuntime(),
+};
+
+Bun.serve({
+  fetch(req) {
+    const body = routes[new URL(req.url).pathname];
+    if (body) {
+      return new Response(body, {
+        headers: { "content-type": "text/javascript; charset=utf-8" },
+      });
+    }
+    return new Response("Not found", { status: 404 });
+  },
+});
+

Browser side — server-rendered HTML that the reactive runtime hydrates:

+
<div data-scope="count: 0">
+  <button data-on-click="count++">+1</button>
+  <span data-text="count"></span>
+  <p>Total: {{count}}</p>
+</div>
+<script src="/__wrnexus/reactive.js"></script>
+

A realtime chat, fully declarative:

+
<div data-room="lobby" data-room-user="ada">
+  <div data-room-status></div>
+  <ul data-room-log></ul>
+  <template data-room-item="chat"><li>%user%: %text%</li></template>
+  <form data-room-send>
+    <input name="text" data-room-reset />
+    <input type="hidden" name="type" value="chat" />
+    <button>Send</button>
+  </form>
+</div>
+<script src="/__wrnexus/realtime.js"></script>
+

Or drive a room from code:

+
const room = wire.room("lobby");
+room.on("chat", (msg) => console.log(msg.user, msg.text));
+room.send({ type: "chat", user: "ada", text: "hi" });
+

Requirements / Notes

+
    +
  • Bun-only on the server (the package integrates with Bun-based WRNexusJS servers); the emitted strings are plain browser JS with no dependencies.
  • +
  • Browser runtimes are self-contained (no imports, no build step) and idempotent, so re-hydration after navigation or HMR is safe.
  • +
  • Designed for a strict CSP: the reactive expression evaluator avoids eval/new Function (no unsafe-eval), and DOM swaps use importNode/attribute writes rather than innerHTML (Trusted-Types friendly).
  • +
  • Peer packages: rendered .wrn components and the serving layer come from @wrnexus/core (the sole dependency); pages are rendered by the WRNexusJS dev/prod server.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * Browser reactive runtime (Point 2: reactive directives).
+ *
+ * Served verbatim at `/__wrnexus/reactive.js` for any page that contains a
+ * `data-scope`. It is plain browser JS (no build step) and self-contained: it
+ * inlines a tiny `signal()` so it has no imports to resolve.
+ *
+ * Supported directives (this is exactly what the `.wrn` compiler emits):
+ *   data-scope="count: 0, name: 'x'"   declare reactive state on a subtree
+ *   data-on-<event>="count++"          run a statement in scope on an event
+ *   data-text="expr"                   element textContent follows an expression
+ *   data-wrnexus-csr="id"                 target for generated CSR fetch bindings
+ *   {{expr}} or {expr}                 interpolation inside text nodes
+ *
+ * Expressions are evaluated by a tiny parser instead of `eval`/`new Function`,
+ * so production can use a strong CSP without `unsafe-eval`.
+ */
+declare const REACTIVE_RUNTIME: string;
+
+/**
+ * Client-side navigation runtime, served at `/__wrnexus/nav.js`.
+ *
+ * Progressive enhancement over normal links: intercepts same-origin `<a>`
+ * clicks, fetches the target page's HTML, swaps the `#app` container in place,
+ * updates history/title/scroll, ensures any framework runtimes the new page
+ * needs are present, and re-hydrates. Anything unexpected (cross-origin,
+ * modified click, non-HTML response, missing `#app`) falls back to a full
+ * browser navigation, so behaviour degrades safely.
+ *
+ * Data "loaders": pages load their data on the server (SSR `api` bindings), so
+ * the fetched HTML already contains fresh data — no separate client loader is
+ * needed. Client-side (`csr`) bindings and reactive scopes re-hydrate after the
+ * swap. Programmatic navigation is exposed as `window.__wrnexusNavigate(url)`.
+ */
+declare const NAV_RUNTIME: string;
+
+/**
+ * Client realtime runtime, served at `/__wrnexus/realtime.js`.
+ *
+ * Two ways to use it — no hand-written WebSocket code either way:
+ *
+ * 1. Declarative (zero JS). Put `data-room="<name>"` on a container; the runtime
+ *    connects, appends incoming messages to `[data-room-log]` using a
+ *    `<template data-room-item="<type>">` (fields via `%field%`, HTML-escaped),
+ *    reflects connection state on `[data-room-status]`, and sends a
+ *    `<form data-room-send>`'s named fields as JSON on submit (fields marked
+ *    `data-room-reset` clear after send). Optional `data-room-user` identifies
+ *    the connection.
+ *
+ * 2. Programmatic: `const room = wire.room("chat"); room.on("chat", fn);
+ *    room.send({ type: "chat", text })`. Handles connect, JSON, reconnect.
+ *
+ * Rebinds on `wrnexus:navigated` (client-side nav) and closes rooms whose
+ * container has left the page.
+ */
+declare const REALTIME_RUNTIME: string;
+
+/**
+ * @wrnexus/csr — the browser reactive runtime.
+ *
+ * Components are `.wrn` files rendered on the SERVER (see @wrnexus/dev-server)
+ * and hydrated in the browser by this single, generic runtime — served once at
+ * `/__wrnexus/reactive.js` for any page that contains a `data-scope`. There are
+ * no per-component browser bundles: SSR stays cleanly separated from CSR.
+ */
+
+/** The reactive runtime served at `/__wrnexus/reactive.js` (plain browser JS). */
+declare function getReactiveRuntime(): string;
+/** The client-side navigation runtime served at `/__wrnexus/nav.js`. */
+declare function getNavRuntime(): string;
+/** The realtime client runtime served at `/__wrnexus/realtime.js`. */
+declare function getRealtimeRuntime(): string;
+
+export { NAV_RUNTIME, REACTIVE_RUNTIME, REALTIME_RUNTIME, getNavRuntime, getReactiveRuntime, getRealtimeRuntime };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/csr

Example 2

getReactiveRuntime(): string   // → REACTIVE_RUNTIME
+getNavRuntime(): string        // → NAV_RUNTIME
+getRealtimeRuntime(): string   // → REALTIME_RUNTIME

Example 3

wire.room(name): Room          // open (or reuse) a room connection
+wire.bindRooms(root?)          // (re)bind declarative [data-room] containers
+
+interface Room {
+  name: string;
+  send(obj: object | string): Room;         // JSON-stringifies objects; queues until open
+  on(type: string, cb): Room;               // filter by msg.type; "*" or a fn = all messages
+  on(cb): Room;
+  close(): Room;
+}

Example 4

import { getReactiveRuntime, getNavRuntime, getRealtimeRuntime } from "@wrnexus/csr";
+
+const routes: Record<string, string> = {
+  "/__wrnexus/reactive.js": getReactiveRuntime(),
+  "/__wrnexus/nav.js": getNavRuntime(),
+  "/__wrnexus/realtime.js": getRealtimeRuntime(),
+};
+
+Bun.serve({
+  fetch(req) {
+    const body = routes[new URL(req.url).pathname];
+    if (body) {
+      return new Response(body, {
+        headers: { "content-type": "text/javascript; charset=utf-8" },
+      });
+    }
+    return new Response("Not found", { status: 404 });
+  },
+});
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/db.wrn b/app/pages/packages/db.wrn new file mode 100644 index 00000000..057a0134 --- /dev/null +++ b/app/pages/packages/db.wrn @@ -0,0 +1,321 @@ +page wrnexusdb { + seo { + title = "@wrnexus/db" + description = "Database adapters, typed queries, models, migrations, and sessions." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Data

@wrnexus/db

Database adapters, typed queries, models, migrations, and sessions.

bun add @wrnexus/db@0.2.12
The database layer for WRNexusJS: TS models as the single source of truth for DDL, validation, and result typing, plus a driver-based Db client, migrations, and a sqlc-style query generator.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/db is the server-side data layer. You describe tables as TypeScript models (the v column builder + table()); those models drive migrations, coerce raw DB rows into typed objects, and feed the query generator. A thin Driver interface is implemented by adapters for SQLite (bun:sqlite), Postgres/MySQL (Bun.SQL), and MongoDB. The Db client adds ergonomics — model-mapped all/one, transactions, createTable, pagination, and batched relation loading. A process-wide registry (getDb/setDb) exposes configured connections to pages and API routes. Reach for it whenever a WRNexusJS app needs persistence.

+

Installation

+
bun add @wrnexus/db
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The core entry (@wrnexus/db) is dependency-free; adapters and connectors live in subpaths so importing the core doesn't pull in every driver.

+
+ +
SubpathExports
@wrnexus/dbv, table, Column, createDb, createTableSql, the client registry (setDb/getDb/…), migrations, the query generator, and query helpers
@wrnexus/db/connectconnectFromConfig, resolveDbUrl, DbConfig — resolve a config to a live SQL Db
@wrnexus/db/sessionsqliteSessionStore — a bun:sqlite session backend for @wrnexus/core
@wrnexus/db/sqlitesqlite(url?) driver
@wrnexus/db/postgrespostgres(url) driver
@wrnexus/db/mysqlmysql(url) driver
@wrnexus/db/mongomongo(url, dbName?) document API
+

Schema — v, table, Column

+

table(name, columns) returns a Model<T>. Columns are built with v:

+
import { v, table } from "@wrnexus/db";
+
+const users = table("users", {
+  id: v.id(), // auto-increment primary key
+  email: v.text().unique(),
+  name: v.text().optional(), // NULLable
+  age: v.int().default(0),
+  active: v.bool().default(true),
+  createdAt: v.timestamp().default("now"), // CURRENT_TIMESTAMP
+});
+

Column builders: v.id, v.text (alias v.string), v.int, v.real (alias v.number), v.bool (alias v.boolean), v.timestamp, v.json. BaseType values are "id" | "text" | "int" | "real" | "bool" | "timestamp" | "json".

+

Column modifiers (chainable): .optional(), .unique(), .default(value) (use the sentinel "now" for a current-timestamp default), .primaryKey(), .references(table, column = "id"). .coerce(raw) converts a raw DB value to its JS type.

+

A Model<T> exposes: name, columns, parse(row) (coerces a raw row into a typed T; unknown columns pass through), and describe() (returns each column's ColumnDef, for migrations and the generator).

+

Driver & client — createDb, Db, Driver

+
createDb(driver: Driver): Db
+

A Driver (implemented by adapters) exposes dialect, query(sql, params?), exec(sql, params?), transaction(fn), and close(). createDb wraps it in a Db:

+
    +
  • all<T>(sql, params?, model?) — all rows, mapped through model.parse when a model is given.
  • +
  • one<T>(sql, params?, model?) — first row or null.
  • +
  • exec(sql, params?)Promise<ExecResult> ({ changes, lastInsertId? }).
  • +
  • tx(fn) — run fn(db) in a transaction; rolls back on throw. Nested tx reuses the current transaction.
  • +
  • createTable(model) — runs the model's CREATE TABLE IF NOT EXISTS DDL.
  • +
  • close().
  • +
+

Every query is parameterized (positional params). createTableSql(model, dialect, ifNotExists?) renders CREATE TABLE directly; Dialect is "sqlite" | "postgres" | "mysql".

+

Client registry — getDb / setDb

+

A process-wide registry the runtime configures at startup from wrnexus.config.ts (the db setting is the default; databases.<name> entries are named).

+
    +
  • setDb(db) / setDb(name, db) — set the default or a named connection.
  • +
  • registerDb(name, db) — alias of setDb(name, db).
  • +
  • getDb(name = "default") — the default or a named Db (throws if unconfigured).
  • +
  • hasDb(name?), databaseNames(), closeDatabases().
  • +
+
const users = await getDb().all("SELECT * FROM users");
+const events = await getDb("analytics").all("SELECT * FROM hits");
+

Adapters

+
    +
  • @wrnexus/db/sqlitesqlite(url = ":memory:"). url may be file:./dev.db, a raw path, or :memory:. Built on bun:sqlite; no external service.
  • +
  • @wrnexus/db/postgrespostgres(url) (e.g. postgres://user:pass@host:5432/db, placeholders $N).
  • +
  • @wrnexus/db/mysqlmysql(url) (e.g. mysql://user:pass@host:3306/db, placeholders ?). Postgres/MySQL both use Bun's native Bun.SQL client and its pooled begin() for transactions.
  • +
  • @wrnexus/db/mongomongo(url, dbName?). A document API, not SQL: db.collection(model) returns a MongoRepo<T> with find, findOne, insert, insertMany, update, delete, count. Reads are coerced through model.parse (_id is mapped to id). The mongodb driver is imported lazily — install it to use Mongo.
  • +
+

Migrations

+

Migrations are .sql files (in e.g. app/db/migrations), each split into -- +up and -- +down sections. A file with no markers is treated entirely as up. Applied names are recorded in a _wire_migrations table so each runs once.

+
    +
  • parseMigration(name, content)Migration ({ name, up, down }).
  • +
  • loadMigrations(dir) — parse all .sql files, sorted by filename.
  • +
  • appliedMigrations(db) — applied names, oldest first.
  • +
  • migrate(db, dir) — apply all pending (each in a transaction); returns applied names.
  • +
  • rollback(db, dir) — roll back the most recent; returns its name or null.
  • +
  • status(db, dir){ name, applied }[] for every migration file.
  • +
  • scaffoldMigration(dir, name, dialect, models?) — write a new numbered migration; with models it generates CREATE/DROP for every table (referenced tables first via topological sort). Returns the file path.
  • +
+

Query generator (sqlc-style)

+

Turns annotated SQL into typed TS functions; params and result types are inferred from the models, and rows map back through model.parse when the selected columns are model columns.

+
    +
  • parseQueries(content)QueryDef[] from -- name: X :one|:many|:exec blocks.
  • +
  • generateQueriesFile(queries, models, dialect) → the queries.gen.ts source. models is a ModelRef[] ({ varName, model }). Rewrites :name placeholders to positional ($N/?) form.
  • +
+

QueryKind is "one" | "many" | "exec".

+

Query helpers

+
    +
  • paginate(db, { sql, params?, countSql?, model? }, opts?) — offset pagination. Pass the base SELECT without a LIMIT; it appends the page window and derives total via a COUNT subquery. PageOptions: { page?, perPage?, maxPerPage? } (defaults page 1, perPage 20, maxPerPage 100). Returns Paginated<T> (items, page, perPage, total, totalPages, hasNext, hasPrev).
  • +
  • loadRelated(db, parents, opts) — load a relation for many parents in ONE query and attach it (no N+1). RelationOptions: { table, foreignKey, as, localKey?, single?, model? }single: true attaches one child (belongsTo), otherwise an array (hasMany). Table/foreign-key names are validated as identifiers.
  • +
+

Session store

+

@wrnexus/db/session exports sqliteSessionStore(path = "sessions.db"), a persistent, process-shared SessionBackend (from @wrnexus/core) backed by bun:sqlite (WAL mode). Sessions survive restarts and are shared by every worker on the same file.

+

Usage

+

Define models, connect, create tables, and query with typed results:

+
import { v, table, createDb } from "@wrnexus/db";
+import { sqlite } from "@wrnexus/db/sqlite";
+
+const users = table<{ id: number; email: string; name: string | null }>("users", {
+  id: v.id(),
+  email: v.text().unique(),
+  name: v.text().optional(),
+  createdAt: v.timestamp().default("now"),
+});
+
+const db = createDb(sqlite("file:./dev.db"));
+await db.createTable(users);
+
+await db.exec("INSERT INTO users (email) VALUES (?)", ["a@b.com"]);
+const list = await db.all("SELECT * FROM users", [], users); // rows typed + coerced
+const one = await db.one("SELECT * FROM users WHERE id = ?", [1], users);
+
+await db.tx(async (tx) => {
+  await tx.exec("UPDATE users SET name = ? WHERE id = ?", ["Ada", 1]);
+});
+

Resolve a config to a live SQL Db, and register it:

+
import { connectFromConfig } from "@wrnexus/db/connect";
+import { setDb, getDb } from "@wrnexus/db";
+
+setDb(connectFromConfig({ driver: "sqlite", url: "file:./dev.db" }, process.cwd()));
+const rows = await getDb().all("SELECT * FROM users");
+

Run migrations and paginate:

+
import { migrate, paginate } from "@wrnexus/db";
+
+await migrate(db, "app/db/migrations");
+const pageTwo = await paginate(
+  db,
+  { sql: "SELECT * FROM users ORDER BY id", model: users },
+  { page: 2 },
+);
+

MongoDB (document API):

+
import { mongo } from "@wrnexus/db/mongo";
+
+const mdb = await mongo(process.env.MONGO_URL!, "app");
+const repo = mdb.collection(users);
+await repo.insert({ email: "a@b.com" });
+const active = await repo.find({ active: true });
+

Configuration

+

connectFromConfig (and the runtime) read a DbConfig ({ driver, url }) where driver is sqlite | postgres | mysql. resolveDbUrl(url, appRoot?) resolves a relative file:/sqlite: URL against the app root. MongoDB is not a SQL driver — use @wrnexus/db/mongo directly.

+

Requirements / Notes

+
    +
  • Bun-only. Uses bun:sqlite (SQLite adapter + session store) and Bun.SQL
  • +

    (Postgres/MySQL). Migrations/scaffolding use node:fs/node:path.

    +
  • Works with @wrnexus/coresqliteSessionStore implements its
  • +

    SessionBackend; getDb/setDb are wired by the WRNexusJS runtime from wrnexus.config.ts.

    +
  • The mongodb npm package is an optional, lazily-imported peer — install it
  • +

    only if you use @wrnexus/db/mongo. The core package stays dependency-free.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { M as Model } from './schema-tVurYsbL.js';
+export { B as BaseType, C as Column, a as ColumnDef, b as Columns, t as table, v } from './schema-tVurYsbL.js';
+import { a as Db, b as Dialect, R as Row } from './driver-DA53QHkO.js';
+export { D as Driver, E as ExecResult, T as TxHandle, c as createDb, d as createTableSql } from './driver-DA53QHkO.js';
+
+/**
+ * A process-wide database registry. The framework configures it at server
+ * startup from `wrnexus.config.ts`: the `db` setting becomes the **default**
+ * connection, and each entry under `databases` becomes a **named** connection.
+ * Pages and API routes then call `getDb()` for the default, or `getDb("<name>")`
+ * for a named one, to run queries (including the generated typed functions).
+ *
+ *   const users = await getDb().all("SELECT * FROM users");            // default db
+ *   const events = await getDb("analytics").all("SELECT * FROM hits"); // named db
+ */
+
+/** Set the default database (called by the runtime at startup). */
+declare function setDb(db: Db): Db;
+/** Set a named database (from `databases.<name>` in config). */
+declare function setDb(name: string, db: Db): Db;
+/** Register a named database. Alias of `setDb(name, db)` for readability. */
+declare function registerDb(name: string, db: Db): Db;
+/** The default database, or a named one. Throws if it isn't configured. */
+declare function getDb(name?: string): Db;
+/** Whether the default (or a named) database has been configured. */
+declare function hasDb(name?: string): boolean;
+/** Names of all configured databases (the default appears as "default"). */
+declare function databaseNames(): string[];
+/** Close every configured database and clear the registry. */
+declare function closeDatabases(): Promise<void>;
+
+/**
+ * Migration runner. Migrations are `.sql` files in `app/db/migrations`, each
+ * split into `-- +up` and `-- +down` sections. Applied migrations are recorded
+ * in a `_wire_migrations` table so they run exactly once, newest-last.
+ *
+ * `scaffoldMigration(..., models)` writes an initial migration straight from the
+ * TS models — the source of truth — so you don't hand-write the first schema.
+ */
+
+interface Migration {
+    name: string;
+    up: string;
+    down: string;
+}
+/** Split a migration file into its `up` and `down` SQL sections. */
+declare function parseMigration(name: string, content: string): Migration;
+/** Load and parse all migration files in a directory, sorted by filename. */
+declare function loadMigrations(dir: string): Migration[];
+/** Names of already-applied migrations, oldest first. */
+declare function appliedMigrations(db: Db): Promise<string[]>;
+/** Apply all pending migrations (each in a transaction). Returns applied names. */
+declare function migrate(db: Db, dir: string): Promise<string[]>;
+/** Roll back the most recently applied migration. Returns its name, or null. */
+declare function rollback(db: Db, dir: string): Promise<string | null>;
+/** Full status: every migration file with whether it has been applied. */
+declare function status(db: Db, dir: string): Promise<{
+    name: string;
+    applied: boolean;
+}[]>;
+/**
+ * Write a new migration file. With `models`, the `up`/`down` are generated from
+ * the TS models (create/drop every table); otherwise empty stubs are written.
+ * Returns the created file path.
+ */
+declare function scaffoldMigration(dir: string, name: string, dialect: Dialect, models?: Model[]): string;
+
+/**
+ * sqlc-style query generator. Annotated SQL in `app/db/queries/*.sql` becomes
+ * typed TS functions whose params + results are inferred from the TS models and
+ * whose rows are mapped back through `model.parse`.
+ *
+ *   -- name: GetUserByEmail :one
+ *   SELECT * FROM users WHERE email = :email;
+ *
+ * →  GetUserByEmail(db, { email: string }): Promise<{…} | null>
+ *
+ * Type inference is best-effort (comparisons + INSERT column lists + SELECT list
+ * vs the model); anything it can't resolve becomes `unknown`.
+ */
+
+type QueryKind = "one" | "many" | "exec";
+interface QueryDef {
+    name: string;
+    kind: QueryKind;
+    sql: string;
+}
+/** A model plus the variable name it is exported under (for imports). */
+interface ModelRef {
+    varName: string;
+    model: Model;
+}
+/** Parse annotated queries from one `.sql` file's contents. */
+declare function parseQueries(content: string): QueryDef[];
+/** Generate the full `queries.gen.ts` source. */
+declare function generateQueriesFile(queries: QueryDef[], models: ModelRef[], dialect: Dialect): string;
+
+/**
+ * Query ergonomics built on the `Db` client: offset pagination and a batched
+ * relation loader (avoids N+1). Both are dialect-aware — placeholders follow the
+ * driver's style (`$N` for Postgres, `?` for SQLite/MySQL).
+ */
+
+interface PageOptions {
+    page?: number;
+    perPage?: number;
+    /** Upper bound on perPage. Default 100. */
+    maxPerPage?: number;
+}
+interface Paginated<T> {
+    items: T[];
+    page: number;
+    perPage: number;
+    total: number;
+    totalPages: number;
+    hasNext: boolean;
+    hasPrev: boolean;
+}
+/**
+ * Paginate a SELECT. Pass the base query WITHOUT a LIMIT; the helper appends the
+ * page window and derives the total with a COUNT over the same query.
+ *
+ *   await paginate(db, { sql: "SELECT * FROM users ORDER BY name", model: users }, { page: 2 })
+ */
+declare function paginate<T = Row>(db: Db, query: {
+    sql: string;
+    params?: unknown[];
+    countSql?: string;
+    model?: Model<T>;
+}, opts?: PageOptions): Promise<Paginated<T>>;
+interface RelationOptions<C> {
+    /** Parent field whose value matches the child's foreign key. Default "id". */
+    localKey?: string;
+    /** Child table to load from. */
+    table: string;
+    /** Child column that references the parent. */
+    foreignKey: string;
+    /** Property name to attach on each parent. */
+    as: string;
+    /** true → attach a single child (belongsTo); false → an array (hasMany). */
+    single?: boolean;
+    /** Map child rows through a model. */
+    model?: Model<C>;
+}
+/**
+ * Load a relation for a set of parent rows in ONE query and attach it to each
+ * parent (no N+1). Returns the same parents, each with `opts.as` populated.
+ *
+ *   await loadRelated(db, users, { table: "posts", foreignKey: "userId", as: "posts" })
+ */
+declare function loadRelated<P extends Row, C extends Row = Row>(db: Db, parents: P[], opts: RelationOptions<C>): Promise<(P & Record<string, C | C[] | null>)[]>;
+
+export { Db, Dialect, type Migration, Model, type ModelRef, type PageOptions, type Paginated, type QueryDef, type QueryKind, type RelationOptions, Row, appliedMigrations, closeDatabases, databaseNames, generateQueriesFile, getDb, hasDb, loadMigrations, loadRelated, migrate, paginate, parseMigration, parseQueries, registerDb, rollback, scaffoldMigration, setDb, status };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/db

Example 2

import { v, table } from "@wrnexus/db";
+
+const users = table("users", {
+  id: v.id(), // auto-increment primary key
+  email: v.text().unique(),
+  name: v.text().optional(), // NULLable
+  age: v.int().default(0),
+  active: v.bool().default(true),
+  createdAt: v.timestamp().default("now"), // CURRENT_TIMESTAMP
+});

Example 3

createDb(driver: Driver): Db

Example 4

const users = await getDb().all("SELECT * FROM users");
+const events = await getDb("analytics").all("SELECT * FROM hits");
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/dev-server.wrn b/app/pages/packages/dev-server.wrn new file mode 100644 index 00000000..fb2f7532 --- /dev/null +++ b/app/pages/packages/dev-server.wrn @@ -0,0 +1,727 @@ +page wrnexusdevserver { + seo { + title = "@wrnexus/dev-server" + description = "Development and production servers, HMR, assets, and gateways." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Runtime

@wrnexus/dev-server

Development and production servers, HMR, assets, and gateways.

bun add @wrnexus/dev-server@0.2.12
The WRNexusJS HTTP + WebSocket server runtime — request dispatch, SSR document assembly, live-reload (HMR), and the portable production handler.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

This package is the server runtime that powers a WRNexusJS app in both development and production. A single request runtime (createHandlers) owns HTTP/WebSocket dispatch and SSR document assembly; it knows nothing about _how_ modules and assets are produced, so the dev and prod entry points wire in different backends: dev uses dynamic module loading plus on-the-fly bundling and injects a live-reload client; prod uses a static, pre-built manifest with cache-immutable assets. The package also ships a multi-app gateway (route several apps by Host header behind one port) and a portable node:http adapter for WinterCG hosts. It is entirely server-side and Bun-native (Bun.serve, Bun.file, Bun.gzipSync).

+

Installation

+
bun add @wrnexus/dev-server
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported for the full server; the node:http adapter is for WinterCG embedding only).
+

API

+

Main entry (@wrnexus/dev-server)

+
+ +
ExportKindPurpose
startServer(opts: ServeOptions)Promise<RunningServer>Start the dev server on Bun.serve: builds the router, connects/migrates databases, wires assets + HMR, and starts the file watcher.
createHandlers(deps: RuntimeDeps)HandlersThe shared request runtime (fetch + websocket handlers). Re-exported from runtime.ts.
createProductionServer(manifest, opts)Bun.ServerStart the production server from a precompiled manifest.
createProductionHandlers(manifest, opts)HandlersBuild the portable prod fetch/websocket handlers with no server bound (the deployment-adapter seam).
startGateway(opts: GatewayOptions)Promise<RunningGateway>Boot multiple apps as child processes and route by Host.
toRequest, writeResponse, nodeListener, serveNodefunctionsnode:http ↔ WinterCG Request/Response adapter.
RESTART_EXIT_CODEnumber (97)Exit code the dev child uses to ask the supervisor for a fresh process.
STYLES_HREF, HMR_CLIENT_JSconstantsThe global stylesheet URL and the inline HMR client script.
+

Exported types: ServeOptions, RunningServer, RuntimeDeps, AssetServer, WsData, GatewayApp, GatewayOptions, GatewayAuth, GatewaySecurity, RunningGateway, FetchHandler.

+

startServer(opts)

+
interface ServeOptions {
+  appDir: string; // absolute/relative path to the app/ dir
+  port?: number; // default 3000
+  hostname?: string; // default "localhost"
+  mode?: Mode; // "development" | "production"; default "development"
+  hmr?: boolean; // inject live-reload client; default (mode === "development")
+  styleEntry?: string | null; // resolved absolute path to the global CSS entry
+  stylesConfig?: StylesConfig; // custom styles processor (e.g. Tailwind/PostCSS)
+  head?: string; // raw HTML appended to every page <head>
+  seo?: SeoConfig; // global SEO defaults
+  security?: SecurityConfig; // security headers + CORS policy
+  theme?: ThemeConfig; // design-token theme (merged over built-in light/dark)
+  i18n?: I18nConfig; // default language + supported locales
+  db?: { driver: string; url: string }; // default db → getDb(); dev auto-migrates
+  databases?: Record<string, { driver: string; url: string }>; // named dbs → getDb("<name>")
+  realtime?: { scale?: boolean; redisUrl?: string }; // bridge rooms over Redis across processes
+}
+
+interface RunningServer {
+  port: number;
+  hostname: string;
+  url: string;
+  router: Router;
+  stop(): void;
+}
+

In development, startServer also connects app/db/migrations (and app/db/<name>/migrations) and auto-applies migrations, then starts an in-process file watcher. CSS edits hot-swap live; any other server change triggers process.exit(RESTART_EXIT_CODE) so the dev supervisor (@wrnexus/cli) respawns the process with fresh modules.

+

createHandlers(deps)

+

The core runtime shared by dev and prod. It handles CORS preflight, /healthz and /__wrnexus/health, request-body size limits (413), HMR socket upgrades (/__wrnexus/hmr), realtime WebSocket upgrades (defineRoom default export or a raw websocket export), the middleware pipeline, API routes (/api/*), framework assets (/__wrnexus/*), public assets, and full SSR page rendering (component mounts, layouts, slots, i18n markers, per-page script selection, ETag/304, gzip).

+
interface RuntimeDeps {
+  mode: Mode;
+  hmr: boolean; // inject the live-reload client into pages
+  router: Router;
+  loadModule(file: string): Promise<Record<string, unknown>>;
+  getMiddleware(): Promise<Middleware[]>;
+  assets: AssetServer; // serves /__wrnexus/* (islands, reactive, hmr)
+  hasStyles?: boolean; // inject the global stylesheet link
+  hasUi?: boolean; // inject the Wire UI stylesheet (/__wrnexus/ui.css)
+  theme?: ResolvedTheme; // enables /__wrnexus/theme.css + <html data-theme>
+  i18n?: ResolvedI18n; // enables ctx.t, <html lang>, {t:key} markers
+  inlineStyles?: string; // inline small prod stylesheets into <head>
+  assetVersion?: string; // cache-busting ?v= on framework asset URLs
+  head?: string; // raw HTML appended to every page <head>
+  seo?: SeoConfig;
+  security?: SecurityConfig;
+  maxBodyBytes?: number; // 413 above this; default 10 MB
+  hub?: HmrHub; // browser HMR sockets (dev only)
+  realtimeBus?: RealtimeBus; // cross-process room bridge (Redis pub/sub)
+}
+
+interface Handlers {
+  fetch(req: Request, server: UpgradeServer): Promise<Response | undefined>;
+  websocket: { open; message; close; drain };
+}
+

WsData is the per-connection socket tag — a discriminated union of { kind: "realtime"; handler }, { kind: "room"; meta }, or { kind: "hmr" }.

+

createProductionServer(manifest, opts) / createProductionHandlers(manifest, opts)

+

Production runs the _same_ request runtime as dev, but with no filesystem scan and no runtime bundling. wrnexus build emits an entry that statically imports every route/component/layout module and passes them as a ProdManifest; the route-matching tables are rebuilt from the raw patterns.

+
interface ProdManifest {
+  pages: { raw: string; mod: RouteModule }[];
+  api: { raw: string; mod: RouteModule }[];
+  realtime: { raw: string; mod: RouteModule }[];
+  middleware: Middleware[];
+  components: { name: string; mod: RouteModule }[];
+  layouts: { name: string; mod: RouteModule }[];
+}
+
+interface ProdOptions {
+  stylesPath?: string;
+  inlineStyles?: string;
+  reactivePath?: string;
+  themePath?: string;
+  themeJsPath?: string;
+  theme?: ResolvedTheme;
+  uiCssPath?: string;
+  schemasJs?: string;
+  i18n?: ResolvedI18n;
+  db?: { driver: string; url: string };
+  databases?: Record<string, { driver: string; url: string }>;
+  realtime?: { scale?: boolean; redisUrl?: string };
+  assetVersion?: string;
+  publicDir?: string;
+  head?: string;
+  seo?: SeoConfig;
+  security?: SecurityConfig;
+  port?: number;
+  hostname?: string;
+  maxBodyBytes?: number;
+}
+

createProductionServer also loads the .env cascade for the production profile, installs SIGTERM/SIGINT graceful shutdown, and binds 0.0.0.0 (port from opts.port or $PORT, default 3000). Migrations are not run here — apply them first (wrnexus db migrate). createProductionHandlers returns the bare handlers for edge/serverless/node:http deployment.

+

startGateway(opts) — multi-app gateway

+

Serves several apps behind one port and routes each request to the right app by its Host header. Each app runs as its own child process (full isolation); the gateway is a thin host-based reverse proxy for HTTP and WebSocket. Apps communicate at runtime via @wrnexus/pubsub (use the Redis driver so messages cross processes).

+
interface GatewayOptions {
+  port?: number; // default 3000
+  hostname?: string; // default "localhost"
+  mode?: "development" | "production";
+  apps: GatewayApp[];
+  security?: GatewaySecurity;
+}
+
+interface GatewayApp {
+  name: string; // app id (for logs)
+  dir: string; // app root (contains app/ + wrnexus.config.ts)
+  domains: string[]; // host names routed here
+  port?: number; // fixed internal port; else assigned
+  auth?: GatewayAuth; // per-app edge access control
+}
+
+interface GatewayAuth {
+  basic?: { user: string; pass: string } | Array<{ user: string; pass: string }>;
+  allowIps?: string[]; // exact-match IP allowlist
+  forward?: { url: string }; // forward-auth (SSO): 2xx allows
+}
+
+interface GatewaySecurity {
+  trustedHostsOnly?: boolean; // 404 unknown hosts instead of first app
+  rateLimit?: { max: number; windowMs?: number }; // global by client IP (429)
+  headers?: boolean; // add baseline edge security headers
+  forwardedHeaders?: boolean; // set X-Forwarded-* (default true)
+  accessLog?: boolean;
+}
+

The gateway exposes /__gateway/health (JSON list of routed apps) and returns a RunningGateway ({ port, url, stop() }).

+

node:http adapter (from ./adapters/node.ts)

+

For embedding the WinterCG handler behind an existing Node server or a WinterCG host. Note the full app still needs Bun-compatible globals (Bun.file, bun:sqlite, etc.); only the Request/Response conversion is fully portable.

+
type FetchHandler = (req: Request) => Response | undefined | Promise<Response | undefined>;
+
+toRequest(req: IncomingMessage, opts?): Promise<Request>
+writeResponse(res: ServerResponse, response: Response): Promise<void>  // preserves multiple Set-Cookie
+nodeListener(handler: FetchHandler, opts?): (req, res) => Promise<void>
+serveNode(handler: FetchHandler, opts?): Promise<Server>
+

Subpath export: @wrnexus/dev-server/serve-entry

+

The child process the dev supervisor launches:

+
bun run serve-entry.ts <appDir> <port> <mode>
+

It loads the optional wrnexus.config.ts, resolves the style entry, calls startServer, and prints the route table (Pages / API / Realtime / Components). Because it runs in its own process, every restart re-imports all route modules fresh — that is how the supervisor delivers live reload of edited server code. startGateway resolves this entry via import.meta.resolve("@wrnexus/dev-server/serve-entry") to spawn each dev app.

+

Usage

+

Programmatic dev server

+
import { startServer } from "@wrnexus/dev-server";
+
+const server = await startServer({
+  appDir: "./app",
+  port: 3000,
+  mode: "development",
+  theme: {/* design tokens */},
+  db: { driver: "sqlite", url: "file:./data/app.db" },
+});
+
+console.log(`Running at ${server.url}`);
+// server.stop();
+

Production server from a build manifest

+
import { createProductionServer } from "@wrnexus/dev-server";
+import { manifest } from "./dist/manifest.js"; // generated by `wrnexus build`
+
+createProductionServer(manifest, {
+  stylesPath: "./dist/styles.css",
+  reactivePath: "./dist/reactive.js",
+  assetVersion: process.env.BUILD_ID,
+  db: { driver: "postgres", url: process.env.DATABASE_URL! },
+  port: Number(process.env.PORT) || 3000,
+});
+

Embedding the handler on node:http

+
import { createProductionHandlers, serveNode } from "@wrnexus/dev-server";
+
+const handlers = createProductionHandlers(manifest, opts);
+await serveNode(handlers.fetch, { port: 8080 });
+

Multi-app gateway

+
import { startGateway } from "@wrnexus/dev-server";
+
+await startGateway({
+  port: 3000,
+  apps: [
+    { name: "web", dir: "./apps/web", domains: ["localhost", "web.localhost"] },
+    {
+      name: "admin",
+      dir: "./apps/admin",
+      domains: ["admin.localhost"],
+      auth: { basic: { user: "root", pass: "s3cret" } },
+    },
+  ],
+  security: { trustedHostsOnly: true, rateLimit: { max: 600 } },
+});
+

Framework asset routes

+

The runtime serves these framework-owned paths (dev builds them live; prod serves pre-built/immutable versions):

+
    +
  • /__wrnexus/nav.js, /__wrnexus/reactive.js, /__wrnexus/realtime.js — client runtimes
  • +
  • /__wrnexus/validate.js, /__wrnexus/schemas.js, /__wrnexus/i18n.js — validation + i18n runtimes
  • +
  • /__wrnexus/theme.css, /__wrnexus/theme.js, /__wrnexus/ui.css, /__wrnexus/styles.css — styles
  • +
  • /__wrnexus/hmr — dev-only HMR WebSocket
  • +
  • /__wrnexus/csr — server-evaluated CSR bindings for browser-side API fetches
  • +
+

Pages get only the scripts they use: nav.js always, reactive.js when a page has a data-scope/CSR fetch, plus theme/validation/i18n/realtime runtimes when the relevant markup is present.

+

Requirements / Notes

+
    +
  • Bun-only. Uses Bun.serve (HTTP + WebSocket), Bun.file, and Bun.gzipSync. The full app also relies on bun:sqlite / Bun.SQL via @wrnexus/db.
  • +
  • Orchestrates the whole framework: @wrnexus/core (context, security, realtime registry), @wrnexus/router, @wrnexus/ssr (renderDocument), @wrnexus/csr (client runtimes), @wrnexus/compiler (.wrn → TS), @wrnexus/styles, @wrnexus/ui, @wrnexus/validation, @wrnexus/i18n, @wrnexus/db, and @wrnexus/pubsub (Redis-backed cross-process realtime).
  • +
  • .wrn files are compiled to TypeScript into a hidden sibling .wrnexus/ cache dir and dynamically imported; the module cache means each edited server module needs a fresh process (dev) — hence the restart-on-change model.
  • +
  • Responses are gzipped when the client accepts it and the body is a buffered, compressible payload ≥ 1 KB; streaming/SSE responses opt out via Cache-Control: no-transform.
  • +

    </content>

    +
+

</invoke>

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Mode, Middleware, SeoConfig, SecurityConfig, RealtimeBus, RealtimeConnectMeta } from '@wrnexus/core';
+import { Router } from '@wrnexus/router';
+import { ResolvedTheme, MobileConfig, PwaConfig, StylesConfig, ThemeConfig } from '@wrnexus/styles';
+import { ResolvedI18n, I18nConfig } from '@wrnexus/i18n';
+import { StorageConfig } from '@wrnexus/uploader';
+import { IncomingMessage, ServerResponse, Server } from 'node:http';
+
+/**
+ * HMR hub — tracks connected browser HMR sockets and broadcasts update events.
+ *
+ * Each open page holds one WebSocket to `/__wrnexus/hmr`. The in-process file
+ * watcher (see index.ts) classifies a change and broadcasts a typed message:
+ *
+ *   { type: "css" }     -> the browser hot-swaps the stylesheet (no reload)
+ *   { type: "reload" }  -> the browser asks for fresh HTML over the HMR socket
+ *
+ * Server-logic changes (pages/api/middleware/realtime) are NOT broadcast here:
+ * they require a fresh process, so the child exits and the supervisor respawns
+ * it. The browser then reconnects and performs a soft DOM morph automatically.
+ */
+type HmrMessage = {
+    type: "css";
+    version: number;
+} | {
+    type: "reload";
+    version: number;
+};
+/** Minimal shape of a Bun ServerWebSocket we rely on. */
+interface Socket {
+    send(data: string): unknown;
+}
+declare class HmrHub {
+    private sockets;
+    private version;
+    add(ws: Socket): void;
+    remove(ws: Socket): void;
+    broadcast(message: HmrMessage): void;
+    get size(): number;
+    css(): void;
+    reload(): void;
+}
+
+/**
+ * Shared request runtime used by BOTH the dev server and the production server.
+ *
+ * It owns the HTTP/WebSocket dispatch and the SSR document assembly, but knows
+ * nothing about *how* modules or assets are produced — those come in via
+ * `RuntimeDeps`. Dev wires in dynamic module loading + on-the-fly bundling;
+ * prod wires in a static manifest + pre-built chunks on disk.
+ */
+
+/** A realtime module's `websocket` export: a bag of optional lifecycle hooks. */
+type WsHandler = Record<string, (...args: any[]) => unknown>;
+/**
+ * Per-connection socket data. A socket is either an app realtime connection or
+ * an internal HMR connection — discriminated by `kind`.
+ */
+type WsData = {
+    kind: "realtime";
+    handler: WsHandler;
+} | {
+    kind: "room";
+    meta: RealtimeConnectMeta;
+} | {
+    kind: "hmr";
+    baseUrl: string;
+    headers: [string, string][];
+};
+type RouteModule$1 = Record<string, unknown>;
+/** Serves framework-owned assets under `/__wrnexus/*` (islands, reactive, hmr). */
+interface AssetServer {
+    serve(pathname: string): Promise<Response | null>;
+}
+interface RuntimeDeps {
+    mode: Mode;
+    /** When true, inject the live-reload client into rendered pages. */
+    hmr: boolean;
+    router: Router;
+    /** Load a route module by absolute path (dev: dynamic import; prod: manifest). */
+    loadModule(file: string): Promise<RouteModule$1>;
+    /** Resolve the ordered middleware chain. */
+    getMiddleware(): Promise<Middleware[]>;
+    /** Serve `/__wrnexus/*` assets. */
+    assets: AssetServer;
+    /** When true, inject the global stylesheet link into every page head. */
+    hasStyles?: boolean;
+    /** When true, inject the Wire UI stylesheet link (`/__wrnexus/ui.css`). */
+    hasUi?: boolean;
+    /** Resolved theme config: enables `/__wrnexus/theme.css` + `<html data-theme>`. */
+    theme?: ResolvedTheme;
+    /** Resolved i18n bundle: enables `ctx.t`, `<html lang>`, and `{t:key}` markers. */
+    i18n?: ResolvedI18n;
+    /** Small production stylesheets can be inlined to avoid a render-blocking request. */
+    inlineStyles?: string;
+    /** Production cache-busting version appended to framework asset URLs. */
+    assetVersion?: string;
+    /** Raw HTML appended to every page head (e.g. CDN framework links). */
+    head?: string;
+    /** Global SEO defaults. */
+    seo?: SeoConfig;
+    mobile?: MobileConfig;
+    pwa?: PwaConfig | false;
+    /** Framework security headers and CORS policy. */
+    security?: SecurityConfig;
+    /** Max request body size in bytes (413 above this). Default 10 MB. */
+    maxBodyBytes?: number;
+    /** HMR hub for browser live-update sockets (dev only). */
+    hub?: HmrHub;
+    /**
+     * Cross-process realtime bus. When provided, room broadcasts/`toUser` sends are
+     * bridged to it so they reach clients on every app process/instance sharing the
+     * bus (use the Redis pub/sub driver). Enables realtime across multiple apps.
+     */
+    realtimeBus?: RealtimeBus;
+}
+interface UpgradeServer {
+    upgrade(req: Request, opts: {
+        data: WsData;
+    }): boolean;
+    /** Bun's per-request socket peer address (used for the non-spoofable client IP). */
+    requestIP?(req: Request): {
+        address: string;
+    } | null;
+}
+/** The subset of Bun's ServerWebSocket the runtime touches. */
+interface Ws {
+    data: WsData;
+    send(data: string | Uint8Array): unknown;
+    close(code?: number, reason?: string): void;
+}
+interface Handlers {
+    fetch(req: Request, server: UpgradeServer): Promise<Response | undefined>;
+    websocket: {
+        open(ws: Ws): void;
+        message(ws: Ws, message: string | Uint8Array): void;
+        close(ws: Ws, code?: number, reason?: string): void;
+        drain(ws: Ws): void;
+    };
+}
+/** Build the fetch + websocket handlers from a set of dependencies. */
+declare function createHandlers(deps: RuntimeDeps): Handlers;
+
+/**
+ * The multi-app **gateway** — serves several WRNexusJS apps behind one port and
+ * routes each request to the right app by its `Host` header (domain). This is how
+ * a monorepo becomes a multi-domain SaaS: `app-a.com` → apps/a, `app-b.com` → apps/b.
+ *
+ * Each app runs as its own **process** (full isolation — its own database
+ * registry, pubsub, in-memory state), and the gateway is a thin host-based
+ * reverse proxy for both HTTP and WebSocket. Apps talk to each other at runtime
+ * via @wrnexus/pubsub (use the Redis driver so messages cross processes).
+ */
+/** Per-app access control, enforced at the gateway before proxying. */
+interface GatewayAuth {
+    /** HTTP Basic auth — one or more allowed user/password pairs. */
+    basic?: {
+        user: string;
+        pass: string;
+    } | Array<{
+        user: string;
+        pass: string;
+    }>;
+    /** Allow only these client IPs (exact match; others get 403). */
+    allowIps?: string[];
+    /**
+     * Forward-auth (SSO): the gateway GETs `url` forwarding the request's cookies +
+     * Authorization; a 2xx allows the request, anything else blocks it (its status
+     * is returned). Point it at your own verify endpoint.
+     */
+    forward?: {
+        url: string;
+    };
+}
+interface GatewayApp {
+    /** App id (for logs). */
+    name: string;
+    /** Path to the app root (the dir containing `app/` and wrnexus.config.ts). */
+    dir: string;
+    /** Host names routed to this app (e.g. ["localhost", "web.localhost"]). */
+    domains: string[];
+    /** Optional fixed internal port; otherwise assigned from the gateway port. */
+    port?: number;
+    /** Access control enforced at the edge for this app. */
+    auth?: GatewayAuth;
+}
+/** Gateway-wide security controls, enforced for every app. */
+interface GatewaySecurity {
+    /** Reject requests whose Host matches no app (404) instead of routing to the first. */
+    trustedHostsOnly?: boolean;
+    /** Global rate limit by client IP (429 over the limit). */
+    rateLimit?: {
+        max: number;
+        windowMs?: number;
+    };
+    /** Add baseline security headers to responses (only where the app didn't set them). */
+    headers?: boolean;
+    /** Set X-Forwarded-For/Host/Proto so apps see the real client. Default true. */
+    forwardedHeaders?: boolean;
+    /** Log each request (host → app, method, path, status). */
+    accessLog?: boolean;
+}
+interface GatewayOptions {
+    port?: number;
+    hostname?: string;
+    mode?: "development" | "production";
+    apps: GatewayApp[];
+    security?: GatewaySecurity;
+}
+interface RunningGateway {
+    port: number;
+    url: string;
+    stop(): void;
+}
+/** Boot every app as a child process, then route by Host on one gateway port. */
+declare function startGateway(opts: GatewayOptions): Promise<RunningGateway>;
+
+/**
+ * @wrnexus/dev-server/prod — the production server (Point 4).
+ *
+ * Unlike dev, there is NO filesystem scan and NO on-the-fly bundling at runtime.
+ * `wrnexus build` generates an entry that statically imports every route and
+ * component module and hands them here as a manifest. We rebuild the (cheap)
+ * route-matching tables from the raw patterns and run the exact same request
+ * runtime as dev — just with production error pages and no live-reload client.
+ */
+
+type RouteModule = Record<string, unknown>;
+interface ManifestRoute {
+    /** URL pattern, e.g. `/users/[id]`. */
+    raw: string;
+    /** The statically-imported route module. */
+    mod: RouteModule;
+}
+interface ProdManifest {
+    pages: ManifestRoute[];
+    api: ManifestRoute[];
+    realtime: ManifestRoute[];
+    middleware: Middleware[];
+    /** Server-rendered components, statically imported and keyed by name. */
+    components: {
+        name: string;
+        mod: RouteModule;
+    }[];
+    /** Named page layouts (from app/layouts/*.wrn). */
+    layouts: {
+        name: string;
+        mod: RouteModule;
+    }[];
+}
+interface ProdOptions {
+    /** Absolute path to the pre-built global stylesheet, if any. */
+    stylesPath?: string;
+    /** Small production stylesheet inlined into the document head. */
+    inlineStyles?: string;
+    /** Absolute path to the pre-built reactive runtime. */
+    reactivePath?: string;
+    /** Absolute path to the pre-built theme stylesheet (`theme.css`). */
+    themePath?: string;
+    /** Absolute path to the pre-built theme runtime (`theme.js`). */
+    themeJsPath?: string;
+    /** Resolved theme config: enables `<html data-theme>` + `theme.css` link. */
+    theme?: ResolvedTheme;
+    /** Absolute path to the pre-built Wire UI stylesheet (`ui.css`). */
+    uiCssPath?: string;
+    /** Pre-built `window.__wireSchemas = {...}` script for client validation. */
+    schemasJs?: string;
+    /** Resolved i18n bundle (default lang + locale messages). */
+    i18n?: ResolvedI18n;
+    /** Default database connection (driver + url); enables `getDb()`. */
+    db?: {
+        driver: string;
+        url: string;
+    };
+    /** Named databases, reached with `getDb("<name>")`. */
+    databases?: Record<string, {
+        driver: string;
+        url: string;
+    }>;
+    /**
+     * Absolute path to the default db's migrations bundled into the build
+     * (`dist/migrations`). When set, they are applied on startup — like dev.
+     */
+    migrationsDir?: string;
+    /** Bundled migrations dirs for named dbs (name → `dist/db/<name>/migrations`). */
+    databaseMigrationDirs?: Record<string, string>;
+    /**
+     * Auto-apply bundled migrations on server startup (default: true). Set false
+     * for deploys that migrate in a separate release step (e.g. multiple instances
+     * behind a load balancer, where you migrate once before rolling out).
+     */
+    autoMigrate?: boolean;
+    /** Realtime scaling: bridge room broadcasts over Redis across app processes. */
+    realtime?: {
+        scale?: boolean;
+        redisUrl?: string;
+    };
+    /** File-upload storage: named stores (local dir / S3). Local dirs resolve against cwd. */
+    storage?: StorageConfig;
+    /** Cache-busting version appended to framework asset URLs. */
+    assetVersion?: string;
+    /** Absolute path to copied public assets, if any. */
+    publicDir?: string;
+    /** Raw HTML appended to every page head. */
+    head?: string;
+    /** Global SEO defaults. */
+    seo?: SeoConfig;
+    mobile?: MobileConfig;
+    pwa?: PwaConfig | false;
+    /** Framework security headers and CORS policy. */
+    security?: SecurityConfig;
+    port?: number;
+    hostname?: string;
+    maxBodyBytes?: number;
+}
+/**
+ * Build the portable request handler from a precompiled manifest — a
+ * WinterCG-style `fetch(request) => Response` plus the websocket handlers, with
+ * NO server bound. This is the deployment-adapter seam: `createProductionServer`
+ * wraps it in `Bun.serve`, `serveNode` bridges it onto `node:http`, and edge or
+ * serverless targets can call `fetch` directly.
+ */
+declare function createProductionHandlers(manifest: ProdManifest, opts: ProdOptions): ReturnType<typeof createHandlers>;
+/** Start the production server on Bun from a precompiled manifest. */
+declare function createProductionServer(manifest: ProdManifest, opts: ProdOptions): Promise<Bun.Server<WsData>>;
+
+/**
+ * node:http adapter — bridge a WinterCG `fetch(request) => Response` handler
+ * onto a Node HTTP server, with no external dependencies. Converts a Node
+ * `IncomingMessage` into a web `Request` and writes a web `Response` back into a
+ * `ServerResponse` (preserving multiple `Set-Cookie` headers).
+ *
+ * Caveat: the production handler uses Bun-native APIs (Bun.file for assets,
+ * Bun.serve for websockets, Bun.SQL / bun:sqlite for the database), so running
+ * the FULL app under plain Node needs Bun-compatible globals. This adapter is
+ * for WinterCG hosts and for embedding the handler behind an existing
+ * `node:http` server; the Request/Response conversion itself is fully portable.
+ */
+
+type FetchHandler = (req: Request) => Response | undefined | Promise<Response | undefined>;
+/** Convert a Node IncomingMessage into a web Request (buffers the body). */
+declare function toRequest(req: IncomingMessage, opts?: {
+    origin?: string;
+}): Promise<Request>;
+/** Write a web Response into a Node ServerResponse. */
+declare function writeResponse(res: ServerResponse, response: Response): Promise<void>;
+/** A `node:http` request listener that dispatches to a fetch handler. */
+declare function nodeListener(handler: FetchHandler, opts?: {
+    origin?: string;
+}): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
+/** Create and start a `node:http` server for a fetch handler. */
+declare function serveNode(handler: FetchHandler, opts?: {
+    port?: number;
+    hostname?: string;
+}): Promise<Server>;
+
+/**
+ * @wrnexus/dev-server — the development HTTP + WebSocket server.
+ *
+ * Thin Bun.serve wrapper around the shared runtime (runtime.ts). Dynamic module
+ * loading makes it fast to iterate; the dev supervisor (see @wrnexus/cli)
+ * restarts this process on file changes.
+ */
+
+/** Exit code the child uses to ask the dev supervisor for a fresh process. */
+declare const RESTART_EXIT_CODE = 97;
+interface ServeOptions {
+    appDir: string;
+    port?: number;
+    hostname?: string;
+    mode?: Mode;
+    /** Inject the live-reload client (defaults to true in development). */
+    hmr?: boolean;
+    /** Resolved absolute path to the global CSS entry, or null. */
+    styleEntry?: string | null;
+    /** Custom styles config (e.g. a Tailwind/PostCSS processor). */
+    stylesConfig?: StylesConfig;
+    /** Raw HTML appended to every page head (from wrnexus.config.ts). */
+    head?: string;
+    /** Global SEO defaults. */
+    seo?: SeoConfig;
+    /** Framework security headers and CORS policy. */
+    security?: SecurityConfig;
+    /** Design-token theme config (merged over the built-in light/dark). */
+    theme?: ThemeConfig;
+    /** i18n config (default language + supported locales). */
+    i18n?: I18nConfig;
+    /** Default database connection (driver + url). Enables `getDb()` and dev auto-migrate. */
+    db?: {
+        driver: string;
+        url: string;
+    };
+    /** Named databases, reached with `getDb("<name>")`; migrations under app/db/<name>/. */
+    databases?: Record<string, {
+        driver: string;
+        url: string;
+    }>;
+    /** Realtime scaling: bridge room broadcasts over Redis across app processes. */
+    realtime?: {
+        scale?: boolean;
+        redisUrl?: string;
+    };
+    /** File-upload storage: named stores (local dir / S3), reached with `getStore()`. */
+    storage?: StorageConfig;
+    mobile?: MobileConfig;
+    pwa?: PwaConfig | false;
+}
+interface RunningServer {
+    port: number;
+    hostname: string;
+    url: string;
+    router: Router;
+    stop(): void;
+}
+declare function startServer(opts: ServeOptions): Promise<RunningServer>;
+
+export { type AssetServer, type FetchHandler, type GatewayApp, type GatewayAuth, type GatewayOptions, type GatewaySecurity, RESTART_EXIT_CODE, type RunningGateway, type RunningServer, type RuntimeDeps, type ServeOptions, type WsData, createHandlers, createProductionHandlers, createProductionServer, nodeListener, serveNode, startGateway, startServer, toRequest, writeResponse };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/dev-server

Example 2

interface ServeOptions {
+  appDir: string; // absolute/relative path to the app/ dir
+  port?: number; // default 3000
+  hostname?: string; // default "localhost"
+  mode?: Mode; // "development" | "production"; default "development"
+  hmr?: boolean; // inject live-reload client; default (mode === "development")
+  styleEntry?: string | null; // resolved absolute path to the global CSS entry
+  stylesConfig?: StylesConfig; // custom styles processor (e.g. Tailwind/PostCSS)
+  head?: string; // raw HTML appended to every page <head>
+  seo?: SeoConfig; // global SEO defaults
+  security?: SecurityConfig; // security headers + CORS policy
+  theme?: ThemeConfig; // design-token theme (merged over built-in light/dark)
+  i18n?: I18nConfig; // default language + supported locales
+  db?: { driver: string; url: string }; // default db → getDb(); dev auto-migrates
+  databases?: Record<string, { driver: string; url: string }>; // named dbs → getDb("<name>")
+  realtime?: { scale?: boolean; redisUrl?: string }; // bridge rooms over Redis across processes
+}
+
+interface RunningServer {
+  port: number;
+  hostname: string;
+  url: string;
+  router: Router;
+  stop(): void;
+}

Example 3

interface RuntimeDeps {
+  mode: Mode;
+  hmr: boolean; // inject the live-reload client into pages
+  router: Router;
+  loadModule(file: string): Promise<Record<string, unknown>>;
+  getMiddleware(): Promise<Middleware[]>;
+  assets: AssetServer; // serves /__wrnexus/* (islands, reactive, hmr)
+  hasStyles?: boolean; // inject the global stylesheet link
+  hasUi?: boolean; // inject the Wire UI stylesheet (/__wrnexus/ui.css)
+  theme?: ResolvedTheme; // enables /__wrnexus/theme.css + <html data-theme>
+  i18n?: ResolvedI18n; // enables ctx.t, <html lang>, {t:key} markers
+  inlineStyles?: string; // inline small prod stylesheets into <head>
+  assetVersion?: string; // cache-busting ?v= on framework asset URLs
+  head?: string; // raw HTML appended to every page <head>
+  seo?: SeoConfig;
+  security?: SecurityConfig;
+  maxBodyBytes?: number; // 413 above this; default 10 MB
+  hub?: HmrHub; // browser HMR sockets (dev only)
+  realtimeBus?: RealtimeBus; // cross-process room bridge (Redis pub/sub)
+}
+
+interface Handlers {
+  fetch(req: Request, server: UpgradeServer): Promise<Response | undefined>;
+  websocket: { open; message; close; drain };
+}

Example 4

interface ProdManifest {
+  pages: { raw: string; mod: RouteModule }[];
+  api: { raw: string; mod: RouteModule }[];
+  realtime: { raw: string; mod: RouteModule }[];
+  middleware: Middleware[];
+  components: { name: string; mod: RouteModule }[];
+  layouts: { name: string; mod: RouteModule }[];
+}
+
+interface ProdOptions {
+  stylesPath?: string;
+  inlineStyles?: string;
+  reactivePath?: string;
+  themePath?: string;
+  themeJsPath?: string;
+  theme?: ResolvedTheme;
+  uiCssPath?: string;
+  schemasJs?: string;
+  i18n?: ResolvedI18n;
+  db?: { driver: string; url: string };
+  databases?: Record<string, { driver: string; url: string }>;
+  realtime?: { scale?: boolean; redisUrl?: string };
+  assetVersion?: string;
+  publicDir?: string;
+  head?: string;
+  seo?: SeoConfig;
+  security?: SecurityConfig;
+  port?: number;
+  hostname?: string;
+  maxBodyBytes?: number;
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/encryption.wrn b/app/pages/packages/encryption.wrn new file mode 100644 index 00000000..eac2dbb6 --- /dev/null +++ b/app/pages/packages/encryption.wrn @@ -0,0 +1,113 @@ +page wrnexusencryption { + seo { + title = "@wrnexus/encryption" + description = "Hashing, HMAC, authenticated encryption, and key derivation." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Security

@wrnexus/encryption

Hashing, HMAC, authenticated encryption, and key derivation.

bun add @wrnexus/encryption@0.2.12
Dependency-free crypto helpers for WRNexusJS: authenticated symmetric encryption (AES-256-GCM), hashing, and HMAC signing.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

This package provides small, focused cryptographic primitives for server-side use: encrypting secrets/tokens/database fields at rest with AES-256-GCM, deriving keys from passwords via PBKDF2, computing SHA-256 digests, and signing/verifying payloads with HMAC-SHA256. It is built entirely on the standard Web Crypto API (crypto.subtle) plus btoa/atob and TextEncoder/TextDecoder — no third-party dependencies. Reach for it whenever you need to protect sensitive values or verify webhook signatures. All functions are async (Web Crypto is promise-based).

+

Installation

+
bun add @wrnexus/encryption
+
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 keys are exchanged as base64 strings and all digests/signatures as hex strings.

+
+ +
ExportSignatureDescription
generateKey() => Promise<string>Generate a random 256-bit AES key, base64-encoded. Store it as a secret.
deriveKey(password: string, salt: string) => Promise<string>Derive a base64 AES-256 key from a password + salt using PBKDF2 (100,000 iterations, SHA-256).
encrypt(plaintext: string, key: string) => Promise<string>AES-256-GCM encrypt a string. Returns base64 of iv(12 bytes) ‖ ciphertext+tag. A fresh random IV is used each call.
decrypt(payload: string, key: string) => Promise<string>Decrypt a value produced by encrypt. Throws if the key is wrong or the data was tampered with.
sha256(data: string) => Promise<string>SHA-256 hex digest of a string (e.g. content hashing, dedup keys).
hmacSign(data: string, secret: string) => Promise<string>HMAC-SHA256 hex signature of data with secret (e.g. signing webhooks).
hmacVerify(data: string, secret: string, signature: string) => Promise<boolean>Constant-time verify of an HMAC-SHA256 hex signature.
+

Notes:

+
    +
  • generateKey produces a 32-byte (256-bit) key via crypto.getRandomValues.
  • +
  • encrypt/decrypt require a base64-encoded 256-bit key; anything else throws "Encryption key must be a base64 256-bit key".
  • +
  • decrypt throws "Invalid ciphertext" if the payload is shorter than the 12-byte IV, and the underlying Web Crypto call throws on any authentication (tag) mismatch.
  • +
  • hmacVerify compares in constant time (length check plus XOR accumulation) to avoid timing leaks.
  • +
+

Usage

+

Symmetric encryption of a secret at rest:

+
import { generateKey, encrypt, decrypt } from "@wrnexus/encryption";
+
+const key = await generateKey(); // store this safely (env/secret manager)
+
+const box = await encrypt("card #1234", key); // opaque base64 string, safe to persist
+const plain = await decrypt(box, key); // "card #1234"
+

Deriving a key from a user password instead of a random key:

+
import { deriveKey, encrypt } from "@wrnexus/encryption";
+
+const key = await deriveKey("correct horse battery staple", "per-user-salt");
+const box = await encrypt("secret note", key);
+

Hashing and webhook signature verification:

+
import { sha256, hmacSign, hmacVerify } from "@wrnexus/encryption";
+
+const digest = await sha256("some content"); // 64-char hex string
+
+const signature = await hmacSign(rawBody, webhookSecret);
+const ok = await hmacVerify(rawBody, webhookSecret, incomingSignatureHeader);
+if (!ok) throw new Error("Invalid webhook signature");
+

Requirements / Notes

+
    +
  • Bun-only. Relies on the Web Crypto API (crypto.subtle, crypto.getRandomValues) and the global btoa/atob, TextEncoder/TextDecoder — all available in Bun's runtime.
  • +
  • No dependencies. The package has an empty dependency set; nothing is bundled beyond standard runtime APIs.
  • +
  • Algorithms: AES-256-GCM (encryption), PBKDF2 with 100k SHA-256 iterations (key derivation), SHA-256 (digest), HMAC-SHA256 (signing).
  • +
  • Keep generated/derived keys and HMAC secrets out of source control; treat them as first-class secrets.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/encryption — authenticated symmetric encryption (AES-256-GCM) via
+ * WebCrypto, dependency-free. Use it to encrypt secrets, tokens, or database
+ * fields at rest.
+ *
+ *   const key = await generateKey();                 // store this safely
+ *   const box = await encrypt("card #1234", key);    // opaque base64 string
+ *   const plain = await decrypt(box, key);           // "card #1234"
+ *
+ * A key derived from a password (PBKDF2) is also supported via `deriveKey`.
+ */
+/** SHA-256 hex digest of a string (e.g. content hashing, dedup keys). */
+declare function sha256(data: string): Promise<string>;
+/** HMAC-SHA256 hex signature of `data` with `secret` (e.g. signing webhooks). */
+declare function hmacSign(data: string, secret: string): Promise<string>;
+/** Constant-time verify of an HMAC-SHA256 signature. */
+declare function hmacVerify(data: string, secret: string, signature: string): Promise<boolean>;
+/** Generate a random 256-bit key, base64-encoded. Store it as a secret. */
+declare function generateKey(): Promise<string>;
+/**
+ * Encrypt a string. Output is base64 of `iv(12) || ciphertext+tag`, safe to
+ * store or transmit. Each call uses a fresh random IV.
+ */
+declare function encrypt(plaintext: string, key: string): Promise<string>;
+/** Decrypt a value produced by `encrypt`. Throws if the key is wrong or data tampered. */
+declare function decrypt(payload: string, key: string): Promise<string>;
+/** Derive a base64 AES key from a password + salt (PBKDF2, 100k iterations). */
+declare function deriveKey(password: string, salt: string): Promise<string>;
+
+export { decrypt, deriveKey, encrypt, generateKey, hmacSign, hmacVerify, sha256 };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/encryption

Example 2

import { generateKey, encrypt, decrypt } from "@wrnexus/encryption";
+
+const key = await generateKey(); // store this safely (env/secret manager)
+
+const box = await encrypt("card #1234", key); // opaque base64 string, safe to persist
+const plain = await decrypt(box, key); // "card #1234"

Example 3

import { deriveKey, encrypt } from "@wrnexus/encryption";
+
+const key = await deriveKey("correct horse battery staple", "per-user-salt");
+const box = await encrypt("secret note", key);

Example 4

import { sha256, hmacSign, hmacVerify } from "@wrnexus/encryption";
+
+const digest = await sha256("some content"); // 64-char hex string
+
+const signature = await hmacSign(rawBody, webhookSecret);
+const ok = await hmacVerify(rawBody, webhookSecret, incomingSignatureHeader);
+if (!ok) throw new Error("Invalid webhook signature");
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/i18n.wrn b/app/pages/packages/i18n.wrn new file mode 100644 index 00000000..a3612c2a --- /dev/null +++ b/app/pages/packages/i18n.wrn @@ -0,0 +1,215 @@ +page wrnexusi18n { + seo { + title = "@wrnexus/i18n" + description = "Translation loading, locale resolution, and Intl formatting." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Frontend

@wrnexus/i18n

Translation loading, locale resolution, and Intl formatting.

bun add @wrnexus/i18n@0.2.12
Per-request translations plus locale-aware number, date, and currency formatting for WRNexusJS apps.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/i18n loads locale files from app/locales/<lang>.json, resolves the active language for each request (cookie → Accept-Language → default), and builds a t(key, params) translator used both in server code and in .wrn views. It also ships Intl-based formatting helpers and a tiny client runtime that wires up a language switcher. Translation lookup, language resolution, and HTML marker rewriting run server-side; only the small I18N_RUNTIME snippet runs in the browser.

+

Installation

+
bun add @wrnexus/i18n
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Loading & resolving

+
+ +
ExportSignatureDescription
loadLocales(dir: string) => Record<string, Messages>Reads every <lang>.json in dir into a { lang: messages } map. Missing dir → {}; a bad file is warned and skipped.
resolveI18n(messages: Record<string, Messages>, config?: I18nConfig) => ResolvedI18nMerges loaded messages + config into a resolved bundle (default lang, supported langs, messages).
resolveLang`(i18n: ResolvedI18n, cookieValue: string \undefined, acceptLanguage: string \null) => string`Picks the active language: matching cookie → best Accept-Language tag (falls back to base tag, e.g. en-USen) → i18n.default.
makeT(i18n: ResolvedI18n, lang: string) => TFunctionBuilds a translator resolving current language → default → the key itself, with {param} interpolation.
+

Types & constants

+
+ +
ExportKindNotes
MessagestypeRecord<string, unknown> — a locale's messages (supports nested/dotted keys).
I18nConfiginterface{ default?: string; locales?: string[] }.
ResolvedI18ninterface{ default: string; langs: string[]; messages: Record<string, Messages> }.
LANG_COOKIEconst"wire-lang" — the cookie the language is read from / written to.
I18N_JS_HREFconst"/__wrnexus/i18n.js" — URL the client runtime is served at.
+

HTML & client runtime

+
+ +
ExportSignatureDescription
translateHtml(html: string, t: TFunction) => stringRewrites markers in rendered HTML: t:<attr>="key"<attr>="<translation>" (attribute-escaped) and <tag data-t="key">…</tag> → element text becomes the translation (HTML-escaped). No-op unless a marker is present.
renderI18nData(i18n: ResolvedI18n, lang: string) => stringJS snippet setting window.__wireI18n = { lang, langs, default } for the client switcher.
I18N_RUNTIMEconst stringBrowser IIFE that binds [data-wire-lang-set="es"] clicks and select[data-wire-lang] changes to set the wire-lang cookie and reload. Exposes window.__wireLang.set(lang).
+

Formatting helpers (re-exported from ./format.ts)

+
+ +
ExportSignatureExample
formatNumber(value: number, lang: string, options?: Intl.NumberFormatOptions) => string1234.5 → "1,234.5"
formatCurrency(value: number, currency: string, lang: string) => string9.99, "USD" → "$9.99"
formatDate`(value: Date \number \string, lang: string, options?: Intl.DateTimeFormatOptions) => string`defaults to { dateStyle: "medium" }
formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, lang: string) => string-3, "day" → "3 days ago" (numeric: "auto")
plural(count: number, forms: Partial<Record<Intl.LDMLPluralRule, string>>, lang: string) => stringpicks CLDR form; # is replaced by count
+

Usage

+

Server: load, resolve, translate

+
import {
+  loadLocales,
+  resolveI18n,
+  resolveLang,
+  makeT,
+  translateHtml,
+  LANG_COOKIE,
+} from "@wrnexus/i18n";
+
+// app/locales/en.json, app/locales/es.json
+const messages = loadLocales("app/locales");
+const i18n = resolveI18n(messages, { default: "en", locales: ["en", "es"] });
+
+// Per request:
+const lang = resolveLang(i18n, req.cookies?.[LANG_COOKIE], req.headers.get("accept-language"));
+const t = makeT(i18n, lang);
+
+t("nav.home"); // dotted key → "Home"
+t("greeting", { name: "Ada" }); // "Hello, {name}" → "Hello, Ada"
+
+// After rendering a .wrn view, resolve translation markers in the HTML:
+const finalHtml = translateHtml(renderedHtml, t);
+

app/locales/en.json:

+
{
+  "nav": { "home": "Home" },
+  "greeting": "Hello, {name}"
+}
+

Views: translation markers

+
<h1 data-t="nav.home">Home</h1>
+<input t:placeholder="search.placeholder" />
+

translateHtml replaces the element text for data-t and the attribute value for any t:<attr> (e.g. t:placeholder, t:aria-label).

+

Client: language switcher

+
import { renderI18nData, I18N_RUNTIME, I18N_JS_HREF } from "@wrnexus/i18n";
+
+// In the document <head>:
+const head = `
+  <script>${renderI18nData(i18n, lang)}</script>
+  <script src="${I18N_JS_HREF}"></script>
+`;
+
+// Serve I18N_RUNTIME at I18N_JS_HREF; then in markup:
+// <button data-wire-lang-set="es">Español</button>
+// <select data-wire-lang>…</select>
+

Formatting

+
import {
+  formatNumber,
+  formatCurrency,
+  formatDate,
+  formatRelativeTime,
+  plural,
+} from "@wrnexus/i18n";
+
+formatNumber(1234.5, lang); // "1,234.5"
+formatCurrency(9.99, "USD", lang); // "$9.99"
+formatDate(Date.now(), lang); // "Jul 4, 2026"
+formatRelativeTime(-3, "day", lang); // "3 days ago"
+plural(2, { one: "# item", other: "# items" }, lang); // "2 items"
+

Configuration

+

resolveI18n accepts an I18nConfig:

+
    +
  • default — fallback language; used when nothing else matches. Ignored if it has
  • +

    no loaded messages, in which case the first supported language is used.

    +
  • locales — explicit supported-language list; defaults to the loaded locale names.
  • +
+

Language resolution order at request time (resolveLang): a supported wire-lang cookie value → the first matching Accept-Language tag (or its base subtag) → the resolved default.

+

Requirements / Notes

+
    +
  • Bun-only. Locale loading uses node:fs (existsSync, readdirSync,
  • +

    readFileSync) and node:path; formatting relies on the platform Intl APIs.

    +
  • Works with [@wrnexus/core](../core) — TFunction (the t(key, params) type)
  • +

    comes from core, and the resolved translator is exposed as ctx.t / ctx.lang in request handling.

    +
  • Nested message objects are supported: keys are looked up whole first, then split
  • +

    on . to walk the object tree.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { TFunction } from '@wrnexus/core';
+
+/**
+ * Locale-aware formatting helpers (Intl-based) + pluralization. Pair with the
+ * request language (`ctx.lang`) so numbers, dates, and currencies render right
+ * for each user.
+ */
+/** Format a number for a locale (e.g. 1234.5 → "1,234.5"). */
+declare function formatNumber(value: number, lang: string, options?: Intl.NumberFormatOptions): string;
+/** Format a currency amount (e.g. 9.99, "USD" → "$9.99"). */
+declare function formatCurrency(value: number, currency: string, lang: string): string;
+/** Format a date/timestamp for a locale. */
+declare function formatDate(value: Date | number | string, lang: string, options?: Intl.DateTimeFormatOptions): string;
+/** Relative time, e.g. -3 days → "3 days ago" (localized). */
+declare function formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, lang: string): string;
+/**
+ * Pick a plural form for `count` in `lang` using CLDR rules, e.g.
+ * `plural(n, { one: "1 item", other: "# items" }, lang)` — "#" is replaced by n.
+ */
+declare function plural(count: number, forms: Partial<Record<Intl.LDMLPluralRule, string>>, lang: string): string;
+
+/**
+ * @wrnexus/i18n — translations for pages and API responses.
+ *
+ * Locales live in `app/locales/<lang>.json`. Per request the active language is
+ * resolved from the `wire-lang` cookie, then Accept-Language, then the default.
+ * `ctx.t(key, params)` translates on the server; in `.wrn` views `{t:key}` and
+ * `t:attr="key"` markers are resolved by `translateHtml` before the HTML is sent.
+ */
+
+type Messages = Record<string, unknown>;
+/** Load `<dir>/<lang>.json` files into a `{ lang: messages }` map. */
+declare function loadLocales(dir: string): Record<string, Messages>;
+interface I18nConfig {
+    /** Default language, used as the fallback and when nothing else matches. */
+    default?: string;
+    /** Explicit set of supported languages (defaults to the loaded locale names). */
+    locales?: string[];
+}
+interface ResolvedI18n {
+    default: string;
+    langs: string[];
+    messages: Record<string, Messages>;
+}
+declare const LANG_COOKIE = "wire-lang";
+declare const I18N_JS_HREF = "/__wrnexus/i18n.js";
+/** Merge loaded locale messages + config into a resolved i18n bundle. */
+declare function resolveI18n(messages: Record<string, Messages>, config?: I18nConfig): ResolvedI18n;
+/** Build a `t()` for a language: current → default → the key itself. */
+declare function makeT(i18n: ResolvedI18n, lang: string): TFunction;
+/** Resolve the active language from a cookie, Accept-Language, then default. */
+declare function resolveLang(i18n: ResolvedI18n, cookieValue: string | undefined, acceptLanguage: string | null): string;
+/**
+ * Resolve translation markers in rendered HTML:
+ *   t:<attr>="key"        → <attr>="<translation>"   (e.g. t:placeholder, t:aria-label)
+ *   <tag data-t="key">…</tag> → element text becomes the translation
+ * Only runs when the HTML actually contains a marker.
+ */
+declare function translateHtml(html: string, t: TFunction): string;
+/** `window.__wireI18n = { lang, langs }` for the client language switcher. */
+declare function renderI18nData(i18n: ResolvedI18n, lang: string): string;
+/**
+ * Client runtime: binds `[data-wire-lang-set="es"]` elements to set the
+ * `wire-lang` cookie and reload, so the server re-renders in the new language.
+ */
+declare const I18N_RUNTIME: string;
+
+export { I18N_JS_HREF, I18N_RUNTIME, type I18nConfig, LANG_COOKIE, type Messages, type ResolvedI18n, formatCurrency, formatDate, formatNumber, formatRelativeTime, loadLocales, makeT, plural, renderI18nData, resolveI18n, resolveLang, translateHtml };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/i18n

Example 2

import {
+  loadLocales,
+  resolveI18n,
+  resolveLang,
+  makeT,
+  translateHtml,
+  LANG_COOKIE,
+} from "@wrnexus/i18n";
+
+// app/locales/en.json, app/locales/es.json
+const messages = loadLocales("app/locales");
+const i18n = resolveI18n(messages, { default: "en", locales: ["en", "es"] });
+
+// Per request:
+const lang = resolveLang(i18n, req.cookies?.[LANG_COOKIE], req.headers.get("accept-language"));
+const t = makeT(i18n, lang);
+
+t("nav.home"); // dotted key → "Home"
+t("greeting", { name: "Ada" }); // "Hello, {name}" → "Hello, Ada"
+
+// After rendering a .wrn view, resolve translation markers in the HTML:
+const finalHtml = translateHtml(renderedHtml, t);

Example 3

{
+  "nav": { "home": "Home" },
+  "greeting": "Hello, {name}"
+}

Example 4

<h1 data-t="nav.home">Home</h1>
+<input t:placeholder="search.placeholder" />
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/jwt.wrn b/app/pages/packages/jwt.wrn new file mode 100644 index 00000000..58da5f55 --- /dev/null +++ b/app/pages/packages/jwt.wrn @@ -0,0 +1,151 @@ +page wrnexusjwt { + seo { + title = "@wrnexus/jwt" + description = "HS256 JWT signing, verification, and bearer authentication." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Security

@wrnexus/jwt

HS256 JWT signing, verification, and bearer authentication.

bun add @wrnexus/jwt@0.2.12
Dependency-free JSON Web Tokens (HS256) via Web Crypto, plus a bearer-token auth middleware for WRNexusJS.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/jwt signs and verifies stateless JSON Web Tokens using the HS256 (HMAC-SHA-256) algorithm. It has no runtime dependencies — signing and verification are implemented directly on the standard Web Crypto API (crypto.subtle), which Bun provides natively. It runs server-side and pairs with the session-based auth in @wrnexus/core, giving you a stateless option for API and mobile clients. Reach for it when you need bearer-token auth rather than cookie sessions.

+

Installation

+
bun add @wrnexus/jwt
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Single entry point (@wrnexus/jwt). All functions are async and return Promises.

+
+ +
ExportKindDescription
signJwt(payload, secret, options?)functionSign claims into an HS256 token string.
verifyJwt<T>(token, secret, options?)functionVerify a token and return its claims, or throw.
jwtAuth(options)functionMiddleware that verifies a bearer JWT and sets ctx.user.
JwtErrorclassError thrown on any signature/payload/expiry failure.
JwtClaimsinterfaceClaims shape (sub, iat, exp, nbf, plus arbitrary keys).
SignOptionsinterfaceOptions for signJwt.
JwtAuthOptionsinterfaceOptions for jwtAuth.
+

signJwt(payload, secret, options?)

+
function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;
+

Signs payload with secret using HS256 and returns the encoded token (header.body.signature). An iat (issued-at) claim is always added.

+

SignOptions:

+
    +
  • expiresIn?: number — seconds until expiry; sets the exp claim.
  • +
  • now?: number — override the issued-at time (seconds), useful for testing.
  • +
+

verifyJwt<T>(token, secret, options?)

+
function verifyJwt<T extends JwtClaims = JwtClaims>(
+  token: string,
+  secret: string,
+  options?: { now?: number },
+): Promise<T>;
+

Verifies the HS256 signature and returns the decoded claims typed as T. Throws JwtError when the token is malformed, the signature is invalid, the payload is not valid JSON, the token is expired (exp), or not yet valid (nbf). Pass now (seconds) to override the reference time for the exp/nbf checks.

+

jwtAuth(options)

+
function jwtAuth(options: JwtAuthOptions): Middleware;
+

Returns a WRNexusJS Middleware that reads a token, verifies it, and assigns the claims to ctx.user.

+

JwtAuthOptions:

+
    +
  • secret: string — the HMAC secret used to verify tokens.
  • +
  • getToken?: (ctx: Context) => string | undefined — how to extract the token.
  • +

    Defaults to reading Authorization: Bearer <token>.

    +
  • required?: boolean — when true (default), a missing or invalid token
  • +

    responds with 401 { ok: false, error: "Unauthorized" }. When false, requests pass through and ctx.user is only set if a valid token is present.

    +
+

Usage

+
import { signJwt, verifyJwt, jwtAuth, JwtError } from "@wrnexus/jwt";
+
+const secret = process.env.JWT_SECRET!;
+
+// Sign a token that expires in one hour
+const token = await signJwt({ sub: user.id, role: "admin" }, secret, {
+  expiresIn: 3600,
+});
+
+// Verify it later
+try {
+  const claims = await verifyJwt<{ sub: string; role: string }>(token, secret);
+  console.log(claims.sub, claims.role);
+} catch (err) {
+  if (err instanceof JwtError) {
+    // invalid signature, expired, malformed, etc.
+  }
+}
+

Protecting routes with the middleware:

+
import { jwtAuth } from "@wrnexus/jwt";
+
+// Require a valid bearer token; ctx.user holds the verified claims
+app.use(jwtAuth({ secret: process.env.JWT_SECRET! }));
+
+// Optional auth — populate ctx.user when present, but don't 401
+app.use(jwtAuth({ secret: process.env.JWT_SECRET!, required: false }));
+

Requirements / Notes

+
    +
  • Bun-only. Uses the standard Web Crypto API (crypto.subtle.importKey,
  • +

    sign, verify) plus btoa/atob and TextEncoder/TextDecoder — all provided by Bun. No third-party crypto dependency.

    +
  • Algorithm: HS256 (HMAC with SHA-256) only. Asymmetric algorithms (RS/ES)
  • +

    are not supported.

    +
  • Integrates with [@wrnexus/core](../core) for Context, Middleware, and
  • +

    ctx.user; it complements the framework's cookie/session auth with a stateless bearer-token flow for API and mobile clients.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Context, Middleware } from '@wrnexus/core';
+
+/**
+ * @wrnexus/jwt — dependency-free JSON Web Tokens (HS256) via WebCrypto, plus a
+ * bearer-token auth middleware. Pairs with the session auth in @wrnexus/core for
+ * stateless (API/mobile) authentication.
+ *
+ *   const token = await signJwt({ sub: user.id, role: "admin" }, secret, { expiresIn: 3600 });
+ *   const claims = await verifyJwt(token, secret); // throws JwtError if invalid/expired
+ */
+
+declare class JwtError extends Error {
+    constructor(message: string);
+}
+interface JwtClaims {
+    /** Subject (user id). */
+    sub?: string;
+    /** Issued-at (seconds). */
+    iat?: number;
+    /** Expiry (seconds). */
+    exp?: number;
+    /** Not-before (seconds). */
+    nbf?: number;
+    [key: string]: unknown;
+}
+interface SignOptions {
+    /** Seconds until expiry (sets `exp`). */
+    expiresIn?: number;
+    /** Override issued-at (seconds). */
+    now?: number;
+}
+/** Sign a payload into a JWT (HS256). */
+declare function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;
+/** Verify a JWT and return its claims. Throws `JwtError` on any failure. */
+declare function verifyJwt<T extends JwtClaims = JwtClaims>(token: string, secret: string, options?: {
+    now?: number;
+}): Promise<T>;
+interface JwtAuthOptions {
+    secret: string;
+    /** Where to read the token. Default: `Authorization: Bearer <token>`. */
+    getToken?: (ctx: Context) => string | undefined;
+    /** Reject unauthenticated requests with 401. Default true. */
+    required?: boolean;
+}
+/**
+ * Middleware that verifies a bearer JWT and sets `ctx.user` to its claims.
+ * When `required` (default), a missing/invalid token gets a 401.
+ */
+declare function jwtAuth(options: JwtAuthOptions): Middleware;
+
+export { type JwtAuthOptions, type JwtClaims, JwtError, type SignOptions, jwtAuth, signJwt, verifyJwt };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/jwt

Example 2

function signJwt(payload: JwtClaims, secret: string, options?: SignOptions): Promise<string>;

Example 3

function verifyJwt<T extends JwtClaims = JwtClaims>(
+  token: string,
+  secret: string,
+  options?: { now?: number },
+): Promise<T>;

Example 4

function jwtAuth(options: JwtAuthOptions): Middleware;
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/mobile.wrn b/app/pages/packages/mobile.wrn new file mode 100644 index 00000000..ecea5821 --- /dev/null +++ b/app/pages/packages/mobile.wrn @@ -0,0 +1,76 @@ +page wrnexusmobile { + seo { + title = "@wrnexus/mobile" + description = "SSR-safe compatibility access to Capacitor plugins." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Native

@wrnexus/mobile

SSR-safe compatibility access to Capacitor plugins.

bun add @wrnexus/mobile@0.2.12

SSR-safe access to Capacitor plugins from WRNexusJS browser code.

+
wrnexus mobile add @capacitor/camera
+
import { Camera } from "@capacitor/camera";
+import { mobile } from "@wrnexus/mobile";
+
+if (mobile.isNative()) {
+  mobile.registerPlugin("Camera", Camera);
+  const photo = await mobile.invoke("Camera", "getPhoto", { resultType: "uri" });
+}
+

isNative() is false and platform() is web during SSR. plugin() returns undefined when unavailable; requirePlugin() and invoke() throw an actionable MobileUnavailableError.

+

Import and register Capacitor packages only from browser-owned code. Do not import them in server routes, SSR helpers, or other Bun-only modules.

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

export { native } from '@wrnexus/native';
+
+/** @wrnexus/mobile — SSR-safe access to Capacitor's native bridge. */
+
+type MobilePlatform = "ios" | "android" | "web" | string;
+interface CapacitorBridge {
+    isNativePlatform?: () => boolean;
+    getPlatform?: () => MobilePlatform;
+    Plugins?: Record<string, unknown>;
+}
+declare class MobileUnavailableError extends Error {
+    constructor(message?: string);
+}
+/** Register a plugin imported by browser-only application code. */
+declare function registerPlugin<T extends object>(name: string, instance: T): T;
+/** True only inside a native Capacitor iOS or Android WebView. SSR-safe. */
+declare function isNative(): boolean;
+/** Current Capacitor platform, falling back to `web` during SSR and in browsers. */
+declare function platform(): MobilePlatform;
+/** Return an injected Capacitor plugin, or undefined when it is unavailable. */
+declare function plugin<T extends object>(name: string): T | undefined;
+/** Require an installed native plugin and produce a useful error when absent. */
+declare function requirePlugin<T extends object>(name: string): T;
+/** Invoke a plugin method without importing native code into an SSR module. */
+declare function invoke<TResult = unknown>(pluginName: string, method: string, options?: unknown): Promise<TResult>;
+/** Run native behavior when available, with an optional SSR/web fallback. */
+declare function whenNative<T>(native: () => T | Promise<T>, fallback?: () => T | Promise<T>): Promise<T | undefined>;
+declare const mobile: {
+    isNative: typeof isNative;
+    platform: typeof platform;
+    registerPlugin: typeof registerPlugin;
+    plugin: typeof plugin;
+    requirePlugin: typeof requirePlugin;
+    invoke: typeof invoke;
+    whenNative: typeof whenNative;
+};
+
+export { type CapacitorBridge, type MobilePlatform, MobileUnavailableError, invoke, isNative, mobile, platform, plugin, registerPlugin, requirePlugin, whenNative };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

wrnexus mobile add @capacitor/camera

Example 2

import { Camera } from "@capacitor/camera";
+import { mobile } from "@wrnexus/mobile";
+
+if (mobile.isNative()) {
+  mobile.registerPlugin("Camera", Camera);
+  const photo = await mobile.invoke("Camera", "getPhoto", { resultType: "uri" });
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/native.wrn b/app/pages/packages/native.wrn new file mode 100644 index 00000000..8b939034 --- /dev/null +++ b/app/pages/packages/native.wrn @@ -0,0 +1,55 @@ +page wrnexusnative { + seo { + title = "@wrnexus/native" + description = "Cross-platform browser and Capacitor capability registry." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Native

@wrnexus/native

Cross-platform browser and Capacitor capability registry.

bun add @wrnexus/native@0.2.12

Cross-platform capabilities for browsers, Capacitor WebViews, and compiled native apps.

+
import { native } from "@wrnexus/native";
+
+if (native.supports("share")) await native.run("share", { title: "WRNexusJS", url: location.href });
+

Built-ins include camera, clipboard.write, share, geolocation, network, haptics, storage, filesystem, notifications, and device information. Browser capabilities use Web APIs; mobile capabilities use installed Capacitor plugins.

+

platform() returns server during SSR, browser on the web, and the Capacitor platform in a native WebView. Unsupported operations reject with NativeUnavailableError; use supports() before presenting optional UI.

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { N as NativePlatform, a as NativeCapability, b as NativeRunOptions, c as NativeTarget } from './types-CDShWg0i.js';
+export { d as NativeAdapter, e as NativeBrowserRuntime } from './types-CDShWg0i.js';
+export { browserCapabilities } from './browser.js';
+export { mobileCapabilities } from './mobile.js';
+
+declare class NativeUnavailableError extends Error {
+    constructor(message: string);
+}
+declare function isMobile(): boolean;
+declare function platform(): NativePlatform;
+declare function register<TOptions = unknown, TResult = unknown>(name: string, capability: NativeCapability<TOptions, TResult>): () => void;
+declare function registered(): string[];
+declare function supports(name: string, target?: NativeTarget): boolean;
+declare function run<TResult = unknown>(name: string, options?: unknown, runOptions?: NativeRunOptions): Promise<TResult>;
+declare function clearRegistry(): void;
+
+declare const native: {
+    isMobile: typeof isMobile;
+    platform: typeof platform;
+    register: typeof register;
+    registered: typeof registered;
+    run: typeof run;
+    supports: typeof supports;
+};
+
+export { NativeCapability, NativePlatform, NativeRunOptions, NativeTarget, NativeUnavailableError, clearRegistry, isMobile, native, platform, register, registered, run, supports };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

import { native } from "@wrnexus/native";
+
+if (native.supports("share")) await native.run("share", { title: "WRNexusJS", url: location.href });
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/oauth.wrn b/app/pages/packages/oauth.wrn new file mode 100644 index 00000000..50f1c495 --- /dev/null +++ b/app/pages/packages/oauth.wrn @@ -0,0 +1,269 @@ +page wrnexusoauth { + seo { + title = "@wrnexus/oauth" + description = "OAuth 2.0, PKCE, provider presets, and profile mapping." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Security

@wrnexus/oauth

OAuth 2.0, PKCE, provider presets, and profile mapping.

bun add @wrnexus/oauth@0.2.12
Dependency-free OAuth 2.0 sign-in for any provider, with PKCE and presets for Google, GitHub, and Discord.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/oauth implements the OAuth 2.0 Authorization Code flow (with PKCE) for server-side sign-in. It ships ready-made provider presets and a defineProvider helper for custom providers, then gives you two flow functions — startAuth (build the redirect) and completeAuth (exchange the code and fetch the user's profile). It has no runtime dependencies: it uses the platform fetch and WebCrypto only. Pairs naturally with @wrnexus/core's logIn to establish a session once you have a normalized profile.

+

Installation

+
bun add @wrnexus/oauth
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Providers

+

Each preset takes ProviderCredentials and returns an OAuthProvider.

+
interface ProviderCredentials {
+  clientId: string;
+  clientSecret: string;
+  scopes?: string[]; // override the preset's default scopes
+}
+
+ +
ExportDefault scopesNotes
google(creds)openid, email, profileSets access_type: offline for refresh tokens.
github(creds)read:user, user:emailMaps name (falls back to login) and avatar_url.
discord(creds)identify, emailBuilds the avatar CDN URL from the user id + hash.
defineProvider(config)Pass a full OAuthProvider to define a custom OAuth 2.0 provider.
+

An OAuthProvider describes the endpoints, scopes, credentials, optional extra authorize params, and a mapProfile normalizer:

+
interface OAuthProvider {
+  name: string;
+  authorizeUrl: string;
+  tokenUrl: string;
+  userInfoUrl: string;
+  scopes: string[];
+  clientId: string;
+  clientSecret: string;
+  authorizeParams?: Record<string, string>; // e.g. access_type, prompt
+  mapProfile: (raw: Record<string, unknown>) => OAuthProfile;
+}
+

Flow

+

startAuth(provider, options): Promise<StartAuthResult>

+

Builds the authorize redirect URL with a generated PKCE challenge and CSRF state. Store the returned state and verifier (session/cookie), then 302 the user to url.

+
interface StartAuthOptions {
+  redirectUri: string;
+  state?: string; // reuse a state instead of generating one
+  params?: Record<string, string>; // extra authorize params, merged last
+}
+
+interface StartAuthResult {
+  url: string; // authorize URL to redirect to
+  state: string; // CSRF state — verify on callback
+  verifier: string; // PKCE code verifier — pass to completeAuth
+}
+

completeAuth(provider, options): Promise<{ tokens, profile }>

+

On the callback: exchanges the authorization code for tokens, then fetches and normalizes the user profile. Convenience wrapper over exchangeCode + fetchProfile.

+
interface CompleteAuthOptions {
+  code: string;
+  redirectUri: string;
+  verifier?: string; // the PKCE verifier from startAuth
+  fetch?: typeof fetch; // inject a fetch implementation (tests)
+}
+

Lower-level helpers

+
+ +
ExportSignaturePurpose
exchangeCode(provider, options)→ Promise<OAuthTokens>Exchange an authorization code for tokens.
fetchProfile(provider, tokens, fetch?)→ Promise<OAuthProfile>Fetch + normalize the user's profile.
randomToken(bytes?)→ stringRandom URL-safe token (default 32 bytes) for state/verifiers.
+

Types

+
interface OAuthTokens {
+  access_token: string;
+  token_type?: string;
+  refresh_token?: string;
+  expires_in?: number;
+  id_token?: string;
+  scope?: string;
+}
+
+interface OAuthProfile {
+  id: string;
+  email?: string;
+  name?: string;
+  avatar?: string;
+  raw: Record<string, unknown>;
+}
+

Usage

+
import { google, startAuth, completeAuth } from "@wrnexus/oauth";
+import { logIn } from "@wrnexus/core";
+
+const provider = google({
+  clientId: process.env.GOOGLE_CLIENT_ID!,
+  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
+});
+
+const redirectUri = "https://example.com/auth/callback";
+
+// 1. Kick off sign-in: redirect the user to the provider.
+async function beginLogin(ctx) {
+  const { url, state, verifier } = await startAuth(provider, { redirectUri });
+  // Persist state + verifier in the session, then redirect.
+  ctx.session.set("oauth_state", state);
+  ctx.session.set("oauth_verifier", verifier);
+  return Response.redirect(url, 302);
+}
+
+// 2. Handle the callback.
+async function handleCallback(ctx, code: string, state: string) {
+  if (state !== ctx.session.get("oauth_state")) throw new Error("bad state");
+
+  const { profile } = await completeAuth(provider, {
+    code,
+    redirectUri,
+    verifier: ctx.session.get("oauth_verifier"),
+  });
+
+  logIn(ctx, { id: profile.id, email: profile.email });
+}
+

Custom provider with defineProvider:

+
import { defineProvider, startAuth } from "@wrnexus/oauth";
+
+const gitlab = defineProvider({
+  name: "gitlab",
+  authorizeUrl: "https://gitlab.com/oauth/authorize",
+  tokenUrl: "https://gitlab.com/oauth/token",
+  userInfoUrl: "https://gitlab.com/api/v4/user",
+  scopes: ["read_user"],
+  clientId: process.env.GITLAB_CLIENT_ID!,
+  clientSecret: process.env.GITLAB_CLIENT_SECRET!,
+  mapProfile: (raw) => ({
+    id: String(raw.id),
+    email: raw.email as string | undefined,
+    name: raw.name as string | undefined,
+    avatar: raw.avatar_url as string | undefined,
+    raw,
+  }),
+});
+

Requirements / Notes

+
    +
  • Bun-only. Relies on the global fetch and WebCrypto (crypto.getRandomValues,
  • +

    crypto.subtle.digest) — no other runtime dependencies.

    +
  • The flow is stateless by design: you are responsible for storing state and
  • +

    verifier between startAuth and completeAuth (session or signed cookie).

    +
  • Pairs with [@wrnexus/core](../core) — feed the normalized OAuthProfile into
  • +

    logIn to establish a session.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/oauth — OAuth 2.0 sign-in with any provider. Ships presets for Google,
+ * GitHub, and Discord, and `defineProvider` for a custom one. Dependency-free
+ * (uses `fetch` + WebCrypto for PKCE). Pairs with @wrnexus/core's `logIn`.
+ *
+ *   const provider = google({ clientId, clientSecret });
+ *   // 1. send the user to the provider:
+ *   const { url, state, verifier } = await startAuth(provider, { redirectUri });
+ *   // (store `state` + `verifier` in the session, then 302 to `url`)
+ *   // 2. on the callback:
+ *   const { profile } = await completeAuth(provider, { code, redirectUri, verifier });
+ *   logIn(ctx, { id: profile.id, email: profile.email });
+ */
+interface OAuthTokens {
+    access_token: string;
+    token_type?: string;
+    refresh_token?: string;
+    expires_in?: number;
+    id_token?: string;
+    scope?: string;
+}
+interface OAuthProfile {
+    id: string;
+    email?: string;
+    name?: string;
+    avatar?: string;
+    raw: Record<string, unknown>;
+}
+interface OAuthProvider {
+    name: string;
+    authorizeUrl: string;
+    tokenUrl: string;
+    userInfoUrl: string;
+    scopes: string[];
+    clientId: string;
+    clientSecret: string;
+    /** Extra params for the authorize request (e.g. `access_type`, `prompt`). */
+    authorizeParams?: Record<string, string>;
+    /** Normalize the provider's raw userinfo into an OAuthProfile. */
+    mapProfile: (raw: Record<string, unknown>) => OAuthProfile;
+}
+interface ProviderCredentials {
+    clientId: string;
+    clientSecret: string;
+    scopes?: string[];
+}
+type FetchLike = typeof fetch;
+declare function google(creds: ProviderCredentials): OAuthProvider;
+declare function github(creds: ProviderCredentials): OAuthProvider;
+declare function discord(creds: ProviderCredentials): OAuthProvider;
+/** Define a custom OAuth2 provider. */
+declare function defineProvider(config: OAuthProvider): OAuthProvider;
+/** A random URL-safe token (for `state` and the PKCE verifier). */
+declare function randomToken(bytes?: number): string;
+interface StartAuthOptions {
+    redirectUri: string;
+    /** Provide to reuse a state (else one is generated). */
+    state?: string;
+    /** Extra authorize params (merged over the provider's). */
+    params?: Record<string, string>;
+}
+interface StartAuthResult {
+    /** The full authorize URL to redirect the user to. */
+    url: string;
+    /** CSRF state — store it (session/cookie) and verify on callback. */
+    state: string;
+    /** PKCE code verifier — store it and pass to `completeAuth`. */
+    verifier: string;
+}
+/** Build the authorize redirect (with PKCE + state). */
+declare function startAuth(provider: OAuthProvider, options: StartAuthOptions): Promise<StartAuthResult>;
+interface CompleteAuthOptions {
+    code: string;
+    redirectUri: string;
+    /** The PKCE verifier from `startAuth`. */
+    verifier?: string;
+    /** Inject a fetch implementation (tests). */
+    fetch?: FetchLike;
+}
+/** Exchange the authorization code for tokens, then fetch the user profile. */
+declare function completeAuth(provider: OAuthProvider, options: CompleteAuthOptions): Promise<{
+    tokens: OAuthTokens;
+    profile: OAuthProfile;
+}>;
+/** Exchange an authorization code for tokens. */
+declare function exchangeCode(provider: OAuthProvider, options: CompleteAuthOptions): Promise<OAuthTokens>;
+/** Fetch + normalize the user's profile from the provider. */
+declare function fetchProfile(provider: OAuthProvider, tokens: OAuthTokens, fetchImpl?: FetchLike): Promise<OAuthProfile>;
+
+export { type CompleteAuthOptions, type OAuthProfile, type OAuthProvider, type OAuthTokens, type ProviderCredentials, type StartAuthOptions, type StartAuthResult, completeAuth, defineProvider, discord, exchangeCode, fetchProfile, github, google, randomToken, startAuth };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/oauth

Example 2

interface ProviderCredentials {
+  clientId: string;
+  clientSecret: string;
+  scopes?: string[]; // override the preset's default scopes
+}

Example 3

interface OAuthProvider {
+  name: string;
+  authorizeUrl: string;
+  tokenUrl: string;
+  userInfoUrl: string;
+  scopes: string[];
+  clientId: string;
+  clientSecret: string;
+  authorizeParams?: Record<string, string>; // e.g. access_type, prompt
+  mapProfile: (raw: Record<string, unknown>) => OAuthProfile;
+}

Example 4

interface StartAuthOptions {
+  redirectUri: string;
+  state?: string; // reuse a state instead of generating one
+  params?: Record<string, string>; // extra authorize params, merged last
+}
+
+interface StartAuthResult {
+  url: string; // authorize URL to redirect to
+  state: string; // CSRF state — verify on callback
+  verifier: string; // PKCE code verifier — pass to completeAuth
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/pubsub.wrn b/app/pages/packages/pubsub.wrn new file mode 100644 index 00000000..4a597e55 --- /dev/null +++ b/app/pages/packages/pubsub.wrn @@ -0,0 +1,137 @@ +page wrnexuspubsub { + seo { + title = "@wrnexus/pubsub" + description = "In-process and Redis-backed publish/subscribe." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Realtime

@wrnexus/pubsub

In-process and Redis-backed publish/subscribe.

bun add @wrnexus/pubsub@0.2.12
Topic-based publish/subscribe with a pluggable driver — in-process by default, Redis for cross-process messaging.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/pubsub is a small server-side pub/sub bus. You publish messages to a topic and subscribe with topic patterns; handlers fire for matching topics. The default driver keeps everything in-process, and you can swap in the Redis driver (@wrnexus/pubsub/redis) to fan messages out across processes or hosts. It also backs @wrnexus/core's realtime bridge for horizontal scaling.

+

Installation

+
bun add @wrnexus/pubsub
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

createPubSub(driver?): PubSub

+

Creates a bus over a driver. Defaults to memoryDriver() (in-process).

+
interface PubSub {
+  publish<T = unknown>(topic: string, message: T): Promise<void>;
+  subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
+}
+
+type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
+
    +
  • publish(topic, message) — resolves once the driver has dispatched the message.
  • +
  • subscribe(pattern, handler) — returns an unsubscribe function.
  • +
+

Pattern matching

+

Subscription patterns match in three ways:

+
    +
  • Exact"order:created" matches only that topic.
  • +
  • Prefix"order:*" matches any topic starting with "order:".
  • +
  • Everything"*" matches all topics.
  • +
+

memoryDriver(): PubSubDriver

+

The default in-process driver. Handlers are invoked synchronously (fire-and-forget for async handlers) whenever a published topic matches a registered pattern.

+
interface PubSubDriver {
+  publish(topic: string, message: unknown): void | Promise<void>;
+  subscribe(pattern: string, handler: Handler): () => void;
+}
+

@wrnexus/pubsub/redisredisDriver(url?)

+

A cross-process driver backed by Redis. It speaks RESP over a raw TCP socket via Bun.connect, so it adds no npm dependency. url defaults to $REDIS_URL, then redis://localhost:6379. The URL may carry a password and a database index (e.g. redis://:secret@host:6379/2).

+
function redisDriver(url?: string): PubSubDriver & { close(): void };
+
    +
  • Exact topics use Redis SUBSCRIBE; wildcard patterns (ns:*, *) use
  • +

    PSUBSCRIBE, whose glob semantics line up with this library's matching.

    +
  • Messages are JSON-stringified on publish and JSON.parsed on receipt; a payload
  • +

    that isn't valid JSON is delivered as the raw string.

    +
  • close() tears down both the subscriber and publisher connections.
  • +
+

RESP codec (internal)

+

redis.ts uses a minimal RESP implementation exported from resp.ts (encodeCommand, parseReply, concat, and the RespValue type). These are implementation details of the Redis driver, not part of the public package entry.

+

Usage

+

In-process (default):

+
import { createPubSub } from "@wrnexus/pubsub";
+
+const bus = createPubSub();
+
+const off = bus.subscribe("order:*", (msg, topic) => {
+  console.log(topic, msg);
+});
+
+await bus.publish("order:created", { id: 7 });
+
+off(); // unsubscribe
+

Cross-process with Redis:

+
import { createPubSub } from "@wrnexus/pubsub";
+import { redisDriver } from "@wrnexus/pubsub/redis";
+
+const driver = redisDriver("redis://localhost:6379");
+const bus = createPubSub(driver);
+
+bus.subscribe("order:*", (msg, topic) => {
+  // received on any app process subscribed to this pattern
+});
+
+await bus.publish("order:created", { id: 7 });
+
+// on shutdown
+driver.close();
+

Requirements / Notes

+
    +
  • Bun-only. The Redis driver depends on Bun.connect; it throws
  • +

    redisDriver requires the Bun runtime (Bun.connect). outside Bun. The default in-memory driver has no runtime dependencies.

    +
  • The Redis driver reads REDIS_URL from the environment when no url is passed.
  • +
  • Backs [@wrnexus/core](../core)'s realtime bridge for horizontal scaling.
  • +
  • No external npm dependencies — the Redis client is a self-contained RESP codec.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/pubsub — topic-based publish/subscribe with a pluggable driver.
+ * The default is in-process; swap in a Redis/NATS driver for cross-instance
+ * messaging (it also backs @wrnexus/core's realtime bridge).
+ *
+ *   const bus = createPubSub();
+ *   const off = bus.subscribe("order:*", (msg, topic) => {...});
+ *   await bus.publish("order:created", { id: 7 });
+ *
+ * Subscriptions match exact topics, "ns:*" prefixes, and "*" (everything).
+ */
+type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;
+interface PubSubDriver {
+    publish(topic: string, message: unknown): void | Promise<void>;
+    subscribe(pattern: string, handler: Handler): () => void;
+}
+interface PubSub {
+    publish<T = unknown>(topic: string, message: T): Promise<void>;
+    subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
+}
+/** In-process pub/sub driver (default). */
+declare function memoryDriver(): PubSubDriver;
+/** Create a pub/sub bus over a driver (in-memory by default). */
+declare function createPubSub(driver?: PubSubDriver): PubSub;
+
+export { type Handler, type PubSub, type PubSubDriver, createPubSub, memoryDriver };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/pubsub

Example 2

interface PubSub {
+  publish<T = unknown>(topic: string, message: T): Promise<void>;
+  subscribe<T = unknown>(pattern: string, handler: Handler<T>): () => void;
+}
+
+type Handler<T = unknown> = (message: T, topic: string) => void | Promise<void>;

Example 3

interface PubSubDriver {
+  publish(topic: string, message: unknown): void | Promise<void>;
+  subscribe(pattern: string, handler: Handler): () => void;
+}

Example 4

function redisDriver(url?: string): PubSubDriver & { close(): void };
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/queue.wrn b/app/pages/packages/queue.wrn new file mode 100644 index 00000000..1a039688 --- /dev/null +++ b/app/pages/packages/queue.wrn @@ -0,0 +1,177 @@ +page wrnexusqueue { + seo { + title = "@wrnexus/queue" + description = "Background jobs with delay, concurrency, retry, and repetition." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Data

@wrnexus/queue

Background jobs with delay, concurrency, retry, and repetition.

bun add @wrnexus/queue@0.2.12
A background job queue with delays, retries + exponential backoff, recurring jobs, and concurrent workers.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/queue is a server-side in-process job queue. You register named workers, enqueue jobs (optionally delayed or recurring), and let the queue poll and run them on a timer — with per-job retry limits and doubling backoff between attempts. The default store lives in memory; the design allows a pluggable driver to back it with Redis/SQL for durability across restarts. Reach for it when you need to defer work (emails, webhooks, cleanup) off the request path without a heavyweight external broker. Tests can drive it deterministically via drain().

+

Installation

+
bun add @wrnexus/queue
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The package exports a single factory plus its supporting types.

+

createQueue(options?): Queue

+

Creates a new queue instance.

+
function createQueue(options?: QueueOptions): Queue;
+

QueueOptions

+
+ +
OptionTypeDefaultDescription
maxAttemptsnumber3Default max attempts per job before it is dead-lettered.
backoffMsnumber1000Base retry backoff in ms; doubles per attempt.
pollMsnumber250Poll interval used once start() is called (ms).
onFailed(job: Job, error: unknown) => voidCalled when a job exhausts its attempts.
now() => numberDate.nowClock injection for deterministic tests.
+

Queue

+

The object returned by createQueue.

+
+ +
MethodSignatureDescription
addadd<T>(name, data: T, options?: AddOptions): Promise<Job<T>>Enqueue a job under a worker name. Returns the created job.
processprocess<T>(name, handler: JobHandler<T>): voidRegister the worker that runs jobs of the given name.
draindrain(now?: number): Promise<number>Run every job whose runAt ≤ now, once. Returns how many ran.
startstart(): voidBegin polling every pollMs. No-op if already started.
stopstop(): voidStop the poll timer.
sizesize(): numberNumber of jobs currently queued.
+

AddOptions

+
+ +
OptionTypeDescription
delayMsnumberDelay before the job becomes runnable (ms).
maxAttemptsnumberMax attempts before dead-lettering. Defaults to the queue's maxAttempts.
repeatnumberRe-enqueue this job this many ms after each successful run (recurring).
+

JobHandler<T>

+
type JobHandler<T = unknown> = (job: Job<T>) => void | Promise<void>;
+

Job<T>

+
interface Job<T = unknown> {
+  id: string; // e.g. "job_1"
+  name: string;
+  data: T;
+  attempts: number;
+  maxAttempts: number;
+  runAt: number; // epoch ms; job runs when now ≥ runAt
+  repeat?: number; // if set, re-enqueue this many ms after each success
+}
+

Usage

+

Register workers, enqueue jobs, then start the poller:

+
import { createQueue } from "@wrnexus/queue";
+
+const queue = createQueue({ maxAttempts: 3, backoffMs: 1000 });
+
+// Register a worker for the "email" job name.
+queue.process<{ to: string }>("email", async (job) => {
+  await send(job.data.to);
+});
+
+// Enqueue a delayed job with up to 3 attempts.
+await queue.add("email", { to: "a@b.com" }, { delayMs: 5000, maxAttempts: 3 });
+
+queue.start(); // begin polling; queue.stop() to halt
+

Recurring jobs

+

Pass repeat to re-enqueue a job a fixed interval after each successful run:

+
queue.process("heartbeat", async () => ping());
+await queue.add("heartbeat", {}, { repeat: 60_000 }); // runs ~every minute
+

Handling permanent failures

+

When a job's attempts reaches maxAttempts, it is dropped and onFailed fires instead of retrying:

+
const queue = createQueue({
+  onFailed: (job, error) => {
+    console.error(`job ${job.id} (${job.name}) gave up`, error);
+  },
+});
+

Deterministic testing

+

Instead of start(), inject a clock and drive the queue with drain():

+
let clock = 0;
+const queue = createQueue({ now: () => clock });
+
+queue.process("task", async () => {
+  /* ... */
+});
+await queue.add("task", {}, { delayMs: 5000 });
+
+clock = 5000;
+const ran = await queue.drain(); // => 1
+

Retry & backoff behavior

+
    +
  • On a thrown handler error, the job is retried while attempts < maxAttempts.
  • +
  • The next runAt is set to now + backoffMs * 2^(attempts - 1) (exponential
  • +

    backoff): with backoffMs: 1000 the delays are 1s, 2s, 4s, …

    +
  • A job whose worker name has no registered handler stays queued until one is
  • +

    registered (it is not counted as runnable by drain).

    +
  • drain is re-entrant-safe: overlapping calls are skipped while one is running.
  • +
+

Requirements / Notes

+
    +
  • Bun-only runtime (Node is not supported), consistent with the rest of the
  • +

    WRNexusJS framework. The queue itself relies only on standard timers (setInterval/clearInterval) and has no runtime dependencies.

    +
  • The default store is in-process, so queued jobs do not survive a restart; a
  • +

    pluggable driver is intended for backing it with Redis/SQL for durability.

    +
  • Works alongside @wrnexus/core for offloading work from the request path.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/queue — a background job queue with delays, retries + backoff, and
+ * concurrent workers. The default store is in-process; a pluggable driver lets
+ * you back it with Redis/SQL for durability across restarts.
+ *
+ *   const queue = createQueue();
+ *   queue.process("email", async (job) => { await send(job.data); });
+ *   await queue.add("email", { to: "a@b.com" }, { delayMs: 5000, maxAttempts: 3 });
+ *   queue.start();                 // begin polling; queue.stop() to halt
+ *
+ * Tests can drive it deterministically with `await queue.drain(now)`.
+ */
+interface Job<T = unknown> {
+    id: string;
+    name: string;
+    data: T;
+    attempts: number;
+    maxAttempts: number;
+    runAt: number;
+    /** If set, re-enqueue this job this many ms after each successful run. */
+    repeat?: number;
+}
+type JobHandler<T = unknown> = (job: Job<T>) => void | Promise<void>;
+interface AddOptions {
+    /** Delay before the job becomes runnable (ms). */
+    delayMs?: number;
+    /** Max attempts before it's dead-lettered. Default from queue options. */
+    maxAttempts?: number;
+    /** Re-enqueue this job this many ms after each successful run (recurring). */
+    repeat?: number;
+}
+interface QueueOptions {
+    /** Default max attempts per job. Default 3. */
+    maxAttempts?: number;
+    /** Base retry backoff (ms); doubles per attempt. Default 1000. */
+    backoffMs?: number;
+    /** Poll interval when started (ms). Default 250. */
+    pollMs?: number;
+    /** Called when a job exhausts its attempts. */
+    onFailed?: (job: Job, error: unknown) => void;
+    /** Clock injection (tests). Default Date.now. */
+    now?: () => number;
+}
+interface Queue {
+    add<T>(name: string, data: T, options?: AddOptions): Promise<Job<T>>;
+    process<T>(name: string, handler: JobHandler<T>): void;
+    /** Run every job whose runAt ≤ now, once. Returns how many ran. */
+    drain(now?: number): Promise<number>;
+    start(): void;
+    stop(): void;
+    size(): number;
+}
+declare function createQueue(options?: QueueOptions): Queue;
+
+export { type AddOptions, type Job, type JobHandler, type Queue, type QueueOptions, createQueue };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/queue

Example 2

function createQueue(options?: QueueOptions): Queue;

Example 3

type JobHandler<T = unknown> = (job: Job<T>) => void | Promise<void>;

Example 4

interface Job<T = unknown> {
+  id: string; // e.g. "job_1"
+  name: string;
+  data: T;
+  attempts: number;
+  maxAttempts: number;
+  runAt: number; // epoch ms; job runs when now ≥ runAt
+  repeat?: number; // if set, re-enqueue this many ms after each success
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/reactive.wrn b/app/pages/packages/reactive.wrn new file mode 100644 index 00000000..12eb1c01 --- /dev/null +++ b/app/pages/packages/reactive.wrn @@ -0,0 +1,139 @@ +page wrnexusreactive { + seo { + title = "@wrnexus/reactive" + description = "Small type-safe reactive signal primitives." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Frontend

@wrnexus/reactive

Small type-safe reactive signal primitives.

bun add @wrnexus/reactive@0.2.12
Tiny, type-safe reactive primitives (signals) with zero dependencies.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/reactive is the seed of WRNexusJS's reactivity layer: a minimal signal primitive that holds a value, notifies subscribers when it changes, and hands back an unsubscribe function. It is deliberately small and framework-agnostic — it powers nothing on its own, but is shaped so client islands (and later the .wrn compiler's state blocks) can build reactive bindings on top of it. Reach for it when you need observable state without pulling in a full reactivity library.

+

Installation

+
bun add @wrnexus/reactive
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The package has a single entry point (.) exporting one function and three types.

+

signal<T>(initial: T): Signal<T>

+

Creates a reactive signal seeded with initial. Returns a Signal<T>:

+
+ +
MemberSignatureDescription
get(): TRead the current value.
set(next: T): voidWrite a new value. Subscribers run only when the value actually changes (compared with Object.is).
update(fn: (current: T) => T): voidApply a function to the current value; equivalent to set(fn(get())).
subscribe(fn: Subscriber<T>): UnsubscribeRegister a subscriber; returns a function that removes it.
+

Types

+
type Subscriber<T> = (value: T) => void;
+type Unsubscribe = () => void;
+
+interface Signal<T> {
+  get(): T;
+  set(next: T): void;
+  update(fn: (current: T) => T): void;
+  subscribe(fn: Subscriber<T>): Unsubscribe;
+}
+

Notes on semantics:

+
    +
  • No-op updates are skipped. set compares the incoming value to the current
  • +

    one with Object.is; identical values do not notify subscribers.

    +
  • Safe unsubscribe during notification. Subscribers are iterated over a copy of
  • +

    the subscriber set, so a subscriber may call its own (or another's) unsubscribe while a notification is in flight.

    +
+

Usage

+
import { signal } from "@wrnexus/reactive";
+
+const count = signal(0);
+
+count.get(); // 0
+
+// Subscribe; the returned function unsubscribes.
+const off = count.subscribe((value) => {
+  console.log("count is now", value);
+});
+
+count.set(1); // logs: count is now 1
+count.set(1); // no-op — value unchanged, no notification
+count.update((n) => n + 1); // logs: count is now 2
+
+off(); // stop listening
+count.set(3); // nothing logged
+

Typed signals infer T from the initial value, or can be annotated explicitly:

+
import { signal, type Signal } from "@wrnexus/reactive";
+
+const user: Signal<{ name: string } | null> = signal(null);
+user.set({ name: "Ada" });
+

Requirements / Notes

+
    +
  • Bun-only. Distributed as TypeScript source (main/exports point at
  • +

    src/index.ts); consume it under Bun, which runs .ts directly.

    +
  • Zero dependencies. The only runtime API used is the standard Object.is.
  • +
  • Foundational primitive for WRNexusJS client islands and the forthcoming .wrn
  • +

    compiler state blocks.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * A minimal, type-safe reactive signal with zero dependencies.
+ *
+ * This is the seed of the framework's reactivity. Today it powers nothing on
+ * its own, but it is shaped so client islands (and later the `.wrn` compiler's
+ * `state` blocks) can build reactive bindings on top of it.
+ *
+ *   const count = signal(0)
+ *   count.get()                 // 0
+ *   count.set(1)                // notifies subscribers
+ *   const off = count.subscribe(v => console.log(v))
+ *   off()                       // unsubscribe
+ */
+type Subscriber<T> = (value: T) => void;
+type Unsubscribe = () => void;
+interface Signal<T> {
+    /** Read the current value. */
+    get(): T;
+    /** Write a new value; subscribers run only when the value actually changes. */
+    set(next: T): void;
+    /** Apply a function to the current value. */
+    update(fn: (current: T) => T): void;
+    /** Subscribe to changes; returns an unsubscribe function. */
+    subscribe(fn: Subscriber<T>): Unsubscribe;
+}
+declare function signal<T>(initial: T): Signal<T>;
+
+export { type Signal, type Subscriber, type Unsubscribe, signal };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/reactive

Example 2

type Subscriber<T> = (value: T) => void;
+type Unsubscribe = () => void;
+
+interface Signal<T> {
+  get(): T;
+  set(next: T): void;
+  update(fn: (current: T) => T): void;
+  subscribe(fn: Subscriber<T>): Unsubscribe;
+}

Example 3

import { signal } from "@wrnexus/reactive";
+
+const count = signal(0);
+
+count.get(); // 0
+
+// Subscribe; the returned function unsubscribes.
+const off = count.subscribe((value) => {
+  console.log("count is now", value);
+});
+
+count.set(1); // logs: count is now 1
+count.set(1); // no-op — value unchanged, no notification
+count.update((n) => n + 1); // logs: count is now 2
+
+off(); // stop listening
+count.set(3); // nothing logged

Example 4

import { signal, type Signal } from "@wrnexus/reactive";
+
+const user: Signal<{ name: string } | null> = signal(null);
+user.set({ name: "Ada" });
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/router.wrn b/app/pages/packages/router.wrn new file mode 100644 index 00000000..909e4b51 --- /dev/null +++ b/app/pages/packages/router.wrn @@ -0,0 +1,266 @@ +page wrnexusrouter { + seo { + title = "@wrnexus/router" + description = "Filesystem discovery, route matching, and typed route generation." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Core

@wrnexus/router

Filesystem discovery, route matching, and typed route generation.

bun add @wrnexus/router@0.2.12
File-based router that maps an app/ directory onto route tables and matches request paths against them.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/router scans an application's app/ directory once at startup and builds route tables for pages, API endpoints, realtime channels, middleware, server-rendered .wrn components, layouts, and validation schemas. It also compiles URL patterns (/users/[id]) into RegExps and matches request paths against them. Request input is never turned into a file path, which makes the router immune to path traversal. This is a server-side package used by the WRNexusJS runtime to resolve incoming requests, plus a codegen helper for compile-time typed links.

+

Installation

+
bun add @wrnexus/router
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

Directory conventions

+

The router maps files under appDir onto routes:

+
app/pages/index.tsx        -> GET /
+app/pages/about.tsx        -> GET /about
+app/pages/users/[id].tsx   -> GET /users/:id
+app/api/hello.ts           -> /api/hello
+app/realtime/chat.ts       -> /realtime/chat
+app/pages/*.wrn  (api)    -> embedded /api/* routes
+app/pages/*.wrn  (rt)     -> embedded /realtime/* routes
+app/middleware/*.ts        -> global middleware (alphabetical)
+app/components/*.wrn      -> server-rendered components (by basename)
+app/layouts/*.wrn         -> named page layouts
+app/schemas/*.ts           -> validation schemas
+

Allowed route extensions are .ts, .tsx, and .wrn. Dotfiles and underscore-prefixed files are ignored. A trailing index segment is dropped from the route. .wrn pages may embed api and realtime blocks, which the router extracts and mounts under /api/* and /realtime/*.

+

API

+

buildRouter(appDir, opts?): Router

+

Scan an app directory and build all route tables.

+
function buildRouter(appDir: string, opts?: RouterOptions): Router;
+
+interface RouterOptions {
+  /** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
+   *  `app/components`, so an app component of the same name wins. */
+  componentDirs?: string[];
+}
+

The returned Router exposes the built tables plus per-kind matchers:

+
interface Router {
+  pages: Route[];
+  api: Route[];
+  realtime: Route[];
+  /** Absolute paths of middleware modules, in execution order (alphabetical). */
+  middlewareFiles: string[];
+  /** Server-rendered `.wrn` components, mounted via `data-component`. */
+  components: ComponentRef[];
+  /** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
+  layouts: ComponentRef[];
+  /** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
+  schemas: ComponentRef[];
+  matchPage(pathname: string): RouteMatch | null;
+  matchApi(pathname: string): RouteMatch | null;
+  matchRealtime(pathname: string): RouteMatch | null;
+}
+
+interface ComponentRef {
+  /** Validated component name (matches a `data-component` attribute). */
+  name: string;
+  /** Absolute path to the component's `.wrn` module. */
+  file: string;
+}
+

Component, layout, and schema names are validated with isSafeIslandName from @wrnexus/core; unsafe names are skipped with a warning. Realtime channel names are validated the same way.

+

Route matching

+
+ +
ExportSignatureDescription
compileRoutePattern`(raw: string) => Pick<Route, "regex" \"paramNames">`Compile a /users/[id] pattern into a RegExp (with optional trailing slash) plus ordered param names.
matchRoute`(routes: Route[], pathname: string) => RouteMatch \null`Return the first route whose regex matches; captured params are decodeURIComponent-decoded.
sortRoutes(routes: Route[]) => Route[]Order routes so static routes win over dynamic ones (fewer params first), then longer/more specific patterns first.
+
interface Route {
+  raw: string; // e.g. "/users/[id]"
+  file: string; // absolute path to the handling module
+  regex: RegExp; // compiled matcher
+  paramNames: string[]; // ordered dynamic param names
+}
+
+interface RouteMatch {
+  route: Route;
+  params: Record<string, string>;
+}
+

Typed-routes codegen

+
function generateRoutesFile(pages: Route[]): string;
+

Emits the source for app/routes.gen.ts: a Routes map (each page path → its [param] types), a RoutePath union, and an href() builder that fills params and rejects unknown paths at compile time. Entries are de-duplicated and sorted by path.

+

Re-exports

+

Middleware (the type from @wrnexus/core) is re-exported for callers that load middleware modules themselves.

+

Usage

+
import { buildRouter } from "@wrnexus/router";
+
+const router = buildRouter("./app", {
+  componentDirs: ["./node_modules/@wrnexus/ui/components"],
+});
+
+// Resolve an incoming request.
+const match = router.matchPage("/users/42");
+if (match) {
+  console.log(match.route.file); // absolute path to the page module
+  console.log(match.params); // { id: "42" }
+}
+
+const api = router.matchApi("/api/hello");
+const rt = router.matchRealtime("/realtime/chat");
+

Generating the typed-routes file (as wrnexus dev does):

+
import { generateRoutesFile } from "@wrnexus/router";
+import { writeFileSync } from "node:fs";
+
+const router = buildRouter("./app");
+writeFileSync("./app/routes.gen.ts", generateRoutesFile(router.pages));
+
// Then, in app code, links are checked at compile time:
+import { href } from "./routes.gen.ts";
+
+href("/users/[id]", { id: "42" }); // "/users/42"
+href("/about"); // "/about"
+href("/nope"); // type error: unknown path
+

Lower-level pattern matching, if you need it directly:

+
import { compileRoutePattern, matchRoute, sortRoutes, type Route } from "@wrnexus/router";
+
+const { regex, paramNames } = compileRoutePattern("/posts/[slug]");
+const routes = sortRoutes([{ raw: "/posts/[slug]", file: "…", regex, paramNames }]);
+const m = matchRoute(routes, "/posts/hello"); // { route, params: { slug: "hello" } }
+

Requirements / Notes

+
    +
  • Scanning uses node:fs (existsSync, readdirSync, statSync) and node:path — runs under Bun.
  • +
  • Depends on [@wrnexus/compiler](../compiler) to parse .wrn pages and extract embedded api / realtime blocks.
  • +
  • Depends on [@wrnexus/core](../core) for isSafeIslandName (name validation) and the Middleware type.
  • +
  • Missing route directories are tolerated — a route kind you don't use simply yields an empty table.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

export { Middleware } from '@wrnexus/core';
+
+/**
+ * Route compilation + matching.
+ *
+ * A "route" is a URL pattern compiled to a RegExp. We support static segments
+ * and dynamic `[param]` segments, e.g. `/users/[id]` -> `{ id }`.
+ */
+interface Route {
+    /** The human-readable route pattern, e.g. `/users/[id]`. */
+    raw: string;
+    /** Absolute path to the module that handles this route. */
+    file: string;
+    /** Compiled matcher. */
+    regex: RegExp;
+    /** Ordered names of dynamic params captured by `regex`. */
+    paramNames: string[];
+}
+interface RouteMatch {
+    route: Route;
+    params: Record<string, string>;
+}
+/** Compile a `/users/[id]` style pattern into a RegExp + param names. */
+declare function compileRoutePattern(raw: string): Pick<Route, "regex" | "paramNames">;
+/**
+ * Order routes so that static routes win over dynamic ones, and longer/more
+ * specific routes win over shorter ones. Sorting once keeps matching simple.
+ */
+declare function sortRoutes(routes: Route[]): Route[];
+/** Find the first route whose pattern matches `pathname`. */
+declare function matchRoute(routes: Route[], pathname: string): RouteMatch | null;
+
+/**
+ * Typed-routes codegen. From the scanned page routes, emit `app/routes.gen.ts`
+ * with a `Routes` map (path → param types) and an `href()` builder — so links
+ * are checked at compile time (unknown path or missing param = type error).
+ */
+
+declare function generateRoutesFile(pages: Route[]): string;
+
+/**
+ * @wrnexus/router — file-based router.
+ *
+ * Maps the `app/` directory onto route tables:
+ *   app/pages/index.tsx     -> GET /
+ *   app/pages/about.tsx     -> GET /about
+ *   app/pages/users/[id].tsx-> GET /users/:id
+ *   app/api/hello.ts        -> /api/hello
+ *   app/realtime/chat.ts    -> /realtime/chat
+ *   app/pages/*.wrn api      -> embedded /api/* routes
+ *   app/pages/*.wrn realtime -> embedded /realtime/* routes
+ *   app/middleware/*.ts     -> global middleware (alphabetical)
+ *   app/components/*.wrn   -> server-rendered components (by basename),
+ *                              mounted in a page via data-component="<name>"
+ */
+
+interface ComponentRef {
+    /** Validated component name (matches a `data-component` attribute). */
+    name: string;
+    /** Absolute path to the component's `.wrn` module. */
+    file: string;
+}
+interface Router {
+    pages: Route[];
+    api: Route[];
+    realtime: Route[];
+    /** Absolute paths of middleware modules, in execution order. */
+    middlewareFiles: string[];
+    /** Server-rendered `.wrn` components, mounted via `data-component`. */
+    components: ComponentRef[];
+    /** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
+    layouts: ComponentRef[];
+    /** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
+    schemas: ComponentRef[];
+    matchPage(pathname: string): RouteMatch | null;
+    matchApi(pathname: string): RouteMatch | null;
+    matchRealtime(pathname: string): RouteMatch | null;
+}
+interface RouterOptions {
+    /**
+     * Extra directories to scan for `.wrn` components (e.g. `@wrnexus/ui`).
+     * Scanned before `app/components`, so an app component of the same name wins.
+     */
+    componentDirs?: string[];
+}
+/** Scan an app directory and build all route tables. */
+declare function buildRouter(appDir: string, opts?: RouterOptions): Router;
+
+export { type ComponentRef, type Route, type RouteMatch, type Router, type RouterOptions, buildRouter, compileRoutePattern, generateRoutesFile, matchRoute, sortRoutes };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/router

Example 2

app/pages/index.tsx        -> GET /
+app/pages/about.tsx        -> GET /about
+app/pages/users/[id].tsx   -> GET /users/:id
+app/api/hello.ts           -> /api/hello
+app/realtime/chat.ts       -> /realtime/chat
+app/pages/*.wrn  (api)    -> embedded /api/* routes
+app/pages/*.wrn  (rt)     -> embedded /realtime/* routes
+app/middleware/*.ts        -> global middleware (alphabetical)
+app/components/*.wrn      -> server-rendered components (by basename)
+app/layouts/*.wrn         -> named page layouts
+app/schemas/*.ts           -> validation schemas

Example 3

function buildRouter(appDir: string, opts?: RouterOptions): Router;
+
+interface RouterOptions {
+  /** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
+   *  `app/components`, so an app component of the same name wins. */
+  componentDirs?: string[];
+}

Example 4

interface Router {
+  pages: Route[];
+  api: Route[];
+  realtime: Route[];
+  /** Absolute paths of middleware modules, in execution order (alphabetical). */
+  middlewareFiles: string[];
+  /** Server-rendered `.wrn` components, mounted via `data-component`. */
+  components: ComponentRef[];
+  /** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
+  layouts: ComponentRef[];
+  /** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
+  schemas: ComponentRef[];
+  matchPage(pathname: string): RouteMatch | null;
+  matchApi(pathname: string): RouteMatch | null;
+  matchRealtime(pathname: string): RouteMatch | null;
+}
+
+interface ComponentRef {
+  /** Validated component name (matches a `data-component` attribute). */
+  name: string;
+  /** Absolute path to the component's `.wrn` module. */
+  file: string;
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/ssr.wrn b/app/pages/packages/ssr.wrn new file mode 100644 index 00000000..bbec320a --- /dev/null +++ b/app/pages/packages/ssr.wrn @@ -0,0 +1,171 @@ +page wrnexusssr { + seo { + title = "@wrnexus/ssr" + description = "Secure HTML document rendering and SEO metadata." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Runtime

@wrnexus/ssr

Secure HTML document rendering and SEO metadata.

bun add @wrnexus/ssr@0.2.12
Server-side rendering: wraps a page's HTML body in a complete HTML document with a metadata-driven <head>.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

Pages in WRNexusJS return an HTML string for the body. @wrnexus/ssr takes that body and produces a full HTML document — building the <head> from page metadata and global SEO defaults, resolving canonical/Open Graph/Twitter tags, and injecting module preloads and <script type="module"> tags. It is deliberately server-only: nothing in this package touches the DOM or ships to the browser, keeping server code genuinely server-only. Reach for it on the server when turning a rendered page body into a response document.

+

Installation

+
bun add @wrnexus/ssr
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The package has a single export.

+

renderDocument(opts: RenderOptions): string

+

Renders a complete HTML document as a string, beginning with <!doctype html>. All metadata is HTML-escaped (via escapeHtml from @wrnexus/core), so a malicious title or description cannot break out of its element or attribute. The body is placed inside <div id="app">.

+

RenderOptions

+
+ +
FieldTypeDescription
metaPageMetaPage metadata for the document head (required).
bodystringRendered HTML for the body, placed inside #app (required).
seoSeoConfigGlobal SEO defaults, typically from wrnexus.config.ts.
urlURLCurrent request URL, used to resolve canonical/Open Graph URLs.
scriptsstring[]URLs of <script type="module"> tags to load (e.g. per-island chunks or the reactive runtime). Each also gets a <link rel="modulepreload">.
defaultTitlestringDefault document title used when meta.title is absent.
extraHeadstringRaw HTML injected at the end of <head> (trusted, framework-controlled — not escaped).
extraBodystringRaw HTML injected at the end of <body> (trusted, framework-controlled — not escaped).
htmlAttrsstringAttributes for the <html> element, e.g. data-theme="dark" (trusted).
+

PageMeta and SeoConfig come from @wrnexus/core. PageMeta is an alias of SeoConfig, whose fields are all optional:

+
type SeoConfig = {
+  title?: string;
+  titleTemplate?: string; // e.g. "%s — My Site"; %s is replaced with the page title
+  description?: string;
+  canonical?: string;
+  canonicalBase?: string; // origin used to absolutize canonical/image URLs
+  robots?: string;
+  keywords?: string | string[];
+  image?: string;
+  siteName?: string;
+  type?: string; // Open Graph type; defaults to "website"
+  locale?: string;
+  twitterCard?: string; // defaults to "summary"
+  twitterSite?: string;
+  themeColor?: string;
+};
+

Metadata resolution

+

renderDocument merges page metadata (meta) over global defaults (seo), field by field, so per-page values win. Notable behavior:

+
    +
  • Title: uses meta.title, else seo.title, else defaultTitle, else "WRNexusJS". When the page sets its own title and seo.titleTemplate contains %s, the template is applied.
  • +
  • Canonical / image URLs: resolved against canonicalBase (or the request url's origin) into absolute URLs when possible.
  • +
  • Keywords: an array is joined with ", ".
  • +
  • Emitted tags: <title>, and as applicable description, robots, keywords, theme-color, and canonical link, plus Open Graph (og:title, og:description, og:type, og:url, og:site_name, og:locale, og:image) and Twitter (twitter:card, twitter:title, twitter:description, twitter:image, twitter:site) meta tags. The document always includes charset, viewport, and a /favicon.ico icon link.
  • +
+

Usage

+
import { renderDocument } from "@wrnexus/ssr";
+
+const html = renderDocument({
+  meta: {
+    title: "About Us",
+    description: "Learn more about our team.",
+  },
+  seo: {
+    titleTemplate: "%s — Acme",
+    siteName: "Acme",
+    canonicalBase: "https://acme.example",
+    twitterSite: "@acme",
+  },
+  url: new URL("https://acme.example/about"),
+  body: "<h1>About Us</h1>",
+  scripts: ["/_wire/runtime.js", "/_wire/islands/about.js"],
+  htmlAttrs: ' data-theme="dark"',
+});
+
+return new Response(html, {
+  headers: { "content-type": "text/html; charset=utf-8" },
+});
+

The produced document has <title>About Us — Acme</title>, the SEO/Open Graph/Twitter tags derived from the merged metadata, a modulepreload link and module <script> for each entry in scripts, and the body wrapped in <div id="app">.

+

Requirements / Notes

+
    +
  • Server-only. This module never imports or touches the DOM and is safe to keep out of client bundles.
  • +
  • Depends on [@wrnexus/core](../core) for escapeHtml and the PageMeta / SeoConfig types.
  • +
  • Bun-only — like the rest of WRNexusJS, this package targets the Bun runtime (Node is not supported).
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { PageMeta, SeoConfig } from '@wrnexus/core';
+
+/**
+ * @wrnexus/ssr — server-side rendering.
+ *
+ * Pages return an HTML string for the body; this module wraps that body in a
+ * full document with a `<head>` built from page metadata. It is intentionally
+ * isolated from any client runtime: nothing here touches the DOM or ships to
+ * the browser, which keeps "server-only code" genuinely server-only.
+ */
+
+interface RenderOptions {
+    /** Page metadata for the document head. */
+    meta: PageMeta;
+    /** Global SEO defaults from `wrnexus.config.ts`. */
+    seo?: SeoConfig;
+    /** Current request URL, used to resolve canonical/Open Graph URLs. */
+    url?: URL;
+    /** Rendered HTML for the body (placed inside `#app`). */
+    body: string;
+    /**
+     * URLs of `<script type="module">` tags to load (e.g. per-island chunks or
+     * the reactive runtime). Only the scripts a page actually needs are passed.
+     */
+    scripts?: string[];
+    /** Optional default document title used when meta.title is absent. */
+    defaultTitle?: string;
+    /** Raw HTML injected at the end of `<head>` (trusted, framework-controlled). */
+    extraHead?: string;
+    /** Raw HTML injected at the end of `<body>` (trusted, framework-controlled). */
+    extraBody?: string;
+    /** Attributes for the `<html>` element, e.g. ` data-theme="dark"` (trusted). */
+    htmlAttrs?: string;
+}
+/**
+ * Render a complete HTML document.
+ *
+ * Metadata is HTML-escaped so a malicious title/description can never break
+ * out of its element or attribute.
+ */
+declare function renderDocument(opts: RenderOptions): string;
+
+export { type RenderOptions, renderDocument };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/ssr

Example 2

type SeoConfig = {
+  title?: string;
+  titleTemplate?: string; // e.g. "%s — My Site"; %s is replaced with the page title
+  description?: string;
+  canonical?: string;
+  canonicalBase?: string; // origin used to absolutize canonical/image URLs
+  robots?: string;
+  keywords?: string | string[];
+  image?: string;
+  siteName?: string;
+  type?: string; // Open Graph type; defaults to "website"
+  locale?: string;
+  twitterCard?: string; // defaults to "summary"
+  twitterSite?: string;
+  themeColor?: string;
+};

Example 3

import { renderDocument } from "@wrnexus/ssr";
+
+const html = renderDocument({
+  meta: {
+    title: "About Us",
+    description: "Learn more about our team.",
+  },
+  seo: {
+    titleTemplate: "%s — Acme",
+    siteName: "Acme",
+    canonicalBase: "https://acme.example",
+    twitterSite: "@acme",
+  },
+  url: new URL("https://acme.example/about"),
+  body: "<h1>About Us</h1>",
+  scripts: ["/_wire/runtime.js", "/_wire/islands/about.js"],
+  htmlAttrs: ' data-theme="dark"',
+});
+
+return new Response(html, {
+  headers: { "content-type": "text/html; charset=utf-8" },
+});
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/styles.wrn b/app/pages/packages/styles.wrn new file mode 100644 index 00000000..688cfebe --- /dev/null +++ b/app/pages/packages/styles.wrn @@ -0,0 +1,562 @@ +page wrnexusstyles { + seo { + title = "@wrnexus/styles" + description = "CSS pipeline, themes, fonts, profiles, and application config." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Frontend

@wrnexus/styles

CSS pipeline, themes, fonts, profiles, and application config.

bun add @wrnexus/styles@0.2.12
Global CSS bundling, the --wire-* design-token theme system, and the wrnexus.config.ts app-config loader for WRNexusJS apps.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

This package owns three server-side concerns that shape every page a WRNexusJS app renders:

+

1. Global stylesheet pipeline — finds app/styles/global.css (or aggregates app/styles/*.css), bundles it with Bun's CSS bundler (which resolves @import, including from node_modules), and produces one stylesheet that is <link>ed into every page's <head>. Because it is a plain global sheet, it styles server-rendered markup and hydrated client islands identically. A custom process hook lets you swap in Tailwind / PostCSS / Sass. 2. Theme system — design tokens exposed as CSS custom properties (--wire-<key>), with built-in light/dark sets, deep-merged user overrides, an SSR <html data-theme> render (no flash), and a tiny client runtime to toggle/persist the choice. 3. App config — loads wrnexus.config.ts (the AppConfig type), applies named profile overrides, and loads the .env cascade.

+

It runs server-side / at build time. Reach for it when configuring an app, defining themes, or customising how global CSS is produced.

+

Installation

+
bun add @wrnexus/styles
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Everything is exported from the package root (@wrnexus/styles).

+

Config loading

+
+ +
ExportSignaturePurpose
loadAppConfig(appRoot: string, profile?: string) => Promise<AppConfig>Load wrnexus.config.* with the active profile deep-merged in (profiles stripped from the result).
loadRawConfig(appRoot: string) => Promise<AppConfig>Load the raw config with the profiles map intact; returns {} if no config file exists.
resolveProfile(options?: { explicit?; mode? }) => stringResolve the active profile: explicit arg > WRNEXUS_PROFILE env var > mode-based default (production in prod, else development).
loadEnv(appRoot: string, profile: string) => Record<string, string>Load the .env cascade for a profile into process.env without clobbering real env vars. Returns what it loaded.
headToString`(head?: string \string[]) => string`Flatten AppConfig.head into a single HTML string.
+

Config file names probed, in order: wrnexus.config.ts, wrnexus.config.js, wrnexus.config.mjs.

+

.env cascade precedence (low → high): .env < .env.<profile> < .env.local < .env.<profile>.local. Variables already present in the real environment always win.

+

AppConfig

+

The type of the object your wrnexus.config.ts default-exports. Every field is optional.

+
+ +
FieldTypeDescription
head`string \string[]`Raw HTML appended to every page's <head> (e.g. CDN stylesheet/script links).
seoSeoConfigGlobal SEO defaults, merged with each page's exported meta. (from @wrnexus/core)
securitySecurityConfigFramework security headers and optional CORS policy. (from @wrnexus/core)
stylesStylesConfigGlobal stylesheet pipeline config (see below).
themeThemeConfigDesign-token themes, deep-merged over the built-in light/dark.
i18n{ default?: string; locales?: string[] }Default language + supported locales (strings live in app/locales/*.json).
db`{ driver: "sqlite" \"postgres" \"mysql" \"mongo"; url: string }`Default database connection; reached with getDb().
databasesRecord<string, { driver; url }>Additional named databases, reached with getDb("<name>"); each has its own app/db/<name>/ migrations/queries.
realtime{ scale?: boolean; redisUrl?: string }When scale is true (or redisUrl is set), room broadcasts bridge over Redis pub/sub so they reach clients on every app process.
portnumberDefault server port.
profilesRecord<string, Partial<Omit<AppConfig, "profiles">>>Named profiles (dev, prod, uat, test, …). The active profile's overrides are deep-merged over the base config. Selected via --profile=<name> or WRNEXUS_PROFILE.
+

Styles pipeline

+
+ +
ExportSignaturePurpose
findStyleEntry`(appDir, appRoot, override?) => string \null`Resolve the CSS entry: override (relative to appRoot) → app/styles/global.css → an aggregate of all app/styles/*.css (written to app/.wrnexus/styles-entry.css). null if the app has no styles.
bundleCss(entryPath: string, mode: Mode) => Promise<string>Bundle an entry with Bun.build (CSS bundler). Resolves @import (local + node_modules), handles nesting, minifies when mode === "production".
renderStyles(ctx: StyleProcessContext, styles?: StylesConfig) => Promise<string>Produce final CSS: runs styles.process(ctx) if provided, else bundleCss. Returns "" when ctx.entryPath is null.
+

StylesConfig:

+
interface StylesConfig {
+  /** CSS entry path relative to the app root. Default: app/styles/global.css */
+  entry?: string;
+  /** Custom processor — return the final CSS string (Tailwind/PostCSS/Sass). */
+  process?: (ctx: StyleProcessContext) => string | Promise<string>;
+}
+
+interface StyleProcessContext {
+  entryPath: string | null; // resolved absolute CSS entry, or null
+  appDir: string;
+  appRoot: string;
+  mode: Mode; // "development" | "production"
+}
+

Theme system

+
+ +
ExportType / SignaturePurpose
DEFAULT_THEMESRecord<string, ThemeTokens>Built-in light and dark token maps.
THEME_COOKIE"wire-theme"Cookie the resolved theme is read from / persisted to.
THEME_CSS_HREF"/__wrnexus/theme.css"URL the generated theme stylesheet is served at.
THEME_JS_HREF"/__wrnexus/theme.js"URL the client theme runtime is served at.
resolveThemeConfig(config?: ThemeConfig) => ResolvedThemeDeep-merge the user's theme config over the defaults; pick the default theme (config's default if valid, else dark, else the first).
resolveThemeName`(cookieValue: string \undefined, theme: ResolvedTheme) => string`Pick a valid theme name from a cookie, falling back to theme.default.
renderThemeCss(theme: ResolvedTheme) => stringGenerate the theme stylesheet: a :root{…} default plus one [data-theme="<name>"]{…} block per theme.
renderThemeRuntime(theme: ResolvedTheme) => stringGenerate the client runtime (see below).
+

Tokens are emitted as --wire-<key> custom properties, except the reserved key color-scheme, which is emitted as the native color-scheme CSS property so form controls and scrollbars match the theme.

+

ThemeConfig / ThemeTokens / ResolvedTheme:

+
type ThemeTokens = Record<string, string>;
+
+interface ThemeConfig {
+  default?: string; // theme used when no cookie is present
+  themes?: Record<string, ThemeTokens>; // deep-merged over built-in light/dark
+}
+
+interface ResolvedTheme {
+  default: string;
+  names: string[];
+  themes: Record<string, ThemeTokens>;
+}
+

Built-in token keys (both light and dark): color-scheme, color-bg, color-surface, color-surface-2, color-text, color-muted, color-border, color-primary, color-primary-hover, color-primary-contrast, color-danger, color-success, color-warning, radius, radius-sm, font-sans, shadow-1.

+

The client runtime (renderThemeRuntime) exposes window.wireTheme with { get, set, toggle, bind, themes }, wires up any [data-wire-theme-toggle] and [data-wire-theme-set] elements on load, and persists the choice to the wire-theme cookie (max-age 1 year, samesite=lax). toggle() cycles through the configured theme names in order.

+

Usage

+

wrnexus.config.ts

+
import type { AppConfig } from "@wrnexus/styles";
+
+export default {
+  head: [
+    '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css">',
+  ],
+  port: 3000,
+  db: { driver: "sqlite", url: "app.db" },
+  theme: {
+    default: "dark",
+    themes: {
+      light: { "color-primary": "#7c3aed" }, // override one token; rest inherited
+      brand: {
+        // add a whole new theme
+        "color-scheme": "dark",
+        "color-bg": "#0a0a0a",
+        "color-primary": "#22d3ee",
+      },
+    },
+  },
+  styles: {
+    entry: "app/styles/main.css",
+  },
+  profiles: {
+    production: {
+      db: { driver: "postgres", url: process.env.DATABASE_URL! },
+    },
+  },
+} satisfies AppConfig;
+

Loading config + producing CSS

+
import {
+  loadAppConfig,
+  resolveProfile,
+  loadEnv,
+  findStyleEntry,
+  renderStyles,
+} from "@wrnexus/styles";
+
+const appRoot = process.cwd();
+const mode = "production" as const;
+
+const profile = resolveProfile({ mode });
+loadEnv(appRoot, profile);
+
+const config = await loadAppConfig(appRoot, profile);
+
+const appDir = `${appRoot}/app`;
+const entryPath = findStyleEntry(appDir, appRoot, config.styles?.entry);
+const css = await renderStyles({ entryPath, appDir, appRoot, mode }, config.styles);
+

Rendering the theme

+
import {
+  resolveThemeConfig,
+  resolveThemeName,
+  renderThemeCss,
+  renderThemeRuntime,
+  THEME_COOKIE,
+} from "@wrnexus/styles";
+
+const theme = resolveThemeConfig(config.theme);
+
+// Server: pick the active theme from the request cookie (no flash).
+const active = resolveThemeName(cookies[THEME_COOKIE], theme);
+// → render <html data-theme={active}>
+
+const themeCss = renderThemeCss(theme); // served at THEME_CSS_HREF
+const themeJs = renderThemeRuntime(theme); // served at THEME_JS_HREF
+

In templates, consume tokens via the custom properties:

+
.card {
+  background: var(--wire-color-surface);
+  color: var(--wire-color-text);
+  border: 1px solid var(--wire-color-border);
+  border-radius: var(--wire-radius);
+  box-shadow: var(--wire-shadow-1);
+}
+
<button data-wire-theme-toggle>Toggle theme</button>
+<button data-wire-theme-set="brand">Brand theme</button>
+

Requirements / Notes

+
    +
  • Bun-only. bundleCss uses Bun.build's CSS bundler for @import resolution, nesting, and minification. Node is not supported.
  • +
  • Config and env loading use node:fs / node:path / node:url and read from process.env.
  • +
  • Peer package: @wrnexus/core supplies the SeoConfig and SecurityConfig types referenced by AppConfig.
  • +
  • The bundled global stylesheet, the theme stylesheet (THEME_CSS_HREF), and the theme runtime (THEME_JS_HREF) are wired into pages by the framework's server; this package only produces their contents.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { SeoConfig, SecurityConfig } from '@wrnexus/core';
+import { StorageConfig } from '@wrnexus/uploader';
+
+/**
+ * Theme system — design tokens that work SSR and client-side.
+ *
+ * Tokens are plain CSS custom properties (`--wire-<key>`) so they cascade and
+ * can be overridden by user CSS. Each theme is a flat token map; the framework
+ * ships default `light`/`dark` sets and the user's config deep-merges over them.
+ *
+ * The server renders `<html data-theme="…">` from the `wire-theme` cookie (no
+ * flash), and a tiny client runtime toggles/persists it. The reserved token key
+ * `color-scheme` is emitted as the native CSS property (not a variable) so form
+ * controls and scrollbars match the theme.
+ */
+type ThemeTokens = Record<string, string>;
+interface ThemeConfig {
+    /** Name of the theme used when no `wire-theme` cookie is present. */
+    default?: string;
+    /** Named token maps. Deep-merged over the framework's built-in light/dark. */
+    themes?: Record<string, ThemeTokens>;
+}
+interface ResolvedTheme {
+    default: string;
+    names: string[];
+    themes: Record<string, ThemeTokens>;
+}
+/** Cookie the resolved theme is read from / persisted to. */
+declare const THEME_COOKIE = "wire-theme";
+declare const THEME_CSS_HREF = "/__wrnexus/theme.css";
+declare const THEME_JS_HREF = "/__wrnexus/theme.js";
+/** Built-in themes so components have tokens out of the box. */
+declare const DEFAULT_THEMES: Record<string, ThemeTokens>;
+/** Merge the user's theme config over the built-in defaults. */
+declare function resolveThemeConfig(config?: ThemeConfig): ResolvedTheme;
+/** Pick a valid theme name from a cookie value, falling back to the default. */
+declare function resolveThemeName(cookieValue: string | undefined, theme: ResolvedTheme): string;
+/** Generate the theme stylesheet: a `:root` default plus one block per theme. */
+declare function renderThemeCss(theme: ResolvedTheme): string;
+/**
+ * Generate the client theme runtime. It exposes `window.wireTheme` and binds
+ * `[data-wire-theme-toggle]` / `[data-wire-theme-set]` elements. The configured
+ * theme names are baked in so `toggle()` cycles through them in order.
+ */
+declare function renderThemeRuntime(theme: ResolvedTheme): string;
+
+/**
+ * Font configuration.
+ *
+ * Declare fonts in `wrnexus.config.ts` under `fonts` and the framework emits
+ * optimized `<head>` markup for you:
+ *   - Google Fonts: `preconnect` hints + a single subsetted stylesheet request
+ *     (only the weights you list) with `font-display`. The CSP is auto-extended
+ *     so the fonts load under the default security policy (see loadAppConfig).
+ *   - Self-hosted fonts: generated `@font-face` rules + optional `<link rel=preload>`
+ *     for above-the-fold text (the fastest, no-third-party option).
+ *   - Family stacks: `sans`/`mono`/`serif` become `--wrn-font-*` CSS variables,
+ *     and `sans` is applied to `body`.
+ */
+type FontDisplay = "auto" | "block" | "swap" | "fallback" | "optional";
+interface GoogleFont {
+    /** Family name as it appears on fonts.google.com, e.g. "Inter". */
+    family: string;
+    /** Weights to load — ONLY these are fetched. Default: [400]. */
+    weights?: (number | string)[];
+    /** Also load italic styles for each weight. */
+    italic?: boolean;
+    /** Per-font `font-display` override (else the config default). */
+    display?: FontDisplay;
+}
+interface LocalFontFace {
+    /** `font-family` name this face defines. */
+    family: string;
+    /** URL to the font file, typically served from `public/` (e.g. "/fonts/inter.woff2"). */
+    src: string;
+    /** e.g. 400, "700", or "100 900" for a variable font. Default: 400. */
+    weight?: number | string;
+    style?: "normal" | "italic";
+    /** CSS `src` format; inferred from the file extension when omitted. */
+    format?: string;
+    display?: FontDisplay;
+    /** Emit `<link rel="preload" as="font">` — use for the primary above-the-fold face. */
+    preload?: boolean;
+    /** Optional `unicode-range` subset. */
+    unicodeRange?: string;
+}
+interface FontConfig {
+    /** Google Fonts, loaded with preconnect + weight subsetting + `font-display`. */
+    google?: GoogleFont[];
+    /** Self-hosted `@font-face` definitions (files served from `public/`). */
+    local?: LocalFontFace[];
+    /** Default `font-display` for faces that don't set their own. Default: "swap". */
+    display?: FontDisplay;
+    /** Body / default family stack → `--wrn-font-sans` + `body { font-family }`. */
+    sans?: string;
+    /** Monospace family stack → `--wrn-font-mono`. */
+    mono?: string;
+    /** Serif family stack → `--wrn-font-serif`. */
+    serif?: string;
+}
+/**
+ * Render all `<head>` markup for a font config. Returns "" when nothing is
+ * configured. The output is trusted, framework-controlled HTML.
+ */
+declare function renderFontHead(fonts?: FontConfig): string;
+/**
+ * CSP source hosts required by the configured fonts, so the policy can be
+ * auto-extended (Google Fonts need their CSS + static hosts allow-listed).
+ */
+declare function fontCspSources(fonts?: FontConfig): {
+    style: string[];
+    font: string[];
+};
+
+/**
+ * App configuration loader (`wrnexus.config.ts`).
+ *
+ * The config is optional. It lets an app inject arbitrary `<head>` HTML (ideal
+ * for CDN-delivered CSS frameworks like Bootstrap or the Tailwind Play CDN) and
+ * customise the global stylesheet pipeline (entry file or a custom processor for
+ * Tailwind / PostCSS / Sass).
+ */
+
+type Mode = "development" | "production";
+interface StyleProcessContext {
+    /** Resolved absolute path to the CSS entry, or null if there is none. */
+    entryPath: string | null;
+    appDir: string;
+    appRoot: string;
+    mode: Mode;
+}
+interface StylesConfig {
+    /** Path to the CSS entry, relative to the app root. Default: app/styles/global.css */
+    entry?: string;
+    /**
+     * Optional custom processor. Return the final CSS string. Use this to run
+     * Tailwind, PostCSS, Sass, etc. When omitted, the built-in Bun CSS bundler is
+     * used (which already resolves `@import`, including from node_modules).
+     */
+    process?: (ctx: StyleProcessContext) => string | Promise<string>;
+}
+interface MobileConfig {
+    enabled?: boolean;
+    /** Mobile renderer. `webview` uses Capacitor; `native` scaffolds an Expo/React Native app. */
+    mode?: "webview" | "native";
+    appId?: string;
+    appName?: string;
+    serverUrl?: string;
+    userAgent?: string;
+    layout?: string;
+    backgroundColor?: string;
+    icon?: string;
+    errorTitle?: string;
+    errorMessage?: string;
+    /** Base URL used by a fully native client for WRNexusJS API and realtime requests. */
+    apiUrl?: string;
+    /** URL scheme used for native deep links (defaults to a slug of appName). */
+    scheme?: string;
+    /** Advanced Expo app config fields merged into generated app.config.ts. */
+    expo?: Record<string, unknown>;
+    /** Advanced CapacitorConfig fields merged into generated capacitor.config.ts. */
+    capacitor?: Record<string, unknown>;
+}
+interface PwaScreenshot {
+    src: string;
+    sizes: string;
+    type?: string;
+    formFactor?: "wide" | "narrow";
+    label?: string;
+}
+interface PwaShortcut {
+    name: string;
+    shortName?: string;
+    description?: string;
+    url: string;
+    icons?: Array<{
+        src: string;
+        sizes: string;
+        type?: string;
+        purpose?: string;
+    }>;
+}
+interface PwaConfig {
+    enabled?: boolean;
+    id?: string;
+    name?: string;
+    shortName?: string;
+    description?: string;
+    startUrl?: string;
+    scope?: string;
+    lang?: string;
+    display?: "standalone" | "fullscreen" | "minimal-ui" | "browser";
+    orientation?: "any" | "natural" | "landscape" | "landscape-primary" | "landscape-secondary" | "portrait" | "portrait-primary" | "portrait-secondary";
+    themeColor?: string;
+    backgroundColor?: string;
+    icons?: Array<{
+        src: string;
+        sizes: string;
+        type?: string;
+        purpose?: string;
+    }>;
+    categories?: string[];
+    screenshots?: PwaScreenshot[];
+    shortcuts?: PwaShortcut[];
+    /** Disable service-worker registration while keeping the web manifest. */
+    serviceWorker?: boolean;
+    /** Navigation shown when both the network and requested page cache are unavailable. */
+    offlineUrl?: string;
+    /** Additional same-origin URLs precached during service-worker installation. */
+    cacheUrls?: string[];
+    /** Service-worker cache key. Change it to invalidate existing PWA caches. */
+    cacheName?: string;
+}
+interface AppConfig {
+    /** Raw HTML appended to every page's `<head>` (e.g. CDN stylesheet links). */
+    head?: string | string[];
+    /** Global SEO defaults merged with every page's exported `meta`. */
+    seo?: SeoConfig;
+    /** Framework security headers and optional CORS policy. */
+    security?: SecurityConfig;
+    styles?: StylesConfig;
+    /** Capacitor/native shell defaults and mobile-only page rendering. */
+    mobile?: MobileConfig;
+    /** Progressive Web App metadata. Enabled by default unless set to false. */
+    pwa?: PwaConfig | false;
+    /**
+     * Fonts. Declare Google Fonts (subsetted + preconnect + `font-display`) and/or
+     * self-hosted `@font-face` (with preload), and set `sans`/`mono`/`serif` family
+     * stacks. Google Fonts auto-extend the CSP so they load under the default policy.
+     */
+    fonts?: FontConfig;
+    /** Design-token themes (deep-merged over the built-in light/dark). */
+    theme?: ThemeConfig;
+    /** i18n: default language + supported locales (strings live in app/locales/*.json). */
+    i18n?: {
+        default?: string;
+        locales?: string[];
+    };
+    /** Default database connection (driver + url); reached with `getDb()`. */
+    db?: {
+        driver: "sqlite" | "postgres" | "mysql" | "mongo";
+        url: string;
+    };
+    /**
+     * File-upload storage. Declare named stores (local dir or S3-compatible),
+     * upload with `handleUpload`/`upload` from `@wrnexus/uploader`, and serve
+     * files back. Each store is `access: "public" | "private"`.
+     */
+    storage?: StorageConfig;
+    /**
+     * Additional named databases, reached with `getDb("<name>")`. Each has its own
+     * migrations/queries under `app/db/<name>/`. Connect to as many as you like and
+     * read/write to any of them per request.
+     *
+     *   databases: { analytics: { driver: "postgres", url: "…" } }
+     */
+    databases?: Record<string, {
+        driver: "sqlite" | "postgres" | "mysql" | "mongo";
+        url: string;
+    }>;
+    /**
+     * Realtime scaling. When `scale` is true (or `redisUrl` is set), room
+     * broadcasts are bridged over Redis pub/sub so they reach clients on **every**
+     * app process/instance — realtime that works with multiple running apps.
+     */
+    realtime?: {
+        scale?: boolean;
+        redisUrl?: string;
+    };
+    /** Default server port. */
+    port?: number;
+    /**
+     * Named config profiles (dev, prod, uat, test, …). When a profile is active
+     * its overrides are DEEP-MERGED over the base config. Select with
+     * `--profile=<name>` or the `WRNEXUS_PROFILE` env var.
+     */
+    profiles?: Record<string, Partial<Omit<AppConfig, "profiles">>>;
+}
+/**
+ * Resolve the active profile name: explicit argument > `WRNEXUS_PROFILE` env var
+ * > a mode-based default ("production" in prod, else "development").
+ */
+declare function resolveProfile(options?: {
+    explicit?: string;
+    mode?: Mode;
+}): string;
+/** Load the raw `wrnexus.config.*` (with the `profiles` map intact), or `{}`. */
+declare function loadRawConfig(appRoot: string): Promise<AppConfig>;
+/** Load `wrnexus.config.*`, applying the active profile's overrides. */
+declare function loadAppConfig(appRoot: string, profile?: string): Promise<AppConfig>;
+/**
+ * Load the `.env` cascade for a profile into `process.env`, WITHOUT clobbering
+ * variables already set in the real environment (which always win). Order, low
+ * → high precedence: `.env` < `.env.<profile>` < `.env.local` < `.env.<profile>.local`.
+ * Returns the variables it loaded.
+ */
+declare function loadEnv(appRoot: string, profile: string): Record<string, string>;
+/** Flatten a head config into a single HTML string. */
+declare function headToString(head?: string | string[]): string;
+
+/**
+ * Global stylesheet pipeline.
+ *
+ * Convention: `app/styles/global.css` is the entry. If it is absent but other
+ * `app/styles/*.css` files exist, they are aggregated into one entry. The entry
+ * is bundled by Bun's CSS bundler, which resolves `@import` — including from
+ * node_modules — so any npm CSS framework (Bootstrap, etc.) works by importing
+ * it. A custom `process` hook can replace the bundler for Tailwind/PostCSS/Sass.
+ */
+
+/**
+ * Resolve the CSS entry for an app.
+ *  - `override` (from config.styles.entry) is resolved relative to `appRoot`.
+ *  - otherwise prefer `app/styles/global.css`.
+ *  - otherwise aggregate all `app/styles/*.css` into a generated entry.
+ * Returns null when the app has no styles.
+ */
+declare function findStyleEntry(appDir: string, appRoot: string, override?: string): string | null;
+/**
+ * Bundle a CSS entry into a single stylesheet string using Bun's CSS bundler.
+ * Resolves `@import` (local and node_modules), handles nesting, minifies in prod.
+ */
+declare function bundleCss(entryPath: string, mode: Mode): Promise<string>;
+
+/**
+ * @wrnexus/styles — global stylesheet pipeline + app config.
+ *
+ * Works for SSR and CSR: the bundled stylesheet is `<link>`ed into every page's
+ * `<head>`, so it styles server-rendered markup and hydrated client islands
+ * alike. Use any CSS framework via `@import` in global.css (npm) or via a CDN
+ * link in `wrnexus.config.ts`'s `head` field.
+ */
+
+/**
+ * Produce the final CSS for an entry: run the config's custom processor if one
+ * is provided (Tailwind/PostCSS/Sass), otherwise use the built-in Bun bundler.
+ *
+ * If a custom processor throws (e.g. Tailwind can't resolve `tailwindcss`
+ * because deps aren't installed), we DON'T crash every request — we log a clear,
+ * actionable message and fall back to best-effort CSS so the app keeps serving.
+ */
+declare function renderStyles(ctx: StyleProcessContext, styles?: StylesConfig): Promise<string>;
+
+export { type AppConfig, DEFAULT_THEMES, type FontConfig, type FontDisplay, type GoogleFont, type LocalFontFace, type MobileConfig, type Mode, type PwaConfig, type ResolvedTheme, type StyleProcessContext, type StylesConfig, type Mode as StylesMode, THEME_COOKIE, THEME_CSS_HREF, THEME_JS_HREF, type ThemeConfig, type ThemeTokens, bundleCss, findStyleEntry, fontCspSources, headToString, loadAppConfig, loadEnv, loadRawConfig, renderFontHead, renderStyles, renderThemeCss, renderThemeRuntime, resolveProfile, resolveThemeConfig, resolveThemeName };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/styles

Example 2

interface StylesConfig {
+  /** CSS entry path relative to the app root. Default: app/styles/global.css */
+  entry?: string;
+  /** Custom processor — return the final CSS string (Tailwind/PostCSS/Sass). */
+  process?: (ctx: StyleProcessContext) => string | Promise<string>;
+}
+
+interface StyleProcessContext {
+  entryPath: string | null; // resolved absolute CSS entry, or null
+  appDir: string;
+  appRoot: string;
+  mode: Mode; // "development" | "production"
+}

Example 3

type ThemeTokens = Record<string, string>;
+
+interface ThemeConfig {
+  default?: string; // theme used when no cookie is present
+  themes?: Record<string, ThemeTokens>; // deep-merged over built-in light/dark
+}
+
+interface ResolvedTheme {
+  default: string;
+  names: string[];
+  themes: Record<string, ThemeTokens>;
+}

Example 4

import type { AppConfig } from "@wrnexus/styles";
+
+export default {
+  head: [
+    '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css">',
+  ],
+  port: 3000,
+  db: { driver: "sqlite", url: "app.db" },
+  theme: {
+    default: "dark",
+    themes: {
+      light: { "color-primary": "#7c3aed" }, // override one token; rest inherited
+      brand: {
+        // add a whole new theme
+        "color-scheme": "dark",
+        "color-bg": "#0a0a0a",
+        "color-primary": "#22d3ee",
+      },
+    },
+  },
+  styles: {
+    entry: "app/styles/main.css",
+  },
+  profiles: {
+    production: {
+      db: { driver: "postgres", url: process.env.DATABASE_URL! },
+    },
+  },
+} satisfies AppConfig;
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/test.wrn b/app/pages/packages/test.wrn new file mode 100644 index 00000000..8c1bcc3a --- /dev/null +++ b/app/pages/packages/test.wrn @@ -0,0 +1,176 @@ +page wrnexustest { + seo { + title = "@wrnexus/test" + description = "WRNexusJS-aware component, route, and browser testing utilities." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Tooling

@wrnexus/test

WRNexusJS-aware component, route, and browser testing utilities.

bun add @wrnexus/test@0.2.12
Testing utilities for WRNexusJS apps — component rendering, reactive-DOM mounting, route handler calls, and a full in-process app harness, plus a one-import re-export of bun:test.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/test is the server-side test toolkit you reach for when writing tests for a WRNexusJS app. It runs under bun test (invoked via wrnexus test) and gives you a single import surface: the bun:test primitives (test, expect, mock, …) re-exported alongside WRNexusJS-aware helpers that compile .wrn components, hydrate server HTML in a DOM, invoke API route handlers, and boot the real app on an ephemeral port for integration tests.

+

Installation

+
bun add @wrnexus/test
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

Re-exported test primitives

+

For one-import DX, the following are re-exported straight from bun:test:

+

test, expect, describe, it, beforeEach, afterEach, beforeAll, afterAll, mock, spyOn.

+

createContext is also re-exported from @wrnexus/core.

+

renderComponent(source, props?)

+
function renderComponent(source: string, props?: Record<string, unknown>): Promise<string>;
+

Compiles a .wrn component source string (via @wrnexus/compiler) and renders it to an HTML string with the given props. Throws if the compiled module has no render export.

+

mountHtml(html)

+
function mountHtml(html: string): {
+  document: Document;
+  window: unknown;
+  querySelector: (sel: string) => Element | null;
+  querySelectorAll: (sel: string) => Element[];
+};
+

Mounts server-rendered html in a happy-dom window with the reactive runtime hydrated, so you can test data-scope / data-text / data-for / data-show behaviour. Returns the window plus document and query helpers; assert on those.

+
happy-dom is loaded lazily (via require), so importing this package never
+
requires it unless you actually call mountHtml.
+

callRoute(handler, request)

+
function callRoute(
+  handler: (ctx: Context) => Response | Promise<Response>,
+  request: Request,
+): Promise<Response>;
+

Calls an API route handler with a Context built from a Request (using createContext). Returns the handler's Response.

+

createHarness(projectRoot, options?)

+
function createHarness(projectRoot: string, options?: HarnessOptions): Promise<Harness>;
+
+interface HarnessOptions {
+  /** Config/env profile. Default "test". */
+  profile?: string;
+}
+
+interface Harness {
+  /** Base URL of the ephemeral test server. */
+  url: string;
+  /** Fetch a path on the app (relative to `url`). */
+  fetch(path: string, init?: RequestInit): Promise<Response>;
+  /** The scanned router (pages/api/realtime/components). */
+  router: unknown;
+  /** Stop the server. */
+  close(): void;
+}
+

Boots the app at projectRoot on an ephemeral port (port: 0) for integration tests covering pages, API routes, middleware, and the full request pipeline. Loads env and app config for the given profile (default "test") so it picks up your test database/env. The server runs in development mode with HMR disabled. Remember to await app.close() when done.

+

Usage

+
import { test, expect, renderComponent, mountHtml, createHarness } from "@wrnexus/test";
+
+test("counter renders its label", async () => {
+  const html = await renderComponent(SRC, { start: 3, label: "Hits" });
+  expect(html).toContain("Hits");
+});
+
+test("reactive scope hydrates", () => {
+  const { querySelector } = mountHtml(serverHtml);
+  expect(querySelector("[data-text]")?.textContent).toBe("3");
+});
+
+test("home page responds", async () => {
+  const app = await createHarness("examples/basic-app");
+  const res = await app.fetch("/");
+  expect(res.status).toBe(200);
+  await app.close();
+});
+

Calling an API route handler directly:

+
import { test, expect, callRoute } from "@wrnexus/test";
+import { GET } from "../app/api/health.ts";
+
+test("health endpoint", async () => {
+  const res = await callRoute(GET, new Request("http://test/api/health"));
+  expect(res.status).toBe(200);
+});
+

Requirements / Notes

+
    +
  • Bun-only. Runs under bun test (via wrnexus test); uses Bun's module
  • +

    loading and the bun:test runtime.

    +
  • mountHtml requires happy-dom to be available in the workspace (loaded
  • +

    lazily; it's a dev dependency, not a runtime dependency of this package).

    +
  • Works with the rest of the WRNexusJS toolchain:
  • +

    [@wrnexus/compiler](../compiler) (compiles .wrn sources), [@wrnexus/core](../core) (Context / createContext), [@wrnexus/csr](../csr) (reactive runtime for mountHtml), [@wrnexus/dev-server](../dev-server) (startServer behind createHarness), and [@wrnexus/styles](../styles) (config/env/profile loading for the harness).

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Context } from '@wrnexus/core';
+export { createContext } from '@wrnexus/core';
+export { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, mock, spyOn, test } from 'bun:test';
+
+/**
+ * @wrnexus/test — testing utilities for WRNexusJS apps. Runs on `bun test` (via
+ * `wrnexus test`). Import everything from one place:
+ *
+ *   import { test, expect, renderComponent, mountHtml, createHarness } from "@wrnexus/test";
+ *
+ *   test("counter renders its label", async () => {
+ *     const html = await renderComponent(SRC, { start: 3, label: "Hits" });
+ *     expect(html).toContain("Hits");
+ *   });
+ *
+ *   test("home page responds", async () => {
+ *     const app = await createHarness("examples/basic-app");
+ *     const res = await app.fetch("/");
+ *     expect(res.status).toBe(200);
+ *     await app.close();
+ *   });
+ */
+
+/** Compile a `.wrn` component source + render it to HTML with the given props. */
+declare function renderComponent(source: string, props?: Record<string, unknown>): Promise<string>;
+/**
+ * Mount server-rendered HTML in a happy-dom window with the reactive runtime
+ * hydrated, so you can test `data-scope`/`data-text`/`data-for`/`data-show`
+ * behaviour. Returns the window; assert on `win.document`.
+ */
+declare function mountHtml(html: string): {
+    document: Document;
+    window: unknown;
+    querySelector: (sel: string) => Element | null;
+    querySelectorAll: (sel: string) => Element[];
+};
+/** Call an API route handler with a `Context` built from a Request. */
+declare function callRoute(handler: (ctx: Context) => Response | Promise<Response>, request: Request): Promise<Response>;
+interface Harness {
+    /** Base URL of the ephemeral test server. */
+    url: string;
+    /** Fetch a path on the app (relative to `url`). */
+    fetch(path: string, init?: RequestInit): Promise<Response>;
+    /** The scanned router (pages/api/realtime/components). */
+    router: unknown;
+    /** Stop the server. */
+    close(): void;
+}
+interface HarnessOptions {
+    /** Config/env profile. Default "test". */
+    profile?: string;
+}
+/**
+ * Boot the app on an ephemeral port for integration tests (pages, API routes,
+ * middleware, the full pipeline). Uses the "test" profile by default so it picks
+ * up your test database/env. Remember to `await app.close()`.
+ */
+declare function createHarness(projectRoot: string, options?: HarnessOptions): Promise<Harness>;
+
+export { type Harness, type HarnessOptions, callRoute, createHarness, mountHtml, renderComponent };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/test

Example 2

function renderComponent(source: string, props?: Record<string, unknown>): Promise<string>;

Example 3

function mountHtml(html: string): {
+  document: Document;
+  window: unknown;
+  querySelector: (sel: string) => Element | null;
+  querySelectorAll: (sel: string) => Element[];
+};

Example 4

function callRoute(
+  handler: (ctx: Context) => Response | Promise<Response>,
+  request: Request,
+): Promise<Response>;
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/tracking.wrn b/app/pages/packages/tracking.wrn new file mode 100644 index 00000000..4dbe5651 --- /dev/null +++ b/app/pages/packages/tracking.wrn @@ -0,0 +1,157 @@ +page wrnexustracking { + seo { + title = "@wrnexus/tracking" + description = "Error/event capture, middleware, filtering, and sinks." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Runtime

@wrnexus/tracking

Error/event capture, middleware, filtering, and sinks.

bun add @wrnexus/tracking@0.2.12
Error tracking for WRNexusJS apps: capture exceptions manually or via middleware and fan them out to pluggable sinks.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/tracking is a small, server-side error-capture layer. You create a tracker with one or more sinks, then feed it errors — either manually with tracker.capture(err, context) or automatically by mounting tracker.middleware() in your request pipeline. A consoleSink is included; forwarding to Sentry, Datadog, or any other backend is just a matter of writing a tiny sink. Reach for it when you want a single, sink-agnostic place to route application errors. Sinks run best-effort — a throwing sink never breaks the request.

+

Installation

+
bun add @wrnexus/tracking
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

createTracker(options?): Tracker

+

Creates a tracker. TrackerOptions:

+
+ +
OptionTypeDescription
sinksErrorSink[]Initial sinks to fan events out to. Defaults to [].
now() => numberClock used for event.timestamp (epoch ms). Defaults to Date.now.
beforeSend`(event: ErrorEvent) => ErrorEvent \null`Scrub/enrich an event before it reaches any sink. Return null to drop it.
+

The returned Tracker:

+
+ +
MemberSignatureDescription
capture(error: unknown, context?: Record<string, unknown>) => Promise<void>Normalizes any thrown value into an Error, builds an ErrorEvent, runs beforeSend, then dispatches to all sinks. Non-Error values are wrapped in an Error named NonError.
addSink(sink: ErrorSink) => voidRegisters an additional sink at runtime.
middleware() => MiddlewareReturns a WRNexusJS Middleware that captures any error thrown downstream, then re-throws it so the framework's error handler still produces the response.
+

The middleware attaches this context to captured events:

+
{ method: ctx.req.method, path: ctx.url.pathname, requestId: ctx.locals.requestId }
+

consoleSink: ErrorSink

+

A built-in sink that logs a compact one-line message via console.error, e.g. [error] TypeError: cannot read x {"userId":42}.

+

Types

+
interface ErrorEvent {
+  error: Error;
+  context: Record<string, unknown>; // request info, user id, tags…
+  timestamp: number; // epoch ms
+}
+
+interface ErrorSink {
+  name?: string;
+  capture(event: ErrorEvent): void | Promise<void>;
+}
+

Usage

+

Manual capture:

+
import { createTracker, consoleSink } from "@wrnexus/tracking";
+
+const tracker = createTracker({ sinks: [consoleSink] });
+
+try {
+  await doWork();
+} catch (err) {
+  await tracker.capture(err, { userId: 42, op: "doWork" });
+  throw err;
+}
+

As request middleware:

+
import { createTracker, consoleSink } from "@wrnexus/tracking";
+
+const tracker = createTracker({ sinks: [consoleSink] });
+
+app.use(tracker.middleware()); // captures + re-throws downstream errors
+

A custom sink with beforeSend scrubbing:

+
import { createTracker, type ErrorSink } from "@wrnexus/tracking";
+
+const sentrySink: ErrorSink = {
+  name: "sentry",
+  async capture(event) {
+    await Sentry.captureException(event.error, { extra: event.context });
+  },
+};
+
+const tracker = createTracker({
+  sinks: [sentrySink],
+  beforeSend(event) {
+    delete event.context.password; // scrub secrets
+    return event; // return null to drop the event entirely
+  },
+});
+
+tracker.addSink(anotherSink); // add more sinks later
+

Requirements / Notes

+
    +
  • Runs on Bun only (Node is not supported).
  • +
  • Peer package: [@wrnexus/core](../core) — the Context and Middleware types
  • +

    used by tracker.middleware() come from there.

    +
  • Sink dispatch is fire-and-forget-safe: all sinks run via Promise.all, and a
  • +

    sink that throws is swallowed so it can never break the app.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Middleware } from '@wrnexus/core';
+
+/**
+ * @wrnexus/tracking — error tracking with pluggable sinks. Capture exceptions
+ * manually or via middleware, and fan them out to any sink (console by default;
+ * write a small sink to forward to Sentry/Datadog/etc.).
+ *
+ *   const tracker = createTracker({ sinks: [consoleSink] });
+ *   app-middleware: tracker.middleware()   // captures + re-throws request errors
+ *   tracker.capture(err, { userId });      // manual
+ */
+
+interface ErrorEvent {
+    error: Error;
+    /** Arbitrary structured context (request info, user id, tags…). */
+    context: Record<string, unknown>;
+    /** Epoch ms. */
+    timestamp: number;
+}
+interface ErrorSink {
+    name?: string;
+    capture(event: ErrorEvent): void | Promise<void>;
+}
+interface Tracker {
+    capture(error: unknown, context?: Record<string, unknown>): Promise<void>;
+    addSink(sink: ErrorSink): void;
+    /** Middleware that captures errors thrown downstream, then re-throws them. */
+    middleware(): Middleware;
+}
+interface TrackerOptions {
+    sinks?: ErrorSink[];
+    now?: () => number;
+    /** Scrub/enrich an event before it hits sinks (return null to drop it). */
+    beforeSend?: (event: ErrorEvent) => ErrorEvent | null;
+}
+/** A sink that logs a compact one-line error to the console. */
+declare const consoleSink: ErrorSink;
+declare function createTracker(options?: TrackerOptions): Tracker;
+
+export { type ErrorEvent, type ErrorSink, type Tracker, type TrackerOptions, consoleSink, createTracker };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/tracking

Example 2

{ method: ctx.req.method, path: ctx.url.pathname, requestId: ctx.locals.requestId }

Example 3

interface ErrorEvent {
+  error: Error;
+  context: Record<string, unknown>; // request info, user id, tags…
+  timestamp: number; // epoch ms
+}
+
+interface ErrorSink {
+  name?: string;
+  capture(event: ErrorEvent): void | Promise<void>;
+}

Example 4

import { createTracker, consoleSink } from "@wrnexus/tracking";
+
+const tracker = createTracker({ sinks: [consoleSink] });
+
+try {
+  await doWork();
+} catch (err) {
+  await tracker.capture(err, { userId: 42, op: "doWork" });
+  throw err;
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/ui.wrn b/app/pages/packages/ui.wrn new file mode 100644 index 00000000..93341ebd --- /dev/null +++ b/app/pages/packages/ui.wrn @@ -0,0 +1,117 @@ +page wrnexusui { + seo { + title = "@wrnexus/ui" + description = "Themeable server-rendered UI components and CSS." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Frontend

@wrnexus/ui

Themeable server-rendered UI components and CSS.

bun add @wrnexus/ui@0.2.12
First-party Wire UI component library — a set of themeable .wrn components plus a single tokenized stylesheet.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

@wrnexus/ui ships a library of server-rendered .wrn components (layout, form controls, and feedback UI) together with one themeable stylesheet, ui.css. The components are auto-discovered by the framework router — you don't import them in code. Once the package's component directory is on the router's scan path, you mount any component in a page with data-component="<name>". Every visual is driven by var(--wire-*) theme tokens, so components restyle instantly when the theme changes. The tiny JS surface (src/index.ts) exists only so the toolchain (CLI build + dev server) can locate the component directory and stylesheet.

+

Installation

+
bun add @wrnexus/ui
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

In practice you rarely install this directly: @wrnexus/cli and @wrnexus/dev-server already depend on it and wire it into the router for you (see [Auto-discovery](#auto-discovery)).

+

Components

+

Components live as .wrn files under packages/ui/components/. The mount name is the lowercase file basename (e.g. button.wrndata-component="button"). Each accepts a class prop (appended to its root element) and most render their body from either a named prop or the default slot.

+

Layout

+
+ +
NamePurposeKey props
containerMax-width centered content wrapperclass
stackVertical column with gapgap (0–8)
hstackHorizontal row with gapgap (0–8)
gridCSS grid containersee source
dividerHorizontal ruleclass
spacerFlexible/empty spacing elementsee source
+

Core / feedback

+
+ +
NamePurposeKey props
buttonButtonlabel, variant (default\primary\danger\ghost), size (sm\md\lg), type
inputText inputsee source
textareaMulti-line inputsee source
checkboxCheckboxsee source
badgeSmall status badgelabel, variant
alertCallout boxvariant (info\success\danger\warning), title, message
cardPadded, bordered surfaceclass
avatarUser avatarsee source
spinnerLoading indicatorsee source
disclosureExpandable details/summarysee source
theme-toggleTheme switch button (binds data-wire-theme-toggle)label
+

Additional controls & data display

+

Also shipped: select, radio, switch, progress, tag, skeleton, tooltip, and table.

+

The authoritative, always-current list is uiComponentNames() (below), which reads the component directory at runtime.

+

API

+

The JS module (@wrnexus/ui) exposes four helpers used by the build tooling to locate the component assets. There is no component code to import — the components are .wrn files rendered server-side.

+
+ +
ExportSignatureReturns
uiComponentsDir() => stringAbsolute path to the .wrn component directory (feed to buildRouter's componentDirs).
uiCssPath() => stringAbsolute path to ui.css.
uiCss() => stringThe ui.css file contents (all .wire-* classes, themed via tokens).
uiComponentNames() => string[]Sorted list of built-in component names (e.g. for wrnexus eject listing).
+

./ui.css asset export

+

package.json also exposes the raw stylesheet as a subpath asset:

+
"exports": {
+  ".": "./src/index.ts",
+  "./ui.css": "./ui.css"
+}
+

The framework serves this stylesheet once at /__wrnexus/ui.css, so pages get all component styles from a single request.

+

Usage

+

Auto-discovery

+

The router scans extra componentDirs (in addition to the app's own app/components) and keys components by name. Library dirs are scanned first and app/components last, so an app component of the same name shadows the library's. The CLI build (@wrnexus/cli) and dev server (@wrnexus/dev-server) both wire the UI directory in for you:

+
import { buildRouter } from "@wrnexus/router";
+import { uiComponentsDir } from "@wrnexus/ui";
+
+const router = buildRouter(appDir, { componentDirs: [uiComponentsDir()] });
+

Mounting components in a page

+

Once discovered, mount any component by name via data-component. Quoted attributes (other than data-component) become string props:

+
<div data-component="card">
+  <div data-component="badge" label="New"></div>
+  <button data-component="button" label="Save" variant="primary" size="lg"></button>
+  <div data-component="alert" variant="success" title="Done" message="Saved."></div>
+</div>
+

Overrides

+

Ways to customize the components, in increasing order of power:

+

1. Theme tokens — override CSS custom properties such as --wire-color-primary, --wire-color-surface, --wire-radius-sm, etc. Every component style resolves through var(--wire-*), so changing a token restyles everything instantly (including across theme switches). 2. App CSS — redefine a .wire-* class in your own stylesheet, which is loaded after ui.css and therefore wins. 3. class prop — pass a class prop to a component; it is appended to the component's root element, letting you add per-instance classes without touching the base styles. 4. wrnexus eject <name> — copy the component's .wrn source into your app/components, where (because app components shadow library ones) you fully own and can edit it. Use uiComponentNames() for the list of ejectable names.

+

Requirements / Notes

+
    +
  • Bun-only — the package uses standard fs/path/url APIs but is published and
  • +

    consumed within the Bun-native WRNexusJS toolchain (Node is not supported).

    +
  • Peer packages: components are discovered and rendered by
  • +

    [@wrnexus/router](../router) (via componentDirs) and served by [@wrnexus/dev-server](../dev-server) / built by [@wrnexus/cli](../cli).

    +
  • Depends on [@wrnexus/core](../core) (dependencies).
  • +
  • theme-toggle relies on the framework's theme runtime, which binds the
  • +

    data-wire-theme-toggle attribute — no per-component JS is required.

    +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * @wrnexus/ui — the Wire UI component library.
+ *
+ * Components are `.wrn` files under `components/`, auto-discovered by the
+ * framework (the router scans this directory in addition to the app's own
+ * `app/components`). Mount them in any page with `data-component="<name>"`.
+ * Their styles live in a single themeable stylesheet, `ui.css`, served once at
+ * `/__wrnexus/ui.css` — every class uses `var(--wire-*)` theme tokens.
+ *
+ * Override, in increasing order of power:
+ *   1. theme tokens (change `--wire-color-primary`, etc.)
+ *   2. redefine a `.wire-*` class in your own CSS (loaded after ui.css)
+ *   3. pass a `class` prop (appended to the component root)
+ *   4. `wrnexus eject <name>` to copy the component into `app/components` and own it
+ */
+/** Absolute path to the directory of Wire UI component `.wrn` files. */
+declare function uiComponentsDir(): string;
+/** Absolute path to the Wire UI stylesheet. */
+declare function uiCssPath(): string;
+/** The Wire UI stylesheet contents (all `.wire-*` classes, themed via tokens). */
+declare function uiCss(): string;
+/** Names of the built-in components (e.g. for `wrnexus eject` listing). */
+declare function uiComponentNames(): string[];
+
+export { uiComponentNames, uiComponentsDir, uiCss, uiCssPath };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/ui

Example 2

"exports": {
+  ".": "./src/index.ts",
+  "./ui.css": "./ui.css"
+}

Example 3

import { buildRouter } from "@wrnexus/router";
+import { uiComponentsDir } from "@wrnexus/ui";
+
+const router = buildRouter(appDir, { componentDirs: [uiComponentsDir()] });

Example 4

<div data-component="card">
+  <div data-component="badge" label="New"></div>
+  <button data-component="button" label="Save" variant="primary" size="lg"></button>
+  <div data-component="alert" variant="success" title="Done" message="Saved."></div>
+</div>
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/uploader.wrn b/app/pages/packages/uploader.wrn new file mode 100644 index 00000000..59c518a8 --- /dev/null +++ b/app/pages/packages/uploader.wrn @@ -0,0 +1,419 @@ +page wrnexusuploader { + seo { + title = "@wrnexus/uploader" + description = "Validated local/S3 uploads and secure file serving." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Data

@wrnexus/uploader

Validated local/S3 uploads and secure file serving.

bun add @wrnexus/uploader@0.2.12

Config-driven file uploads + serving for WRNexusJS. Declare named storage stores (local disk or any S3-compatible backend) in wrnexus.config.ts, upload with one function call, drop a drag-and-drop widget on a page, and serve files back — public or private. Zero external dependencies (S3 is signed with a built-in AWS SigV4 implementation, like the rest of the framework).

+

Configure

+
// wrnexus.config.ts
+import type { AppConfig } from "@wrnexus/styles";
+
+const config: AppConfig = {
+  storage: {
+    default: "public",
+    stores: {
+      // Local disk, world-readable — served by the framework with a 1-year cache.
+      public: {
+        driver: "local",
+        dir: "uploads/public", // relative to the app root (dev) / cwd (prod)
+        access: "public",
+        maxBytes: 10_000_000,
+        accept: ["image/*", ".pdf"], // MIME, "type/*" wildcards, or ".ext"
+      },
+      // Private S3 (works with AWS, Cloudflare R2, Backblaze B2, MinIO, DO Spaces).
+      docs: {
+        driver: "s3",
+        access: "private",
+        bucket: "my-bucket",
+        region: "auto",
+        endpoint: "https://<acct>.r2.cloudflarestorage.com",
+        accessKeyId: process.env.S3_KEY!,
+        secretAccessKey: process.env.S3_SECRET!,
+      },
+    },
+  },
+};
+export default config;
+

Upload (server)

+
// app/api/upload.ts — one-liner
+import { handleUpload } from "@wrnexus/uploader";
+export const POST = handleUpload({ store: "public" });
+// → { ok: true, files: [{ key, url, name, type, size }] }
+
// or drive it yourself, anywhere you have the request
+import { upload, getStore } from "@wrnexus/uploader";
+const { files } = await upload("docs", ctx.req, { prefix: "invoices" });
+await getStore("docs").driver.delete(files[0].key);
+

Uploads are validated (size + type), stored under a random, collision-proof, path-safe key (the client filename is never used as a path), and — for public stores — returned with a servable url.

+

Widget (client)

+

Drop the element anywhere; the runtime (drag-and-drop, per-file progress, success/failed states) is auto-injected on pages that contain data-uploader:

+
<div
+  data-uploader="public"
+  data-endpoint="/api/upload"
+  data-accept="image/*"
+  data-max="10000000"
+  data-multiple
+></div>
+

Or via the first-party UI component:

+
<div
+  data-component="file-upload"
+  store="public"
+  endpoint="/api/upload"
+  accept="image/*"
+  multiple="true"
+></div>
+

It dispatches bubbling events you can listen for:

+
    +
  • wrnexus:uploaddetail: { file, result: { key, url, name, size, type } }
  • +
  • wrnexus:upload-errordetail: { file, error }
  • +
+

Serve files

+
    +
  • Public + local → served automatically at /__wrnexus/uploads/<store>/<key> (immutable cache).
  • +
  • Public + S3url is the bucket/CDN URL directly.
  • +
  • Private (any driver) → mount a route and gate it with your auth middleware:
  • +
+
// app/api/files/[key].ts
+import { serveFromStore } from "@wrnexus/uploader";
+export const GET = serveFromStore("docs"); // your middleware decides who gets in
+

API

+
+ +
ExportWhat
handleUpload(opts)POST route handler → JSON { ok, files }
upload(store, req, opts)Parse + validate + store; returns { files }
serveFromStore(store)Route handler that streams an object back (gate it for private)
getStore(name?) / hasStorage(name?)Reach a store's driver (put/get/delete/publicUrl)
configureStorage(config, root)Build the registry (the framework calls this at startup)
s3Driver / localDriver / signS3Lower-level building blocks
+

Notes

+
    +
  • Uploads count against the server's maxBodyBytes; per-file limits use each store's maxBytes.
  • +
  • SigV4 signing is implemented from scratch (no @aws-sdk); tested against local S3 semantics.
  • +

    Live AWS/R2 connectivity depends on your credentials + bucket policy.

    +
  • v1 buffers each file in memory up to its size cap (fine for images/docs up to tens of MB).
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

import { Context } from '@wrnexus/core';
+
+/**
+ * Storage driver contract + config types.
+ *
+ * A `StorageDriver` is the low-level object store (local disk, S3, …). It knows
+ * how to put/get/delete raw bytes under a key — nothing about HTTP, multipart
+ * parsing, validation, or URLs. The registry (`client.ts`) builds one driver per
+ * configured store and the upload layer (`upload.ts`) drives them. This mirrors
+ * `@wrnexus/db`'s driver/adapter split.
+ */
+/** Whether a store's objects are world-readable or served behind app auth. */
+type StoreAccess = "public" | "private";
+/** An object read back from a store. */
+interface StoredObject {
+    /** Object bytes as a web stream (preferred) or a buffer. */
+    body: ReadableStream<Uint8Array> | Uint8Array;
+    /** MIME type to serve with. */
+    contentType: string;
+    /** Size in bytes, when known. */
+    size?: number;
+}
+/** Metadata passed alongside the bytes on `put`. */
+interface PutMeta {
+    contentType: string;
+    /** Original client filename (informational only — NEVER used as a path). */
+    filename?: string;
+}
+/** The low-level object store. Implementations: `adapters/local.ts`, `adapters/s3.ts`. */
+interface StorageDriver {
+    /** Persist `data` under `key` (overwrites). */
+    put(key: string, data: Uint8Array, meta: PutMeta): Promise<void>;
+    /** Fetch an object, or `null` if it doesn't exist. */
+    get(key: string): Promise<StoredObject | null>;
+    /** Remove an object. No error if it's already gone. */
+    delete(key: string): Promise<void>;
+    /**
+     * A directly-servable absolute URL for a PUBLIC object (e.g. an S3/CDN URL), or
+     * `null` when the framework should serve it (local public stores). Private
+     * stores always return `null`.
+     */
+    publicUrl(key: string): string | null;
+}
+/** Local-disk store. `dir` is resolved against the app root when relative. */
+interface LocalStoreConfig {
+    driver: "local";
+    access: StoreAccess;
+    /** Directory the files live under (e.g. "uploads/public"). */
+    dir: string;
+    /** Reject files larger than this many bytes (per file). */
+    maxBytes?: number;
+    /** Allowed types: MIME (`"image/*"`, `"application/pdf"`) and/or extensions (`".pdf"`). */
+    accept?: string[];
+}
+/** S3 / S3-compatible store (AWS, Cloudflare R2, Backblaze B2, MinIO, DO Spaces). */
+interface S3StoreConfig {
+    driver: "s3";
+    access: StoreAccess;
+    bucket: string;
+    region: string;
+    accessKeyId: string;
+    secretAccessKey: string;
+    /**
+     * Custom endpoint for non-AWS services, e.g.
+     * `https://<acct>.r2.cloudflarestorage.com`. Omit for AWS S3.
+     */
+    endpoint?: string;
+    /** Force path-style URLs (`/bucket/key`). Defaults on for custom endpoints. */
+    forcePathStyle?: boolean;
+    /** Public base URL for `publicUrl()` (a CDN or public bucket domain). */
+    publicBaseUrl?: string;
+    maxBytes?: number;
+    accept?: string[];
+}
+type StoreConfig = LocalStoreConfig | S3StoreConfig;
+/** The `storage` block in `wrnexus.config.ts`. */
+interface StorageConfig {
+    /** Name of the store used when a call omits one. Defaults to the first store. */
+    default?: string;
+    /** Named stores, reached with `getStore("<name>")` / `upload("<name>", …)`. */
+    stores: Record<string, StoreConfig>;
+}
+
+/**
+ * Process-wide store registry, configured once at server startup from the
+ * `storage` block in `wrnexus.config.ts` (mirrors `@wrnexus/db`'s registry).
+ * Handlers then call `getStore("<name>")` — or omit the name for the default.
+ */
+
+interface Store {
+    name: string;
+    access: StoreAccess;
+    driver: StorageDriver;
+    config: StoreConfig;
+}
+/** Build a driver per configured store. Safe to call again (fully replaces). */
+declare function configureStorage(config: StorageConfig | undefined, appRoot: string): void;
+/** Whether the default (or a named) store is configured. */
+declare function hasStorage(name?: string): boolean;
+/** The default store, or a named one. Throws if it isn't configured. */
+declare function getStore(name?: string): Store;
+/** Names of all configured stores. */
+declare function storeNames(): string[];
+
+/**
+ * The HTTP-facing upload + serve layer: parse multipart requests, validate,
+ * store, and serve files back. Built on the store registry (`client.ts`).
+ */
+
+/** Reserved prefix the framework serves PUBLIC local objects from. */
+declare const UPLOADS_PREFIX = "/__wrnexus/uploads/";
+interface UploadedFile {
+    /** Storage key — pass to `getStore().driver.get/delete` or a serve route. */
+    key: string;
+    /** A servable URL for public objects, or `null` for private stores. */
+    url: string | null;
+    /** Original (sanitized) client filename, for display. */
+    name: string;
+    type: string;
+    size: number;
+}
+interface UploadOptions {
+    /** Only read files from this form field (default: every file field). */
+    field?: string;
+    /** Override the store's `maxBytes`. */
+    maxBytes?: number;
+    /** Override the store's `accept` list. */
+    accept?: string[];
+    /** Key prefix, e.g. `"avatars"` → keys become `avatars/<yyyy>/<mm>/<rand>.<ext>`. */
+    prefix?: string;
+}
+/** A 4xx-carrying error so `handleUpload` can map it to a status. */
+declare class UploadError extends Error {
+    readonly status: number;
+    constructor(message: string, status?: number);
+}
+/** The servable URL for a stored object (public → URL, private → null). */
+declare function storedUrl(store: Store, key: string): string | null;
+/**
+ * Read multipart file(s) from a request and store them. Throws `UploadError`
+ * (4xx) on validation failures. Call it directly, or use `handleUpload`.
+ */
+declare function upload(storeName: string | undefined, req: Request, opts?: UploadOptions): Promise<{
+    files: UploadedFile[];
+}>;
+/**
+ * Ready-made POST handler:
+ *
+ *   // app/api/upload.ts
+ *   export const POST = handleUpload({ store: "public" });
+ *
+ * Returns `{ ok:true, files:[…] }` on success, or `{ ok:false, error }` with a
+ * 4xx/5xx status.
+ */
+declare function handleUpload(opts?: UploadOptions & {
+    store?: string;
+}): (ctx: Context) => Promise<Response>;
+/**
+ * Serve an object from a store as a route handler — mount it behind your auth
+ * middleware to gate PRIVATE files:
+ *
+ *   // app/api/files/[key].ts
+ *   export const GET = serveFromStore("docs");
+ *
+ * Reads the key from `ctx.params.key` (or `ctx.params.path`); it may contain `/`.
+ */
+declare function serveFromStore(storeName?: string, opts?: {
+    param?: string;
+}): (ctx: Context) => Promise<Response>;
+/**
+ * Framework asset hook: serve PUBLIC local objects at
+ * `/__wrnexus/uploads/<store>/<key>`. Returns `null` for anything it doesn't
+ * own (unknown/private/S3-backed store) so the caller falls through. Wired into
+ * the dev + prod asset servers.
+ */
+declare function serveStoredFile(pathname: string): Promise<Response | null>;
+
+/**
+ * Client runtime for `<div data-uploader>` elements — drag-and-drop + file
+ * input, per-file progress bars, and success/failed states. Injected by
+ * `collectScripts` only on pages that contain `data-uploader` (same mechanism as
+ * `validate.js`). Self-contained: it injects its own themed stylesheet (using
+ * `--wire-*` tokens) and posts each file via XHR so upload progress is live.
+ *
+ * Markup it enhances (also a valid no-JS `<form>` fallback if you wrap it):
+ *   <div data-uploader="public" data-endpoint="/api/upload"
+ *        data-accept="image/*" data-max="10000000" data-multiple></div>
+ *
+ * Events dispatched on the element (bubble):
+ *   wrnexus:upload        detail: { file, result: { key, url, name, size, type } }
+ *   wrnexus:upload-error  detail: { file, error }
+ *
+ * NOTE: written with single/double quotes + string concatenation only — no
+ * backticks and no ${...}, so it embeds safely in the exported template string.
+ */
+declare const UPLOAD_JS_HREF = "/__wrnexus/uploader.js";
+declare const UPLOAD_RUNTIME = "\n(function () {\n  if (typeof document === \"undefined\") return;\n  var CSRF_COOKIE = \"wire-csrf\";\n\n  var CSS =\n    \".wire-uploader{display:block}\" +\n    \".wire-uploader-zone{display:flex;align-items:center;justify-content:center;text-align:center;\" +\n      \"min-height:8rem;padding:1.25rem;border:2px dashed var(--wire-border,#cbd5e1);border-radius:12px;\" +\n      \"background:var(--wire-surface,transparent);color:var(--wire-muted,#64748b);cursor:pointer;\" +\n      \"transition:border-color .15s ease,background-color .15s ease;position:relative}\" +\n    \".wire-uploader-zone:hover,.wire-uploader-zone:focus-visible{border-color:var(--wire-brand,#3f7dff);outline:none}\" +\n    \".wire-uploader-zone.is-drag{border-color:var(--wire-brand,#3f7dff);background:color-mix(in oklab,var(--wire-brand,#3f7dff) 8%,transparent)}\" +\n    \".wire-uploader-prompt{font-size:.9rem;pointer-events:none}\" +\n    \".wire-uploader-input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}\" +\n    \".wire-uploader-list{list-style:none;margin:.75rem 0 0;padding:0;display:flex;flex-direction:column;gap:.5rem}\" +\n    \".wire-uploader-item{display:grid;grid-template-columns:1fr auto;gap:.15rem .75rem;align-items:center;\" +\n      \"font-size:.82rem;padding:.5rem .7rem;border:1px solid var(--wire-border,#e2e8f0);border-radius:8px}\" +\n    \".wire-uploader-name{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--wire-text,#0f172a)}\" +\n    \".wire-uploader-meta{color:var(--wire-muted,#94a3b8);font-variant-numeric:tabular-nums}\" +\n    \".wire-uploader-bar{grid-column:1/-1;height:5px;border-radius:999px;background:var(--wire-border,#e2e8f0);overflow:hidden}\" +\n    \".wire-uploader-fill{height:100%;width:0;border-radius:999px;background:var(--wire-brand,#3f7dff);transition:width .15s ease}\" +\n    \".wire-uploader-status{grid-column:1/-1;font-size:.75rem;color:var(--wire-muted,#94a3b8);font-variant-numeric:tabular-nums}\" +\n    \".wire-uploader-item.is-done .wire-uploader-fill{background:var(--wire-success,#16a34a)}\" +\n    \".wire-uploader-item.is-done .wire-uploader-status{color:var(--wire-success,#16a34a)}\" +\n    \".wire-uploader-item.is-error .wire-uploader-fill{background:var(--wire-danger,#dc2626)}\" +\n    \".wire-uploader-item.is-error .wire-uploader-status{color:var(--wire-danger,#dc2626)}\";\n\n  function injectCss() {\n    if (document.getElementById(\"wire-uploader-css\")) return;\n    var s = document.createElement(\"style\");\n    s.id = \"wire-uploader-css\";\n    s.textContent = CSS;\n    document.head.appendChild(s);\n  }\n\n  function cookie(name) {\n    var m = document.cookie.match(new RegExp(\"(?:^|; )\" + name + \"=([^;]*)\"));\n    return m ? decodeURIComponent(m[1]) : \"\";\n  }\n  function el(tag, cls, text) {\n    var e = document.createElement(tag);\n    if (cls) e.className = cls;\n    if (text != null) e.textContent = text;\n    return e;\n  }\n  function fmt(n) {\n    if (n < 1024) return n + \" B\";\n    if (n < 1048576) return (n / 1024).toFixed(1) + \" KB\";\n    return (n / 1048576).toFixed(1) + \" MB\";\n  }\n  function accepts(accept, file) {\n    var list = (accept || \"\").split(\",\").map(function (s) { return s.trim().toLowerCase(); }).filter(Boolean);\n    if (!list.length) return true;\n    var type = (file.type || \"\").toLowerCase();\n    var name = (file.name || \"\").toLowerCase();\n    var ext = name.indexOf(\".\") >= 0 ? name.slice(name.lastIndexOf(\".\")) : \"\";\n    return list.some(function (rule) {\n      if (rule.charAt(0) === \".\") return rule === ext;\n      if (rule.slice(-2) === \"/*\") return type.indexOf(rule.slice(0, -1)) === 0;\n      return rule === type;\n    });\n  }\n\n  function setup(root) {\n    if (root.__wrnexusUploader) return;\n    root.__wrnexusUploader = true;\n\n    var endpoint = root.getAttribute(\"data-endpoint\") || \"/api/upload\";\n    var multipleAttr = root.getAttribute(\"data-multiple\");\n    var multiple = root.hasAttribute(\"data-multiple\") && multipleAttr !== \"false\";\n    var accept = root.getAttribute(\"data-accept\") || \"\";\n    var maxBytes = parseInt(root.getAttribute(\"data-max\") || \"0\", 10) || 0;\n    var field = root.getAttribute(\"data-field\") || (multiple ? \"files\" : \"file\");\n    var promptText = root.getAttribute(\"data-label\") || \"Drag files here or click to browse\";\n\n    root.classList.add(\"wire-uploader\");\n    var zone = el(\"div\", \"wire-uploader-zone\");\n    zone.setAttribute(\"role\", \"button\");\n    zone.setAttribute(\"tabindex\", \"0\");\n    zone.appendChild(el(\"div\", \"wire-uploader-prompt\", promptText));\n    var input = document.createElement(\"input\");\n    input.type = \"file\";\n    input.className = \"wire-uploader-input\";\n    if (multiple) input.multiple = true;\n    if (accept) input.accept = accept;\n    zone.appendChild(input);\n    var listEl = el(\"ul\", \"wire-uploader-list\");\n    root.appendChild(zone);\n    root.appendChild(listEl);\n\n    zone.addEventListener(\"keydown\", function (e) {\n      if (e.key === \"Enter\" || e.key === \" \") { e.preventDefault(); input.click(); }\n    });\n    [\"dragenter\", \"dragover\"].forEach(function (ev) {\n      zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.add(\"is-drag\"); });\n    });\n    [\"dragleave\", \"drop\"].forEach(function (ev) {\n      zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.remove(\"is-drag\"); });\n    });\n    zone.addEventListener(\"drop\", function (e) {\n      if (e.dataTransfer && e.dataTransfer.files) handle(e.dataTransfer.files);\n    });\n    input.addEventListener(\"change\", function () {\n      if (input.files) handle(input.files);\n      input.value = \"\";\n    });\n\n    function handle(files) {\n      var arr = Array.prototype.slice.call(files);\n      if (!multiple) arr = arr.slice(0, 1);\n      arr.forEach(uploadOne);\n    }\n\n    function row(file) {\n      var li = el(\"li\", \"wire-uploader-item\");\n      li.appendChild(el(\"span\", \"wire-uploader-name\", file.name));\n      li.appendChild(el(\"span\", \"wire-uploader-meta\", fmt(file.size)));\n      var bar = el(\"div\", \"wire-uploader-bar\");\n      var fill = el(\"div\", \"wire-uploader-fill\");\n      bar.appendChild(fill);\n      li.appendChild(bar);\n      var status = el(\"span\", \"wire-uploader-status\", \"\");\n      li.appendChild(status);\n      listEl.appendChild(li);\n      return { li: li, fill: fill, status: status };\n    }\n\n    function uploadOne(file) {\n      var ui = row(file);\n      if (maxBytes && file.size > maxBytes) return fail(ui, \"Too large (max \" + fmt(maxBytes) + \")\", file);\n      if (!accepts(accept, file)) return fail(ui, \"Type not allowed\", file);\n\n      var fd = new FormData();\n      fd.append(field, file, file.name);\n      var xhr = new XMLHttpRequest();\n      xhr.open(\"POST\", endpoint, true);\n      var token = cookie(CSRF_COOKIE);\n      if (token) xhr.setRequestHeader(\"x-csrf-token\", token);\n      xhr.upload.addEventListener(\"progress\", function (e) {\n        if (e.lengthComputable) {\n          var pct = Math.round((e.loaded / e.total) * 100);\n          ui.fill.style.width = pct + \"%\";\n          ui.status.textContent = pct + \"%\";\n        }\n      });\n      xhr.addEventListener(\"load\", function () {\n        var data = null;\n        try { data = JSON.parse(xhr.responseText); } catch (e2) {}\n        if (xhr.status >= 200 && xhr.status < 300 && data && data.ok) {\n          done(ui, (data.files && data.files[0]) || null, file);\n        } else {\n          fail(ui, (data && data.error) || (\"Upload failed (\" + xhr.status + \")\"), file);\n        }\n      });\n      xhr.addEventListener(\"error\", function () { fail(ui, \"Network error\", file); });\n      xhr.send(fd);\n    }\n\n    function done(ui, info, file) {\n      ui.li.classList.remove(\"is-error\");\n      ui.li.classList.add(\"is-done\");\n      ui.fill.style.width = \"100%\";\n      ui.status.textContent = \"\\u2713 Uploaded\";\n      root.dispatchEvent(new CustomEvent(\"wrnexus:upload\", { bubbles: true, detail: { file: file, result: info } }));\n    }\n    function fail(ui, msg, file) {\n      ui.li.classList.add(\"is-error\");\n      ui.status.textContent = \"\\u2717 \" + msg;\n      root.dispatchEvent(new CustomEvent(\"wrnexus:upload-error\", { bubbles: true, detail: { file: file, error: msg } }));\n    }\n  }\n\n  function init() {\n    injectCss();\n    var nodes = document.querySelectorAll(\"[data-uploader]\");\n    for (var i = 0; i < nodes.length; i++) setup(nodes[i]);\n  }\n  if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", init);\n  else init();\n})();\n";
+
+/**
+ * Local-disk storage driver. Files live under a configured directory; keys map
+ * to relative paths inside it. Path traversal is rejected — a key can never
+ * escape the base dir.
+ */
+
+declare function localDriver(config: LocalStoreConfig, appRoot: string): StorageDriver;
+
+/**
+ * S3 (and S3-compatible) storage driver — zero deps, SigV4-signed `fetch`.
+ * Works with AWS S3, Cloudflare R2, Backblaze B2, MinIO, DigitalOcean Spaces.
+ *
+ * Path-style vs virtual-hosted: AWS defaults to virtual-hosted
+ * (`bucket.s3.region.amazonaws.com`); custom endpoints (R2/MinIO) default to
+ * path-style (`endpoint/bucket/key`). Override with `forcePathStyle`.
+ */
+
+declare function s3Driver(config: S3StoreConfig): StorageDriver;
+
+/**
+ * AWS Signature Version 4 for S3 requests — zero external deps, built on
+ * `node:crypto` + `fetch`. Matches the framework's zero-dep ethos (like
+ * `@wrnexus/ai`) and works with any S3-compatible service (AWS, Cloudflare R2,
+ * Backblaze B2, MinIO, DigitalOcean Spaces).
+ *
+ * Reference: docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
+ */
+/** Hex-encoded SHA-256 of a payload. */
+declare function sha256Hex(data: Uint8Array | string): string;
+/**
+ * Percent-encode an S3 object key for the request path. Every character except
+ * the RFC 3986 unreserved set is encoded; `/` between segments is preserved.
+ */
+declare function encodeKey(key: string): string;
+interface SignInput {
+    method: string;
+    host: string;
+    /** Canonical URI — already `%`-encoded, begins with `/`. */
+    path: string;
+    region: string;
+    accessKeyId: string;
+    secretAccessKey: string;
+    /** Hex SHA-256 of the body, or `"UNSIGNED-PAYLOAD"`. */
+    payloadHash: string;
+    /** Extra headers to sign (e.g. `content-type`). `host`/`x-amz-*` are added here. */
+    headers?: Record<string, string>;
+    date: Date;
+    service?: string;
+}
+/**
+ * Compute the signed header set for an S3 request. Returns the headers to send
+ * (lowercased names, including `authorization`, `host`, `x-amz-date`,
+ * `x-amz-content-sha256`).
+ */
+declare function signS3(input: SignInput): Record<string, string>;
+
+/**
+ * Minimal extension ↔ MIME mapping + `accept` matching. Zero-dep: just a table
+ * big enough for the common upload types (images, docs, media, archives).
+ */
+/** Lowercased extension WITHOUT the dot (e.g. "png"), or "" if none. */
+declare function extOf(name: string): string;
+/** MIME type for a filename/key by its extension, or a safe default. */
+declare function contentTypeOf(name: string, fallback?: string): string;
+/** The conventional extension for a MIME type, or "" (used to name S3 keys). */
+declare function extForType(type: string): string;
+/**
+ * Does `file` (its MIME `type` + `name`) satisfy an `accept` list? Each accept
+ * entry is a MIME type (`"image/png"`), a wildcard MIME (`"image/*"`), or a
+ * dotted extension (`".pdf"`). An empty/omitted list accepts everything.
+ */
+declare function accepts(accept: string[] | undefined, file: {
+    type: string;
+    name: string;
+}): boolean;
+
+export { type LocalStoreConfig, type PutMeta, type S3StoreConfig, type StorageConfig, type StorageDriver, type Store, type StoreAccess, type StoreConfig, type StoredObject, UPLOADS_PREFIX, UPLOAD_JS_HREF, UPLOAD_RUNTIME, UploadError, type UploadOptions, type UploadedFile, accepts, configureStorage, contentTypeOf, encodeKey, extForType, extOf, getStore, handleUpload, hasStorage, localDriver, s3Driver, serveFromStore, serveStoredFile, sha256Hex, signS3, storeNames, storedUrl, upload };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

// wrnexus.config.ts
+import type { AppConfig } from "@wrnexus/styles";
+
+const config: AppConfig = {
+  storage: {
+    default: "public",
+    stores: {
+      // Local disk, world-readable — served by the framework with a 1-year cache.
+      public: {
+        driver: "local",
+        dir: "uploads/public", // relative to the app root (dev) / cwd (prod)
+        access: "public",
+        maxBytes: 10_000_000,
+        accept: ["image/*", ".pdf"], // MIME, "type/*" wildcards, or ".ext"
+      },
+      // Private S3 (works with AWS, Cloudflare R2, Backblaze B2, MinIO, DO Spaces).
+      docs: {
+        driver: "s3",
+        access: "private",
+        bucket: "my-bucket",
+        region: "auto",
+        endpoint: "https://<acct>.r2.cloudflarestorage.com",
+        accessKeyId: process.env.S3_KEY!,
+        secretAccessKey: process.env.S3_SECRET!,
+      },
+    },
+  },
+};
+export default config;

Example 2

// app/api/upload.ts — one-liner
+import { handleUpload } from "@wrnexus/uploader";
+export const POST = handleUpload({ store: "public" });
+// → { ok: true, files: [{ key, url, name, type, size }] }

Example 3

// or drive it yourself, anywhere you have the request
+import { upload, getStore } from "@wrnexus/uploader";
+const { files } = await upload("docs", ctx.req, { prefix: "invoices" });
+await getStore("docs").driver.delete(files[0].key);

Example 4

<div
+  data-uploader="public"
+  data-endpoint="/api/upload"
+  data-accept="image/*"
+  data-max="10000000"
+  data-multiple
+></div>
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/pages/packages/validation.wrn b/app/pages/packages/validation.wrn new file mode 100644 index 00000000..5454f7b7 --- /dev/null +++ b/app/pages/packages/validation.wrn @@ -0,0 +1,316 @@ +page wrnexusvalidation { + seo { + title = "@wrnexus/validation" + description = "Typed schemas, coercion, validation, and browser descriptors." + } + + view { +
+
+ W WRNexusJS + + +
+
+ +
Security

@wrnexus/validation

Typed schemas, coercion, validation, and browser descriptors.

bun add @wrnexus/validation@0.2.12
One fluent schema, validated on the server (API bodies, env vars) and mirrored to an eval-free browser validator for forms.
+

Part of the WRNexusJS framework — an SSR-first, Bun-native full-stack web framework.

+

Overview

+

Define a schema once with the fluent v builder, then reuse it in three places: .parse() runs server-side and returns coerced values plus per-field errors; .describe() emits a plain-JSON SchemaDescriptor that the browser runtime interprets (no eval, no bundled validator); and helpers like parseBody and parseEnv wire schemas straight into API routes and startup config. The server rule logic (applyRule/checkField) and the client runtime (VALIDATE_RUNTIME) mirror each other exactly, so a form validates identically in both places. Schemas are conventionally kept in app/schemas/.

+

Installation

+
bun add @wrnexus/validation
+
Private package — the machine must be authenticated to the wrnexus npm org
+
(a read token in ~/.npmrc). Requires Bun (Node is not supported).
+

API

+

The v builder

+
import { v } from "@wrnexus/validation";
+
+ +
FactoryReturnsField methods
v.string()StringSchemaemail(), url(), uuid(), date(), length(n), oneOf(string[]), pattern(re), trim(), min(n), max(n)
v.number()NumberSchemainteger(), positive(), oneOf(number[]), min(n), max(n)
v.boolean()BooleanSchema(base methods only)
v.object(fields)ObjectSchemaparse(input), describe()
+

Every field schema is chainable and shares these base methods:

+
    +
  • min(n, message?) / max(n, message?) — for strings, bounds the length; for numbers, bounds the value.
  • +
  • optional() — an empty/missing value passes instead of erroring "Required".
  • +
  • label(text) — human label carried into the descriptor.
  • +
  • default(value) — value substituted when the field is absent (implies optional).
  • +
  • refine(fn, message?)server-only predicate. fn returns true (ok), false (use message), or a string (that error). Not serialized to the client.
  • +
+

Each string rule accepts an optional trailing message to override the default error text.

+

ObjectSchema

+
schema.parse(input: unknown): ParseResult
+schema.describe(): SchemaDescriptor
+

parse coerces each field (strings stay strings, v.number() runs Number(), v.boolean() treats true / "true" / "on" as true), applies its rules and refinements, fills in default() values, and returns:

+
interface ParseResult<T = Record<string, unknown>> {
+  ok: boolean; // true when errors is empty
+  value: T; // coerced values (present pass or fail)
+  errors: Record<string, string>; // field name → first failing message
+}
+

describe() returns the JSON bridge for the client:

+
interface SchemaDescriptor {
+  type: "object";
+  fields: Record<string, FieldDescriptor>;
+}
+interface FieldDescriptor {
+  type: "string" | "number" | "boolean";
+  optional?: boolean;
+  label?: string;
+  trim?: boolean; // strings only
+  rules: RuleDescriptor[];
+}
+

Rules and coercion

+

RuleDescriptor is a discriminated union of the serializable rules — min, max, length, email, url, uuid, date, oneOf, pattern, integer. Two exported functions apply them and are shared by the server (the client runtime reimplements the same logic):

+
    +
  • applyRule(type, rule, value): string | null — validate one already-coerced value against one rule.
  • +
  • checkField(desc, raw): { value, error } — coerce and validate one field. Empty input (undefined/null/"") is "Required" unless optional. Strings with trim are trimmed first. Numbers that fail Number() yield "Must be a number".
  • +
+

Notes on specific rules: email/url/uuid test built-in regexes; date uses Date.parse; pattern reconstructs a RegExp from its source/flags and passes silently if the pattern is invalid; integer requires Number.isInteger; positive() is implemented as min(Number.MIN_VALUE).

+

API helpers

+
invalid(errors: Record<string, string>): Response   // ready 400 { ok:false, errors }
+
+parseBody<T>(schema, req):
+  Promise<{ ok: true; value: T } | { ok: false; response: Response }>
+

parseBody reads the request body from JSON, application/x-www-form-urlencoded, or multipart/form-data, validates it, and on failure hands back a ready 400 Response.

+

Environment config

+
parseEnv<T>(schema: ObjectSchema, source?): T
+

Validates env vars (from Bun.env, falling back to process.env) against a schema and coerces them (PORT → number, DEBUG → boolean). On any problem it throws one error listing every offending variable, so misconfiguration fails fast at startup.

+

Client runtime (from runtime.ts)

+
renderSchemasScript(descriptors: Record<string, SchemaDescriptor>): string
+VALIDATE_RUNTIME: string
+
    +
  • renderSchemasScript produces window.__wireSchemas = { name: descriptor, … }; to inline in the page.
  • +
  • VALIDATE_RUNTIME is a self-contained, eval-free IIFE string. Injected as a <script>, it binds every form[data-schema] and validates on submit and blur, writing messages into [data-error="<field>"] elements and toggling aria-invalid / .wire-invalid. On a valid submit it fetches the form action as JSON (attaching the wire-csrf cookie as an x-csrf-token header), then follows data-redirect / a redirect in the response, surfaces server-side field errors, and fires wire:success / wire:error events. It exposes window.__wireValidate.init(root) and self-initializes on DOMContentLoaded.
  • +
+

Usage

+

Define a schema and validate an API body:

+
import { v, parseBody } from "@wrnexus/validation";
+
+export const signupSchema = v.object({
+  email: v.string().trim().email(),
+  password: v.string().min(8).max(200),
+  age: v.number().integer().min(13).max(120).optional(),
+  role: v.string().oneOf(["user", "admin"]).default("user"),
+  agree: v.boolean(),
+});
+
+// inside a route handler
+const result = await parseBody(signupSchema, req);
+if (!result.ok) return result.response; // ready 400 with field errors
+const { email, password, role } = result.value;
+

Server-only refinement:

+
const schema = v.object({
+  username: v
+    .string()
+    .min(3)
+    .refine((name) => !RESERVED.has(String(name)), "That name is taken"),
+});
+

Validate environment at startup:

+
import { v, parseEnv } from "@wrnexus/validation";
+
+export const env = parseEnv(
+  v.object({
+    DATABASE_URL: v.string().min(1),
+    PORT: v.number().integer().default(3000),
+    DEBUG: v.boolean().optional(),
+  }),
+);
+// throws one readable error listing every bad variable if misconfigured
+

Wire the same schema into the browser:

+
import { renderSchemasScript, VALIDATE_RUNTIME } from "@wrnexus/validation";
+import { signupSchema } from "./app/schemas/signup.ts";
+
+const head = `<script>${renderSchemasScript({ signup: signupSchema.describe() })}</script>
+<script>${VALIDATE_RUNTIME}</script>`;
+// render a <form data-schema="signup"> with [data-error="email"] etc.
+

Requirements / Notes

+
    +
  • Bun-only. parseEnv reads Bun.env (falling back to process.env); parseBody and invalid use the Web Request/Response APIs that back Bun.serve.
  • +
  • Refinements (refine) run only server-side and are never serialized — client and server agree on every other rule because both interpret the same RuleDescriptor list.
  • +
  • No runtime dependencies. Ships as TypeScript source (src/index.ts) executed directly by Bun.
  • +
  • Pairs with the WRNexusJS server (@wrnexus/core) for route handlers and the SSR layer that injects renderSchemasScript / VALIDATE_RUNTIME.
  • +

Complete TypeScript API

This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

/**
+ * Client-side validation. `renderSchemasScript` bakes the discovered schema
+ * descriptors into `window.__wireSchemas`; `VALIDATE_RUNTIME` is a generic,
+ * eval-free validator that reads them and validates every `form[data-schema]`
+ * on submit and blur, writing messages into `[data-error="<field>"]` elements.
+ * The rule logic mirrors `checkField`/`applyRule` in index.ts.
+ */
+
+/** `window.__wireSchemas = { name: descriptor, ... }` for the client validator. */
+declare function renderSchemasScript(descriptors: Record<string, SchemaDescriptor>): string;
+declare const VALIDATE_RUNTIME: string;
+
+/**
+ * @wrnexus/validation — one schema, validated on the server (API) and the browser
+ * (forms). A schema is a fluent builder; `.parse()` runs server-side and returns
+ * coerced values + field errors, while `.describe()` emits a JSON descriptor the
+ * eval-free client validator interprets. Define schemas once in `app/schemas/`.
+ */
+type RuleDescriptor = {
+    kind: "min";
+    n: number;
+    message?: string;
+} | {
+    kind: "max";
+    n: number;
+    message?: string;
+} | {
+    kind: "length";
+    n: number;
+    message?: string;
+} | {
+    kind: "email";
+    message?: string;
+} | {
+    kind: "url";
+    message?: string;
+} | {
+    kind: "uuid";
+    message?: string;
+} | {
+    kind: "date";
+    message?: string;
+} | {
+    kind: "oneOf";
+    values: (string | number)[];
+    message?: string;
+} | {
+    kind: "pattern";
+    source: string;
+    flags?: string;
+    message?: string;
+} | {
+    kind: "integer";
+    message?: string;
+};
+interface FieldDescriptor {
+    type: "string" | "number" | "boolean";
+    optional?: boolean;
+    label?: string;
+    /** Trim string input before validating. */
+    trim?: boolean;
+    rules: RuleDescriptor[];
+}
+interface SchemaDescriptor {
+    type: "object";
+    fields: Record<string, FieldDescriptor>;
+}
+interface ParseResult<T = Record<string, unknown>> {
+    ok: boolean;
+    /** Coerced values (present whether or not validation passed). */
+    value: T;
+    /** Field name → message, only for fields that failed. */
+    errors: Record<string, string>;
+}
+/**
+ * Apply one rule to an already-coerced value. Shared by the server; the client
+ * runtime (runtime.ts) mirrors this exactly. Returns an error message or null.
+ */
+declare function applyRule(type: string, rule: RuleDescriptor, value: unknown): string | null;
+/** Coerce + validate one field against its descriptor. */
+declare function checkField(desc: FieldDescriptor, raw: unknown): {
+    value: unknown;
+    error: string | null;
+};
+/** A server-only refinement (a predicate that can't be serialized to the client). */
+type Refinement = {
+    fn: (value: unknown) => boolean | string;
+    message?: string;
+};
+declare abstract class FieldSchema {
+    abstract readonly type: "string" | "number" | "boolean";
+    protected _optional: boolean;
+    protected _label?: string;
+    protected _default?: unknown;
+    protected rules: RuleDescriptor[];
+    protected refinements: Refinement[];
+    optional(): this;
+    label(label: string): this;
+    /** Value used when the field is absent (implies optional). */
+    default(value: unknown): this;
+    min(n: number, message?: string): this;
+    max(n: number, message?: string): this;
+    /**
+     * Custom SERVER-side validation. `fn` returns true (ok), false (use `message`),
+     * or a string (that error). Not mirrored to the client validator.
+     */
+    refine(fn: (value: unknown) => boolean | string, message?: string): this;
+    getDefault(): unknown;
+    runRefinements(value: unknown): string | null;
+    describe(): FieldDescriptor;
+}
+declare class StringSchema extends FieldSchema {
+    readonly type: "string";
+    private _trim;
+    email(message?: string): this;
+    url(message?: string): this;
+    uuid(message?: string): this;
+    date(message?: string): this;
+    length(n: number, message?: string): this;
+    oneOf(values: string[], message?: string): this;
+    trim(): this;
+    pattern(re: RegExp, message?: string): this;
+    describe(): FieldDescriptor;
+}
+declare class NumberSchema extends FieldSchema {
+    readonly type: "number";
+    integer(message?: string): this;
+    positive(message?: string): this;
+    oneOf(values: number[], message?: string): this;
+}
+declare class BooleanSchema extends FieldSchema {
+    readonly type: "boolean";
+}
+declare class ObjectSchema {
+    private readonly fields;
+    constructor(fields: Record<string, FieldSchema>);
+    /** Validate an input object; returns coerced values + per-field errors. */
+    parse(input: unknown): ParseResult;
+    describe(): SchemaDescriptor;
+}
+/** The fluent schema builder. */
+declare const v: {
+    string: () => StringSchema;
+    number: () => NumberSchema;
+    boolean: () => BooleanSchema;
+    object: (fields: Record<string, FieldSchema>) => ObjectSchema;
+};
+/**
+ * Validate environment variables against a schema at startup. Values are read
+ * from `Bun.env` / `process.env` by default and coerced by the schema (so
+ * `PORT` becomes a number, `DEBUG` a boolean). On any problem it throws ONE
+ * readable error listing every offending variable, so misconfiguration fails
+ * fast with an actionable message instead of surfacing deep inside the app.
+ *
+ *   export const env = parseEnv(v.object({
+ *     DATABASE_URL: v.string().min(1),
+ *     PORT: v.number(),
+ *   }));
+ */
+declare function parseEnv<T = Record<string, unknown>>(schema: ObjectSchema, source?: Record<string, string | undefined>): T;
+/** A 400 response carrying field errors, for API routes. */
+declare function invalid(errors: Record<string, string>): Response;
+/**
+ * Parse a request's JSON body against a schema. On failure returns
+ * `{ ok: false, response }` (a ready 400); on success `{ ok: true, value }`.
+ */
+declare function parseBody<T = Record<string, unknown>>(schema: ObjectSchema, req: Request): Promise<{
+    ok: true;
+    value: T;
+} | {
+    ok: false;
+    response: Response;
+}>;
+
+export { type FieldDescriptor, ObjectSchema, type ParseResult, type RuleDescriptor, type SchemaDescriptor, VALIDATE_RUNTIME, applyRule, checkField, invalid, parseBody, parseEnv, renderSchemasScript, v };
+

Examples

Copy-ready examples taken from this package's published documentation.

Example 1

bun add @wrnexus/validation

Example 2

import { v } from "@wrnexus/validation";

Example 3

schema.parse(input: unknown): ParseResult
+schema.describe(): SchemaDescriptor

Example 4

interface ParseResult<T = Record<string, unknown>> {
+  ok: boolean; // true when errors is empty
+  value: T; // coerced values (present pass or fail)
+  errors: Record<string, string>; // field name → first failing message
+}
+ +
+
WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
+
+ } +} diff --git a/app/routes.gen.ts b/app/routes.gen.ts new file mode 100644 index 00000000..248c8ee5 --- /dev/null +++ b/app/routes.gen.ts @@ -0,0 +1,53 @@ +// AUTO-GENERATED by `wrnexus dev` — do not edit. +// Typed routes: a compile-time map of every page path to its [param] types, +// plus an href() builder that fills params and rejects unknown paths. + +export interface Routes { + "/": Record; + "/architecture": Record; + "/getting-started": Record; + "/language": Record; + "/packages": Record; + "/packages/ai": Record; + "/packages/authz": Record; + "/packages/cli": Record; + "/packages/compiler": Record; + "/packages/core": Record; + "/packages/csr": Record; + "/packages/db": Record; + "/packages/dev-server": Record; + "/packages/encryption": Record; + "/packages/i18n": Record; + "/packages/jwt": Record; + "/packages/mobile": Record; + "/packages/native": Record; + "/packages/oauth": Record; + "/packages/pubsub": Record; + "/packages/queue": Record; + "/packages/reactive": Record; + "/packages/router": Record; + "/packages/ssr": Record; + "/packages/styles": Record; + "/packages/test": Record; + "/packages/tracking": Record; + "/packages/ui": Record; + "/packages/uploader": Record; + "/packages/validation": Record; +} + +export type RoutePath = keyof Routes; + +export function href

( + path: P, + ...args: Routes[P] extends Record ? [] : [params: Routes[P]] +): string { + const params = (args[0] ?? {}) as Record; + return String(path) + .split("/") + .map((seg) => + seg.startsWith("[") && seg.endsWith("]") + ? encodeURIComponent(params[seg.slice(1, -1)] ?? "") + : seg, + ) + .join("/"); +} diff --git a/app/styles/global.css b/app/styles/global.css new file mode 100644 index 00000000..c78aa81f --- /dev/null +++ b/app/styles/global.css @@ -0,0 +1,757 @@ +@import "tailwindcss"; +@source "../**/*.{wrn,ts,tsx}"; + +:root { + color-scheme: light; + --bg: #f8fafc; + --surface: #ffffff; + --surface-soft: #f1f5f9; + --text: #0f172a; + --muted: #526075; + --border: #dbe3ee; + --brand: #5b5cf0; + --brand-strong: #4338ca; + --code: #111827; + --code-text: #dbeafe; + --shadow: 0 18px 60px rgba(15, 23, 42, 0.08); +} + +[data-theme="dark"] { + color-scheme: dark; + --bg: #080b14; + --surface: #101522; + --surface-soft: #161c2c; + --text: #f4f7fb; + --muted: #9ba8bc; + --border: #263047; + --brand: #8b8df8; + --brand-strong: #a5b4fc; + --code: #05070d; + --code-text: #dbeafe; + --shadow: 0 22px 70px rgba(0, 0, 0, 0.3); +} + +* { + box-sizing: border-box; +} +html { + scroll-behavior: smooth; +} +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: "Plus Jakarta Sans", ui-sans-serif, system-ui, sans-serif; + overflow-x: hidden; +} +a { + color: inherit; +} +.docs-shell { + position: relative; + isolation: isolate; + min-height: 100vh; + overflow: hidden; +} +.docs-shell::before, +.docs-shell::after { + position: fixed; + z-index: -1; + width: 38rem; + height: 38rem; + border-radius: 999px; + content: ""; + pointer-events: none; + filter: blur(110px); + opacity: 0.12; + animation: ambient-float 16s ease-in-out infinite alternate; +} +.docs-shell::before { + top: -16rem; + left: -12rem; + background: #6366f1; +} +.docs-shell::after { + right: -15rem; + bottom: -18rem; + background: #a855f7; + animation-delay: -7s; +} +.topbar { + position: sticky; + top: 0; + z-index: 20; + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 2rem; + height: 74px; + padding: 0 clamp(20px, 4vw, 72px); + border-bottom: 1px solid color-mix(in srgb, var(--border) 80%, transparent); + background: color-mix(in srgb, var(--bg) 82%, transparent); + backdrop-filter: blur(22px) saturate(145%); +} +.brand { + display: inline-flex; + align-items: center; + gap: 0.65rem; + width: fit-content; + font-weight: 800; + text-decoration: none; + letter-spacing: -0.02em; +} +.brand span { + display: grid; + place-items: center; + width: 34px; + height: 34px; + border-radius: 11px; + color: white; + background: linear-gradient(145deg, #6366f1, #8b5cf6); + box-shadow: 0 8px 24px rgba(99, 102, 241, 0.3); + animation: logo-pulse 4s ease-in-out infinite; +} +.topbar nav { + display: flex; + gap: 1.5rem; +} +.topbar nav a { + position: relative; + color: var(--muted); + font-size: 0.9rem; + font-weight: 600; + text-decoration: none; +} +.topbar nav a::after { + position: absolute; + right: 0; + bottom: -0.45rem; + left: 0; + height: 2px; + border-radius: 2px; + background: linear-gradient(90deg, var(--brand), #a855f7); + content: ""; + transform: scaleX(0); + transition: transform 0.2s ease; +} +.topbar nav a:hover::after { + transform: scaleX(1); +} +.topbar nav a:hover { + color: var(--text); +} +.theme-button { + justify-self: end; + border: 1px solid var(--border); + border-radius: 9px; + padding: 0.5rem 0.8rem; + color: var(--muted); + background: var(--surface); + cursor: pointer; + transition: + transform 0.18s ease, + border-color 0.18s ease, + box-shadow 0.18s ease; +} +.theme-button:hover { + transform: translateY(-2px); + border-color: var(--brand); + box-shadow: 0 10px 28px color-mix(in srgb, var(--brand) 18%, transparent); +} +.page { + width: 100%; + margin: 0; + padding-inline: clamp(20px, 4vw, 72px); +} +.hero { + display: grid; + place-items: center; + min-height: 670px; + padding: 100px 0; + text-align: center; + background: + radial-gradient( + circle at 50% 25%, + color-mix(in srgb, var(--brand) 19%, transparent), + transparent 34% + ), + radial-gradient(circle at 75% 55%, color-mix(in srgb, #a855f7 9%, transparent), transparent 26%); +} +.hero.compact { + min-height: auto; + padding: 100px 0 60px; +} +.eyebrow, +.category { + color: var(--brand); + font-size: 0.72rem; + font-weight: 800; + letter-spacing: 0.14em; + text-transform: uppercase; +} +.hero h1 { + max-width: 920px; + margin: 1rem 0; + font-size: clamp(3rem, 7vw, 6.6rem); + line-height: 0.96; + letter-spacing: -0.065em; + animation: reveal-up 0.72s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.hero.compact h1 { + font-size: clamp(2.8rem, 5vw, 4.8rem); +} +.hero h1 em { + color: transparent; + background: linear-gradient(105deg, var(--brand), #a855f7, #0ea5e9, var(--brand)); + background-size: 240% auto; + background-clip: text; + font-style: normal; + animation: gradient-shift 7s linear infinite; +} +.hero > p { + max-width: 720px; + margin: 0.75rem auto 0; + color: var(--muted); + font-size: 1.15rem; + line-height: 1.75; + animation: reveal-up 0.72s 0.1s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.actions { + display: flex; + flex-wrap: wrap; + gap: 0.8rem; + margin-top: 2rem; + animation: reveal-up 0.72s 0.18s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.actions a { + padding: 0.8rem 1.15rem; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface); + font-weight: 700; + text-decoration: none; + transition: + transform 0.18s ease, + box-shadow 0.18s ease, + border-color 0.18s ease; +} +.actions a:hover { + transform: translateY(-3px); + border-color: var(--brand); + box-shadow: 0 14px 35px color-mix(in srgb, var(--brand) 18%, transparent); +} +.actions .primary { + border-color: var(--brand); + color: white; + background: var(--brand); +} +.code-window { + width: min(680px, 100%); + margin-top: 3rem; + overflow: hidden; + border: 1px solid var(--border); + border-radius: 16px; + text-align: left; + background: var(--code); + box-shadow: var(--shadow); + animation: reveal-up 0.8s 0.28s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.code-window > span { + display: block; + padding: 0.7rem 1rem; + border-bottom: 1px solid #283044; + color: #94a3b8; + font: + 0.75rem ui-monospace, + monospace; +} +pre { + position: relative; + overflow: auto; + margin: 1.25rem 0; + padding: 1.2rem 1.35rem; + border: 1px solid #20283a; + border-radius: 12px; + color: var(--code-text); + background: var(--code); + font: + 0.82rem/1.7 ui-monospace, + SFMono-Regular, + Consolas, + monospace; + tab-size: 2; +} +.code-window pre { + margin: 0; + border: 0; + border-radius: 0; +} +code { + border-radius: 5px; + padding: 0.12rem 0.35rem; + color: var(--brand-strong); + background: var(--surface-soft); + font: + 0.88em ui-monospace, + SFMono-Regular, + Consolas, + monospace; +} +pre code, +.sidebar > code { + padding: 0; + color: inherit; + background: transparent; +} +.feature-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 1rem; + padding: 0 0 100px; +} +.feature-grid article, +.package-card { + border: 1px solid var(--border); + border-radius: 16px; + padding: 1.5rem; + background: linear-gradient( + 145deg, + var(--surface), + color-mix(in srgb, var(--surface-soft) 42%, var(--surface)) + ); + box-shadow: var(--shadow); + animation: reveal-up 0.62s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.feature-grid article:nth-child(2), +.package-card:nth-child(3n + 2) { + animation-delay: 0.06s; +} +.feature-grid article:nth-child(3), +.package-card:nth-child(3n) { + animation-delay: 0.12s; +} +.feature-grid h2, +.package-card h2 { + margin: 0.7rem 0; + letter-spacing: -0.025em; +} +.feature-grid p, +.package-card p { + color: var(--muted); + line-height: 1.65; +} +.search { + width: min(620px, 100%); + margin-top: 2rem; + border: 1px solid var(--border); + border-radius: 13px; + padding: 0.9rem 1rem; + color: var(--text); + background: var(--surface); + font: inherit; + box-shadow: var(--shadow); + transition: + border-color 0.18s ease, + box-shadow 0.18s ease, + transform 0.18s ease; +} +.search:focus { + transform: translateY(-2px); + border-color: var(--brand); + outline: none; + box-shadow: 0 18px 50px color-mix(in srgb, var(--brand) 18%, transparent); +} +.category-filter { + display: grid; + gap: 0.8rem; + margin-bottom: 1.5rem; +} +.category-row { + display: flex; + gap: 0.55rem; + overflow-x: auto; + padding: 0.2rem 0 0.65rem; + scrollbar-width: thin; +} +.category-row button { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: 0.45rem; + border: 1px solid var(--border); + border-radius: 999px; + padding: 0.55rem 0.8rem; + color: var(--muted); + background: var(--surface); + font-family: inherit; + font-size: 0.82rem; + font-weight: 600; + line-height: 1; + cursor: pointer; + transition: + border-color 0.16s ease, + color 0.16s ease, + transform 0.16s ease; +} +.category-row button:hover, +.category-row button:focus-visible { + transform: translateY(-1px); + border-color: var(--brand); + color: var(--brand); + outline: none; +} +.category-row button span { + display: grid; + place-items: center; + min-width: 1.35rem; + height: 1.35rem; + border-radius: 999px; + color: var(--text); + background: var(--surface-soft); + font-size: 0.7rem; +} +.category-filter p { + margin: 0; + color: var(--muted); + font-size: 0.85rem; +} +.category-filter strong { + color: var(--text); +} +.package-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 1rem; + padding-bottom: 100px; +} +.package-card { + display: block; + text-decoration: none; + transition: + transform 0.18s ease, + border-color 0.18s ease, + box-shadow 0.18s ease; +} +.package-card:hover { + transform: translateY(-7px); + border-color: var(--brand); + box-shadow: 0 24px 60px color-mix(in srgb, var(--brand) 14%, transparent); +} +.card-link { + color: var(--brand); + font-size: 0.88rem; + font-weight: 700; +} +.package-page { + display: grid; + grid-template-columns: 250px minmax(0, 1fr) 200px; + gap: 48px; + align-items: start; + padding-top: 56px; + padding-bottom: 110px; +} +.on-this-page { + position: sticky; + top: 110px; + min-width: 0; + border-left: 1px solid var(--border); + padding-left: 1rem; +} +.on-this-page h2 { + margin: 0 0 0.8rem; + font-size: 0.78rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} +.on-this-page nav { + display: grid; + gap: 0.48rem; + max-height: calc(100vh - 160px); + overflow-y: auto; +} +.on-this-page a { + overflow: hidden; + color: var(--muted); + font-size: 0.78rem; + line-height: 1.35; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; +} +.on-this-page a:hover { + color: var(--brand); +} +.on-this-page .toc-level-3, +.on-this-page .toc-level-4 { + padding-left: 0.7rem; +} +.sidebar { + position: sticky; + top: 110px; + display: grid; + gap: 0.85rem; +} +.sidebar > a { + color: var(--muted); + font-size: 0.85rem; + text-decoration: none; +} +.sidebar h1 { + overflow-wrap: anywhere; + margin: 0; + font-size: 1.55rem; + letter-spacing: -0.035em; +} +.sidebar p { + margin: 0; + color: var(--muted); + line-height: 1.55; +} +.sidebar > code { + overflow-x: auto; + padding: 0.8rem; + border: 1px solid var(--border); + border-radius: 9px; + color: var(--text); + background: var(--surface-soft); +} +.sidebar nav { + display: grid; + gap: 0.55rem; + padding-top: 0.5rem; + border-top: 1px solid var(--border); +} +.sidebar nav a { + color: var(--muted); + text-decoration: none; +} +.documentation { + min-width: 0; + animation: reveal-up 0.65s 0.08s cubic-bezier(0.16, 1, 0.3, 1) both; +} +.documentation.standalone, +.standalone { + width: 100%; + max-width: none; + margin: 0; + padding: 90px clamp(0px, 5vw, 90px) 120px; +} +.standalone > * { + max-width: 1000px; +} +.doc-intro { + padding-bottom: 2rem; + border-bottom: 1px solid var(--border); +} +.doc-intro h1, +.standalone h1 { + margin: 0.7rem 0; + font-size: clamp(2.5rem, 5vw, 4.2rem); + letter-spacing: -0.055em; +} +.doc-intro p { + color: var(--muted); + font-size: 1.1rem; +} +.prose { + color: var(--muted); + font-size: 1rem; + line-height: 1.8; +} +.prose > * { + max-width: 850px; +} +.prose h2, +.prose h3, +.prose h4 { + scroll-margin-top: 90px; + color: var(--text); + line-height: 1.2; + letter-spacing: -0.035em; +} +.prose h2 { + margin: 3.5rem 0 1rem; + font-size: 2rem; +} +.prose h3 { + margin: 2.5rem 0 0.8rem; + font-size: 1.4rem; +} +.prose ul { + padding-left: 1.25rem; +} +.prose li { + margin: 0.45rem 0; +} +.prose blockquote { + margin: 1.5rem 0; + border-left: 3px solid var(--brand); + padding: 0.5rem 1.2rem; + color: var(--text); + background: var(--surface-soft); +} +.table-wrap { + overflow-x: auto; + margin: 1.5rem 0; + border: 1px solid var(--border); + border-radius: 12px; +} +.prose table { + width: 100%; + border-collapse: collapse; + background: var(--surface); + font-size: 0.9rem; +} +.prose th, +.prose td { + min-width: 130px; + padding: 0.75rem 0.9rem; + border-bottom: 1px solid var(--border); + text-align: left; + vertical-align: top; +} +.prose th { + color: var(--text); + background: var(--surface-soft); + font-weight: 700; +} +.prose tr:last-child td { + border-bottom: 0; +} +.prose a { + color: var(--brand); +} +.api { + margin-top: 4rem; + border-top: 1px solid var(--border); +} +.api pre { + max-height: 760px; +} +#guide, +#api, +#examples { + scroll-margin-top: 90px; +} +.examples { + margin-top: 4rem; + border-top: 1px solid var(--border); +} +.example-grid { + display: grid; + gap: 1rem; +} +.example-card { + min-width: 0; +} +.example-card h3 { + margin-bottom: -0.5rem; + font-size: 0.88rem; +} +.language-reference { + max-width: 920px; +} +footer { + border-top: 1px solid var(--border); + padding: 34px 20px; + color: var(--muted); + font-size: 0.82rem; + text-align: center; +} + +@keyframes reveal-up { + from { + opacity: 0; + transform: translateY(22px); + } + to { + opacity: 1; + transform: translateY(0); + } +} +@keyframes ambient-float { + from { + transform: translate3d(-3%, -2%, 0) scale(0.95); + } + to { + transform: translate3d(8%, 7%, 0) scale(1.12); + } +} +@keyframes gradient-shift { + to { + background-position: 240% center; + } +} +@keyframes logo-pulse { + 0%, + 100% { + box-shadow: 0 8px 24px rgba(99, 102, 241, 0.28); + } + 50% { + box-shadow: 0 10px 34px rgba(139, 92, 246, 0.5); + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} + +@media (max-width: 900px) { + .topbar { + grid-template-columns: 1fr auto; + padding: 0 20px; + } + .topbar nav { + display: none; + } + .feature-grid, + .package-grid { + grid-template-columns: repeat(2, 1fr); + } + .package-page { + grid-template-columns: 1fr; + gap: 35px; + } + .sidebar { + position: static; + } + .on-this-page { + display: none; + } +} + +@media (min-width: 901px) and (max-width: 1120px) { + .package-page { + grid-template-columns: 230px minmax(0, 1fr); + } + .on-this-page { + display: none; + } +} + +@media (max-width: 600px) { + .page { + width: 100%; + padding-inline: 14px; + } + .hero { + min-height: 580px; + padding: 70px 0; + } + .feature-grid, + .package-grid { + grid-template-columns: 1fr; + } + .package-page { + padding-top: 30px; + } +} diff --git a/bun.lock b/bun.lock new file mode 100644 index 00000000..3f54a10f --- /dev/null +++ b/bun.lock @@ -0,0 +1,463 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "wrnexusjs", + "dependencies": { + "@wrnexus/ai": "0.2.12", + "@wrnexus/authz": "0.2.12", + "@wrnexus/compiler": "0.2.12", + "@wrnexus/core": "0.2.12", + "@wrnexus/csr": "0.2.12", + "@wrnexus/db": "0.2.12", + "@wrnexus/dev-server": "0.2.12", + "@wrnexus/encryption": "0.2.12", + "@wrnexus/i18n": "0.2.12", + "@wrnexus/jwt": "0.2.12", + "@wrnexus/mobile": "0.2.12", + "@wrnexus/native": "0.2.12", + "@wrnexus/oauth": "0.2.12", + "@wrnexus/pubsub": "0.2.12", + "@wrnexus/queue": "0.2.12", + "@wrnexus/reactive": "0.2.12", + "@wrnexus/router": "0.2.12", + "@wrnexus/ssr": "0.2.12", + "@wrnexus/styles": "0.2.12", + "@wrnexus/test": "0.2.12", + "@wrnexus/tracking": "0.2.12", + "@wrnexus/ui": "0.2.12", + "@wrnexus/uploader": "0.2.12", + "@wrnexus/validation": "0.2.12", + }, + "devDependencies": { + "@eslint/js": "^9.0.0", + "@tailwindcss/cli": "^4.0.0", + "@types/bun": "latest", + "@wrnexus/cli": "0.2.12", + "eslint": "^9.0.0", + "prettier": "latest", + "tailwindcss": "^4.0.0", + "typescript": "^5.5.0", + "typescript-eslint": "latest", + }, + }, + }, + "packages": { + "@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.9.1", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ=="], + + "@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.2", "", {}, "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew=="], + + "@eslint/config-array": ["@eslint/config-array@0.21.2", "", { "dependencies": { "@eslint/object-schema": "^2.1.7", "debug": "^4.3.1", "minimatch": "^3.1.5" } }, "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw=="], + + "@eslint/config-helpers": ["@eslint/config-helpers@0.4.2", "", { "dependencies": { "@eslint/core": "^0.17.0" } }, "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw=="], + + "@eslint/core": ["@eslint/core@0.17.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ=="], + + "@eslint/eslintrc": ["@eslint/eslintrc@3.3.6", "", { "dependencies": { "ajv": "^6.14.0", "debug": "^4.3.2", "espree": "^10.0.1", "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.3.0", "minimatch": "^3.1.5", "strip-json-comments": "^3.1.1" } }, "sha512-l2Ul9PrHsPCKcEY/ac7VgFj9D80C7S68sOKc618SyHDPK36s1XcFebXY0iTzUVn4Yq+YbwvSnDmCz9yxjX+QrA=="], + + "@eslint/js": ["@eslint/js@9.39.5", "", {}, "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A=="], + + "@eslint/object-schema": ["@eslint/object-schema@2.1.7", "", {}, "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA=="], + + "@eslint/plugin-kit": ["@eslint/plugin-kit@0.4.1", "", { "dependencies": { "@eslint/core": "^0.17.0", "levn": "^0.4.1" } }, "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA=="], + + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], + + "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], + + "@humanfs/types": ["@humanfs/types@0.15.0", "", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="], + + "@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="], + + "@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.3", "", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="], + + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], + + "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@parcel/watcher": ["@parcel/watcher@2.5.1", "", { "dependencies": { "detect-libc": "^1.0.3", "is-glob": "^4.0.3", "micromatch": "^4.0.5", "node-addon-api": "^7.0.0" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.5.1", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", "@parcel/watcher-freebsd-x64": "2.5.1", "@parcel/watcher-linux-arm-glibc": "2.5.1", "@parcel/watcher-linux-arm-musl": "2.5.1", "@parcel/watcher-linux-arm64-glibc": "2.5.1", "@parcel/watcher-linux-arm64-musl": "2.5.1", "@parcel/watcher-linux-x64-glibc": "2.5.1", "@parcel/watcher-linux-x64-musl": "2.5.1", "@parcel/watcher-win32-arm64": "2.5.1", "@parcel/watcher-win32-ia32": "2.5.1", "@parcel/watcher-win32-x64": "2.5.1" } }, "sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg=="], + + "@parcel/watcher-android-arm64": ["@parcel/watcher-android-arm64@2.5.1", "", { "os": "android", "cpu": "arm64" }, "sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA=="], + + "@parcel/watcher-darwin-arm64": ["@parcel/watcher-darwin-arm64@2.5.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw=="], + + "@parcel/watcher-darwin-x64": ["@parcel/watcher-darwin-x64@2.5.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg=="], + + "@parcel/watcher-freebsd-x64": ["@parcel/watcher-freebsd-x64@2.5.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ=="], + + "@parcel/watcher-linux-arm-glibc": ["@parcel/watcher-linux-arm-glibc@2.5.1", "", { "os": "linux", "cpu": "arm" }, "sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA=="], + + "@parcel/watcher-linux-arm-musl": ["@parcel/watcher-linux-arm-musl@2.5.1", "", { "os": "linux", "cpu": "arm" }, "sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q=="], + + "@parcel/watcher-linux-arm64-glibc": ["@parcel/watcher-linux-arm64-glibc@2.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w=="], + + "@parcel/watcher-linux-arm64-musl": ["@parcel/watcher-linux-arm64-musl@2.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg=="], + + "@parcel/watcher-linux-x64-glibc": ["@parcel/watcher-linux-x64-glibc@2.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A=="], + + "@parcel/watcher-linux-x64-musl": ["@parcel/watcher-linux-x64-musl@2.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg=="], + + "@parcel/watcher-win32-arm64": ["@parcel/watcher-win32-arm64@2.5.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw=="], + + "@parcel/watcher-win32-ia32": ["@parcel/watcher-win32-ia32@2.5.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ=="], + + "@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.5.1", "", { "os": "win32", "cpu": "x64" }, "sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA=="], + + "@tailwindcss/cli": ["@tailwindcss/cli@4.3.2", "", { "dependencies": { "@parcel/watcher": "2.5.1", "@tailwindcss/node": "4.3.2", "@tailwindcss/oxide": "4.3.2", "enhanced-resolve": "5.21.6", "mri": "^1.2.0", "picocolors": "^1.1.1", "tailwindcss": "4.3.2" }, "bin": { "tailwindcss": "./dist/index.mjs" } }, "sha512-Fzt+HrIZHDlkRYKdLMBeufaroaPvwCBG70sMLdmurdeadNMO/LxbmT8Sbb+P83ep0iAlAImettb7Y+rO+37rXw=="], + + "@tailwindcss/node": ["@tailwindcss/node@4.3.2", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "5.21.6", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.2" } }, "sha512-yWP/sqEcBLaD8JuA6zNwxoYKr75qxTioYwlRwekj5Jr/I5GXnoJfjetH/psLUIv74cYTH2lBUEzBkinthoYcBg=="], + + "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.2", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.2", "@tailwindcss/oxide-darwin-arm64": "4.3.2", "@tailwindcss/oxide-darwin-x64": "4.3.2", "@tailwindcss/oxide-freebsd-x64": "4.3.2", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.2", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.2", "@tailwindcss/oxide-linux-arm64-musl": "4.3.2", "@tailwindcss/oxide-linux-x64-gnu": "4.3.2", "@tailwindcss/oxide-linux-x64-musl": "4.3.2", "@tailwindcss/oxide-wasm32-wasi": "4.3.2", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.2", "@tailwindcss/oxide-win32-x64-msvc": "4.3.2" } }, "sha512-z8ZgnzX8gdNoWLBLqBPoh/sjnxkwvf9ZuWjnO0l0yIzbLa5/9S+eC5QxGZKRobVHIC3/1BoMWjHblqWjcgFgag=="], + + "@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.3.2", "", { "os": "android", "cpu": "arm64" }, "sha512-WHxqIuHpvZ5VtdX6GTl1Ik/Vp2YuN42Et+0CdeaVd/frQ9jAvGmvR8vLT+jk3e8/Q3x8kECB9+R17pgpp2BulA=="], + + "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.3.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-GZypeUY/IDJW3877KeM+O67vbXr3MBnbtEL4aYhNErv/JWZhye2vGSWWG9tB6iiqR2MqRNkY8IOUy4NdSZV26w=="], + + "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.3.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-UIIzmefR6KO1sDU7MzRqAxC8iBpft/VhkGjTjnhoS6k7Z3rQ9wEgA1ODSiyH/tcSYssulNm4Ci3hOeK1jH7ccQ=="], + + "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.3.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-GN+uAmcI6DNspnCDwtOAZrTz6oukJnp337qZvxqCGLd3BHBzJpO0ZbTLRvJNdztOeAmTzewewGIMPb0tk2R4WA=="], + + "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.3.2", "", { "os": "linux", "cpu": "arm" }, "sha512-4ABn7qSbdHRwTiDiuWNegCyb5+2FJ4vKIKc3DmKrvAFw7MU1Lm11dIkTPwUaFdTzc7IsOpDbqBrlh0x6y36U/w=="], + + "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-wDgEIGwoM8w8pufh9LVt1PahDgNdKXrLC2qfAnV3vAmococ9RWbxeAw4pxPttd/TsJfwjyLf90Dg1y9y8I6Emw=="], + + "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-J5Nuk0uZQIiMTJj3LEx4sAA9tMFUoXQZFv1J6An+QGYe53HKRJuFDi0rpq/tuouCZeAbOBY3kQ6g8qeD4TUjtA=="], + + "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-kqCZpSKOBEJO4mz7OqWoofBZeXTAwaVGPj0ErAj7CojmhKpWVWVOnrt9dE8odoIraZq4oj3ausM37kXi+Tow8w=="], + + "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-cixpqbh2toJDmkuCRI68nXA8ZxNmdK9Y+9v5h3MC3ZQKy/0BO8AWzlkWyRM7JAFSGBlfig4YVTPsK6MVgqz1uw=="], + + "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.3.2", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-4ec2Z/LOmRsAgU23CS4xeJfcJlmRg94A/XrbGRCF1gyU/zdDfRLYDVsS+ynSZCmGNxQ1jQriQOKMQeQxBA3Isw=="], + + "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.3.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Zyr/M0+XcYZu3bZrUytc7TXvrk0ftWfl8gN2MwekNDzhqhKRUucMPSeOzM0o0wH5AWOU49BsKRrfKxI2atCPMQ=="], + + "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.3.2", "", { "os": "win32", "cpu": "x64" }, "sha512-QI9BO7KlNZsp2GuO0jwAAj5jCDABOKXRkCk2XuKTSaNEFSdfzqswYVTtCHBNKHLsqyjFyFkqlDiwkNbTYSssMQ=="], + + "@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + + "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + + "@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], + + "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.63.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.63.0", "@typescript-eslint/type-utils": "8.63.0", "@typescript-eslint/utils": "8.63.0", "@typescript-eslint/visitor-keys": "8.63.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.63.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-rvwSgqT+DHpWdzfSzPatRLm02a0GlESt++9iy3hLCDY4BgkaLcl8LBi9Yh7XGFBpwcBE/K3024QuXWTpbz4FfQ=="], + + "@typescript-eslint/parser": ["@typescript-eslint/parser@8.63.0", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.63.0", "@typescript-eslint/types": "8.63.0", "@typescript-eslint/typescript-estree": "8.63.0", "@typescript-eslint/visitor-keys": "8.63.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-gwh4gvvlaVDKKxyfxMG+Gnu1u9X0OQBwyGLkbwB65dIzBKnxeRiJlNFqlI3zwVhNXJIs6qV7mlFCn/BIajlVig=="], + + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.63.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.63.0", "@typescript-eslint/types": "^8.63.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-e5dh0/UI0ok53AlZ5wRkXCB32z/f2jUZqPR/ygAw5WYaSw8j9EoJWlS7wQjr/dmOaqWjnPIn2m+HhVPCMWGZVQ=="], + + "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.63.0", "", { "dependencies": { "@typescript-eslint/types": "8.63.0", "@typescript-eslint/visitor-keys": "8.63.0" } }, "sha512-uUyfMWCnDSN8bCpcrY8nGP2BLkQ9Xn0GsipcONcpIDWhwhO4ZSyHvyS14U3X75mzxWxL3I2UZIrenTzdzcJO8A=="], + + "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.63.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-sUAbkulqBAsncKnbRP3+7CtQFRKicexnj7ZwNC6ddCR7EmrXvjvdCYMJbUIqMd6lwoEriZjwLo08aS5tSjVMHg=="], + + "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.63.0", "", { "dependencies": { "@typescript-eslint/types": "8.63.0", "@typescript-eslint/typescript-estree": "8.63.0", "@typescript-eslint/utils": "8.63.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-Nzzh/OGxVCOjObjaj1CQF2RUasyYy2Jfuh+zZ3PjLzG2fYRriAiZLib9UKtO+CpQAS3YHiAS+ckZDclwqI1TPA=="], + + "@typescript-eslint/types": ["@typescript-eslint/types@8.63.0", "", {}, "sha512-xyLtl9DUBBFrcJS4x2pIqGLH68/tC2uOa4Z7pUteW09D3bXnnXUom4dyPikzWgB7llmIc1zoeI3aoUdC4rPK/Q=="], + + "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.63.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.63.0", "@typescript-eslint/tsconfig-utils": "8.63.0", "@typescript-eslint/types": "8.63.0", "@typescript-eslint/visitor-keys": "8.63.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-ygBkU+B7ex5UI/gKhaqexWev79uISfIv7XQCRNYO/jmD8rGLPyWLAb3KMRT6nd8Gt9bmUBi9+iX6tBdYfOY81Q=="], + + "@typescript-eslint/utils": ["@typescript-eslint/utils@8.63.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.63.0", "@typescript-eslint/types": "8.63.0", "@typescript-eslint/typescript-estree": "8.63.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-fUKaeAvrTuQg/Tgt3nliAUSZHJM6DlCcfyEmxCvlX8kieWSStBX+5O5Fnidtc3i2JrH+9c/GL4RY2iasd/GPTA=="], + + "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.63.0", "", { "dependencies": { "@typescript-eslint/types": "8.63.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-UexrHGnGTpbuQHct2ExOc2ZcFbGUS9FOesCxxqdBGcpI1BxYu/LZ6U8Aq6/72XtF/qRBk9nhuGHFJIXXMhPMdw=="], + + "@wrnexus/ai": ["@wrnexus/ai@0.2.12", "", {}, "sha512-yk9l9iJUskiJaJou2nMhizVCq3WqAjQkF6eizEpM5UVsLYvPMZGolTM9/7TbkI+a7cuc/EKjeuBXT55Jo1rS8g=="], + + "@wrnexus/authz": ["@wrnexus/authz@0.2.12", "", {}, "sha512-LEsqeutezOmbzUwmljWL9n/aoGXTizG0EvZENGwgIbyuOLCaWN9eDVgEcYAjAsKR4k00gdHdND0m2Xho3Asc3w=="], + + "@wrnexus/cli": ["@wrnexus/cli@0.2.12", "", { "dependencies": { "@wrnexus/compiler": "^0.2.12", "@wrnexus/core": "^0.2.12", "@wrnexus/csr": "^0.2.12", "@wrnexus/db": "^0.2.12", "@wrnexus/dev-server": "^0.2.12", "@wrnexus/i18n": "^0.2.12", "@wrnexus/router": "^0.2.12", "@wrnexus/styles": "^0.2.12", "@wrnexus/ui": "^0.2.12", "@wrnexus/validation": "^0.2.12" }, "bin": { "wrnexus": "dist/index.js" } }, "sha512-qw6f8cxH7wS15MTNzSGEMmUTCWfCk1aPBhE8euQ1kd2keysK15mVrqrmANq5aui1kwuVKTZ+T3/aCuo8GL5spQ=="], + + "@wrnexus/compiler": ["@wrnexus/compiler@0.2.12", "", {}, "sha512-TFLkz/J/SJgRKe2WJRA7Way5QAda8k6TT4/jF/HhSOLm1H88gzof1QDG6X+9ORdfSZdcbduq2GwQK3Ulp59d2Q=="], + + "@wrnexus/core": ["@wrnexus/core@0.2.12", "", {}, "sha512-JkLQ27zUiNvUWLWFSnNY2pZPwio/PVOx27cQll4HEGlALMAWLoLZOKV/5eRYktBN+vW0hhyFXJQvvpeIRT+IaQ=="], + + "@wrnexus/csr": ["@wrnexus/csr@0.2.12", "", { "dependencies": { "@wrnexus/core": "^0.2.12" } }, "sha512-aXK3EmvhXfKFJPrME/pDwepAwWucVBq+9dBc0OUipsDWmGQOmlqxeZBZ95RbBrDwRbLp8ZRaOHJC1dMcaOlJzA=="], + + "@wrnexus/db": ["@wrnexus/db@0.2.12", "", {}, "sha512-+ToSWC+Kj+nY6nX/FZw2lVW+8OlzH+k0H6YPrH4tReFyGdbFztbSaaielTQ6E97IwkzCofAF8Y5JMSt7avDOeQ=="], + + "@wrnexus/dev-server": ["@wrnexus/dev-server@0.2.12", "", { "dependencies": { "@wrnexus/compiler": "^0.2.12", "@wrnexus/core": "^0.2.12", "@wrnexus/csr": "^0.2.12", "@wrnexus/db": "^0.2.12", "@wrnexus/i18n": "^0.2.12", "@wrnexus/pubsub": "^0.2.12", "@wrnexus/router": "^0.2.12", "@wrnexus/ssr": "^0.2.12", "@wrnexus/styles": "^0.2.12", "@wrnexus/ui": "^0.2.12", "@wrnexus/uploader": "^0.2.12", "@wrnexus/validation": "^0.2.12" } }, "sha512-foN6tBqNaAkzCBe5HZXbyh6cua4Km3dAbaHaVCpVyVywgNzm717JFKNH8+CFu30XW8pUdMe0auOoV+wiqHY5lw=="], + + "@wrnexus/encryption": ["@wrnexus/encryption@0.2.12", "", {}, "sha512-o6HxrcQG0X4CwJYHFCrVH1oxydk3k8/v621I6rQz/IVkrdN5axPTU65xDMLXK48b3pF1LkgsLTV/GwBve3+tZA=="], + + "@wrnexus/i18n": ["@wrnexus/i18n@0.2.12", "", { "dependencies": { "@wrnexus/core": "^0.2.12" } }, "sha512-tLUEv3iHNLtGMPuNd15+N/YWWmDkBW4rqbtMeFa4oILRKZykUN+JRsl3WkBFD8xYso1hBGG1gubJVwrvcT5FHw=="], + + "@wrnexus/jwt": ["@wrnexus/jwt@0.2.12", "", {}, "sha512-6m2/HAds3dfCh/kwC1zU4JJFtyXDLV0MvByqw8YNF2Tmvlx+3H4pwW+XcoJEj9ksWBKkjxcetaOySKb1pLq+hQ=="], + + "@wrnexus/mobile": ["@wrnexus/mobile@0.2.12", "", { "dependencies": { "@wrnexus/native": "^0.2.12" } }, "sha512-D+y+MPz07hV8w75JYos4tSR3snSWHK3iaOdedJL7bl2wZ9Ap/pUeAKV3RtyoUHQ3yKgh+m0r8Mzdu8Mv0K3jgA=="], + + "@wrnexus/native": ["@wrnexus/native@0.2.12", "", {}, "sha512-Zc1j1ZqTIlwWFDFrwkm/Cz7Y4hotIHXuSWDEPEn5BehCtTn4cVmh5psiNF4MYho4La752HRp+8qDQhDDg7kmTA=="], + + "@wrnexus/oauth": ["@wrnexus/oauth@0.2.12", "", {}, "sha512-6hOFSFVhWp4Dn2ztWFEOo+XKB5BmXX8Hrrq3GMhiMxC8p7p8KiQhyofDZ8mG+WfkAjrG0QeifW0wecxd8fAoBg=="], + + "@wrnexus/pubsub": ["@wrnexus/pubsub@0.2.12", "", {}, "sha512-ul4w+8gW06rqMx9wcJ+F/PsdAAd2p7YsWzelv0fNOgfINvyG5VPkBaozqtNl9sbckhJlRC3/wEvHhRQJQaG5cQ=="], + + "@wrnexus/queue": ["@wrnexus/queue@0.2.12", "", {}, "sha512-onogt5wDDrokbGapKTHUgOeqlBGcX8faA5rg/Gqi/pbiv3SvA62vtkX7t3ZaUZKnkGF/gG5ReE9Pt8VLQ1E0Dg=="], + + "@wrnexus/reactive": ["@wrnexus/reactive@0.2.12", "", {}, "sha512-7oykh0M8ig6/cGBwyQ+5rNn3nypw8ziVqNMkIHfvDr0opQd/ZrQ0NzwbVVrmv90MspfWRyKemRsw6zA6xlPuTA=="], + + "@wrnexus/router": ["@wrnexus/router@0.2.12", "", { "dependencies": { "@wrnexus/compiler": "^0.2.12", "@wrnexus/core": "^0.2.12" } }, "sha512-v72kL6xjybgqAgfLzjgwMBaGJIuHh1fSI1JwKk7OK+jrWNAn7fqEN6mIOnzKgBtKerFa62KW+oPw1pGLvVnkEA=="], + + "@wrnexus/ssr": ["@wrnexus/ssr@0.2.12", "", { "dependencies": { "@wrnexus/core": "^0.2.12" } }, "sha512-DB2VFqzMDmAJG/k80gJMQ1mU+sfr7QVCyr3HHgrpKd1aHmLoIlTg1ItChrSZc9OsnYgiRXSMx290GRkG2POi/g=="], + + "@wrnexus/styles": ["@wrnexus/styles@0.2.12", "", { "dependencies": { "@wrnexus/uploader": "^0.2.12" } }, "sha512-SQtvuxCCbR3OMmPDeV9zZtCL3ohPeOQ9tHp77aqMLHQchXEmhxQ831nYZqufSJ7xj9WafMJGnyN5HUe8LqqaQg=="], + + "@wrnexus/test": ["@wrnexus/test@0.2.12", "", {}, "sha512-XfovFKYRRPBmwjpa4xbD6vuRa4zs0YnSAEn++yiC/CfP2N6st567y3rK5PxbXL6mC6rQR35xPGlVlIr+WeZtKQ=="], + + "@wrnexus/tracking": ["@wrnexus/tracking@0.2.12", "", {}, "sha512-2pd2/lmRkGt3fVKc6Nw2/HFs0bWqqaNr5i1mrvtc7yVLuVkf8I6gtikWyJrUCkJCxKhGXZWLMmGqRHvep5BuiA=="], + + "@wrnexus/ui": ["@wrnexus/ui@0.2.12", "", { "dependencies": { "@wrnexus/core": "^0.2.12" } }, "sha512-jKz8qGNtCbW0BvzXbMYttgUHDr11MacT886siIbTA36TtlxrY+6a0JVw4h+XMLYhFk1CjD6YXWyA2ZIoy0qHxQ=="], + + "@wrnexus/uploader": ["@wrnexus/uploader@0.2.12", "", { "dependencies": { "@wrnexus/core": "^0.2.12" } }, "sha512-olRQ+5spWTWplWBWEr89ZVw/CphhJgTQ/quxVwgXZmh0yznqqmvrGq3//bUAwF9WVTusK2EMtOOUSpfVSxn8cw=="], + + "@wrnexus/validation": ["@wrnexus/validation@0.2.12", "", {}, "sha512-cN9g6EKcGIuyQx2AFu9Qy2v0FD3neXsCA1uORr+T/x7ta/IDe8WzTall6EpcKzGq2RsLp/mCPspoF3t0CY7V2w=="], + + "acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], + + "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + + "brace-expansion": ["brace-expansion@1.1.16", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw=="], + + "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], + + "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], + + "callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="], + + "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="], + + "detect-libc": ["detect-libc@1.0.3", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="], + + "enhanced-resolve": ["enhanced-resolve@5.21.6", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ=="], + + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + + "eslint": ["eslint@9.39.5", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.21.2", "@eslint/config-helpers": "^0.4.2", "@eslint/core": "^0.17.0", "@eslint/eslintrc": "^3.3.6", "@eslint/js": "9.39.5", "@eslint/plugin-kit": "^0.4.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.4.0", "eslint-visitor-keys": "^4.2.1", "espree": "^10.4.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw=="], + + "eslint-scope": ["eslint-scope@8.4.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="], + + "eslint-visitor-keys": ["eslint-visitor-keys@4.2.1", "", {}, "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ=="], + + "espree": ["espree@10.4.0", "", { "dependencies": { "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.1" } }, "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ=="], + + "esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="], + + "esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="], + + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + + "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + + "fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="], + + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], + + "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], + + "flat-cache": ["flat-cache@4.0.1", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="], + + "flatted": ["flatted@3.4.2", "", {}, "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA=="], + + "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], + + "globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="], + + "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + + "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], + + "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], + + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], + + "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + + "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], + + "js-yaml": ["js-yaml@4.3.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="], + + "json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="], + + "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + + "json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="], + + "keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="], + + "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + + "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.32.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.32.0", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.32.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], + + "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], + + "lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], + + "minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], + + "mri": ["mri@1.2.0", "", {}, "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + + "node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="], + + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], + + "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + + "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], + + "parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="], + + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + + "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="], + + "prettier": ["prettier@3.9.5", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], + + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="], + + "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "tailwindcss": ["tailwindcss@4.3.2", "", {}, "sha512-WtctNNSH8A9jlMIqxzuYumOHU5uGZyRv0Q5svQl+oEPy5w84YpBxdb7MdqyiSPQge5jTJ6zFQLq0PFygdccSBA=="], + + "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], + + "ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="], + + "type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "typescript-eslint": ["typescript-eslint@8.63.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.63.0", "@typescript-eslint/parser": "8.63.0", "@typescript-eslint/typescript-estree": "8.63.0", "@typescript-eslint/utils": "8.63.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-xgwXyzG4sK9ALkBxbyGkTMMOS+imnW65iPhxCQMK83KhxyoDNW7l+IDqEf9vMdoUidHpOoS967RCq4eMiTexwQ=="], + + "undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + + "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], + + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + + "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" }, "bundled": true }, "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + + "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" }, "bundled": true }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], + + "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], + + "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="], + + "@typescript-eslint/typescript-estree/minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="], + + "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + + "lightningcss/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "tinyglobby/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + + "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@5.0.7", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA=="], + + "@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + } +} diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..5c86a656 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,44 @@ +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import js from "@eslint/js"; +import tseslint from "typescript-eslint"; + +const tsconfigRootDir = dirname(fileURLToPath(import.meta.url)); + +export default tseslint.config( + { + ignores: [ + "node_modules/**", + "dist/**", + ".wrnexus/**", + "**/.wrnexus/**", + "mobile/android/**", + "mobile/ios/**", + ], + }, + { + languageOptions: { + parserOptions: { + tsconfigRootDir, + }, + }, + }, + js.configs.recommended, + ...tseslint.configs.recommended, + { + files: ["**/*.{ts,tsx}"], + rules: { + "no-undef": "off", + "no-console": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-unused-vars": [ + "warn", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + caughtErrorsIgnorePattern: "^_", + }, + ], + }, + }, +); diff --git a/llms.txt b/llms.txt new file mode 100644 index 00000000..6ce52319 --- /dev/null +++ b/llms.txt @@ -0,0 +1,259 @@ +# WrNexus + +> WrNexus is an SSR-first, **Bun-native** full-stack web framework. UI is written in +> `.wrn` files (its own component language — NOT React/JSX/Vue). Routing is file-based. +> This document teaches an AI how to write correct WrNexus code. It is private and +> post-dates model training data, so rely on THIS document, not prior web-framework +> assumptions. + +## Golden rules + +- **Pages, components, and layouts are `.wrn` files.** Do NOT write `.tsx`/`.jsx`/React + for UI. Do NOT use `useState`, hooks, JSX, or a client bundler. +- **Routing is file-based** under `app/`. The filename is the route. No router config. +- **Interactivity** lives in `state` + `{expr}` + `@event` inside `.wrn`. Components render + on the server and hydrate automatically — you never write client-side JS islands. +- **Runtime is Bun only** (uses `Bun.serve`, `bun:sqlite`, `Bun.password`, …). Node is not supported. +- To add files, prefer the CLI: `wrnexus generate page ` / `component ` / `api ` / `schema `. + +## Project layout + +``` +app/ + pages/ *.wrn → routes: index.wrn = "/", about.wrn = "/about", blog/[slug].wrn = "/blog/:slug" + components/ *.wrn → reusable UI, mounted in a page/component via

+ layouts/ *.wrn → named layouts; a page opts in with layout = "name" + api/ *.ts → HTTP handlers: export const GET/POST/PUT/PATCH/DELETE = async (ctx) => Response + middleware/ *.ts → export default async (ctx, next) => next() + realtime/ *.ts → export default defineRoom({ ... }) from "@wrnexus/core" (ws://host/realtime/) + schemas/ *.ts → validation schemas (the `v` builder), used by forms + parseBody + locales/ *.json → i18n messages per language + db/ schema.ts, queries/*.sql, migrations/*.sql + styles/ global.css → Tailwind (default) or plain CSS +wrnexus.config.ts → app config (AppConfig from "@wrnexus/styles") +public/ → static assets served at / +``` + +## `.wrn` page + +```wrn +page Home { + layout = "public" // optional: a component in app/layouts/.wrn ("none" to skip) + + state count = 0 // optional: seeds client-reactive state (omit for pure SSR) + + seo { + title = "Home" + description = "..." + canonical = "/" + } + + view { +

Hello

+

Count is {count}, doubled is {count * 2}.

+ +
+ } + + style { + h1 { color: var(--wire-color-text); } + } +} +``` + +## `.wrn` component + +```wrn +component Counter { + props { // props come from mount attributes; each is coerced to the + start = 0 // TYPE of its default (so start="5" arrives as the number 5) + label = "Count" + } + state count = start // state may reference props + view { + + } +} +``` + +Mount it from any page/component: `
`. +Components render on the server with their props, then hydrate — no per-component JS. + +## The `view { }` block (plain HTML + a few directives) + +- `{expr}` — interpolate a JS expression. Reactive if it references `state`: `{count}`, `{count * 2}`, `{user.name}`. +- `@event="expr"` — bind a DOM event; the expression runs in the reactive scope: `@click="count++"`, `@input="name = event.target.value"`. +- `
` — mount a component (attrs become string props, coerced). +- `` / `` — component/layout slots; fill with `
`. +- **Server loop (DB/list/table):** `{#each as [, ]} …rows… {:empty} …fallback… {/each}` — iterates SSR data on the server and renders markup per item. `{item.field}` interpolates (HTML-escaped, XSS-safe). `` is a JS expression, usually an `ssr` data binding (see "Data-driven tables" below). This is how you render a database table in `.wrn`. +- **Server conditional:** `{#if } … {:else if } … {:else} … {/if}` — renders the first truthy branch on the server. `` can reference `ssr` data, or the `item`/`index` of an enclosing `{#each}`. Works at page level and inside loops (e.g. `{#if r.active}{:else}{/if}` per row). For client-side show/hide based on reactive `state`, use `data-show="expr"` instead. +- i18n: `{t:home.title}` in text, `t:placeholder="form.name"` on attributes — resolved per request from `app/locales/`. +- Theme: any element with `data-wire-theme-toggle` toggles light/dark; `data-wire-theme-set="dark"` sets it. +- Void/self-closing tags are fine: `
`, ``. +- Only `{` and `}` are special (interpolation). Don't use a bare `}` in view text. + +## Data-driven tables / lists (server-rendered `.wrn`) + +Use an `ssr` data binding to fetch rows on the server, then `{#each}` to render them. +This renders on the **server** (SSR-first) and is HTML-escaped by default. + +```wrn +page Admin { + layout = "dashboard" + + // Fetch on the server. The api handler at /api/contacts returns { contacts: [...] }; + // this block's `return contacts` exposes that array (via `$data`) as the binding `rows`. + ssr { + api rows GET /api/contacts { return contacts } + } + + view { + + + {#each rows as r, i} + + + + + + {:empty} + + {/each} + +
#{i}{r.name}{r.email}
No submissions yet.
+ } +} +``` + +The matching API returns the array under a key the `ssr` block reads: + +```ts +// app/api/contacts.ts → GET /api/contacts +import { getDb } from "@wrnexus/db"; +export const GET = async () => { + const contacts = await getDb().all("SELECT id, name, email FROM contacts ORDER BY id DESC"); + return Response.json({ contacts }); // ssr block does `return contacts` +}; +``` + +**Prefer this `.wrn` + `{#each}` approach for DB-backed tables and lists.** (`.ts`/`.tsx` +pages returning an HTML string are also supported for fully-custom programmatic rendering, +but a `.wrn` page with `ssr` data + `{#each}` is the idiomatic, SSR-first way.) + +## API routes (`app/api/*.ts`) + +```ts +// app/api/users/list.ts → GET /api/users/list +import { getDb } from "@wrnexus/db"; + +export const GET = async (ctx) => { + return Response.json({ users: await ListUsers(getDb()) }); +}; + +export const POST = async (ctx) => { + const body = await ctx.req.json(); + return Response.json({ ok: true, body }, { status: 201 }); +}; +``` + +`ctx` (the `Context` from `@wrnexus/core`) has: +`req: Request`, `url: URL`, `params: Record` (dynamic route params, e.g. `/users/[id]` → `ctx.params.id`), +`lang: string`, `t(key, params?)` (i18n), `cookies` (get/set), `session` (get/set). Auth: `getUser(ctx)` after `sessionAuth`/`logIn`. + +## Middleware & realtime + +```ts +// app/middleware/logger.ts +export default async function logger(ctx, next) { + console.log(ctx.req.method, ctx.url.pathname); + return next(); // return a Response WITHOUT calling next() to short-circuit +} +``` + +```ts +// app/realtime/chat.ts → ws://host/realtime/chat +import { defineRoom } from "@wrnexus/core"; +export default defineRoom({ + onConnect(client) { client.send({ type: "system", text: "connected" }); }, + onMessage(client, msg) { client.room.broadcast({ type: "message", data: msg }); }, +}); +``` +Client side: a page opts in with `data-room="chat"` (handled by the realtime runtime). + +## Config (`wrnexus.config.ts`) + +```ts +import type { AppConfig } from "@wrnexus/styles"; +const config: AppConfig = { + seo: { title: "App", titleTemplate: "%s | App", description: "..." }, + styles: { entry: "app/styles/global.css", process: async ({ entryPath, mode }) => /* Tailwind */ "" }, + fonts: { sans: '"Inter", system-ui, sans-serif', google: [{ family: "Inter", weights: [400, 600] }] }, + theme: { default: "dark", themes: { light: { "color-primary": "#2563eb" } } }, + i18n: { default: "en", locales: ["en", "es"] }, + db: { driver: "sqlite", url: "file:./dev.db" }, + security: { cors: { enabled: true, origin: ["http://localhost:5173"] } }, + // profiles: { production: { db: { driver: "postgres", url: process.env.DATABASE_URL } } }, +}; +export default config; +``` + +## Database (`@wrnexus/db`) + +```ts +// app/db/schema.ts +import { v, table } from "@wrnexus/db"; +export const users = table("users", { + id: v.id(), + name: v.string(), + email: v.string().unique(), + createdAt: v.timestamp(), +}); +``` +- Queries: write `app/db/queries/*.sql` with `-- name: ListUsers :many` blocks; `wrnexus db generate` emits typed functions. +- Access at runtime: `import { getDb } from "@wrnexus/db"; const rows = await ListUsers(getDb());` +- Migrations in `app/db/migrations/`; run `wrnexus db migrate` (dev auto-migrates sqlite). + +## Validation (`@wrnexus/validation`) + +```ts +// app/schemas/login.ts +import { v } from "@wrnexus/validation"; +export default v.object({ + email: v.string().email(), + password: v.string().min(8), +}); +``` +In an API route: `import s from "../schemas/login"; import { parseBody } from "@wrnexus/validation"; const r = await parseBody(s, ctx.req);` → `r.ok ? r.value : r.response`. +In a form: `` + `` (client + server validation wired automatically). + +## AI / LLM (`@wrnexus/ai`) + +```ts +// app/api/ai.ts +import { createAI } from "@wrnexus/ai"; +const ai = createAI(); // reads ANTHROPIC_API_KEY; default model claude-opus-4-8 +export const POST = async (ctx) => { + const { prompt } = await ctx.req.json(); + return ai.streamResponse(prompt); // or: return Response.json({ text: await ai.generate(prompt) }) +}; +``` + +## CLI + +``` +wrnexus dev . # dev server + HMR +wrnexus build . # production build → dist/server.js +wrnexus create # scaffold a new app +wrnexus generate page # scaffold a page (aliases: g p) +wrnexus generate component | api | schema +wrnexus db migrate | rollback | status | new [--from-models] | generate | seed +wrnexus eject # copy a Wire UI component's .wrn into app/components to customize +``` + +## When asked to "create a page/component/feature" + +1. Create the `.wrn` file under `app/pages/` (or `app/components/`) with a `page`/`component` block — or run `wrnexus generate page `. +2. Put markup in `view { }`, interactive bits in `state` + `{expr}` + `@event`, reusable UI as components mounted via `data-component`. +3. For data, add an `app/api/*.ts` route and `getDb()`; for forms, add an `app/schemas/*.ts` and `data-schema`. +4. Style with Tailwind utility classes in the view, or theme tokens (`var(--wire-*)`), or `style { }`. +5. Never emit React/JSX, a manual router, or client-side island JS — the framework handles hydration. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..54e504dd --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2667 @@ +{ + "name": "wrnexusjs", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "wrnexusjs", + "version": "0.1.0", + "dependencies": { + "@wrnexus/ai": "0.2.12", + "@wrnexus/authz": "0.2.12", + "@wrnexus/compiler": "0.2.12", + "@wrnexus/core": "0.2.12", + "@wrnexus/csr": "0.2.12", + "@wrnexus/db": "0.2.12", + "@wrnexus/dev-server": "0.2.12", + "@wrnexus/encryption": "0.2.12", + "@wrnexus/i18n": "0.2.12", + "@wrnexus/jwt": "0.2.12", + "@wrnexus/mobile": "0.2.12", + "@wrnexus/native": "0.2.12", + "@wrnexus/oauth": "0.2.12", + "@wrnexus/pubsub": "0.2.12", + "@wrnexus/queue": "0.2.12", + "@wrnexus/reactive": "0.2.12", + "@wrnexus/router": "0.2.12", + "@wrnexus/ssr": "0.2.12", + "@wrnexus/styles": "0.2.12", + "@wrnexus/test": "0.2.12", + "@wrnexus/tracking": "0.2.12", + "@wrnexus/ui": "0.2.12", + "@wrnexus/uploader": "0.2.12", + "@wrnexus/validation": "0.2.12" + }, + "devDependencies": { + "@eslint/js": "^9.0.0", + "@tailwindcss/cli": "^4.0.0", + "@types/bun": "latest", + "@types/node": "^26.1.1", + "@wrnexus/cli": "0.2.12", + "eslint": "^9.0.0", + "prettier": "latest", + "tailwindcss": "^4.0.0", + "typescript": "^5.5.0", + "typescript-eslint": "latest" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.6", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.3.0", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.5.1", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^1.0.3", + "is-glob": "^4.0.3", + "micromatch": "^4.0.5", + "node-addon-api": "^7.0.0" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.5.1", + "@parcel/watcher-darwin-arm64": "2.5.1", + "@parcel/watcher-darwin-x64": "2.5.1", + "@parcel/watcher-freebsd-x64": "2.5.1", + "@parcel/watcher-linux-arm-glibc": "2.5.1", + "@parcel/watcher-linux-arm-musl": "2.5.1", + "@parcel/watcher-linux-arm64-glibc": "2.5.1", + "@parcel/watcher-linux-arm64-musl": "2.5.1", + "@parcel/watcher-linux-x64-glibc": "2.5.1", + "@parcel/watcher-linux-x64-musl": "2.5.1", + "@parcel/watcher-win32-arm64": "2.5.1", + "@parcel/watcher-win32-ia32": "2.5.1", + "@parcel/watcher-win32-x64": "2.5.1" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.1.tgz", + "integrity": "sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.1.tgz", + "integrity": "sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.1.tgz", + "integrity": "sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.1.tgz", + "integrity": "sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.1.tgz", + "integrity": "sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.1.tgz", + "integrity": "sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.1.tgz", + "integrity": "sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.1.tgz", + "integrity": "sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.1.tgz", + "integrity": "sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.1.tgz", + "integrity": "sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.1.tgz", + "integrity": "sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-ia32": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.1.tgz", + "integrity": "sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.5.1", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/cli": { + "version": "4.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@parcel/watcher": "2.5.1", + "@tailwindcss/node": "4.3.2", + "@tailwindcss/oxide": "4.3.2", + "enhanced-resolve": "5.21.6", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "tailwindcss": "4.3.2" + }, + "bin": { + "tailwindcss": "dist/index.mjs" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "5.21.6", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.2" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.2", + "@tailwindcss/oxide-darwin-arm64": "4.3.2", + "@tailwindcss/oxide-darwin-x64": "4.3.2", + "@tailwindcss/oxide-freebsd-x64": "4.3.2", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.2", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.2", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.2", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.2", + "@tailwindcss/oxide-linux-x64-musl": "4.3.2", + "@tailwindcss/oxide-wasm32-wasi": "4.3.2", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.2", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.2" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.2.tgz", + "integrity": "sha512-WHxqIuHpvZ5VtdX6GTl1Ik/Vp2YuN42Et+0CdeaVd/frQ9jAvGmvR8vLT+jk3e8/Q3x8kECB9+R17pgpp2BulA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.2.tgz", + "integrity": "sha512-GZypeUY/IDJW3877KeM+O67vbXr3MBnbtEL4aYhNErv/JWZhye2vGSWWG9tB6iiqR2MqRNkY8IOUy4NdSZV26w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.2.tgz", + "integrity": "sha512-UIIzmefR6KO1sDU7MzRqAxC8iBpft/VhkGjTjnhoS6k7Z3rQ9wEgA1ODSiyH/tcSYssulNm4Ci3hOeK1jH7ccQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.2.tgz", + "integrity": "sha512-GN+uAmcI6DNspnCDwtOAZrTz6oukJnp337qZvxqCGLd3BHBzJpO0ZbTLRvJNdztOeAmTzewewGIMPb0tk2R4WA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.2.tgz", + "integrity": "sha512-4ABn7qSbdHRwTiDiuWNegCyb5+2FJ4vKIKc3DmKrvAFw7MU1Lm11dIkTPwUaFdTzc7IsOpDbqBrlh0x6y36U/w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.2.tgz", + "integrity": "sha512-wDgEIGwoM8w8pufh9LVt1PahDgNdKXrLC2qfAnV3vAmococ9RWbxeAw4pxPttd/TsJfwjyLf90Dg1y9y8I6Emw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.2.tgz", + "integrity": "sha512-J5Nuk0uZQIiMTJj3LEx4sAA9tMFUoXQZFv1J6An+QGYe53HKRJuFDi0rpq/tuouCZeAbOBY3kQ6g8qeD4TUjtA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.2.tgz", + "integrity": "sha512-kqCZpSKOBEJO4mz7OqWoofBZeXTAwaVGPj0ErAj7CojmhKpWVWVOnrt9dE8odoIraZq4oj3ausM37kXi+Tow8w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.2.tgz", + "integrity": "sha512-cixpqbh2toJDmkuCRI68nXA8ZxNmdK9Y+9v5h3MC3ZQKy/0BO8AWzlkWyRM7JAFSGBlfig4YVTPsK6MVgqz1uw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.2.tgz", + "integrity": "sha512-4ec2Z/LOmRsAgU23CS4xeJfcJlmRg94A/XrbGRCF1gyU/zdDfRLYDVsS+ynSZCmGNxQ1jQriQOKMQeQxBA3Isw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.1", + "@emnapi/runtime": "^1.11.1", + "@emnapi/wasi-threads": "^1.2.2", + "@napi-rs/wasm-runtime": "^1.1.4", + "@tybys/wasm-util": "^0.10.2", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.2.tgz", + "integrity": "sha512-Zyr/M0+XcYZu3bZrUytc7TXvrk0ftWfl8gN2MwekNDzhqhKRUucMPSeOzM0o0wH5AWOU49BsKRrfKxI2atCPMQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.2", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@types/bun": { + "version": "1.3.14", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.3.14.tgz", + "integrity": "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bun-types": "1.3.14" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.1.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz", + "integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.3.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.63.0", + "@typescript-eslint/type-utils": "8.63.0", + "@typescript-eslint/utils": "8.63.0", + "@typescript-eslint/visitor-keys": "8.63.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.63.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.6", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.63.0", + "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/typescript-estree": "8.63.0", + "@typescript-eslint/visitor-keys": "8.63.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.63.0", + "@typescript-eslint/types": "^8.63.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/visitor-keys": "8.63.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/typescript-estree": "8.63.0", + "@typescript-eslint/utils": "8.63.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.63.0", + "@typescript-eslint/tsconfig-utils": "8.63.0", + "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/visitor-keys": "8.63.0", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "10.2.5", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch/node_modules/brace-expansion": { + "version": "5.0.7", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match": { + "version": "4.0.4", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.63.0", + "@typescript-eslint/types": "8.63.0", + "@typescript-eslint/typescript-estree": "8.63.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.63.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.63.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@wrnexus/ai": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/authz": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/cli": { + "version": "0.2.12", + "dev": true, + "license": "MIT", + "dependencies": { + "@wrnexus/compiler": "^0.2.12", + "@wrnexus/core": "^0.2.12", + "@wrnexus/csr": "^0.2.12", + "@wrnexus/db": "^0.2.12", + "@wrnexus/dev-server": "^0.2.12", + "@wrnexus/i18n": "^0.2.12", + "@wrnexus/router": "^0.2.12", + "@wrnexus/styles": "^0.2.12", + "@wrnexus/ui": "^0.2.12", + "@wrnexus/validation": "^0.2.12" + }, + "bin": { + "wrnexus": "dist/index.js" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/compiler": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/core": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/csr": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/db": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/dev-server": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/compiler": "^0.2.12", + "@wrnexus/core": "^0.2.12", + "@wrnexus/csr": "^0.2.12", + "@wrnexus/db": "^0.2.12", + "@wrnexus/i18n": "^0.2.12", + "@wrnexus/pubsub": "^0.2.12", + "@wrnexus/router": "^0.2.12", + "@wrnexus/ssr": "^0.2.12", + "@wrnexus/styles": "^0.2.12", + "@wrnexus/ui": "^0.2.12", + "@wrnexus/uploader": "^0.2.12", + "@wrnexus/validation": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/encryption": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/i18n": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/jwt": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/mobile": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/native": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/native": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/oauth": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/pubsub": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/queue": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/reactive": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/router": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/compiler": "^0.2.12", + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/ssr": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/styles": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/uploader": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/test": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/tracking": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/ui": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/uploader": { + "version": "0.2.12", + "license": "MIT", + "dependencies": { + "@wrnexus/core": "^0.2.12" + }, + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/@wrnexus/validation": { + "version": "0.2.12", + "license": "MIT", + "engines": { + "bun": ">=1.1.0" + } + }, + "node_modules/acorn": { + "version": "8.17.0", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "1.1.16", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/bun-types": { + "version": "1.3.14", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "1.0.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "detect-libc": "bin/detect-libc.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.21.6", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.5", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "dev": true, + "license": "ISC" + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "dev": true, + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.7.0", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-yaml": { + "version": "4.3.0", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss/node_modules/detect-libc": { + "version": "2.1.2", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "dev": true, + "license": "MIT" + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "dev": true, + "license": "MIT" + }, + "node_modules/optionator": { + "version": "0.9.4", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.9.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.5.tgz", + "integrity": "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.2", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.63.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.63.0.tgz", + "integrity": "sha512-xgwXyzG4sK9ALkBxbyGkTMMOS+imnW65iPhxCQMK83KhxyoDNW7l+IDqEf9vMdoUidHpOoS967RCq4eMiTexwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.63.0", + "@typescript-eslint/parser": "8.63.0", + "@typescript-eslint/typescript-estree": "8.63.0", + "@typescript-eslint/utils": "8.63.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/undici-types": { + "version": "8.3.0", + "dev": true, + "license": "MIT" + }, + "node_modules/uri-js": { + "version": "4.4.1", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..4579c0c6 --- /dev/null +++ b/package.json @@ -0,0 +1,55 @@ +{ + "name": "wrnexusjs", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "wrnexus dev .", + "build": "wrnexus build .", + "test": "bun test app", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "format": "prettier . --write", + "format:check": "prettier . --check", + "check": "bun run lint && bun run test && bun run format:check", + "docs:generate": "bun run scripts/generate-docs.ts" + }, + "dependencies": { + "@wrnexus/ai": "0.2.12", + "@wrnexus/authz": "0.2.12", + "@wrnexus/compiler": "0.2.12", + "@wrnexus/core": "0.2.12", + "@wrnexus/csr": "0.2.12", + "@wrnexus/db": "0.2.12", + "@wrnexus/dev-server": "0.2.12", + "@wrnexus/encryption": "0.2.12", + "@wrnexus/i18n": "0.2.12", + "@wrnexus/jwt": "0.2.12", + "@wrnexus/mobile": "0.2.12", + "@wrnexus/native": "0.2.12", + "@wrnexus/oauth": "0.2.12", + "@wrnexus/pubsub": "0.2.12", + "@wrnexus/queue": "0.2.12", + "@wrnexus/reactive": "0.2.12", + "@wrnexus/router": "0.2.12", + "@wrnexus/ssr": "0.2.12", + "@wrnexus/styles": "0.2.12", + "@wrnexus/test": "0.2.12", + "@wrnexus/tracking": "0.2.12", + "@wrnexus/ui": "0.2.12", + "@wrnexus/uploader": "0.2.12", + "@wrnexus/validation": "0.2.12" + }, + "devDependencies": { + "@eslint/js": "^9.0.0", + "@tailwindcss/cli": "^4.0.0", + "@types/bun": "latest", + "@types/node": "^26.1.1", + "@wrnexus/cli": "0.2.12", + "eslint": "^9.0.0", + "prettier": "latest", + "tailwindcss": "^4.0.0", + "typescript": "^5.5.0", + "typescript-eslint": "latest" + } +} diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 00000000..c2a49f4f --- /dev/null +++ b/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Allow: / diff --git a/public/theme-navigation.js b/public/theme-navigation.js new file mode 100644 index 00000000..5e8a0466 --- /dev/null +++ b/public/theme-navigation.js @@ -0,0 +1,9 @@ +/* global window, document */ + +// Re-bind theme controls after WRNexusJS swaps the page during client navigation. +// bind() is idempotent, so this is safe alongside newer framework runtimes. +window.addEventListener("wrnexus:navigated", function () { + if (window.wireTheme && typeof window.wireTheme.bind === "function") { + window.wireTheme.bind(document); + } +}); diff --git a/scripts/generate-docs.ts b/scripts/generate-docs.ts new file mode 100644 index 00000000..d5db5fe7 --- /dev/null +++ b/scripts/generate-docs.ts @@ -0,0 +1,397 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const root = resolve(import.meta.dir, ".."); +const pages = join(root, "app", "pages"); +const packagePages = join(pages, "packages"); +mkdirSync(packagePages, { recursive: true }); + +const catalog = [ + ["ai", "AI", "Server-side Anthropic client with generation and streaming."], + ["authz", "Security", "Role, permission, policy, and authorization guards."], + ["cli", "Tooling", "Create, develop, build, generate, test, and maintain WrNexus apps."], + ["compiler", "Core", "Parser and code generators for the .wrn language."], + ["core", "Core", "Contexts, middleware, security, sessions, caching, JSX, and realtime."], + ["csr", "Frontend", "Reactive, navigation, and realtime browser runtimes."], + ["db", "Data", "Database adapters, typed queries, models, migrations, and sessions."], + ["dev-server", "Runtime", "Development and production servers, HMR, assets, and gateways."], + ["encryption", "Security", "Hashing, HMAC, authenticated encryption, and key derivation."], + ["i18n", "Frontend", "Translation loading, locale resolution, and Intl formatting."], + ["jwt", "Security", "HS256 JWT signing, verification, and bearer authentication."], + ["mobile", "Native", "SSR-safe compatibility access to Capacitor plugins."], + ["native", "Native", "Cross-platform browser and Capacitor capability registry."], + ["oauth", "Security", "OAuth 2.0, PKCE, provider presets, and profile mapping."], + ["pubsub", "Realtime", "In-process and Redis-backed publish/subscribe."], + ["queue", "Data", "Background jobs with delay, concurrency, retry, and repetition."], + ["reactive", "Frontend", "Small type-safe reactive signal primitives."], + ["router", "Core", "Filesystem discovery, route matching, and typed route generation."], + ["ssr", "Runtime", "Secure HTML document rendering and SEO metadata."], + ["styles", "Frontend", "CSS pipeline, themes, fonts, profiles, and application config."], + ["test", "Tooling", "WrNexus-aware component, route, and browser testing utilities."], + ["tracking", "Runtime", "Error/event capture, middleware, filtering, and sinks."], + ["ui", "Frontend", "Themeable server-rendered UI components and CSS."], + ["uploader", "Data", "Validated local/S3 uploads and secure file serving."], + ["validation", "Security", "Typed schemas, coercion, validation, and browser descriptors."], +] as const; + +const escape = (value: string) => + value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/\{/g, "{") + .replace(/\}/g, "}"); + +function inline(value: string): string { + return escape(value) + .replace(/`([^`]+)`/g, "$1") + .replace(/\*\*([^*]+)\*\*/g, "$1") + .replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '$1'); +} + +interface DocHeading { + id: string; + title: string; + level: number; +} + +function markdown(source: string): { html: string; headings: DocHeading[] } { + const lines = source.replace(/\r/g, "").split("\n"); + const out: string[] = []; + const headings: DocHeading[] = []; + const usedIds = new Map(); + let code: string[] | null = null; + let language = ""; + let list = false; + let paragraph: string[] = []; + let table: string[][] = []; + const flushParagraph = () => { + if (paragraph.length) out.push(`

${inline(paragraph.join(" "))}

`); + paragraph = []; + }; + const closeList = () => { + if (list) out.push(""); + list = false; + }; + const flushTable = () => { + if (!table.length) return; + const separator = table[1]?.every((cell) => /^:?-{3,}:?$/.test(cell.trim())); + const header = separator ? table[0]! : undefined; + const rows = separator ? table.slice(2) : table; + out.push('
'); + if (header) { + out.push( + `${header.map((cell) => ``).join("")}`, + ); + } + out.push( + `${rows.map((row) => `${row.map((cell) => ``).join("")}`).join("")}
${inline(cell.trim())}
${inline(cell.trim())}
`, + ); + table = []; + }; + for (const line of lines) { + if (/^\|.*\|\s*$/.test(line)) { + flushParagraph(); + closeList(); + table.push(line.slice(1, line.lastIndexOf("|")).split("|")); + continue; + } + flushTable(); + const fence = /^```(.*)$/.exec(line); + if (fence) { + flushParagraph(); + closeList(); + if (code) { + out.push( + `
${escape(code.join("\n"))}
`, + ); + code = null; + } else { + code = []; + language = fence[1]!.trim(); + } + continue; + } + if (code) { + code.push(line); + continue; + } + const heading = /^(#{1,4})\s+(.+)$/.exec(line); + if (heading) { + flushParagraph(); + closeList(); + const level = Math.min(4, heading[1]!.length + 1); + const title = heading[2]!.replace(/[`*_]/g, "").trim(); + const base = + title + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, "") || "section"; + const occurrence = usedIds.get(base) ?? 0; + usedIds.set(base, occurrence + 1); + const id = occurrence ? `${base}-${occurrence + 1}` : base; + headings.push({ id, title, level }); + out.push(`${inline(heading[2]!)}`); + continue; + } + const item = /^[-*]\s+(.+)$/.exec(line); + if (item) { + flushParagraph(); + if (!list) out.push("
    "); + list = true; + out.push(`
  • ${inline(item[1]!)}
  • `); + continue; + } + if (!line.trim()) { + flushParagraph(); + closeList(); + continue; + } + if (/^>\s?/.test(line)) { + flushParagraph(); + closeList(); + out.push(`
    ${inline(line.replace(/^>\s?/, ""))}
    `); + continue; + } + if (/^---+$/.test(line.trim())) continue; + paragraph.push(line.trim()); + } + flushParagraph(); + closeList(); + flushTable(); + if (code) out.push(`
    ${escape(code.join("\n"))}
    `); + return { html: out.join("\n"), headings }; +} + +function examplesFrom(readme: string, name: string): string { + const examples = [...readme.matchAll(/```([^\n]*)\n([\s\S]*?)```/g)] + .map((match) => ({ language: match[1]!.trim(), code: match[2]!.trim() })) + .filter((example) => example.code) + .filter( + (example, index, all) => all.findIndex((value) => value.code === example.code) === index, + ) + .slice(0, 4); + if (!examples.length) { + examples.push({ + language: "ts", + code: `import * as packageApi from "@wrnexus/${name}";\n\nconsole.log(packageApi);`, + }); + } + return examples + .map( + (example, index) => + `

    Example ${index + 1}

    ${escape(example.code)}
    `, + ) + .join(""); +} + +function shell(title: string, description: string, content: string, state = ""): string { + const document = `page ${title.replace(/[^A-Za-z0-9]/g, "")} { + seo { + title = "${title.replace(/"/g, "'")}" + description = "${description.replace(/"/g, "'")}" + } +${state} + view { +
    +
    + W WrNexus + + +
    + ${content} +
    WrNexus 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.
    +
    + } +} +`; + return document.replace(/\bWrNexus\b/g, "WRNexusJS"); +} + +const cards = catalog + .map( + ([ + name, + category, + summary, + ]) => ` + ${category}

    @wrnexus/${name}

    ${summary}

    Open documentation → +
    `, + ) + .join("\n"); + +const categories = ["All", ...new Set(catalog.map(([, category]) => category))]; +const categoryButtons = categories + .map((category) => { + const count = + category === "All" + ? catalog.length + : catalog.filter(([, value]) => value === category).length; + return ``; + }) + .join(""); + +writeFileSync( + join(pages, "packages.wrn"), + shell( + "Packages", + "Explore every WrNexus package, API, function, and copy-ready usage example.", + `
    25 focused packages

    Package reference

    Everything in the framework, organized by responsibility and documented from the published 0.2.12 APIs.

    ${categoryButtons}

    Showing {category} packages

    ${cards}
    `, + ' state query = ""\n state category = "All"\n', + ), +); + +for (const [name, category, summary] of catalog) { + const packageRoot = join(root, "node_modules", "@wrnexus", name); + const readmePath = join(packageRoot, "README.md"); + const typesPath = join(packageRoot, "dist", "index.d.ts"); + if (!existsSync(readmePath) || !existsSync(typesPath)) + throw new Error(`Install @wrnexus/${name} before generating docs`); + const readme = readFileSync(readmePath, "utf8").replace(/^#\s+[^\n]+\n?/, ""); + const types = readFileSync(typesPath, "utf8"); + const guide = markdown(readme); + const toc = [ + { id: "guide", title: "Guide", level: 2 }, + ...guide.headings, + { id: "api", title: "Complete API", level: 2 }, + { id: "examples", title: "Examples", level: 2 }, + ] + .map( + (heading) => + `${escape(heading.title)}`, + ) + .join(""); + const content = `
    + +
    ${category}

    @wrnexus/${name}

    ${summary}

    bun add @wrnexus/${name}@0.2.12
    ${guide.html}

    Complete TypeScript API

    This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.

    ${escape(types)}

    Examples

    Copy-ready examples taken from this package's published documentation.

    ${examplesFrom(readme, name)}
    + +
    `; + writeFileSync(join(packagePages, `${name}.wrn`), shell(`@wrnexus/${name}`, summary, content)); +} + +writeFileSync( + join(pages, "index.wrn"), + shell( + "Home", + "WrNexus documentation: build secure, server-rendered, reactive applications with Bun.", + `
    WrNexus 0.2.12

    Build from the server.
    Ship only what matters.

    An SSR-first, Bun-native framework with reactive .wrn components, typed data, realtime rooms, mobile capabilities, and production security built in.

    app/pages/counter.wrn
    page Counter {
    +  state count = 0
    +  view {
    +    <button @click="count++">
    +      Count {count}
    +    </button>
    +  }
    +}

    SSR by default

    Useful HTML reaches the browser immediately. Interactive pages hydrate only the runtime they use.

    Secure foundations

    CSP, Trusted Types, CSRF, sessions, validation, authorization, encryption, and safe rendering are integrated.

    Web to native

    Share markup through Capacitor or compile portable pages into Expo and React Native routes.

    `, + ), +); + +const guides = { + "getting-started": [ + "Getting started", + "Getting started with WrNexus", + `
    Guide

    Getting started

    Create a production-ready WrNexus application with Bun.

    1. Create the project

    bunx @wrnexus/cli create my-app
    +cd my-app
    +bun install
    +bun run dev

    2. Add a page

    page Dashboard {
    +  state count = 0
    +  view {
    +    <main>
    +      <h1>Dashboard</h1>
    +      <button @click="count++">{count}</button>
    +    </main>
    +  }
    +}

    3. Verify and build

    wrnexus doctor
    +wrnexus test
    +wrnexus build

    Where things live

    • app/pages contains routes.
    • app/components contains reusable .wrn components.
    • app/api contains server API handlers.
    • app/layouts contains shared shells.
    • app/middleware contains request middleware.
    • wrnexus.config.ts configures security, styles, data, mobile, and deployment.
    `, + ], + language: [ + "Language and directives", + "Complete WrNexus language reference for events, directives, loops, conditionals, data, components, forms, realtime, and native behavior.", + `
    Complete reference

    Language and directives

    This page documents the .wrn language and declarative browser features that span multiple packages.

    +

    File anatomy

    A file declares a page or component and can contain metadata, props, state, data, view, style, server functions, APIs, and realtime handlers.

    ${escape(`page Dashboard {
    +  layout = "default"
    +  seo { title = "Dashboard" }
    +  state count = 0
    +  view {  }
    +  style { button { padding: 12px; } }
    +}`)}
    +

    State and interpolation

    State is scoped to the nearest generated data-scope. Text expressions update reactively after hydration.

    ${escape(`state count = 0
    +state user = { name: "Ada" }
    +
    +view {
    +  

    Count: {count}

    +

    {user.name}

    +}`)}
    +

    Events

    Any DOM event can use @event="statement". The compiler emits data-on-event. The expression receives event and can mutate state.

    SyntaxPurpose
    @clickPointer or keyboard activation.
    @inputRead live field values.
    @changeReact to committed field changes.
    @submitHandle form submission behavior.
    @browser-clickRun only in a browser target.
    @mobile-clickRun only in a native/mobile target.
    ${escape(`
    +
    +...`)}
    +

    Reactive data attributes

    DirectiveBehavior
    data-scopeDeclares reactive state for a subtree.
    data-textSynchronizes textContent with an expression.
    data-showShows or hides an element by truthiness.
    data-forRepeats an element for a client-side list.
    data-on-<event>Compiled form of an event binding.
    data-componentMounts a server-rendered component.
    data-slotFills a named component or layout slot.
    data-wrnexus-csrConnects generated client data fetching.
    +

    Conditional rendering

    Server conditionals

    Server blocks render only the selected branch into the response.

    ${escape(`{#if user.isAdmin}
    +  Admin
    +{:else if user}
    +  

    Welcome {user.name}

    +{:else} + Sign in +{/if}`)}

    Client visibility

    ${escape(`
    Visible while open is true
    `)}
    +

    Loops and lists

    Server each block

    ${escape(`{#each users as user, i}
    +  

    {i + 1}. {user.name}

    +{:empty} +

    No users

    +{/each}`)}

    Reactive client loop

    ${escape(`
  • + + +
  • `)}
    +

    Components, props, and slots

    ${escape(`component Card {
    +  props { title = "Card" }
    +  view {
    +    

    {title}

    + } +} + +
    +

    Card content

    +
    `)}
    +

    Server and client data

    Use named data bindings for SSR data or client hydration. Secrets and database work stay on the server.

    ${escape(`data users {
    +  ssr GET "/api/users"
    +}
    +
    +view {
    +  {#each users as user}

    {user.name}

    {/each} +}`)}
    +

    Forms and validation

    Schema-backed forms validate in the browser and on the server with the same descriptor.

    ${escape(`
    + + + + +
    `)}
    +

    Internationalization and themes

    ${escape(`

    {t:home.title}

    + + +`)}
    +

    Realtime rooms

    ${escape(`
    + +
    + +
    +
    `)}
    +

    Browser and native directives

    ${escape(`
    +
    +

    Browser instructions

    +`)}
    +

    Other framework attributes

    AttributePurpose
    data-errorField validation error destination.
    data-successSuccessful form message.
    data-redirectNavigation after form success.
    data-room-*Realtime status, templates, sending, and reset behavior.
    data-uploaderConfig-driven upload widget.
    data-wire-theme-*Theme selection and toggling.
    data-wire-lang*Language selection.
    data-native-*Cross-platform capability and visibility behavior.
    `, + ], + architecture: [ + "Architecture", + "Understand the WrNexus SSR, compiler, runtime, and package architecture.", + `
    Concepts

    Architecture

    WrNexus separates server work, generated markup, and browser behavior so applications stay understandable and efficient.

    Request path

    Request → Router → Middleware → Page/API → SSR document → Browser runtime

    Compiler

    The compiler parses .wrn files and lowers state, events, interpolation, loops, conditionals, data bindings, components, and styles into server modules and small declarative browser directives.

    Runtime

    The server owns routing, data, secrets, sessions, validation, uploads, and rendering. The browser owns reactive scopes, navigation, forms, realtime clients, and native capability dispatch.

    Package boundaries

    Each package is independently installable. Start with the CLI and core, then add database, security, realtime, native, UI, and operational packages as required.

    `, + ], +} as const; +for (const [route, [title, description, content]] of Object.entries(guides)) { + writeFileSync(join(pages, `${route}.wrn`), shell(title, description, content)); +} + +console.log( + `Generated ${catalog.length} package pages and ${Object.keys(guides).length + 2} site pages.`, +); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..a24dcdf8 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": [ + "ESNext", + "DOM", + "DOM.Iterable" + ], + "types": [ + "bun" + ], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": false, + "esModuleInterop": true, + "resolveJsonModule": true, + "jsx": "react-jsx", + "jsxImportSource": "@wrnexus/core", + }, + "include": [ + "app", + "wrnexus.config.ts" + ], + "exclude": [ + "node_modules", + "dist", + "**/dist", + "**/.wrnexus" + ] +} \ No newline at end of file diff --git a/wrnexus.config.ts b/wrnexus.config.ts new file mode 100644 index 00000000..0799ddb5 --- /dev/null +++ b/wrnexus.config.ts @@ -0,0 +1,73 @@ +import type { AppConfig } from "@wrnexus/styles"; + +const config: AppConfig = { + // Compatibility bridge for the currently published runtime. It can be + // removed after the navigation-aware theme runtime is released. + head: '', + + mobile: { + enabled: true, + appId: "com.example.wrnexusjs", + appName: "WRNexusJS", + userAgent: "WRNexusJSMobile", + backgroundColor: "#0f172a", + // layout: "mobile", // app/layouts/mobile.wrn + // icon: "resources/icon.png", + }, + + // PWA support is enabled automatically. Override any install metadata here. + pwa: { + name: "WRNexusJS Documentation", + shortName: "WRNexusJS Docs", + display: "standalone", + themeColor: "#6366f1", + backgroundColor: "#0f172a", + }, + + seo: { + title: "WRNexusJS Documentation", + titleTemplate: "%s | WRNexusJS", + description: "Complete documentation for every WRNexusJS package, API, function, and workflow.", + robots: "index,follow", + themeColor: "#6366f1", + }, + + styles: { + entry: "app/styles/global.css", + + // Tailwind v4 build. Runs once at dev-serve time (cached; re-run on restart) + // and at `wrnexus build`. `@tailwindcss/cli` writes to stdout, so we capture + // and return the final CSS. Delete this hook to drop Tailwind — global.css is + // still bundled and served as-is. + process: async ({ entryPath, mode }) => { + const args = ["@tailwindcss/cli", "-i", entryPath!]; + if (mode === "production") args.push("--minify"); + return await Bun.$`bunx ${args}`.text(); + }, + }, + + fonts: { + sans: '"Plus Jakarta Sans", ui-sans-serif, system-ui, sans-serif', + google: [{ family: "Plus Jakarta Sans", weights: [400, 500, 600, 700, 800] }], + }, + + // Fonts — the framework emits optimized markup (preconnect, subsetted + // Google Fonts with font-display, self-hosted @font-face with preload) and + // auto-extends the CSP for Google Fonts. Uncomment to use a custom font: + // + // fonts: { + // sans: '"Plus Jakarta Sans", ui-sans-serif, system-ui, sans-serif', + // google: [{ family: "Plus Jakarta Sans", weights: [400, 500, 600, 700] }], + // // Or self-host (fastest, no third party) — drop files in public/fonts/: + // // local: [{ family: "Plus Jakarta Sans", src: "/fonts/jakarta.woff2", weight: "100 900", preload: true }], + // }, + + // security: { + // cors: { + // enabled: true, + // origin: ["http://localhost:5173"], + // }, + // }, +}; + +export default config;