### Running the Kakera Example Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Instructions for setting up and running the example application. This includes installing dependencies and starting the development server. ```sh cd example bun install bun run dev # wrangler dev (runs [build] automatically, watches routes/) bun run deploy # wrangler deploy ``` -------------------------------- ### Example Project Setup Source: https://github.com/yusukebe/kakera/blob/main/README.md Commands to set up and run the example Kakera project locally. ```sh cd example bun install bun run dev ``` -------------------------------- ### Complete Project Setup for Kakera Worker Source: https://context7.com/yusukebe/kakera/llms.txt Step-by-step guide to setting up a new project with Kakera Worker, including dependency installation, creating the host worker, defining routes with Hono, and creating the build script. This covers the essential files and commands. ```sh # 1. Create project mkdir my-app && cd my-app bun init -y # 2. Install dependencies bun add kakera-worker hono bun add -d wrangler typescript @cloudflare/workers-types # 3. Create host worker mkdir src echo 'export { app as default } from "kakera-worker"' > src/app.ts # 4. Create routes mkdir routes cat > routes/index.ts << 'EOF' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello!')) export default app EOF cat > routes/users.ts << 'EOF' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.json({ users: [] })) app.get('/:id', (c) => c.json({ id: c.req.param('id') })) export default app EOF # 5. Create build script cat > build.ts << 'EOF' import { Glob } from 'bun' const entrypoints = [...new Glob('routes/*.{ts,tsx}').scanSync('.')] const result = await Bun.build({ entrypoints, outdir: './dist', target: 'browser', format: 'esm' }) if (!result.success) { for (const log of result.logs) console.error(log); process.exit(1) } EOF # 6. wrangler.jsonc already shown above # 7. Run locally — wrangler runs [build].command automatically bun run dev # → GET http://localhost:8787/ → "Hello!" # → GET http://localhost:8787/users → {"users":[]} # → GET http://localhost:8787/users/42 → {"id":"42"} ``` -------------------------------- ### Install Kakera Worker Source: https://github.com/yusukebe/kakera/blob/main/README.md Install the kakera-worker package using npm. ```sh npm i kakera-worker ``` -------------------------------- ### Define a Route with Hono Source: https://github.com/yusukebe/kakera/blob/main/README.md Example of a route file defining a Hono application for handling requests. This file would typically be placed in the 'routes/' directory. ```ts // routes/users.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.json({ users: [] })) app.get('/:id', (c) => c.json({ id: c.req.param('id') })) export default app ``` -------------------------------- ### Index Route Handler with Hono Tiny Source: https://context7.com/yusukebe/kakera/llms.txt Example of an index route file (`routes/index.ts`) using Hono Tiny to handle the root path. This route handles requests to the base URL. ```typescript // routes/index.ts — handles GET / import { Hono } from 'hono/tiny' const app = new Hono() app.get('/', (c) => c.text('Hello from kakera!')) export default app ``` -------------------------------- ### User Route Handler with Hono Source: https://context7.com/yusukebe/kakera/llms.txt Example of a route file (`routes/users.ts`) using Hono to handle requests. The host worker strips the first path segment, so this route handles paths relative to `/users`. ```typescript // routes/users.ts import { Hono } from 'hono' const app = new Hono() // Receives GET / (original request was GET /users) app.get('/', (c) => { return c.json({ users: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ] }) }) // Receives GET /42 (original request was GET /users/42) app.get('/:id', (c) => { const id = c.req.param('id') return c.json({ id, name: `User ${id}` }) }) export default app ``` -------------------------------- ### Example Route Module with Hono Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Define a route module by default-exporting a fetch handler, typically an instance of a framework like Hono. The host worker strips the first path segment, so the route module receives requests relative to its own path. ```typescript // routes/users.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.json({ users: [] })) app.get('/:id', (c) => c.json({ id: c.req.param('id') })) export default app ``` -------------------------------- ### Bun Build Script for Kakera Routes Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Use a Bun script to bundle route files into individual ESM modules. This script uses `Bun.Glob` to find entrypoints and `Bun.build` to create the bundles, targeting the browser environment. It includes error handling for the build process. ```typescript // build.ts import { Glob } from 'bun' const entrypoints = [...new Glob('routes/*.{ts,tsx}').scanSync('.')] const result = await Bun.build({ entrypoints, outdir: './dist', target: 'browser', format: 'esm' }) if (!result.success) { for (const log of result.logs) console.error(log) process.exit(1) } ``` -------------------------------- ### Per-Route Bundling Script (`build.ts`) Source: https://context7.com/yusukebe/kakera/llms.txt This script uses Bun.Glob to find route files and Bun.build to compile each into an ESM bundle. Dependencies are inlined, suitable for a Worker Loader that receives one module per route. Ensure `target` is 'browser' for Workerd. ```typescript // build.ts import { Glob } from 'bun' const entrypoints = [...new Glob('routes/*.{ts,tsx}').scanSync('.')] const result = await Bun.build({ entrypoints, outdir: './dist', target: 'browser', // correct for workerd (V8, no Node built-ins) format: 'esm' }) if (!result.success) { for (const log of result.logs) console.error(log) process.exit(1) } // Output: dist/index.js, dist/users.js, dist/posts.js ... ``` ```json { "scripts": { "dev": "wrangler dev", "build": "bun run build.ts", "deploy": "wrangler deploy" } } ``` -------------------------------- ### Configure Route File Extensions Source: https://github.com/yusukebe/kakera/blob/main/README.md Customize the file extensions that Kakera should consider as route entry points using the 'extensions' option. ```ts kakera({ extensions: ['js', 'mjs'] }) ``` -------------------------------- ### NPM Scripts for Development and Deployment Source: https://github.com/yusukebe/kakera/blob/main/README.md Defines NPM scripts for common development tasks: 'dev' to run the development server, 'build' to bundle routes, and 'deploy' to deploy to Cloudflare. ```json { "scripts": { "dev": "wrangler dev", "build": "bun run build.ts", "deploy": "wrangler deploy" } } ``` -------------------------------- ### Kakera Public API Imports Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Import core Kakera components like the default app instance, the kakera factory function, and type definitions for bindings and options. Use the zero-config path by exporting `app` directly. ```typescript import { app, kakera, type KakeraBindings, type KakeraOptions } from 'kakera-worker' ``` -------------------------------- ### Bun Build Script for Routes Source: https://github.com/yusukebe/kakera/blob/main/README.md A build script using Bun's Glob API to find and bundle all TypeScript and TSX route files in the 'routes/' directory into the 'dist/' directory. ```ts // build.ts import { Glob } from 'bun' const entrypoints = [...new Glob('routes/*.{ts,tsx}').scanSync('.')] const result = await Bun.build({ entrypoints, outdir: './dist', target: 'browser', format: 'esm' }) if (!result.success) { for (const log of result.logs) console.error(log) process.exit(1) } ``` -------------------------------- ### Wrangler Configuration for Kakera Source: https://github.com/yusukebe/kakera/blob/main/README.md Wrangler configuration file specifying the main entry point, build command, asset directory, and worker loader binding for a Kakera application. ```jsonc // wrangler.jsonc { "name": "my-app", "main": "src/app.ts", "build": { "command": "bun run build", "watch_dir": "routes" }, "assets": { "directory": "dist", "binding": "ASSETS" }, "worker_loaders": [{ "binding": "LOADER" }], "compatibility_date": "2026-03-17" } ``` -------------------------------- ### Host Worker Entry Point Source: https://github.com/yusukebe/kakera/blob/main/README.md The default host worker entry point, re-exporting the app from 'kakera-worker'. ```ts // src/app.ts export { app as default } from 'kakera-worker' ``` -------------------------------- ### Host Worker with Options Source: https://github.com/yusukebe/kakera/blob/main/README.md Configure the kakera worker with options, such as specifying a different directory for route fetching. ```ts import { kakera } from 'kakera-worker' export default kakera({ dir: 'subdir' }) // fetches subdir/.js via ASSETS ``` -------------------------------- ### Wrangler Configuration for Kakera Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Configure Wrangler to use Kakera by specifying the main entry point, build command, asset directory for bundles, and worker loader bindings. Ensure the compatibility date is set appropriately. ```json { "main": "src/app.ts", "build": { "command": "bun run build", "watch_dir": "routes" }, "assets": { "directory": "dist", "binding": "ASSETS" }, "worker_loaders": [{ "binding": "LOADER" }], "compatibility_date": "2026-03-17" } ``` -------------------------------- ### KakeraOptions Configuration Shape Source: https://context7.com/yusukebe/kakera/llms.txt Define `KakeraOptions` to configure the `dir` (asset path prefix) and `extensions` (probed file extensions) for the `kakera()` factory. ```typescript import { kakera, type KakeraOptions } from 'kakera-worker' const options: KakeraOptions = { dir: 'routes', extensions: ['js', 'mjs'] } export default kakera(options) // A request to /users/42 will probe: // ASSETS /routes/users.js → if 200, load and forward /42 // ASSETS /routes/users.mjs → fallback // 404 if neither found ``` -------------------------------- ### Kakera Worker Dispatch Flow Source: https://context7.com/yusukebe/kakera/llms.txt Illustrates how the host worker extracts the route name, fetches the bundle from ASSETS, and uses the LOADER cache. On a cache miss, the bundle source is fetched and provided as a single module. This simplified implementation shows the core logic. ```plaintext GET /users/42 │ ├─ routeName = "users" ├─ env.ASSETS.fetch HEAD /users.js → 200 OK ├─ env.LOADER.get("users", loader) │ └─ cache miss → fetch GET /users.js → pass source as { "index.js": "" } ├─ subPath = "/42" └─ worker.getEntrypoint().fetch(new Request("/42", original)) ``` ```typescript // Simplified internal implementation (src/index.ts) import { kakera, type KakeraBindings } from 'kakera-worker' // The factory returns this handler: const handler: ExportedHandler = { async fetch(request, env) { const url = new URL(request.url) const segments = url.pathname.split('/').filter(Boolean) const routeName = segments[0] || 'index' // "/" → "index" // Probe extensions in order let path: string | null = null for (const ext of ['js']) { const res = await env.ASSETS.fetch( new Request(`http://dummy/${routeName}.${ext}`, { method: 'HEAD' }) ) if (res.ok) { path = `${routeName}.${ext}`; break } } if (path === null) return new Response('Not Found', { status: 404 }) // Load (or retrieve cached) isolated worker const worker = env.LOADER.get(routeName, async () => { const res = await env.ASSETS.fetch(new Request(`http://dummy/${path}`)) return { compatibilityDate: '2026-03-24', mainModule: 'index.js', modules: { 'index.js': await res.text() }, globalOutbound: null } }) // Strip first segment, forward the rest const subPath = '/' + segments.slice(1).join('/') const forwarded = new URL(subPath + url.search, url.origin) return worker.getEntrypoint().fetch(new Request(forwarded, request)) } } ``` -------------------------------- ### Custom Kakera Factory with Options Source: https://context7.com/yusukebe/kakera/llms.txt Use the `kakera` factory function to customize asset directory and file extensions. This factory is tree-shakeable. ```typescript // src/app.ts — serve bundles from a subdirectory and support both .js and .mjs import { kakera } from 'kakera-worker' export default kakera({ dir: 'workers', extensions: ['js', 'mjs'] }) ``` -------------------------------- ### Pure Annotation for Tree-Shaking Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md Use `/* @__PURE__ */` annotations to help bundlers tree-shake exported variables when they are not directly used. This is a cheap optimization to keep. ```typescript export const app = /* @__PURE__ */ kakera() ``` -------------------------------- ### Kakera Public API Source: https://github.com/yusukebe/kakera/blob/main/AGENTS.md The public API of the kakera-worker package includes imports for `app`, `kakera`, `KakeraBindings`, and `KakeraOptions`. `app` is a pre-built default handler, while `kakera` is a factory function for creating custom handlers. `KakeraBindings` defines the required Cloudflare Worker bindings, and `KakeraOptions` allows customization of the worker's directory and file extensions. ```APIDOC ## Imports ```ts import { app, kakera, type KakeraBindings, type KakeraOptions } from 'kakera-worker' ``` ### `app` - **Description**: A pre-built default `ExportedHandler` instance. This is the zero-configuration entry point for Kakera. - **Usage**: `export { app as default } from 'kakera-worker'` ### `kakera(options?)` - **Description**: A factory function that returns an `ExportedHandler`. Use this when you need to override default options like `dir` or `extensions`. - **Parameters**: - `options` (KakeraOptions) - Optional. Configuration options for the Kakera handler. ### `KakeraBindings` - **Description**: Type definition for the required Cloudflare Worker bindings. This specifies the shape of the environment variables your worker needs. - **Shape**: `{ ASSETS: Fetcher; LOADER: WorkerLoader }` ### `KakeraOptions` - **Description**: Type definition for options that can be passed to the `kakera` factory function. - **Shape**: `{ dir?: string; extensions?: string[] }` - **Properties**: - `dir` (string) - Optional. The directory where route files are located. Defaults to `''`. - `extensions` (string[]) - Optional. An array of file extensions to consider as routes. Defaults to `['ts', 'tsx']`. ``` -------------------------------- ### KakeraBindings TypeScript Interface Usage Source: https://context7.com/yusukebe/kakera/llms.txt Use the `KakeraBindings` interface as a generic parameter for `ExportedHandler` to access `env.ASSETS` and `env.LOADER` in custom handlers. ```typescript // TypeScript usage — the generic parameter unlocks env.ASSETS and env.LOADER import { type KakeraBindings } from 'kakera-worker' // When building a custom handler that wraps kakera: const handler: ExportedHandler = { async fetch(request, env) { // env.ASSETS — Fetcher for pre-built bundles // env.LOADER — WorkerLoader for isolated worker instantiation console.log(env.ASSETS, env.LOADER) return new Response('ok') } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.