Files
core/src/views.ts
T
chrnx 4896ee86d2
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
fix(jsr): resolve require from source, not from tsup's banner
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.

The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.

Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.

Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.

Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.

Closes #69.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:50:42 -05:00

147 lines
5.7 KiB
TypeScript

// src/views.ts — HTML views: built-in templating, content-type map, and boot-time builders.
// fs/path are lazy-required inside functions so the barrel stays edge-loadable (workerd has no filesystem).
import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata';
import { nodeRequire } from './node-require';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string {
const map: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
return s.replace(/[&<>"']/g, (c) => map[c]);
}
function stringify(v: unknown): string {
return v === null || v === undefined ? '' : String(v);
}
/**
* Minimal built-in template engine: `{{ key }}` interpolates HTML-escaped, `{{{ key }}}` raw,
* `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials.
*/
export function render(source: string, data: unknown): string {
const lookup = (key: string): unknown =>
key.split('.').reduce<any>((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data);
return source
.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key)))
.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key))));
}
const CONTENT_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
/** Content-type for a file extension (case-insensitive, leading dot); unknown → `application/octet-stream`. */
export function contentTypeFor(ext: string): string {
return CONTENT_TYPES[ext.toLowerCase()] ?? 'application/octet-stream';
}
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8' } as const;
/** Boot-time context for building `@Html` transformers: the views base dir and an optional BYO engine. */
export interface ViewsContext {
views?: string;
viewEngine?: (source: string, data: unknown) => string;
}
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
* filesystem should hear about it here rather than at the first request. */
function readViewFile(views: string | undefined, path: string): string {
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
try {
return fs.readFileSync(full, 'utf8');
} catch (err) {
throw new Error(
`@Html('${path}') could not read '${full}' — on a runtime without a filesystem (edge), return a string from @Html instead. (${(err as Error).message})`,
);
}
}
/** A static-file hit: the raw bytes and the content-type to send. */
export interface StaticHit {
body: Buffer;
contentType: string;
}
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/**
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss.
*/
export function buildStaticResolver(root: string | true): StaticResolver {
let fs: typeof import('node:fs');
let nodePath: typeof import('node:path');
try {
fs = nodeRequire('node:fs');
nodePath = nodeRequire('node:path');
} catch {
throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
);
}
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
return async (urlPath) => {
let rel: string;
try {
rel = decodeURIComponent(urlPath.split('?')[0]);
} catch {
return undefined;
}
if (rel === '' || rel.endsWith('/')) rel += 'index.html';
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
try {
const stat = await fs.promises.stat(full);
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
const body = await fs.promises.readFile(target);
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
} catch {
return undefined;
}
};
}
/** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */
export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn {
if (!meta.path) {
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: String(value) });
}
const source = readViewFile(ctx.views, meta.path);
if (meta.template) {
const engine = ctx.viewEngine ?? render;
return (value) => ({ status: 200, headers: { ...HTML_HEADERS }, body: engine(source, value) });
}
return () => ({ status: 200, headers: { ...HTML_HEADERS }, body: source });
}