Skip to content

Private previewMost of the architecture is written. First public release in 2027.

hamur/kit

The module author's tools. A module's setup runs while the build is configured, and the functions here act on that build. They also work inside the build hooks; from build:before on, the ones that add pages, layouts, route middleware, app plugins, a server door, templates, type templates or imports throw, naming the function and the hook. Calling one outside setup and the hooks throws, except createResolver, useLogger, logger and defineModule, which work anywhere. The guide is Modules.

defineModule

Returns the module unchanged and types its options.

ts
function defineModule<T extends Record<string, any>>(module: HamurModule<T>): HamurModule<T>
ts
import { defineModule } from "hamur/kit";
import type { HamurModule, ModuleMeta } from "hamur/kit";

const meta: ModuleMeta = { name: "analytics", configKey: "analytics" };

const analytics: HamurModule<{ id: string }> = {
  meta,
  defaults: { id: "" },
  setup(options, hamur) {
    console.log(`analytics ${options.id} in ${hamur.options.rootDir}`);
  },
};

export default defineModule(analytics);

HamurModule, ModuleMeta

HamurModule<T> has meta, defaults, hooks and setup(options, hamur). setup receives the options merged in this order, first wins: the inline options of [module, options] in modules, then config[meta.configKey], then defaults. ModuleMeta has name, so a module listed twice runs once, and configKey, the config key that holds the module's options; it defaults to name, and hooks, the names of the hooks the module calls and declares on HamurHooks, so a config hooks entry naming one is not reported as an unknown hook. defaults is an object, or a function (hamur) => options called once before the merge. hooks maps hook names to a function or an array of functions, registered just before setup (also for a module without setup) and not at all for a module skipped as a duplicate. A module file may also default-export a plain setup function.

HamurModuleOptions

The interface a module augments to type its options under its configKey, as shown on the hamur page. It is the same type that hamur exports.

createResolver, Resolver

createResolver(base) takes a directory, a file path or import.meta.url. resolve(...paths) joins paths onto that directory; resolvePath(id) resolves a module id the way Bun does from there.

ts
function createResolver(base: string): Resolver
interface Resolver { resolve(...paths: string[]): string; resolvePath(id: string): string }
ts
import { createResolver } from "hamur/kit";
import type { Resolver } from "hamur/kit";

const resolver: Resolver = createResolver(import.meta.url);

export const handler = resolver.resolve("./runtime/handler.ts");
export const entry = resolver.resolvePath("hamur");

readImageMeta

readImageMeta(bytes, extension, shown?) gives { width, height, format, animated? } of a PNG, JPEG, GIF, WebP, AVIF or SVG file from its header, without decoding it. extension is png, jpg, jpeg, gif, webp, avif or svg, in any case. format is "png", "jpeg", "gif", "webp", "avif" or "svg". A JPEG whose EXIF orientation is 5 to 8 has its width and height swapped, an AVIF with a 90 or 270 degree irot too, so the size is the one shown. animated is true for a GIF with more than one frame and a WebP with the animation flag.

It needs no module context and works anywhere. A file that is not what its extension says throws an error that starts with shown (default "image"), such as public/hero.png: not a PNG file (no IHDR chunk); an SVG with neither a size in pixels nor a viewBox throws SVG has no size in pixels and no viewBox. The type of the value without src is the ImageMeta of a ?meta import.

ts
function readImageMeta(bytes: Uint8Array, extension: string, shown?: string): Omit<ImageMeta, "src">
ts
import { readImageMeta } from "hamur/kit";

const bytes = new Uint8Array(await Bun.file("public/hero.jpg").arrayBuffer());
const { width, height, format } = readImageMeta(bytes, "jpg", "public/hero.jpg");

useHamur, HamurContext

Returns the build context of the module that is running setup: options is the resolved config and hooks the build hooks. It is also the second argument of setup.

ts
function useHamur(): HamurContext

HamurContext is the type of that value, for a helper that takes the context as an argument.

ts
import { defineModule, useLogger, useHamur } from "hamur/kit";
import type { Logger } from "hamur/kit";

const log: Logger = useLogger("my-module");

export default defineModule({
  setup() {
    log.info("preset chosen", { preset: useHamur().options.preset });
    log.warn("this module is experimental");
  },
});

envName

ts
function envName(key: string): string

The variable stem of a runtime-config key, as HAMUR_<KEY> overrides it at run time (02 §5): apiBase is API_BASE, apiURLBase is API_URL_BASE, oauthXClientId is OAUTH_X_CLIENT_ID. It has no imports, so build code of a module may call it; server code of @hamur/* reads it from hamur/server/internal.

useLogger, Logger, LogFields

The build logger's child for a module: every line starts with [tag] ([hamur] without a tag), fields follow as key=value, and an error's stack goes on the next lines. info and below print on stdout, warn and above on stderr. HAMUR_LOG_FORMAT=json prints one JSON line per record instead, HAMUR_LOG_LEVEL sets the level (default info) and --debug sets debug. Values under keys such as password, token, secret or authorization print as [redacted].

ts
function useLogger(tag?: string): Logger
type LogFields = Record<string, unknown>
interface Logger {
  readonly level: "trace" | "debug" | "info" | "warn" | "error" | "fatal" | "silent";
  trace(msg: string, fields?: LogFields): void;   // also (error: unknown, msg?: string, fields?: LogFields)
  debug: …; info: …; warn: …; error: …; fatal: …;
  child(bindings: LogFields): Logger;
  enabled(level: "trace" | "debug" | "info" | "warn" | "error" | "fatal"): boolean;
}

logger

Deprecated, kept through 1.x: use useLogger(tag). Returns { info, warn, error } that take any arguments, join them as console does (objects as JSON) and write the line through useLogger(tag).

ts
function logger(tag: string): { info(...args: unknown[]): void; warn(...args: unknown[]): void; error(...args: unknown[]): void }

writeAppKey, WriteAppKeyResult

Gives <rootDir>/.env a new app key (hamur create-key --env runs it). A line that sets HAMUR_KEY to a value, also with export, spaces or quotes, is left alone and nothing changes (status: "present"); an empty HAMUR_KEY= line is filled in place; otherwise HAMUR_KEY=<key> is appended and the file is created when missing (status: "written", with the key). It does not touch process.env. Build-time code only.

ts
function writeAppKey(rootDir: string): WriteAppKeyResult
interface WriteAppKeyResult { status: "written" | "present"; file: string; key?: string }

addPage, extendPages, PageInput

addPage adds a route. PageInput is a route record: name, path, file, optional loader and optional children of the same shape. extendPages receives the scanned route list and may change it, once the pages directory was scanned.

ts
function addPage(page: PageInput): void
function extendPages(fn: (routes: RouteRecord[]) => void | Promise<void>): void
ts
import { addLayout, addPage, createResolver, defineModule, extendPages } from "hamur/kit";

export default defineModule({
  meta: { name: "docs-pages" },
  setup() {
    const { resolve } = createResolver(import.meta.url);
    addPage({ name: "docs", path: "/docs", file: resolve("./runtime/docs.tsx") });
    addLayout({ name: "docs", file: resolve("./runtime/layout.tsx") });
    extendPages((routes) => {
      routes.sort((a, b) => a.path.localeCompare(b.path));
    });
  },
});

route, index, group, prefix

Helpers for app/routes.ts, the optional route table in code. Its default export receives the routes of the pages directories, after every module's pages:extend, and returns the routes the app serves: typegen, the manifest and the router read that list as they read scanned routes.

ts
function route(path: string, file: string, children?: RouteRecord[]): RouteRecord
function index(file: string): RouteRecord
function group(file: string, children: RouteRecord[]): RouteRecord
function prefix(path: string, children: RouteRecord[]): RouteRecord[]
ts
// app/routes.ts
import { group, index, prefix, route, type RouteRecord } from "hamur/kit";

export default (scanned: RouteRecord[]): RouteRecord[] => [
  ...scanned,
  index("screens/home.tsx"),
  route("users", "screens/users.tsx", [index("screens/users-list.tsx"), route(":id", "screens/user.tsx")]),
  group("screens/(shell).tsx", [route("settings", "screens/settings.tsx")]),
  ...prefix("/v2", [route("about", "screens/about.tsx")]),
];
  • A file is relative to the app/ folder (srcDir) or absolute; a <name>.load.ts beside it is its load, as beside a page.
  • A path without a leading / is below the parent route's path, or below / at the top. index(file) is the route at its parent's path. prefix(path, children) puts path before every path of children, those with a leading / too, and returns copies, so [...scanned, ...prefix("/en", scanned)] serves both.
  • Names follow the path as a page file's do: route("/blog/:slug", …) is blog-slug, an index below users is users-index, and prefix("/en", …) names blog as en-blog.
  • group(file, children) is a pathless layout, like a (group).tsx beside a (group)/ folder: it renders Outlet, adds nothing to the paths of its routes, is named (<file name>) (admin-(shell) below /admin), and adds the file name to their groups.
  • A record the function returns is checked as a scanned one, and the build fails with app/routes.ts: before the message: app/routes.ts: Duplicate route /about: …/app/pages/about.tsx and …/app/screens/about.tsx, an invalid pattern, a duplicate name, or app/routes.ts: the route /gone renders app/screens/gone.tsx, which does not exist. A default export that is not a function, or a result that is not an array, fails the build too.
  • Error, not-found, pending and template files and _meta.ts folder configs come from the pages directories; a record built here has none unless it sets error, notFound, pending, template or folderConfig itself.
  • Under hamur dev an edit of app/routes.ts scans again and reloads the browser.

addLayout

Registers a layout by name. A layout of the same name in app/layouts/ wins.

ts
function addLayout(layout: { name: string; file: string }): void

addRouteMiddleware

Registers route middleware by name. global: true runs it on every navigation. A scanned file of the same name wins.

ts
function addRouteMiddleware(entry: { name: string; path: string; global?: boolean }): void

addAppPlugin

Adds an app plugin file. It runs before the app's own plugins. mode limits it to "client" or "server"; the default is "all".

ts
function addAppPlugin(plugin: string | { src: string; mode?: "client" | "server" | "all" }): void

addServer

Adds the module's door: a .ts file read like server/index.ts, its re-exports and export default defineServer(…) included. Client code under root (default the file's folder) reads it as #server, and the app takes a handler with export { x } from "#server/<meta.name>". The module's plugins, middleware and handlerMiddleware run before the layers' and the app's, in module order; handlerMiddleware governs the door's own handlers. A relative path is resolved from the app's root. A module without meta.name fails with addServer(file) needs meta.name in defineModule, and a second call with Module "x" has one door; list its handlers in <file>.

ts
function addServer(file: string, options?: { root?: string }): void
ts
import { addAppPlugin, addRouteMiddleware, addServer, createResolver, defineModule } from "hamur/kit";

export default defineModule({
  meta: { name: "runtime" },
  setup() {
    const { resolve } = createResolver(import.meta.url);
    addServer(resolve("./runtime/server.ts"));
    addAppPlugin({ src: resolve("./runtime/app-plugin.ts"), mode: "client" });
    addRouteMiddleware({ name: "auth", path: resolve("./runtime/auth.ts"), global: false });
  },
});
ts
setup() {
  const { resolve } = createResolver(import.meta.url);
  addServer(resolve("./runtime/server.ts"), { root: resolve("./runtime") });
}

A value from module options reaches a door through addTemplate: the build reads a door as text and runs nothing, so a route is a literal in a generated file. Write the door and its definitions with write: true to a folder of their own in the build directory, and pass the door's path. Their getContents runs before the scan, so it reads options, not the routes.

ts
setup(options, hamur) {
  addTemplate({ filename: "feed/q.ts", write: true, getContents: () => `import { defineHandler } from "hamur/server";\nexport const feed = defineHandler({ route: ${JSON.stringify(options.path)}, handler: () => "ok" });\n` });
  addTemplate({ filename: "feed/server.ts", write: true, getContents: () => `export { feed } from "./q.ts";\n` });
  addServer(join(hamur.options.buildDir, "feed/server.ts"));
}

addComponent

Adds a module component: name resolves to the export (default "default") of from, a package specifier or an absolute path, resolved from the app root at build. It is used in the app's files without an import and typed in .hamur/types/imports.d.ts, as an app/components file is, and it needs components: true (the html adapter accepts and ignores it). A module that renders per library writes from with the adapter's name: hamur.options.framework is resolved before modules run. The app's own component of the same name wins and the build logs [hamur] component Img from @hamur/image is shadowed by app/components/Img.tsx once. name matches /^[A-Z][A-Za-z0-9]*$/ (hamur/kit: addComponent name "img" must start with an upper-case letter); two modules adding one name fail with hamur/kit: addComponent "Img" is added by two modules (image, gallery); a from that does not resolve fails with hamur/kit: addComponent "Img" from "@hamur/image/vue" does not resolve from <rootDir>. An adding call: from build:before on it throws as the others do.

ts
function addComponent(component: { name: string; from: string; export?: string }): void
ts
setup(_options, hamur) {
  addComponent({ name: "Img", from: `@hamur/image/${hamur.options.framework}` });
}

addComponentsDir

Adds a directory scanned as app/components is, each name <prefix><name> (Button.tsx with prefix: "Ui" is UiButton, and forms/Field.tsx is UiFormsField). pathPrefix: false names a file by its base name only, so forms/Field.tsx is Field; extensions default to the adapter's. path is absolute or relative to the app root and must exist: hamur/kit: addComponentsDir path "<path>" does not exist. The directories follow app/components in the components:dirs hook, and an app component of the same name wins.

ts
function addComponentsDir(dir: { path: string; prefix?: string; pathPrefix?: boolean; extensions?: string[] }): void

addComponentExports

Adds every named export of file whose name starts with an upper-case letter as a component <prefix><name>. The exports are read from the source without running the file. A name two modules add fails as addComponent does.

ts
function addComponentExports(file: string, options?: { prefix?: string }): void

addTask

Adds a task to the app's: file is an absolute .ts path whose default export is defineTask(…), read as a server/tasks file is, and name follows the task name rule (segments of A-Z, a-z, 0-9, _ and -, joined by :). A name the app or a layer already has fails the build: Task "db:migrate" of module @hamur/db conflicts with server/tasks/db/migrate.ts.

ts
function addTask(task: { name: string; file: string }): void

addServerAssets

Mounts a directory of the module read-only as useStorage("assets:<name>") in the server. The files are data: a build inlines each file up to 1 MB in the server bundle and copies a larger one to .output/server/assets/<name>/ (on cloudflare every file is inlined), and hamur dev reads the directory live. name matches /^[a-z0-9][a-z0-9-]*$/; dir is absolute or relative to the app's root and must exist. server is the app's own server/assets, so addServerAssets({ name: "server", … }) fails with hamur/kit: addServerAssets name "server" is the app's server/assets; a missing directory fails with hamur/kit: addServerAssets dir "<path>" does not exist and a name added twice with hamur/kit: addServerAssets name "icons" is added twice. An adding call: from build:before on it throws as the others do.

ts
function addServerAssets(options: { name: string; dir: string }): void
ts
setup() {
  addServerAssets({ name: "icons", dir: createResolver(import.meta.url).resolve("./icons") });
}

addStorageDriver

Adds a storage driver name to the build's driver table and its preset check: a storage mount with driver: name imports the default export of from (an absolute path or a package specifier), a function (options) => StorageDriver that gets the mount's other options, and the build refuses the mount on a preset that is not in presets, with the message of a built-in driver (Storage mount "x" uses the "name" driver, which the "cloudflare" preset cannot run (it runs on: bun, node)). name matches /^[a-z0-9][a-z0-9-]*$/; the factory also gets the mount's name as its second argument. from is an absolute path or a package specifier resolved from the app root (a relative path fails with from must be an absolute path or a package specifier). A built-in name fails with hamur/kit: addStorageDriver("fs"): a built-in driver has this name, an unknown preset with hamur/kit: addStorageDriver("db"): unknown preset "deno", and a name added twice with hamur/kit: addStorageDriver("db"): added twice. An adding call: from build:before on it throws as the others do. @hamur/db adds db with it.

ts
function addStorageDriver(driver: { name: string; from: string; presets: string[] }): void
ts
setup() {
  addStorageDriver({ name: "mine", from: createResolver(import.meta.url).resolve("./driver.ts"), presets: ["bun", "node"] });
}

hasStorageMount

True when the build mounts the storage name on its preset: a storage.<name> key of the config, data (every preset gives it a default), or session where the preset gives the session store a default (fs under hamur dev and on bun, node and static; cloudflare-kv on cloudflare when the app's wrangler config declares a kv_namespaces entry with binding SESSION; none on vercel and netlify). A module checks a mount name its options give with it, at build:before or later, when the config is final. @hamur/auth checks auth.session.storage with it.

ts
function hasStorageMount(name: string): boolean
ts
hamur.hooks.hook("build:before", () => {
  if (!hasStorageMount("session")) throw new Error(`my-module needs storage.session on the ${hamur.options.preset} preset`);
});

presetFeatures, PresetFeatures, PresetFeatureLevel

The traits of preset name, as PresetFeatures; pass hamur.options.preset. A name the build does not list throws Unknown preset "x". imageTransforms is a PresetFeatureLevel, "stable", "experimental" or "unsupported": stable on bun, unsupported on every other preset. imageService is the platform image service provider: "auto" picks ("vercel" on vercel, "netlify" on netlify), absent elsewhere. @hamur/image reads them to decide where the hamur provider transforms and which service auto is. It works anywhere, in setup or a hook.

ts
function presetFeatures(name: string): PresetFeatures
interface PresetFeatures { imageTransforms: PresetFeatureLevel; imageService?: "vercel" | "netlify" }
type PresetFeatureLevel = "stable" | "experimental" | "unsupported"

addTemplate, addTypeTemplate, TemplateInput

addTemplate adds a virtual module with a filename and getContents(hamur). Its id is exactly #hamur/<filename>, extension included, and the contents are loaded by that extension: .ts, .mts and .cts as TypeScript, .tsx, .jsx, .json and .css as themselves, anything else as JavaScript. A .css template is dropped from the server bundle. write: true also writes it to the build directory, and hamur dev rewrites it after files are added or removed. It returns the template. addTypeTemplate adds a .d.ts file that is written to types/ in the build directory and referenced from its hamur.d.ts.

ts
function addTemplate(template: TemplateInput): TemplateInput
function addTypeTemplate(template: { filename: string; getContents(hamur: HamurContext): string | Promise<string> }): void

updateTemplates

Recomputes the templates that filter accepts (all by default) and rewrites their write: true files in the build directory. The virtual modules read their contents on every load. It works in setup and in any hook.

ts
function updateTemplates(options?: { filter?: (template: { filename: string }) => boolean }): Promise<void>

createRouteRules, RouteRules, RouteRuleMatch, RouteRule

The matcher the server uses for routeRules (07 §3), for a module that must decide a path as the server does. createRouteRules(rules) throws a TypeError for a pattern that does not start with /, uses ** before its last segment, names a param twice, mixes text and a param in one segment or has a :name(<regex>) constraint that is not a valid regular expression, and for a key whose method is not one upper-case method and one space. match(path, request?) returns the merged rule (the most specific pattern wins, objects merge by key) and each matching key in matches, least specific first, with what its ** matched (rest) and its params: the key's :name params as the request sent them, and the named groups of the conditions of the entry that applied; request gives the method that method keys ("GET /feed") and the headers, cookies, query and host that the conditions of an entry list read, and without it the match is a GET with none of them, as at build. variants(path) lists every merged rule a GET of path can get, one per choice of entry (or of none) in each matching key with conditions. prerenderPaths() lists the patterns without wildcards, of keys without a method or with GET, whose merged rule has prerender: true.

ts
function createRouteRules(rules?: Record<string, RouteRule | RuleEntry[]>): RouteRules
interface RouteRules {
  match(path: string, request?: { method?: string; headers?: Headers; cookies?: Record<string, string>; query?: URLSearchParams; host?: string }): RouteRuleMatch;
  variants(path: string): RouteRule[];
  prerenderPaths(): string[];
}

addImports, KitImport

addImports makes an export auto-imported: { name, as?, from }.

ts
function addImports(imports: KitImport | KitImport[]): void

addBunPlugin

Adds a Bun.build plugin to the client build, the server build, or both (the default). In hamur dev, the client bundler gets every plugin added for the client; the server build always drops .css files before a plugin can load them.

ts
function addBunPlugin(plugin: BunPlugin, target?: { client?: boolean; server?: boolean }): void

HamurHooks, TsConfigFile

The map of build hook names to their functions, the type behind hamur.hooks and behind hooks in the config, and TsConfigFile, what prepare:types gets for each context. hamur exports the same types; the hamur page lists the hooks.

PrerenderPage, PrerenderedPage

The argument of the prerender:page hook and the items of the list prerender:done gets.

ts
interface PrerenderPage {
  path: string
  status: number
  headers: Headers
  body: string | Uint8Array
  readonly links: readonly string[]
  prerenderRoutes(...paths: string[]): void
}

interface PrerenderedPage {
  path: string
  status: number
  file: string
}

prerender:page runs once for each page file before it is written, with the final answer of the built server: the CSP hash <meta> and the integrity attributes are already in it. Assign body to change what is written; it is a string for text, JSON, XML and JavaScript answers and a Uint8Array for any other. A hook that adds an inline script or style to a page under server.csp in hash mode must add the hash itself. links are the same-origin <a href> paths of an HTML page. prerenderRoutes queues paths as a crawled link, so prerender.ignore and prerender: false apply, even with prerender.crawl off. A page whose file public/ already has is kept and the hook does not run for it; _payload.json, 200.html and 404.html are not passed to it. A redirect page is passed with the redirect's status. prerender:done runs once on every hamur build, [] when nothing was prerendered, with file relative to .output/public/, sorted by path. It is not called in hamur dev.

RouteRecord

One scanned route: name, path, file, an optional loader, groups (the group folders of the page file without parentheses, outermost first, set only when it is in one), matchers (param name to matcher name, set when the file name has [id=integer]), pathless: true on the record of a (group).<ext> file, which renders Outlet for the routes of its folder and is matched only through them, slots on a page with @<slot>/ folders beside its folder (each { routes, default?, intercepts }: the slot's records with their full paths, its default.<ext>, and its intercepting routes), and children of the same shape. It is the item type of the list that extendPages and the pages:extend hook receive.

Hooks

The type of hamur.hooks on the context: hook(name, fn) and hookOnce(name, fn) register a function and return a function that removes it, callHook and callHookParallel call the registered functions, and removeHook(name, fn) removes one. hamur/app exports the same type.

updateRuntimeConfig

Merges a patch over runtimeConfig: a key in the patch wins over the same key in the app's config. HAMUR_* environment variables still override the result at runtime.

ts
function updateRuntimeConfig(patch: Record<string, unknown>): void

addRouteRules

Adds route rules from a module, for rules it can only decide once the routes are known. The build reads hamur.routeRules: per pattern the config's rule merged over the modules' rules in call order, so the app's value wins; hamur.options.routeRules stays the config's. Rules added in setup, modules:done or templates:extend stay; rules added in pages:extend or server:extend belong to that scan, and hamur dev drops them before it calls those hooks again, so a removed route takes its rule along. A route record's fn.handlerImport ({ from, name }, when the definition's handler is one call of a named import) tells a server:extend hook which helper a route runs. Each rule is checked as the config's are, and from build:before on the call throws.

ts
function addRouteRules(rules: Record<string, RouteRule>): void

addPublicAssets

Serves a directory of the module below baseURL, on every preset. hamur build copies its files into .output/public/<baseURL> before the public files are compressed and listed in the public asset table, and hamur dev reads the directory live. baseURL defaults to "/", starts and ends with / and is below app.baseURL. dir is absolute or relative to the app's root and must exist: hamur/kit: addPublicAssets dir "<path>" does not exist. Files whose path has a segment starting with . are not served, as in public/. maxAge (a non-negative integer, seconds) adds the route rule { "<baseURL>**": { headers: { "cache-control": "public, max-age=<maxAge>, immutable" } } } through addRouteRules, so it reaches the files wherever route rule headers do (_headers, vercel.json, the server). An adding call: from build:before on it throws as the others do.

ts
function addPublicAssets(options: { dir: string; baseURL?: string; maxAge?: number }): void
ts
setup() {
  addPublicAssets({ dir: createResolver(import.meta.url).resolve("./fonts"), baseURL: "/_fonts/", maxAge: 31536000 });
}

emitPublicAsset

Writes one file at a fixed public path below app.baseURL; a string is written as UTF-8. Call it from setup or any build hook through prerender:done, so a module can write what depends on the pages (an index, image variants); a later call throws hamur/kit: emitPublicAsset() was called in the "close" hook, after the public files were written; call it by prerender:done. The file is compressed and listed in the public asset table like a public/ file, and hamur dev serves it from memory (a call in setup, or in a hook that runs before dev:ready). The same path twice with the same bytes is one file; with other bytes it throws hamur/kit: emitPublicAsset "/_fonts/a.woff2" was emitted twice with different bytes. A path that public/, an addPublicAssets directory or another emit also gives fails the build and names both: public file /_fonts/a.woff2 comes from public/_fonts/a.woff2 and from emitPublicAsset (module fonts). The module name is shown for a call made in setup.

ts
function emitPublicAsset(path: string, data: string | Uint8Array): void
ts
hamur.hooks.hook("prerender:done", (pages) => {
  emitPublicAsset("/search-index.json", JSON.stringify(pages.map((page) => page.path)));
});

emitFile

Writes a file named by its content and returns its URL. The file is <stem>-<first 8 hex of SHA-256>.<ext> below <app.baseURL><app.buildAssetsDir>, the form of the files the build writes for imported assets, so it is served immutable; equal bytes give one file and one URL. name needs an extension: hamur/kit: emitFile name "font" needs an extension. Callable when emitPublicAsset is, and a file written in dev has the same URL.

ts
function emitFile(file: { name: string; source: string | Uint8Array }): Promise<string>
ts
const url = await emitFile({ name: "inter.woff2", source: bytes });
// "/_hamur/inter-1a2b3c4d.woff2"

addDevServerHandler

Answers requests in hamur dev only: a mock API, a dev page of the module, a proxy to a local tool. route starts with / (hamur/kit: addDevServerHandler route "mock" must start with "/") and is a path prefix below app.baseURL, matched on a segment boundary: /__devtools/ and /__devtools match /__devtools and /__devtools/a, not /__devtoolsy. The dev server runs the handlers after the host and origin checks and before imported assets, public files, server routes and pages: first those of devServer.handlers in the config, then those of modules in the order of the calls. The first handler whose route matches and that returns a Response answers; undefined passes the request on. A handler that throws answers 500 (with the dev overlay for an HTML request) and logs [hamur] dev handler /__devtools/ (module devtools) threw: <message>. Nothing of a handler reaches hamur build or the built server, which answers its routes as any unknown path. An adding call: from build:before on it throws as the others do.

ts
type DevHandler = (request: Request) => Response | undefined | Promise<Response | undefined>;
function addDevServerHandler(options: { route: string; handler: DevHandler }): void
ts
setup() {
  addDevServerHandler({ route: "/__devtools/", handler: () => new Response("devtools") });
}

DevHandler

The handler type addDevServerHandler takes and a devServer.handlers file default-exports: it gets the request (a clone when it has a body) and returns a Response to answer or undefined to pass the request on.

ts
type DevHandler = (request: Request) => Response | undefined | Promise<Response | undefined>;

addWatchFile

hamur dev restarts when the file changes, as for an edit of hamur.config.ts, and logs [hamur] <path> changed; restarting. path is absolute or relative to the app's root; a file outside the app's directories is watched through its folder. hamur build ignores it.

ts
function addWatchFile(path: string): void
ts
import { addBunPlugin, addImports, addTemplate, addTypeTemplate, defineModule, updateRuntimeConfig } from "hamur/kit";
import type { KitImport, TemplateInput } from "hamur/kit";

export default defineModule({
  setup() {
    const template: TemplateInput = { filename: "theme.js", write: true, getContents: () => `export const useTheme = () => "dark";\n` };
    const imports: KitImport[] = [{ name: "useTheme", from: "#hamur/theme.js" }];
    addTemplate(template);
    addTypeTemplate({ filename: "theme.d.ts", getContents: () => `declare module "#hamur/theme.js" {\n  export function useTheme(): string;\n}\n` });
    addImports(imports);
    addBunPlugin({ name: "noop", setup() {} }, { server: false });
    updateRuntimeConfig({ public: { theme: "dark" } });
  },
});