### Setup and Build Commands for Astro Fragno Project
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/astro-example/README.md
Provides essential bash commands for setting up dependencies, starting the development server, building the project for production, and previewing the production build. These commands are standard for pnpm-based Astro projects.
```bash
pnpm install
pnpm run dev
pnpm run build
pnpm run preview
```
--------------------------------
### Create Fragno Fragment with bun
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Quickstart your fragment from scratch using the bun create command. This command initiates the creation of a new Fragno fragment project, setting up the basic structure and necessary files.
```bash
bun create fragno@latest
```
--------------------------------
### Fetch and Display Data with exampleFragment (Vanilla JS)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
This vanilla JavaScript example shows how to subscribe to data changes from 'exampleFragment.useData()'. It updates a DOM element with the fetched data or a loading indicator. Ensure '@your-org/your-package' is installed and an element with id 'data-display' exists.
```javascript
import { exampleFragment } from "@/lib/example-fragment-client";
exampleFragment.useData().subscribe(({ data, loading }) => {
const dataDisplay = document.getElementById("data-display")!;
dataDisplay.textContent = loading ? "loading..." : data;
});
```
--------------------------------
### GET /api/example-fragment/
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/astro-example/README.md
Retrieves a simple 'Hello, world!' message from the example fragment API.
```APIDOC
## GET /api/example-fragment/
### Description
Returns a static 'Hello, world!' greeting.
### Method
GET
### Endpoint
/api/example-fragment/
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **message** (string) - A greeting message.
#### Response Example
```json
{
"message": "Hello, world!"
}
```
```
--------------------------------
### Create Fragno Fragment with npm
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Quickstart your fragment from scratch using the npm create command. This command initiates the creation of a new Fragno fragment project, setting up the basic structure and necessary files.
```bash
npm create fragno@latest
```
--------------------------------
### GET /api/example-fragment/data
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/astro-example/README.md
Fetches the current server-side data managed by the example fragment.
```APIDOC
## GET /api/example-fragment/data
### Description
Retrieves the current server-side data stored within the example fragment.
### Method
GET
### Endpoint
/api/example-fragment/data
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **data** (any) - The current server-side data.
#### Response Example
```json
{
"data": "current_server_data"
}
```
```
--------------------------------
### Fragno ClientBuilder Basic Setup (TypeScript)
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/client-state-management.md
This snippet illustrates the basic setup of Fragno's ClientBuilder in TypeScript. It shows how to create a client instance for the 'todos' fragment and export a hook for the '/todos' GET route. The example verifies that the `useTodos` hook is correctly defined.
```typescript
// should create a basic client builder
export function createTodoClient(fragnoConfig: FragnoPublicClientConfig = {}) {
const builder = createClientBuilder(todoFragment, fragnoConfig, [routes]);
return {
useTodos: builder.createHook("/todos"),
};
}
const client = createTodoClient();
expect(client.useTodos).toBeDefined();
```
--------------------------------
### Setup Database Adapter for Fragno Fragment (TypeScript)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
Configure a database adapter if the fragment requires database integration. This involves installing necessary packages, creating an adapter instance, and passing it during fragment creation.
```typescript
import { KyselyAdapter } from "@fragno-dev/db/adapters/kysely";
import { db } from "./database"; // Your existing Kysely/Drizzle instance
export const fragmentDbAdapter = new KyselyAdapter({
db,
provider: "postgresql", // or "mysql", "sqlite"
});
```
```typescript
import { createExampleFragment } from "@fragno-dev/example-fragment";
import { fragmentDbAdapter } from "./database-adapter";
export function createExampleFragmentInstance() {
return createExampleFragment(
{
someApiKey: process.env.EXAMPLE_API_KEY!,
},
{
databaseAdapter: fragmentDbAdapter,
},
);
}
```
--------------------------------
### Create Solid JS Client Entrypoint for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Establishes the client entrypoint for Solid JS applications. This setup uses `createTodosClients` and the `@fragno-dev/core/solid` hook for integrating the Fragment with Solid JS.
```typescript
import { createTodosClients } from "../fragment";
import { useFragno } from "@fragno-dev/core/solid";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClient(config: FragnoPublicClientConfig = {}) {
return useFragno(createTodosClients(config));
}
```
--------------------------------
### Install Fragno Fragment Package
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
Install the desired fragment package using npm. This is the first step to integrating a fragment into your project.
```npm
npm i @fragno-dev/example-fragment
```
--------------------------------
### Install Stripe Fragment and DB Package (npm)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/stripe/quickstart.mdx
Installs the necessary Stripe fragment and Fragno DB packages using npm. This is the initial step for integrating Stripe functionality into your application.
```bash
npm install @fragno-dev/stripe @fragno-dev/db
```
--------------------------------
### Create Fragno Fragment with yarn
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Quickstart your fragment from scratch using the yarn create command. This command initiates the creation of a new Fragno fragment project, setting up the basic structure and necessary files.
```bash
yarn create fragno@latest
```
--------------------------------
### Install Fragno Core Package with npm
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Install the core Fragno package as a regular dependency using npm. This command adds the necessary Fragno library to your project's dependencies, enabling you to build fragments.
```npm
npm install @fragno-dev/core
```
--------------------------------
### Create Vanilla JavaScript Client Entrypoint for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Sets up the client entrypoint for vanilla JavaScript projects. It integrates the Fragment by using `createTodosClients` and the `@fragno-dev/core/vanilla` hook.
```typescript
import { createTodosClients } from "../fragment";
import { useFragno } from "@fragno-dev/core/vanilla";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClient(config: FragnoPublicClientConfig = {}) {
return useFragno(createTodosClients(config));
}
```
--------------------------------
### Fetch and Display Data with exampleFragment (SolidJS)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
This SolidJS component illustrates fetching data using 'exampleFragment.useData()'. It utilizes Solid's 'Show' component for conditional rendering of loading states and data. Ensure '@your-org/your-package' is installed.
```typescript
import { exampleFragment } from "@/lib/example-fragment-client";
import { Show } from "solid-js";
export default function ExampleComponent() {
const { data, loading } = exampleFragment.useData();
return (
Loading...
{data()}
);
}
```
--------------------------------
### Create React Client Entrypoint for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Sets up the client entrypoint for React applications. It leverages the core `createTodosClients` function and the `@fragno-dev/core/react` hook to integrate the Fragment into a React frontend.
```typescript
import { createTodosClients } from "../fragment";
import { useFragno } from "@fragno-dev/core/react";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClient(config: FragnoPublicClientConfig = {}) {
return useFragno(createTodosClients(config));
}
```
--------------------------------
### Install Shadcn UI Component using npm/pnpm
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/stripe-webshop/CLAUDE.md
This command demonstrates how to install a new component, such as a button, into the project using Shadcn UI's CLI. It requires Node.js and npm/pnpm to be installed. This is a common development task for adding UI elements.
```bash
pnpx shadcn@latest add button
```
--------------------------------
### Create Server-Side Fragment Instance with Fragno
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Creates a server-side fragment instance using the instantiate builder pattern. It configures the fragment with definition, configuration, routes, and options. Dependencies: @fragno-dev/core.
```typescript
import { todosDefinition, type TodosConfig } from "./definition";
import { getTodosRoute } from "./routes/get-todos";
import { addTodoRoute } from "./routes/post-todos";
import { instantiate } from "@fragno-dev/core";
import type { FragnoPublicConfig } from "@fragno-dev/core";
export function createTodos(config: TodosConfig, options: FragnoPublicConfig = {}) {
return instantiate(todosDefinition)
.withConfig(config)
.withRoutes([getTodosRoute, addTodoRoute])
.withOptions(options)
.build();
}
```
--------------------------------
### Install Fragno Packages
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-users/database-fragments/overview.mdx
Installs the core database package for Fragno and the CLI tool for database migrations and schema generation. The CLI is a development dependency.
```bash
npm install @fragno-dev/db
npm install --save-dev @fragno-dev/cli
```
--------------------------------
### Fetch and Display Data with exampleFragment (React)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
This React component demonstrates how to use the 'exampleFragment.useData()' hook to fetch and display data. It handles a loading state by showing 'Loading...' until the data is available. Ensure '@your-org/your-package' is installed.
```typescript
import { exampleFragment } from "@/lib/example-fragment-client";
export default function ExampleComponent() {
const { data, loading } = exampleFragment.useData();
return (
Example Component
{loading ?
Loading...
:
{data}
}
);
}
```
--------------------------------
### Basic KyselyAdapter Setup (SQLite)
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/kysely-adapter.md
Demonstrates the basic setup of a KyselyAdapter using a SQLite dialect and the BetterSQLite3 driver configuration. This is a common pattern for initializing the adapter for SQLite databases.
```typescript
const dialect = new SqliteDialect({
database: new SQLite(":memory:"),
});
export const adapter = new KyselyAdapter({
dialect,
driverConfig: new BetterSQLite3DriverConfig(),
});
```
--------------------------------
### Create Svelte Client Entrypoint for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Configures the client entrypoint for Svelte applications. It imports `createTodosClients` and uses the `@fragno-dev/core/svelte` hook to enable Fragment usage within Svelte components.
```typescript
import { createTodosClients } from "../fragment";
import { useFragno } from "@fragno-dev/core/svelte";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClient(config: FragnoPublicClientConfig = {}) {
return useFragno(createTodosClients(config));
}
```
--------------------------------
### Install Kysely and Fragno DB dependencies
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-users/database-fragments/kysely.mdx
Installs the necessary packages for integrating Kysely with Fragno database fragments. This includes the Kysely query builder and the Fragno database package.
```bash
npm install kysely @fragno-dev/db
```
--------------------------------
### Add ShadCN Components
Source: https://github.com/rejot-dev/fragno/blob/main/packages/jsonforms-shadcn-renderers/README.md
Install required ShadCN UI components using the ShadCN CLI.
```bash
pnpm dlx shadcn@latest add button \
calendar \
card \
checkbox \
field \
input \
label \
popover \
radio-group \
select \
slider \
switch \
tabs \
textarea
```
--------------------------------
### Basic Middleware Setup in Fragno
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-users/middleware.mdx
Demonstrates the basic usage of middleware in Fragno. This example shows how to define a middleware that checks a query parameter and either allows the request to proceed or returns an unauthorized error. It uses `queryParams.get` to access query parameters and `error` to return a response.
```typescript
import { createExampleFragment } from "@fragno-dev/example-fragment";
export function createExampleFragmentInstance() {
return createExampleFragment({
// Fragment-specific config fields
someApiKey: process.env.EXAMPLE_API_KEY!,
}).withMiddleware(async ({ queryParams, path, method }, { error, json }) => {
const q = queryParams.get("q");
if (q === "secret") {
return undefined;
}
return error({ message: "Unauthorized", code: "UNAUTHORIZED" }, 401);
});
}
```
--------------------------------
### Install @fragno-dev/db and @fragno-dev/core
Source: https://github.com/rejot-dev/fragno/blob/main/packages/fragno-db/README.md
Installs the necessary packages for the @fragno-dev/db layer and core Fragno functionality using npm or pnpm.
```bash
npm install @fragno-dev/db @fragno-dev/core
# or
pnpm add @fragno-dev/db @fragno-dev/core
```
--------------------------------
### Install @fragno-dev/cli for migrations
Source: https://github.com/rejot-dev/fragno/blob/main/packages/fragno-db/README.md
Installs the @fragno-dev/cli package as a development dependency for performing database migrations and schema generation.
```bash
npm install --save-dev @fragno-dev/cli
# or
pnpm add --dev @fragno-dev/cli
```
--------------------------------
### Fragno API Authentication Workflow (Bash)
Source: https://github.com/rejot-dev/fragno/blob/main/example-fragments/simple-auth-fragment/test.md
This snippet demonstrates a typical authentication workflow using cURL to interact with the Fragno project's simple authentication API. It includes creating a user, extracting the session ID using `jq`, checking the current user, signing out, and verifying that the session is no longer valid. Ensure `jq` is installed for response parsing.
```bash
# 1. Create a user and save the session ID
RESPONSE=$(curl -s -X POST http://localhost:5173/api/simple-auth/sign-up \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"mypassword123"}')
echo "Sign-up response: $RESPONSE"
# Extract sessionId (requires jq - install with: brew install jq)
SESSION_ID=$(echo $RESPONSE | jq -r '.sessionId')
# 2. Check current user
curl -X GET "http://localhost:5173/api/simple-auth/me?sessionId=$SESSION_ID"
# 3. Sign out
curl -X POST http://localhost:5173/api/simple-auth/sign-out \
-H "Content-Type: application/json" \
-d "{\"sessionId\":\"$SESSION_ID\"}"
# 4. Verify session is invalid
curl -X GET "http://localhost:5173/api/simple-auth/me?sessionId=$SESSION_ID"
```
--------------------------------
### Install Fragno CLI (npm)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/reference/cli.mdx
Installs the Fragno CLI as a development dependency using npm. This command is essential for projects that utilize database-enabled Fragno Fragments.
```bash
npm install --save-dev @fragno-dev/cli
```
--------------------------------
### POST /api/example-fragment/sample
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/astro-example/README.md
Updates the server-side data with new sample data.
```APIDOC
## POST /api/example-fragment/sample
### Description
Updates the server-side data with new sample data. This operation is type-safe and uses Zod schemas.
### Method
POST
### Endpoint
/api/example-fragment/sample
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **newData** (any) - The new data to set on the server.
### Request Example
```json
{
"newData": {
"key": "value"
}
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the update was successful.
- **updatedData** (any) - The data after the update.
#### Response Example
```json
{
"success": true,
"updatedData": {
"key": "value"
}
}
```
```
--------------------------------
### Basic Fragment Instantiation with Builder
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/fragment-instantiation.md
Demonstrates the basic usage of the Fragno builder pattern to instantiate a fragment. It shows how to define fragment configuration and use `instantiate`, `withConfig`, and `withOptions` to build a fragment instance.
```typescript
/** Fragment specific config */
interface AppConfig {
apiKey: string;
}
const fragmentDefinition = defineFragment("api-fragment").build();
// User-facing fragment creator function. This is the main integration point for users of your fragment.
export function createMyFragment(config: AppConfig, options: FragnoPublicConfig = {}) {
return (
instantiate(fragmentDefinition)
.withConfig(config)
/** Options are passed to Fragno internally */
.withOptions(options)
.build()
);
}
// What your user will call to instantiate the fragment:
const instance = createMyFragment({ apiKey: "my-secret-key" }, { mountRoute: "/api/v1" });
expect(instance.name).toBe("api-fragment");
expect(instance.mountRoute).toBe("/api/v1");
```
--------------------------------
### Run Fragno Database Migrations (Bash)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/user-quick-start.mdx
Execute database migrations for Fragno Fragments using the Fragno CLI. This command generates migration files and applies them to your database.
```bash
npx fragno-cli db generate lib/example-fragment-server.ts
npx fragno-cli db migrate lib/example-fragment-server.ts
```
--------------------------------
### GET /todos
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Retrieves a list of todos. It supports filtering by a 'done' query parameter.
```APIDOC
## GET /todos
### Description
Retrieves a list of todos. It supports filtering by a 'done' query parameter.
### Method
GET
### Endpoint
/todos
### Parameters
#### Query Parameters
- **done** (string) - Optional - If set to 'true', only completed todos are returned.
### Request Example
```json
{
"example": "GET /todos?done=true"
}
```
### Response
#### Success Response (200)
- **array of Todo objects** (array) - A list of todo items.
- **id** (string) - The unique identifier for the todo.
- **text** (string) - The content of the todo item.
- **done** (boolean) - Indicates if the todo is completed.
- **createdAt** (string) - The timestamp when the todo was created.
#### Response Example
```json
{
"example": [
{
"id": "1",
"text": "Learn Fragno",
"done": false,
"createdAt": "2023-10-27T10:00:00.000Z"
}
]
}
```
```
--------------------------------
### PGLite Example for KyselyAdapter
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/kysely-adapter.md
Illustrates setting up a KyselyAdapter using the PGLite dialect and its corresponding driver configuration. This is specific to using PGLite for PostgreSQL connections.
```typescript
const { dialect } = await KyselyPGlite.create();
export const adapter = new KyselyAdapter({
dialect,
driverConfig: new PGLiteDriverConfig(),
});
```
--------------------------------
### Define GET /todos Route with Fragno
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Defines a GET route for fetching todos. It uses zod for output schema validation and returns a hardcoded list of todos. The 'done' status is determined by a query parameter. Dependencies: @fragno-dev/core, zod.
```typescript
import { defineRoutes } from "@fragno-dev/core";
import { z } from "zod";
import { TodoSchema, todosDefinition, type Todo } from "../definition";
export const getTodosRoute = defineRoutes(todosDefinition).create(({ defineRoute }) => [
defineRoute({
method: "GET",
path: "/todos",
outputSchema: z.array(TodoSchema),
handler: async ({ query }, { json }) => {
return json([
{
id: "1",
text: "Learn Fragno",
done: query.get("done") === "true",
createdAt: new Date().toISOString(),
},
]);
},
}),
]);
```
--------------------------------
### User Sign-up
Source: https://github.com/rejot-dev/fragno/blob/main/example-fragments/simple-auth-fragment/test.md
Creates a new user account and returns a session ID for the newly created user.
```APIDOC
## POST /api/simple-auth/sign-up
### Description
Creates a new user account with the provided email and password. Upon successful creation, it returns a session ID that can be used for subsequent authenticated requests.
### Method
POST
### Endpoint
/api/simple-auth/sign-up
### Parameters
#### Request Body
- **email** (string) - Required - The email address for the new user.
- **password** (string) - Required - The password for the new user.
### Request Example
```json
{
"email": "user@example.com",
"password": "mypassword123"
}
```
### Response
#### Success Response (200)
- **sessionId** (string) - The unique session identifier for the authenticated user.
#### Response Example
```json
{
"sessionId": "some_session_id_string"
}
```
```
--------------------------------
### Define API Route with Server Handlers in TanStack Start
Source: https://github.com/rejot-dev/fragno/blob/main/example-apps/stripe-webshop/CLAUDE.md
This snippet illustrates how to create an API route ('/api/todos') using TanStack Start, including server-side handlers for GET and POST requests. It shows how to handle request data and return JSON responses. This requires a server environment compatible with TanStack Router.
```tsx
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/api/todos")({
server: {
handlers: {
GET: () => {
return Response.json({ todos: [] });
},
POST: async ({ request }) => {
const data = await request.json();
return Response.json({ success: true });
},
},
},
});
```
--------------------------------
### Get Current User
Source: https://github.com/rejot-dev/fragno/blob/main/example-fragments/simple-auth-fragment/test.md
Retrieves information about the currently authenticated user based on the provided session ID.
```APIDOC
## GET /api/simple-auth/me
### Description
Fetches details of the user associated with the given session ID. This endpoint is used to verify the current logged-in user.
### Method
GET
### Endpoint
/api/simple-auth/me
### Parameters
#### Query Parameters
- **sessionId** (string) - Required - The session ID obtained after successful sign-up or login.
### Response
#### Success Response (200)
- **userId** (string) - The unique identifier for the user.
- **email** (string) - The email address of the user.
#### Response Example
```json
{
"userId": "user_123",
"email": "user@example.com"
}
```
```
--------------------------------
### POST /todos
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Adds a new todo item to the list. Optionally, it can summarize the todo text using an AI service.
```APIDOC
## POST /todos
### Description
Adds a new todo item to the list. Optionally, it can summarize the todo text using an AI service.
### Method
POST
### Endpoint
/todos
### Parameters
#### Query Parameters
- **summarize** (string) - Optional - If present, the text of the new todo will be summarized using an AI service.
#### Request Body
- **text** (string) - Required - The content of the todo item to be created.
### Request Example
```json
{
"example": {
"text": "Buy groceries"
}
}
```
### Response
#### Success Response (200)
- **Todo object** (object) - The newly created todo item.
- **id** (string) - The unique identifier for the todo.
- **text** (string) - The content of the todo item.
- **done** (boolean) - Indicates if the todo is completed.
- **createdAt** (string) - The timestamp when the todo was created.
#### Response Example
```json
{
"example": {
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"text": "Buy groceries",
"done": false,
"createdAt": "2023-10-27T10:05:00.000Z"
}
}
```
#### Error Response (503)
- **Error object** (object) - Returned when the AI summarization service fails.
- **message** (string) - "Summary error"
- **code** (string) - "SUMMARY_ERROR"
```
--------------------------------
### Upgrade Subscription Client Mutation (TypeScript)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/stripe/quickstart.mdx
Demonstrates how to use the `upgradeSubscription` mutator from the Stripe client to initiate a subscription. It takes a `priceId`, `successUrl`, and `cancelUrl` as input and handles redirection to the Stripe Checkout Portal.
```typescript
import { stripeClient } from "@/lib/stripe-client";
export function SubscribeButton() {
const { mutate, loading, error } = stripeClient.upgradeSubscription();
const handleSubscribe = async () => {
const { url, redirect } = await mutate({
body: {
priceId: "price_1234567890", // The Stripe price ID being subscribed to
successUrl: `${window.location.origin}/success`,
cancelUrl: window.location.href,
},
});
if (redirect) {
window.location.href = url; // Redirect to Stripe Checkout Portal
}
};
return (
);
}
```
--------------------------------
### Fragno createHook for GET Routes (TypeScript)
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/client-state-management.md
This example details the creation of read-only query hooks for GET routes using Fragno's `createHook` method. It demonstrates how to instantiate a client and access the `useTodos` hook, verifying that the hook exposes `store` and `query` methods for interacting with the data.
```typescript
// should create a hook for GET routes
export function createTodoClient(fragnoConfig: FragnoPublicClientConfig = {}) {
const builder = createClientBuilder(todoFragment, fragnoConfig, [routes]);
return {
useTodos: builder.createHook("/todos"),
};
}
const client = createTodoClient();
const hook = client.useTodos;
// Hook has store and query methods
expect(hook.store).toBeDefined();
expect(hook.query).toBeDefined();
```
--------------------------------
### Framework Client Adapters for Fragno
Source: https://context7.com/rejot-dev/fragno/llms.txt
Illustrates how to use framework-specific client adapters provided by Fragno to integrate fragment functionality into different frontend frameworks. This includes examples for Vue, Solid.js, Svelte, and Vanilla JavaScript (using nanostores).
```typescript
// Vue Composition API
import { createExampleFragmentClient } from "@fragno-dev/example-fragment/vue";
const { useData } = createExampleFragmentClient();
// In Vue component
const { data, loading } = useData({ query: { filter: "active" } });
```
```typescript
// Solid.js
import { createExampleFragmentClient } from "@fragno-dev/example-fragment/solid";
const { useData } = createExampleFragmentClient();
// In Solid component
const dataResource = useData();
```
```typescript
// Svelte
import { createExampleFragmentClient } from "@fragno-dev/example-fragment/svelte";
const { useData } = createExampleFragmentClient();
// In Svelte component - hooks return Svelte stores
const dataStore = useData();
// $dataStore.data, $dataStore.loading in template
```
```typescript
// Vanilla JavaScript (nanostores)
import { createExampleFragmentClient } from "@fragno-dev/example-fragment/vanilla";
const { useData } = createExampleFragmentClient();
const store = useData();
store.subscribe((value) => {
console.log("Data:", value.data);
console.log("Loading:", value.loading);
});
```
--------------------------------
### Todo App Example with Fragno in Vanilla JS
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-users/client-frameworks/vanilla-js.mdx
Demonstrates a practical implementation of Fragno in a vanilla JavaScript Todo application. It shows how to access and subscribe to data stores (e.g., `todosStore`, `addTodoStore`), handle loading and error states, render lists, and trigger mutations.
```javascript
import { exampleFragment } from "@/lib/example-fragment-client";
// Access the stores
const todosStore = exampleFragment.useTodos();
const addTodoStore = exampleFragment.useAddTodo();
// Subscribe to todos data - this will update UI immediately and on changes
todosStore.subscribe(({ data: todos, loading, error }) => {
if (loading) {
document.getElementById("loading").style.display = "block";
} else {
document.getElementById("loading").style.display = "none";
if (error) {
document.getElementById("error").textContent = error.message;
} else {
renderTodos(todos);
}
}
});
// Listen only to changes (not initial state) for analytics
todosStore.listen(({ data: todos }) => {
// Track when todos change for analytics
analytics.track("todos_updated", { count: todos?.length || 0 });
});
// Trigger actions
document.getElementById("add-todo").addEventListener("click", async () => {
await addTodoStore.mutate({ body: { text: "New todo" } });
});
function renderTodos(todos) {
const container = document.getElementById("todos");
container.innerHTML =
todos?.map((todo) => `
${todo.text} - ${todo.done ? "Done" : "Pending"}
`).join("") ||
"";
}
```
--------------------------------
### Usage Example with JSONForms React
Source: https://github.com/rejot-dev/fragno/blob/main/packages/jsonforms-shadcn-renderers/README.md
Integrate the shadcnRenderers and shadcnCells into your React application by passing them to the JsonForms component. This enables the use of ShadCN UI components within your JSONForms.
```typescript
import { JsonForms } from "@jsonforms/react";
import {
shadcnRenderers,
shadcnCells,
} from "@fragno-dev/jsonforms-shadcn-renderers";
function MyDynamicForm() {
return (
setData(data)}
/>
);
}
```
--------------------------------
### Shared Adapter Configuration Example (TypeScript)
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/database-adapters.md
Shows how multiple fragments (`Fragment1Config`, `Fragment2Config`) can utilize the same `DatabaseAdapter` instance. This promotes efficient resource usage by sharing a single database connection across different parts of the application.
```typescript
declare const adapter: DatabaseAdapter;
// All fragments use the same adapter
export interface Fragment1Config {
databaseAdapter: typeof adapter;
}
export interface Fragment2Config {
databaseAdapter: typeof adapter;
}
```
--------------------------------
### Create Vue Client Entrypoint for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Provides the client entrypoint for Vue.js applications. This file utilizes the `createTodosClients` function and the `@fragno-dev/core/vue` hook for seamless integration within a Vue project.
```typescript
import { createTodosClients } from "../fragment";
import { useFragno } from "@fragno-dev/core/vue";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClient(config: FragnoPublicClientConfig = {}) {
return useFragno(createTodosClients(config));
}
```
--------------------------------
### Define Fragment Schema and Types in TypeScript
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Define the schema for a 'todos' fragment using Zod for validation and TypeScript for type safety. This includes defining the structure of a Todo item and its associated configuration.
```typescript
import { defineFragment } from "@fragno-dev/core";
import { z } from "zod";
export const TodoSchema = z.object({
id: z.string(),
text: z.string(),
done: z.boolean(),
createdAt: z.string(),
});
export type Todo = z.infer;
// Any configuration the users of your Fragment will need to provide
export interface TodosConfig {
openaiApiKey: string;
onTodoCreated?: (todo: Todo & { textSummary?: string }) => void;
}
export const todosDefinition = defineFragment("todos-fragment").build();
```
--------------------------------
### Defining a Fragno Fragment and Client (Core)
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/blog/.welcome-to-fragno.mdx
Illustrates the author-side experience of defining a Fragno fragment, including routes and their handlers, and creating a corresponding client with reactive hooks. It uses Nanostores for reactivity and TanStack Query-like ergonomics.
```typescript
import { defineFragment, defineRoute, createFragment } from "@fragno-dev/core";
import { createClientBuilder } from "@fragno-dev/core/client";
const todos = defineFragment<{ onTodoCreated?: (todo: Todo) => void }>("todos");
const getTodos = defineRoute({
method: "GET",
path: "/todos",
outputSchema: TodoSchema,
handler: async ({ query }, { json }) => json([]),
});
export function createTodos(config: { onTodoCreated?: (todo: Todo) => void }) {
return createFragment(todos, config, [getTodos]);
}
export function createTodosClient() {
const cb = createClientBuilder(todos, {}, [getTodos]);
return {
useTodos: cb.createHook("/todos"),
// Mutations: cb.createMutator("POST", "/todos")
} as const;
}
```
--------------------------------
### Create Client Hooks for Fragment
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Defines the client-side hooks for interacting with the Fragment's routes. This function uses a builder to create hooks for fetching and mutating data, supporting multiple frontend frameworks.
```typescript
import { todosDefinition } from "./definition";
import { getTodosRoute } from "./routes/get-todos";
import { addTodoRoute } from "./routes/post-todos";
import { createClientBuilder } from "@fragno-dev/core/client";
import type { FragnoPublicClientConfig } from "@fragno-dev/core/client";
export function createTodosClients(fragnoConfig: FragnoPublicClientConfig) {
const cb = createClientBuilder(todosDefinition, fragnoConfig, [getTodosRoute, addTodoRoute]);
return {
useTodos: cb.createHook("/todos"),
useAddTodo: cb.createMutator("POST", "/todos"),
};
}
```
--------------------------------
### Fragno Imports and Setup for Database Operations
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/src/subjects/database-querying.md
Imports necessary modules from Fragno for defining fragments, interacting with databases, schema definition, and testing. It sets up a test fragment with a SQLite database adapter.
```typescript
import { defineFragment, instantiate } from "@fragno-dev/core";
import { withDatabase } from "@fragno-dev/db";
import { schema, idColumn, column } from "@fragno-dev/db/schema";
import type { SimpleQueryInterface } from "@fragno-dev/db/query";
import { buildDatabaseFragmentsTest } from "@fragno-dev/test";
// Example schema for testing
const userSchema = schema((s) => {
return s
.addTable("users", (t) => {
return t
.addColumn("id", idColumn())
.addColumn("email", column("string"))
.addColumn("name", column("string"))
.addColumn("age", column("integer").nullable())
.createIndex("idx_email", ["email"], { unique: true });
})
.addTable("posts", (t) => {
return t
.addColumn("id", idColumn())
.addColumn("title", column("string"))
.addColumn("content", column("string"))
.addColumn("authorId", column("string"))
.addColumn("publishedAt", column("timestamp").nullable())
.createIndex("idx_author", ["authorId"]);
});
});
type UserSchema = typeof userSchema;
// Create a test fragment with database
const testFragmentDef = defineFragment<{}>("test-fragment")
.extend(withDatabase(userSchema))
.providesBaseService(() => ({}))
.build();
const { fragments, test } = await buildDatabaseFragmentsTest()
.withTestAdapter({ type: "kysely-sqlite" })
.withFragment("test", instantiate(testFragmentDef).withConfig({}).withRoutes([]))
.build();
const db = fragments.test.db;
```
--------------------------------
### Fragno CLI Usage Examples
Source: https://github.com/rejot-dev/fragno/blob/main/packages/corpus/README.md
Provides examples of how to use the Fragno CLI to view corpus subjects. Demonstrates viewing a single subject, showing headings and code block IDs with line numbers, specifying line ranges, and viewing multiple subjects.
```bash
# View a subject
fragno-cli corpus database-querying
# Show only headings and code block IDs with line numbers
fragno-cli corpus --headings database-querying
# Show specific line range with line numbers
fragno-cli corpus --line-numbers --start 1 --end 50 database-querying
# Multiple subjects (automatically ordered by subject tree)
fragno-cli corpus database-adapters kysely-adapter
```
--------------------------------
### Add Dependencies to Fragment Definition in TypeScript
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Define dependencies for a Fragno fragment, such as an AI wrapper, using the `withDependencies` method. This allows private access to services and configurations within the fragment's server-side logic.
```typescript
import { defineFragment } from "@fragno-dev/core";
import { MyOpenAIWrapper } from "./lib/my-openai-wrapper";
export const todosDefinition = defineFragment("todos-fragment")
.withDependencies(({ config }) => {
return {
aiWrapper: new MyOpenAIWrapper({
apiKey: config.openaiApiKey,
}),
};
})
.build();
```
--------------------------------
### Creating Records with `create`
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/database-integration/querying.mdx
Demonstrates the process of creating new records in the 'users' and 'posts' tables using the `create` method. It shows how to schedule creations and wait for mutations to complete. Columns with `defaultTo$()` are automatically populated.
```typescript
const uow = this.uow(mySchema);
// Schedule create
const userId = uow.create("users", {
name: "Alice",
email: "alice@example.com",
age: 25,
});
// Wait until the handler commits (or call executeMutate() if you're in a handler)
await uow.mutationPhase;
// Columns with defaultTo$() are auto-populated
uow.create("posts", {
title: "My Post",
content: "Content here",
userId: userId.toString(),
// createdAt auto-generated via defaultTo$("now")
});
await uow.mutationPhase;
```
--------------------------------
### Integrate Fragno Server with Next.js
Source: https://context7.com/rejot-dev/fragno/llms.txt
This section illustrates how to set up a Fragno server within a Next.js application. It involves creating a server instance using `createExampleFragment` and then exposing its handlers for Next.js API routes. The `handlersFor("next-js")` method is used to generate the necessary route handlers.
```typescript
// lib/example-fragment-server.ts
import { createExampleFragment } from "@fragno-dev/example-fragment";
export function createExampleFragmentServer() {
return createExampleFragment(
{ initialData: "Server-side data" },
{ mountRoute: "/api/example-fragment" }
);
}
// app/api/example-fragment/[...all]/route.ts
import { createExampleFragmentServer } from "@/lib/example-fragment-server";
export const { GET, POST, PUT, PATCH, DELETE } =
createExampleFragmentServer().handlersFor("next-js");
```
--------------------------------
### Define POST /todos Route with Fragno
Source: https://github.com/rejot-dev/fragno/blob/main/apps/docs/content/docs/fragno/for-library-authors/getting-started.mdx
Defines a POST route for adding a new todo. It validates input using zod, supports an optional 'summarize' query parameter via an AI wrapper dependency, and handles potential summary errors. Dependencies: @fragno-dev/core, zod.
```typescript
import { defineRoutes } from "@fragno-dev/core";
import { z } from "zod";
import { TodoSchema, todosDefinition, type Todo } from "../definition";
export const addTodoRoute = defineRoutes(todosDefinition).create(
({ config, deps, defineRoute }) => {
const { aiWrapper } = deps;
return [
defineRoute({
method: "POST",
path: "/todos",
inputSchema: z.object({ text: z.string() }),
outputSchema: TodoSchema,
queryParameters: ["summarize"],
errorCodes: ["SUMMARY_ERROR"],
handler: async ({ input, query }, { json, error }) => {
const { text } = await input.valid();
const todo = {
id: crypto.randomUUID(),
text,
done: false,
createdAt: new Date().toISOString(),
} satisfies Todo;
let textSummary: string | undefined;
try {
textSummary = query.get("summarize") ? await aiWrapper.summarizeText(text) : undefined;
} catch {
return error({ message: "Summary error", code: "SUMMARY_ERROR" }, 503);
}
// Call the user's callback if provided
config?.onTodoCreated?.({
...todo,
textSummary,
});
return json(todo);
},
}),
];
},
);
```