### Set up Valyrian.js Project with Node.js and Inline Tooling
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
Provides the bash commands to create a new Valyrian.js project, initialize npm, and install the Valyrian.js package. This is the first step for the Node.js path, enabling local JSX/TSX development.
```bash
mkdir my-valyrian-app
cd my-valyrian-app
npm init -y
npm install valyrian.js
```
--------------------------------
### Basic Router Setup in Valyrian.js
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Illustrates the fundamental setup of a router in Valyrian.js using the `Router` class and `mountRouter` function. This example defines a simple router with two routes ('/' and '/about') and mounts it to the 'body' element. It also shows how to create a router with a path prefix and inspect the route table.
```tsx
import { Router, mountRouter } from "valyrian.js/router";
const router = new Router();
router.add("/", () =>
Home
);
router.add("/about", () =>
About
);
mountRouter("body", router);
```
```ts
const apiRouter = new Router("/app");
```
```ts
const routeTable = router.routes();
```
--------------------------------
### Serve Static Files Locally
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
This command uses the 'serve' package (typically installed via npm or npx) to start a local static file server in the current directory. This is useful for testing HTML files and their associated JavaScript, like the Valyrian.js application.
```bash
npx serve .
```
--------------------------------
### Basic Valyrian.js Router Setup
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.1-routing-and-navigation.md
Demonstrates the fundamental setup of a Valyrian.js router. It involves creating a new Router instance, adding routes with their corresponding component handlers, and mounting the router to a specified DOM element. This is the starting point for any Valyrian.js application's routing.
```tsx
import { Router, mountRouter } from "valyrian.js/router";
const router = new Router();
router.add("/", () =>
Home
);
router.add("/about", () =>
About
);
mountRouter("body", router);
```
--------------------------------
### Serve Valyrian.js Distilled App Locally
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
Demonstrates the final step of the Node.js method: building the application using `node build.js` and then serving the generated `dist.js` file via a static server. A minimal HTML file is provided to load the `dist.js` script, allowing the Valyrian.js application to run in the browser.
```bash
node build.js
```
--------------------------------
### Quick Start: Making a GET Request with Valyrian.js
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.2.1-request.md
Demonstrates how to import and use the `request` object to perform a simple GET request to an API endpoint, including passing query parameters. This is the most straightforward way to initiate a request.
```typescript
import { request } from "valyrian.js/request";
const users = await request.get("/api/users", { page: 1 });
```
--------------------------------
### GET /api/users
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Example of making a GET request to fetch users with pagination.
```APIDOC
## GET /api/users
### Description
Fetches a list of users, optionally with pagination parameters.
### Method
GET
### Endpoint
/api/users
### Query Parameters
* **page** (number) - Optional - The page number for pagination.
### Request Example
```ts
import { request } from "valyrian.js/request";
const users = await request.get("/api/users", { page: 1 });
```
### Response
#### Success Response (200)
* **users** (array) - An array of user objects.
* **totalPages** (number) - The total number of pages available.
#### Response Example
```json
{
"users": [
{
"id": 1,
"name": "John Doe"
}
],
"totalPages": 10
}
```
```
--------------------------------
### Render First Component in Browser (Valyrian.js)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
Demonstrates how to use Valyrian.js directly in the browser via ES modules and a CDN. It imports the library, defines a simple App component using `v()` for VNode creation, and mounts it to the 'body'. This method requires no build step and is ideal for quick testing.
```html
Valyrian.js App
```
--------------------------------
### Create Valyrian.js App Entry Point with JSX (index.tsx)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
Shows how to define a Valyrian.js application component using JSX syntax in a TypeScript file (`index.tsx`). It imports the `mount` function and defines an `App` component that renders a simple UI with a button. This file serves as the entry point for the Node.js build process.
```tsx
import { mount } from "valyrian.js";
const App = () => (
Hello World
Built with Valyrian internal tooling.
);
mount("body", App);
```
--------------------------------
### Render 'Hello World' Component with Valyrian.js
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/3-the-essentials.md
Demonstrates the basic render flow by mounting a simple 'Hello World' component to the DOM. This is the starting point for new Valyrian.js users.
```tsx
import { mount } from "valyrian.js";
const App = () => (
Hello World
Welcome to Valyrian.js
);
mount("body", App);
```
--------------------------------
### Valyrian.js Query Client Setup and Fetching
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Shows the initialization of a Valyrian.js QueryClient with configuration options like `staleTime`, `cacheTime`, and persistence. It also demonstrates how to define and fetch data using a query with a specified key and fetcher function.
```typescript
import { QueryClient } from "valyrian.js/query";
const client = new QueryClient({
staleTime: 30000,
cacheTime: 300000,
persist: true,
persistId: "my-cache"
});
const posts = client.query({
key: ["posts", { page: 1 }],
fetcher: () => request.get("/api/posts", { page: 1 })
});
await posts.fetch();
```
--------------------------------
### Install Webpack Dependencies
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Installs Webpack, Webpack CLI, Webpack Dev Server, ts-loader, and html-webpack-plugin as development dependencies.
```bash
npm i -D webpack webpack-cli webpack-dev-server ts-loader html-webpack-plugin
```
--------------------------------
### Create a PulseStore with Actions
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Demonstrates how to create a `PulseStore`, which manages shared state with associated actions. State is immutable outside of actions, and updates are batched for efficiency. It includes an example of an asynchronous action.
```typescript
import { createPulseStore } from "valyrian.js/pulses";
const store = createPulseStore(
{ todos: [], loading: false },
{
addTodo(state, text: string) {
state.todos.push({ text, done: false });
},
async fetchTodos(state) {
state.loading = true;
this.$flush();
const response = await fetch("/api/todos");
state.todos = await response.json();
state.loading = false;
}
}
);
```
--------------------------------
### Basic SSR Setup with Valyrian.js
Source: https://context7.com/masquerade-circus/valyrian.js/llms.txt
Demonstrates how to set up basic Server-Side Rendering (SSR) using Valyrian.js. It covers rendering components to HTML strings on the server and client-side hydration. Dependencies include 'valyrian.js' and 'valyrian.js/node'.
```tsx
import { v } from "valyrian.js";
import { render, ServerStorage } from "valyrian.js/node";
const App = ({ initialState }) => (
Hello from SSR
Current path: {initialState.path}
);
const AppShell = ({ initialState }, children) => {
const serializedState = JSON.stringify(initialState).replace(/
{""}
Valyrian SSR App
{children}
>
);
};
// Express.js handler
app.get("*", (req, res) => {
ServerStorage.run(() => {
const initialState = { path: req.url };
const html = render(
);
res.type("html").send(html);
});
});
// Client-side hydration (client.js)
import { mount } from "valyrian.js";
import { App } from "./app";
mount("body", );
```
--------------------------------
### Build Valyrian.js App using Node.js Inline Utility (build.js)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
A Node.js script (`build.js`) that utilizes Valyrian.js's `inline` utility to process a JSX/TSX entry file (`index.tsx`) and output a single JavaScript file (`dist.js`). This script handles the transformation of JSX into standard JavaScript, enabling a build-free experience for local development.
```javascript
import fs from "fs";
import { inline } from "valyrian.js/node";
async function build() {
const result = await inline("./index.tsx", {
compact: true
});
fs.writeFileSync("./dist.js", result.raw);
}
build().catch((error) => {
console.error(error);
process.exit(1);
});
```
--------------------------------
### Install Rspack Dependencies
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Installs Rspack core, Rspack CLI, and Rspack Dev Server as development dependencies.
```bash
npm i -D @rspack/core @rspack/cli @rspack/dev-server
```
--------------------------------
### Runtime Setup
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/7.1.1-node-runtime-apis.md
Importing 'valyrian.js/node' initializes server-side globals like document, FormData, and storage.
```APIDOC
## Runtime Setup
### Description
Importing `valyrian.js/node` initializes server-side globals.
* `global.document` (lightweight DOM adapter)
* `global.FormData`
* `global.sessionStorage` and `global.localStorage` backed by `ServerStorage`
Import this module before using server-side modules that expect these globals.
### Method
`import`
### Endpoint
`valyrian.js/node`
### Parameters
None
### Request Example
```javascript
import "valyrian.js/node";
```
### Response
No direct response, but initializes global variables.
```
--------------------------------
### Node.js Runtime Setup for Native Stores
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/8.3-native-store.md
Shows the necessary import for Node.js environments to enable native store functionality. This ensures that the required storage globals are available before creating any native stores.
```typescript
import "valyrian.js/node";
import { createNativeStore } from "valyrian.js/native-store";
```
--------------------------------
### Basic Router Setup in Valyrian.js
Source: https://context7.com/masquerade-circus/valyrian.js/llms.txt
Sets up a basic router for Single Page Application navigation in Valyrian.js. It supports static routes, dynamic routes with parameters, query parameters, wildcard routes, and custom error handlers.
```tsx
import { Router, mountRouter, redirect } from "valyrian.js/router";
const router = new Router();
// Static routes
router.add("/", () =>
));
mountRouter("body", router);
```
--------------------------------
### Initialize QueryClient with Options (TypeScript)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.2.4-query.md
Demonstrates how to initialize the QueryClient with various configuration options like staleTime, cacheTime, and persistence settings. This setup is crucial for controlling cache behavior and data freshness.
```typescript
import { QueryClient } from "valyrian.js/query";
const client = new QueryClient({
staleTime: 30000,
cacheTime: 300000,
persist: true,
persistId: "my-cache"
});
```
--------------------------------
### Basic FormStore Initialization with Schema and Transforms
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.3-forms.md
Demonstrates creating a FormStore instance with initial state, validation schema, and clean transforms for email and password fields. This setup ensures data is validated and cleaned upon input.
```tsx
import { FormStore } from "valyrian.js/forms";
const loginForm = new FormStore({
state: { email: "", password: "" },
validationMode: "safe", // default
schema: {
type: "object",
properties: {
email: { type: "string", format: "email" },
password: { type: "string", minLength: 8 }
},
required: ["email", "password"]
},
clean: {
email: (value) => String(value).trim().toLowerCase()
},
onSubmit: async (values) => {
await authApi.login(values as { email: string; password: string });
}
});
```
--------------------------------
### Valyrian.js App Entry Point with Vite
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.1-vite-integration.md
Defines the main application component and mounts it to the DOM using Valyrian.js. This example demonstrates a simple React-like component structure within a Vite project.
```tsx
import { mount, v } from "valyrian.js";
function App() {
return (
Valyrian + Vite
HMR and production bundling are now configured.
);
}
mount("#app", App);
```
--------------------------------
### Install Valyrian.js via npm
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/README.md
This command shows how to add Valyrian.js to your project using npm, the Node Package Manager. After installation, you can proceed with setting up the build process, including TSX/JSX support, by following the project's documentation.
```bash
npm install valyrian.js
```
--------------------------------
### Run Valyrian.js Tests (Bash)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/README.md
Commands to execute tests for the Valyrian.js framework repository. These are intended for contributors developing the framework itself. For application usage, refer to the getting started documentation.
```bash
bun test
```
```bash
bun run dev:test
```
--------------------------------
### Persist Language Selection with Valyrian.js Translate
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/8.1-translate.md
Integrates custom language persistence for the Valyrian.js translate module using `setStoreStrategy`. This allows storing the user's selected language, for example, in `localStorage`. The strategy requires `get` and `set` functions to manage the language data.
```typescript
import { setStoreStrategy } from "valyrian.js/translate";
setStoreStrategy({
get: () => localStorage.getItem("lang") || "en",
set: (lang) => localStorage.setItem("lang", lang)
});
```
--------------------------------
### Minimal HTML to Load Valyrian.js Distilled App
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/2-getting-started.md
A basic HTML file designed to load the `dist.js` file generated by the Valyrian.js Node.js build process. This script tag points to the compiled application, allowing it to run when the HTML page is opened in a browser, typically served locally.
```html
Valyrian App
```
--------------------------------
### Initialize FluxStore with State, Mutations, Actions, and Getters
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/5.3-flux-store.md
Demonstrates the basic initialization of a FluxStore instance with its core components: state, mutations for synchronous state changes, actions for asynchronous operations, and getters for computed state values. This setup is fundamental for managing application state.
```typescript
import { FluxStore } from "valyrian.js/flux-store";
const store = new FluxStore({
state: { count: 0 },
mutations: {
INCREMENT(state, amount: number) {
state.count += amount;
}
},
actions: {
async incrementAsync(store, amount: number) {
await Promise.resolve();
store.commit("INCREMENT", amount);
}
},
getters: {
doubled(state) {
return state.count * 2;
}
}
});
```
--------------------------------
### Install Valyrian.js and TypeScript
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.2-webpack-rspack-integration.md
Installs the Valyrian.js library and TypeScript as development dependencies. This is the initial step for setting up a project that uses Valyrian.js with TypeScript.
```bash
npm i valyrian.js
npm i -D typescript
```
--------------------------------
### Install Valyrian.js in Vite Project
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.1-vite-integration.md
Installs Valyrian.js into a new Vite project initialized with the vanilla-ts template. This sets up the basic project structure and adds the necessary Valyrian.js library.
```bash
npm create vite@latest my-valyrian-vite -- --template vanilla-ts
cd my-valyrian-vite
npm i valyrian.js
```
--------------------------------
### createNativeStore API
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/8.3-native-store.md
Documentation for the `createNativeStore` function, its parameters, and usage.
```APIDOC
## createNativeStore Function
### Description
Provides a small persisted store over `localStorage` or `sessionStorage`.
### Method
`createNativeStore(id, definition?, storageType?, reuseIfExist?)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters Details
* `id` (string) - Required - A unique identifier for the store.
* `definition` (object) - Optional - An object containing the initial state and methods for the store.
* `storageType` (StorageType) - Optional - Specifies the storage type: `StorageType.Local` or `StorageType.Session`.
* `reuseIfExist` (boolean) - Optional - If `true`, returns an existing store for the same `id`; otherwise, creating a store with a duplicate `id` throws an error.
### Request Example
```ts
import { createNativeStore, StorageType } from "valyrian.js/native-store";
const settings = createNativeStore(
"app-settings",
{
state: { theme: "light" },
toggleTheme() {
this.set("theme", this.state.theme === "light" ? "dark" : "light");
}
},
StorageType.Local
);
```
### Response
#### Success Response (200)
Returns a store object with the following API:
* `state` (object) - The current state of the store.
* `set(key, value)` - Sets a value for a given key in the store.
* `get(key)` - Retrieves the value for a given key from the store.
* `delete(key)` - Deletes a key-value pair from the store.
* `load()` - Loads the store state from the underlying storage.
* `clear()` - Clears the entire store.
#### Response Example
```json
{
"state": {
"theme": "light"
}
}
```
### Notes
* Store identity is keyed by `id` in-memory. Creating the same `id` twice throws unless `reuseIfExist` is `true`.
* For `StorageType.Local` in a browser runtime, store state syncs across tabs via the `storage` event.
* `StorageType.Session` does not use cross-tab sync.
* In Node.js, import `valyrian.js/node` before creating native stores so storage globals are available.
```
--------------------------------
### v-model for Local Forms (TypeScript)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Shows a basic example of using the `v-model` directive for two-way data binding on input elements, suitable for lightweight, local form management.
```typescript
const state = { email: "", newsletter: false };
```
--------------------------------
### Core Runtime API
Source: https://context7.com/masquerade-circus/valyrian.js/llms.txt
APIs for mounting components, triggering updates, managing component lifecycles, and safely rendering HTML.
```APIDOC
## Core Runtime API
### mount(container, component)
Mounts a component to a DOM container. Accepts a selector string, DOM element, function component, POJO component with `view()` method, vnode, or plain value. In browsers, the selector resolves via `document.querySelector`. In Node.js, it creates an isolated element per render call for SSR.
#### Method
POST
#### Endpoint
/mount
#### Parameters
##### Request Body
- **container** (string | HTMLElement | Function | Object | VNode | any) - Required - The DOM element or selector to mount the component to.
- **component** (Function | Object | VNode | any) - Required - The component to mount.
#### Request Example
```tsx
import { mount } from "valyrian.js";
// Function component
const App = () =>
Hello Valyrian.js
;
mount("body", App);
// POJO component with state
const Counter = {
count: 0,
view() {
return (
Count: {this.count}
);
}
};
mount("#app", Counter);
// Plain value mount
mount("body", "Hello World");
```
### update() and debouncedUpdate(timeout?)
Triggers a patch pass for the mounted app. Use `update()` when state changes happen outside delegated event handlers or after async operations. `debouncedUpdate(timeout?)` debounces rendering with a default 42ms timeout.
#### Method
POST
#### Endpoint
/update
#### Parameters
##### Query Parameters
- **timeout** (number) - Optional - The debounce timeout in milliseconds for `debouncedUpdate`.
#### Request Example
```tsx
import { update, debouncedUpdate } from "valyrian.js";
const SearchBox = {
term: "",
results: [],
async onInput(event) {
this.term = event.target.value;
debouncedUpdate(80); // Debounce to avoid excessive renders
// Fetch results after user stops typing
const response = await fetch(`/api/search?q=${this.term}`);
this.results = await response.json();
update(); // Manual update after async operation
},
view() {
return (
this.onInput(e)} />
{this.results.map(r =>
{r.name}
)}
);
}
};
```
### Component Lifecycle Helpers
Register lifecycle callbacks inside component render paths: `onCreate`, `onUpdate`, `onCleanup`, and `onRemove`. These throw if called outside component execution.
#### Method
POST
#### Endpoint
/lifecycle
#### Parameters
##### Request Body
- **callbackType** (string) - Required - The type of lifecycle callback (onCreate, onUpdate, onCleanup, onRemove).
- **callback** (Function) - Required - The function to execute for the lifecycle event.
#### Request Example
```tsx
import { onCreate, onUpdate, onCleanup, onRemove } from "valyrian.js";
const Timer = () => {
let seconds = 0;
let timer = null;
onCreate(() => {
console.log("Timer created");
timer = setInterval(() => {
seconds++;
update();
}, 1000);
});
onUpdate(() => {
console.log("Timer updated, seconds:", seconds);
});
onCleanup(() => {
console.log("Cleaning up timer");
if (timer) clearInterval(timer);
});
onRemove(() => {
console.log("Timer removed from DOM");
});
return
Elapsed: {seconds}s
;
};
```
### trust(html)
Parses an HTML string into vnode-compatible children. Only use with trusted/sanitized HTML to prevent XSS attacks.
#### Method
POST
#### Endpoint
/trust
#### Parameters
##### Request Body
- **html** (string) - Required - The HTML string to parse.
#### Request Example
```tsx
import { trust } from "valyrian.js";
const BlogPost = ({ content }) => (
{trust(content)}
);
// Usage
const htmlContent = "
This is bold text.
";
mount("body", );
```
### v-model Directive
Two-way data binding directive that syncs form controls with a model object. Requires a `name` attribute on controls.
#### Method
POST
#### Endpoint
/v-model
#### Parameters
##### Request Body
- **model** (Object) - Required - The object to bind the form controls to.
- **element** (HTMLElement) - Required - The form element.
- **attributeName** (string) - Required - The name of the attribute (e.g., `v-model`).
#### Request Example
```tsx
const state = {
email: "",
password: "",
newsletter: false,
role: "user",
tags: [],
bio: ""
};
const Form = () => (
);
```
```
--------------------------------
### Valyrian.js Context API Usage (TypeScript)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/7.4-server-context.md
Demonstrates how to create, set, get, and run code within a Valyrian.js context scope. This API is designed for server-side request-scoped values.
```typescript
import { createContextScope, getContext, hasContext, setContext, runWithContext } from "valyrian.js/context";
const scope = createContextScope("example");
runWithContext(scope, "value", () => {
console.log(getContext(scope)); // "value"
});
const restore = setContext(scope, "another-value");
restore();
```
--------------------------------
### Client Entry Point and Hydration
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.3-express-fastify-ssr.md
Handles client-side hydration from server-provided state and mounts the router. It initializes the request API and creates the client router instance. Dependencies include 'valyrian.js/router' and 'valyrian.js/request'.
```typescript
import { mountRouter } from "valyrian.js/router";
import { request } from "valyrian.js/request";
import { createClientRouter } from "./app/router";
declare global {
interface Window {
__INITIAL_STATE__?: any;
}
}
const initialState = window.__INITIAL_STATE__ || {};
const api = request.new("", {
headers: { "Content-Type": "application/json" }
});
const router = createClientRouter({ api, initialState });
mountRouter("body", router);
```
--------------------------------
### Task Strategy Selection (JavaScript)
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms.txt
When orchestrating asynchronous operations in Valyrian.js, choosing the appropriate `Task` strategy is important. For UI-related tasks, `takeLatest` is often a suitable starting policy to manage concurrent operations.
```javascript
Task.takeLatest(asyncOperation)
```
--------------------------------
### Verification Commands
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.2-webpack-rspack-integration.md
Commands to verify the Webpack and Rspack integration. Running these commands will start the development servers and build production bundles, allowing for visual and functional checks of the Valyrian.js application.
```bash
npm run dev:webpack
npm run build:webpack
npm run dev:rspack
npm run build:rspack
```
--------------------------------
### Configuring Scoped Clients with Base URLs and Headers
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.2.1-request.md
Demonstrates creating a scoped client with a base URL and default headers. It also shows how to dynamically set and retrieve specific options, such as authorization headers, using helper methods.
```typescript
const api = request.new("/api", {
headers: { "Content-Type": "application/json" },
urls: { base: "", api: "/api", node: "http://localhost:3000" }
});
api.setOption("headers.Authorization", `Bearer ${token}`);
const auth = api.getOption("headers.Authorization");
```
--------------------------------
### Create a Basic Pulse with createPulse
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Shows how to create a simple reactive primitive called a 'pulse' using `createPulse`. It returns a tuple for reading, writing, and manually running subscribers. Updates are only sent when the value changes.
```typescript
import { createPulse } from "valyrian.js/pulses";
const [count, setCount, runSubscribers] = createPulse(0);
setCount((current) => current + 1);
```
--------------------------------
### Client-Side Routing with Valyrian.js
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/9.3-express-fastify-ssr.md
Sets up the client-side router for the application. It creates page instances for each route navigation and reuses user data if hydration state matches the route ID. Dependencies include 'valyrian.js/router'.
```typescript
import { Router } from "valyrian.js/router";
import { createEditUserPage } from "./views/edit-user.page";
type User = { id: string; name: string; email: string };
export type ClientAppContext = {
api: any; // request.new(...)
initialState: {
userId?: string;
user?: User | null;
};
};
export function createClientRouter(ctx: ClientAppContext) {
const router = new Router();
router.add("/", () =>
Home
);
router.add("/users/:id/edit", (req) => {
const id = req.params.id as string;
const initialUser =
ctx.initialState.user && ctx.initialState.userId === id ? (ctx.initialState.user as User) : null;
return createEditUserPage({
api: ctx.api,
userId: id,
initialUser
});
});
router.catch(404, () =>
Not found
);
return router;
}
```
--------------------------------
### Client Entry for Router-Driven SSR
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/7.1-ssr.md
The client-side entry point for applications using the router-driven SSR pattern. It simply imports the main app module, which typically includes the router setup and mounting logic.
```tsx
import "./app";
```
--------------------------------
### Scoped Clients
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/llms-full.txt
Demonstrates how to create and configure scoped clients for specific API base URLs or default options.
```APIDOC
## Scoped Clients and Options
### Description
Allows the creation of isolated `request` instances with predefined base URLs, headers, and other options. This is useful for managing different API endpoints or authentication contexts.
### Creating a Scoped Client
```ts
import { request } from "valyrian.js/request";
const api = request.new("/api", {
headers: { "Content-Type": "application/json" },
urls: { base: "", api: "/api", node: "http://localhost:3000" }
});
// Making a request with the scoped client
await api.get("/users");
```
### Managing Options
* `setOption(path, value)`: Sets a specific option value using a dot-notation path.
* `setOptions(values)`: Sets multiple options at once.
* `getOption(path)`: Retrieves a specific option value.
* `getOptions(path?)`: Retrieves all options or options matching a path.
### Example of Option Management
```ts
const api = request.new("/api");
// Set a header
api.setOption("headers.Authorization", `Bearer ${token}`);
// Get a header
const authHeader = api.getOption("headers.Authorization");
// Set multiple options
api.setOptions({
timeout: 5000,
retries: 3
});
```
### Inheritance
Scoped clients inherit plugins from their parent client. For detailed runtime URL rewriting, refer to [./7.2-isomorphic-networking-and-storage.md](./7.2-isomorphic-networking-and-storage.md).
```
--------------------------------
### Initialize and Run a Task with takeLatest Strategy
Source: https://github.com/masquerade-circus/valyrian.js/blob/main/docs/4.2.3-tasks.md
Demonstrates how to create a new Task instance with the 'takeLatest' strategy and execute it with a payload. The Task wraps an asynchronous function that performs a PUT request. It uses a signal for cancellation.
```TypeScript
import { Task } from "valyrian.js/tasks";
const saveTask = new Task(
async (payload: { name: string }, { signal }) => request.put("/api/profile", payload, { signal }),
{ strategy: "takeLatest" }
);
await saveTask.run({ name: "Arya" });
```