@blinkk/root
The Root.js framework: config, routing, components, hooks and the server. This reference is generated from the package's TypeScript types and doc comments.
@blinkk/root
import {…} from '@blinkk/root';
Bodyvariable
const Body: FunctionalComponent<BodyProps>;
The <Body> component can be used to update attrs in the <body> tag.
Usage:
<Body className="body">
<h1>Hello world</h1>
</Body>
Output:
<body class="body">
<h1>Hello world</h1>
</body>
ConfigureServerHooktype
type ConfigureServerHook = (server: Server, options: ConfigureServerOptions) => MaybePromise<void> | MaybePromise<() => void>;
ConfigureServerOptionsinterface
interface ConfigureServerOptions
Members (2)
type: 'dev' | 'preview' | 'prod';
rootConfig: RootConfig;
configureServerPluginsfunction
function configureServerPlugins(server: Server, callback: () => Promise<void>, plugins: Plugin[], options: ConfigureServerOptions): Promise<void>;
Runs the pre-hook configureServer method of every plugin, calls a callback function, and then runs the configureServer's post-hook if provided. Plugins provide a post-hook by returning a callback function from configureServer.
ContentSecurityPolicyConfiginterface
interface ContentSecurityPolicyConfig
Members (2)
directives?: Record<string, string[]>;
reportOnly?: boolean;
defineConfigfunction
function defineConfig(config: RootUserConfig): RootUserConfig;
definePodfunction
function definePod(pod: Pod): Pod;
Helper to define a pod with type-checking.
ElementTagNameMatchertype
type ElementTagNameMatcher = Array<string | RegExp> | ((tagName: string) => boolean);
Matches custom elements by tag name (e.g. debug-panel).
Accepts a list of strings (matched exactly) and RegEx patterns (tested against the tag name), or a predicate function that receives the tag name and returns true to match. The function form is useful for logic that a pattern can't express, e.g. allowlisting a known set of elements.
const ssrOnly = new Set(['help-overlay', 'debug-panel']);
const matcher: ElementTagNameMatcher = (tagName) => ssrOnly.has(tagName);
GetStaticContenttype
type GetStaticContent = (props: any) => Promise<StaticContentResult | string> | StaticContentResult | string;
The getStaticContent() function is a SSG handler function for non-HTML routes, e.g. routes/sitemap.xml.ts.
If the route exports a getStaticProps() function, the props returned from that function is passed to getStaticContent(). Otherwise a default props value is passed which includes the rootConfig and route param values.
GetStaticPathstype
type GetStaticPaths<T = RouteParams> = (ctx: {
rootConfig: RootConfig;
}) => Promise<{
paths: Array<{
params: T;
}>;
}>;
The getStaticPaths() is used by the SSG build to determine all of the paths that exist for a given route. This should be used alongside a parameterized route, e.g. /routes/blog/[slug].tsx.
GetStaticPropstype
type GetStaticProps<T = unknown> = (ctx: {
rootConfig: RootConfig;
params: RouteParams;
}) => Promise<{
props?: T;
locale?: string;
translations?: Record<string, string>;
notFound?: boolean;
}>;
The getStaticProps() function is an optional function that routes can define to fetch and transform props before passing it to the route's component.
getTranslationsfunction
function getTranslations(locale: string): Record<string, string>;
getVitePluginsfunction
function getVitePlugins(plugins: Plugin[]): VitePlugin[];
Handlertype
type Handler = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
The handle() function can be exported by a route to define a custom express request handler. The req object will contain a handlerContext which contains the route's param values and also a render() method that can be used to render the route's default component.
HandlerContextinterface
interface HandlerContext<Props = any>
A context variable passed to a route's handle() method within the req object.
Members (6)
route: Route;
The resolved route.
params: RouteParams;
Param values from the route, e.g. a route like /route/[slug].tsx will pass {slug: 'foo'}.
i18nFallbackLocales: string[];
i18n locales to try for the user's http request. The priority order mimics the Firebase Hosting i18n fallback logic. https://firebase.google.com/docs/hosting/i18n-rewrites#priority-order
getPreferredLocale: (availableLocales: string[]) => string;
Iterates through the i18nFallbackLocales and returns the first available locale.
render: HandlerRenderFn<Props>;
Renders the default exported component from the route.
render404: (options?: {
nextRoute?: boolean;
}) => Promise<void>;
Renders a 404 page. When nextRoute is true, the next matching route handler will be invoked instead of rendering the default 404 page.
HandlerRenderFntype
type HandlerRenderFn<Props = any> = (props: Props, options?: HandlerRenderOptions) => Promise<void>;
HandlerRenderOptionsinterface
interface HandlerRenderOptions
Members (4)
statusCode?: number;
HTTP status code to return. Defaults to 200.
locale?: string;
The rendered locale.
translations?: Record<string, string>;
Translations to pass to useTranslations(). If provided, the translations map passed here will be merged with the translations from /translations/{locale}.json.
renderMode?: JsxRenderMode;
Overrides the JSX render mode for this render. 'pretty' adds newlines around block elements; 'minimal' outputs compact HTML. If not provided, defaults to the jsxRenderer.mode specified in root.config.ts.
Headvariable
const Head: FunctionalComponent<HeadProps>;
The <Head> component can be used for injecting elements into the HTML head tag from any part of a page. The <Head> can be added via any component or sub-component and will automatically be hoisted to the <head> element.
Usage:
<Head>
<link rel="preconnect" href="https://fonts.googleapis.com" />
</Head>
Htmlvariable
const Html: FunctionalComponent<HtmlProps>;
The <Html> component can be used to update attrs in the <html> tag.
Usage:
<Html lang="en-US">
<h1>Hello world</h1>
</Html>
HTML_CONTEXTvariable
const HTML_CONTEXT: import("preact").Context<HtmlContext | null>;
I18nContextinterface
interface I18nContext
Members (2)
locale: string;
translations: Record<string, string>;
LocaleGroupinterface
interface LocaleGroup
Members (2)
label?: string;
locales: RootLocale[];
MultipartFileinterface
interface MultipartFile
Multipart file type for the multipartMiddleware().
Members (5)
fieldname: string;
originalName: string;
encoding: string;
mimetype: string;
buffer: Buffer;
NextFunctiontype
type NextFunction = ExpressNextFunction;
Root.js express next function.
Plugininterface
interface Plugin
Members (8)
name?: string;
The name of the plugin.
configureServer?: ConfigureServerHook;
Configures the root.js express server. Any middleware defined by the plugin will be added to the server first. If a callback fn is returned, it will be called after the root.js middlewares are added.
onFileChange?: (eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string) => void;
Hook for file changes.
ssrInput?: () => {
[entryAlias: string]: string;
};
Returns a list of deps to bundle for ssr. The files will be bundled and output to dist/server/. The return value should be a map of {output filename => input filepath}.
E.g. a value of {foo: 'path/to/bar.js'} will output dist/server/foo.js.
vitePlugins?: VitePlugin[];
Adds vite plugins.
hooks?: PluginHooks;
Plugin lifecycle callback hooks.
handle404?: (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
Custom 404 handler.
pod?: Pod | Pod[] | PodFactory;
Registers a pod (a mini root.js site) that gets merged into the parent site at dev/build time. A plugin may return a single pod, an array of pods, or a factory that receives the rootConfig.
PluginHooksinterface
interface PluginHooks
Members (3)
preBuild?: PreBuildHook;
Hook that runs before the build starts.
postBuild?: PostBuildHook;
Hook that runs after the build completes.
preRender?: (html: string) => void | MaybePromise<string>;
Post-render hook that's called before the HTML is rendered to the response object. If a string is returned from this hook, it will replace the rendered HTML.
Podinterface
interface Pod
Members (9)
name: string;
Unique pod name, e.g. '@blinkk/root-docs-pod'.
mount?: string;
URL prefix for pod routes. Routes within the pod are served under this mount path. Defaults to '/'.
priority?: number;
Priority for route conflict resolution. Higher values win when multiple pods register the same URL path. User-site routes always take precedence regardless of priority. Defaults to 0.
routesDir?: string;
Absolute path to the pod's routes/ directory.
elementsDirs?: string[];
Absolute path(s) to the pod's elements/ directory(s).
bundlesDir?: string;
Absolute path to the pod's bundles/ directory.
collectionsDir?: string;
Absolute path to the pod's collections/ directory (root-cms only).
translationsDir?: string;
Absolute path to the pod's translations/ directory.
vitePlugins?: VitePlugin[];
Extra Vite plugins contributed by the pod.
PodConfiginterface
interface PodConfig
Members (5)
enabled?: boolean;
Whether the pod is enabled. Defaults to true.
mount?: string;
Override the pod's mount path.
priority?: number;
Override the pod's priority.
routes?: {
exclude?: (string | RegExp)[];
};
Filter pod routes.
collections?: {
exclude?: string[];
rename?: Record<string, string>;
};
Configure pod collections.
PodFactorytype
type PodFactory = (ctx: {
rootConfig: RootConfig;
}) => Pod | Promise<Pod>;
PostBuildOptionsinterface
interface PostBuildOptions
Members (1)
ssrOnly?: boolean;
Whether the build was SSR-only (no SSG pre-rendering).
replaceParamsfunction
function replaceParams(urlPathFormat: string, params: Record<string, string>): string;
Requesttype
type Request = ExpressRequest & {
rootConfig?: RootConfig & {
rootDir: string;
};
viteServer?: ViteDevServer;
renderer?: Renderer;
user?: {
email: string;
role?: string | null;
};
handlerContext?: HandlerContext;
hooks: Hooks;
session: Session;
rawBody?: any;
files?: {
[fieldname: string]: MultipartFile;
};
};
Root.js express request.
RequestContextinterface
interface RequestContext
Members (7)
currentPath: string;
The current request path, e.g. /foo/bar (default route path) or /{locale}/foo/bar (localized route path).
route: Route;
The route file.
routeParams: Record<string, string>;
Route param values. E.g. for a route like routes/blog/[slug].tsx, visiting /blog/foo will pass {slug: 'foo'} here.
props: any;
Props passed to the route's server component.
locale: string;
The current locale.
translations: Record<string, string>;
Translations map for the current locale.
nonce?: string;
CSP nonce value.
RequestMiddlewaretype
type RequestMiddleware = ((req: Request, res: Response) => any) | ((req: Request, res: Response, next: NextFunction) => any) | ((err: any, req: Request, res: Response, next: NextFunction) => any);
Responsetype
type Response = ExpressResponse & {
session: Session;
saveSession: (options?: SaveSessionOptions) => void;
};
Root.js express response.
RootBuildConfiginterface
interface RootBuildConfig
Members (1)
excludeDefaultLocaleFromIntlPaths?: boolean;
Excludes the /intl/{defaultLocale}/... path from the SSG build.
RootConfigtype
type RootConfig = RootUserConfig & {
rootDir: string;
};
RootHeaderConfiginterface
interface RootHeaderConfig
Members (2)
source: string;
A glob pattern match (regex not supported yet).
headers: Array<{
key: string;
value: string;
}>;
RootI18nConfiginterface
interface RootI18nConfig
Members (6)
locales?: RootLocale[];
Locales enabled for the site.
defaultLocale?: RootLocale;
The default locale to use. Defaults is en.
urlFormat?: string;
URL format for localized content. Default is /[locale]/[base]/[path].
groups?: Record<string, LocaleGroup>;
Localization groups, to help UIs (like Root.js CMS) logically group locales.
translationLanguages?: Record<RootLocale, TranslationLanguage>;
Maps a root locale to the "translation language" used by translation systems. Translation systems often use different language identifiers than root locales, and multiple root locales may share the same translations. For example:
i18n: {
locales: ['en', 'es_mx', 'es_co', 'en_gb', 'en_ca', 'fr_ca'],
translationLanguages: {
es_mx: 'es-419',
es_co: 'es-419',
en_gb: 'en-GB',
en_ca: 'en-GB',
fr_ca: 'fr-CA',
},
}
With the config above, translations for the es_mx and es_co locales are imported and exported using a single es-419 language. The conversion applies anywhere translations are used, e.g. CSV and Google Sheets import/export, translation services, and the CMS translations pages. Locales not listed here use the locale id as the translation language.
fallbacks?: Record<RootLocale, RootLocale[]>;
Locale fallback chains for translations. When a translation is missing for a locale, each fallback locale is checked (in order) before falling back to defaultLocale and finally the source string. Fallbacks are resolved recursively, e.g. with the config below, en-CA resolves to ['en-CA', 'en-GB', 'en']. For example:
i18n: {
locales: ['en', 'en-GB', 'en-CA'],
fallbacks: {
'en-CA': ['en-GB'],
},
}
RootLocaletype
type RootLocale = string;
A site-defined locale identifier, as configured in i18n.locales. Root is agnostic to its format.
RootRedirectConfiginterface
interface RootRedirectConfig
Members (3)
source: string;
The source path to redirect. Accepts placeholders in the format [key] or [...key]. Use [key] for single segments and [...key] for multi-segment wildcards.
"/old-path/[id]" or "/old-path/[...wildcard]"
destination: string;
The destination to redirect to. Placeholders from the source can optionally be inserted into the destination using the same placeholder format.
"/new-path/[id]" or "/new-path/[...wildcard]"
type?: 301 | 302;
The redirect type (301 = permanent, 302 = temporary). If unspecified, defaults to 302 (temporary).
RootSecurityConfiginterface
interface RootSecurityConfig
Members (5)
contentSecurityPolicy?: ContentSecurityPolicyConfig | boolean;
Content-Security-Policy config. If enabled, a nonce is auto-generated for every request and appended to script and stylesheet tags. You can validate your CSP headers using a tool like https://csp-evaluator.withgoogle.com/.
strictTransportSecurity?: boolean;
Strict-Transport-Security config. When enabled, the header value is set to Strict-Transport-Security: max-age=63072000; includeSubDomains; preload.
xContentTypeOptions?: boolean;
X-Content-Type-Options config. When enabled, the header value is set to X-Content-Type-Options: nosniff.
xFrameOptions?: 'DENY' | 'SAMEORIGIN' | boolean;
X-Frame-Options config. Setting this value to true will default the header value to X-Frame-Options: SAMEORIGIN.
xXssProtection?: boolean;
X-XSS-Protection config. When enabled, the header value is set to X-XSS-Protection: 1; mode=block.
RootServerConfiginterface
interface RootServerConfig
Members (7)
middlewares?: RequestMiddleware[];
An array of middleware to add to the express server. These middleware are added to the beginning of the express app.
trailingSlash?: boolean;
The trailingSlash config allows you to control how the server handles trailing slashes. This config only affects URLs that do not have a file extension (i.e. HTML paths).
- When true, the server redirects URLs to add a trailing slash - When false, the server redirects URLs to remove a trailing slash - When unspecified, the server allows URLs with and without trailing slash
sessionCookieSecret?: string | string[];
Cookie secret for the session middleware.
Generate a secure secret with:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
redirects?: RootRedirectConfig[];
List of redirects. Supports optional wildcards.
redirects: [
{
source: '/old-path/[id]',
destination: '/new-path/[id]',
type: 301,
},
{
source: '/old-path/[...wildcard]',
destination: '/new-path/[...wildcard]',
},
]
headers?: RootHeaderConfig[];
HTTP headers to add to a response.
security?: RootSecurityConfig;
HTTP security settings. By default, all security settings are enabled with commonly used default values.
homePagePath?: string;
Home page URL path, which is printed when the dev server starts.
RootUserConfiginterface
interface RootUserConfig
Members (18)
domain?: string;
Canonical domain the website will serve on. Useful for things like the sitemap, SEO tags, etc.
base?: string;
The base URL path that the site will serve on. Defaults to /;
elements?: {
include?: string[];
exclude?: RegExp[];
excludeFromSsg?: ElementTagNameMatcher;
};
Config for auto-injecting custom element dependencies.
styles?: {
entries?: string[];
};
Config for manually injecting stylesheet entries as <link rel="stylesheet"> tags.
modulePreload?: boolean;
Whether to auto-inject <link rel="modulepreload"> tags for the JS chunks imported by the page's <script type="module"> tags. Disabled by default; pass modulePreload: true to opt in.
Root injects a <script type="module"> tag for every custom element and bundle used on the page, but the shared chunks those scripts import are only discovered once the browser has downloaded and parsed the script. Preloading them removes that request waterfall.
Chunks that are already injected as <script> tags are skipped, and no tags are injected by the dev server (where modules are served unbundled).
i18n?: RootI18nConfig;
Config options for localization and internationalization.
server?: RootServerConfig;
Config options for the Root.js express server.
build?: RootBuildConfig;
Build options for the root build command.
vite?: ViteUserConfig;
Vite config.
jsxRenderer?: JsxRenderOptions;
Config for the built-in JSX-to-HTML renderer.
- mode: 'pretty' (default) — block-level elements render on their own line with no indentation. - mode: 'minimal' — compact output with no extra whitespace.
Use blockElements to specify additional custom element tag names that should be treated as block-level in pretty mode.
export default defineConfig({
jsxRenderer: {
mode: 'pretty',
blockElements: ['my-card', 'my-section'],
},
});
minifyHtml?: boolean;
Whether to minify HTML output via html-minifier-terser. Disabled by default; pass minifyHtml: true to opt in.
Ignored when the built-in JSX renderer (jsxRenderer) is enabled, since that renderer controls its own output formatting via its mode option.
minifyHtmlOptions?: HtmlMinifyOptions;
Options to pass to html-minifier-terser.
prettyHtml?: boolean;
Whether to pretty print HTML output via js-beautify. Disabled by default; pass prettyHtml: true to opt in. When both prettyHtml and minifyHtml are set, prettyHtml takes precedence.
Ignored when the built-in JSX renderer (jsxRenderer) is enabled, since that renderer controls its own output formatting via its mode option.
prettyHtmlOptions?: HtmlPrettyOptions;
Options to pass to js-beautify.
sitemap?: boolean;
Whether to include a sitemap.xml file to the build output.
plugins?: Plugin[];
Plugins.
pods?: Record<string, PodConfig>;
Per-pod user-level overrides. The key is the pod name as declared in Pod.name.
experiments?: {
enableScriptAsync?: boolean;
};
Experimental config options. Note: these are subject to change at any time.
Routeinterface
interface Route
Members (7)
src: string;
The relative path to the route file, e.g. routes/index.tsx.
module: RouteModule;
The imported route module.
locale: string;
The locale used for the route.
isDefaultLocale: boolean;
Returns true if the route is the default locale route mapped without the i18n url prefix. For example, a route may be mapped to /foo and /[locale]/foo. The /foo route would have route.isDefaultLocale set to true whereas for /[locale]/foo it would be false.
routePath: string;
The mapped URL path for the route, e.g.:
routes/index.tsx => /. routes/events.tsx => /events. routes/blog/[slug].tsx => /blog/[slug].
Per the example above, this value may contain placeholder params.
localeRoutePath: string;
The localized URL path for the route, e.g. /[locale]/blog/[slug]. Per the example above, this value contains placeholder params.
podName?: string;
The name of the pod that contributed this route, or undefined if the route is from the user's project.
RouteConfiginterface
interface RouteConfig
Route-level config that a route module can export to override the site-wide serving behavior on a per-route basis.
Members (1)
locales?: string[];
Overrides the site-wide i18n.locales for this route. When set, the SSG build only generates localized paths for the locales listed here instead of the locales defined in root.config.ts. The default-locale path is always generated. Defaults to the site-wide i18n.locales.
RouteModuleinterface
interface RouteModule
Members (6)
default?: ComponentType<unknown>;
getStaticPaths?: GetStaticPaths;
getStaticProps?: GetStaticProps;
handle?: Handler;
getStaticContent?: GetStaticContent;
config?: RouteConfig;
RouteParamstype
type RouteParams = Record<string, string>;
Param values from the route, e.g. a route like /route/[slug].tsx will pass {slug: 'foo'}.
Scriptvariable
const Script: FunctionalComponent<ScriptProps>;
The <Script> component is used for rendering any custom script modules. At the moment, the system only pre-renders and bundles files that are in the /bundles folder at the root of the project.
Usage:
<Script src="/bundles/main.ts" />
Servertype
type Server = Express & {
use(...middlewares: Array<RequestMiddleware | RequestMiddleware[]>): any;
use(urlPath: string, ...middlewares: Array<RequestMiddleware | RequestMiddleware[]>): any;
};
Root.js express app.
Sitemaptype
type Sitemap = Record<string, SitemapItem>;
Sitemap is a map of URL path -> route info.
SitemapIteminterface
interface SitemapItem
Sitemap route info. The "default locale" route provides "alts" that can be used for outputting the localized url paths.
Members (6)
urlPath: string;
route: Route;
params: Record<string, string>;
locale: string;
hrefLang: string;
alts: Record<string, {
hrefLang: string;
urlPath: string;
}>;
Hreflang alts.
StaticContentResultinterface
interface StaticContentResult
Members (2)
body: string;
contentType?: string;
StringParamsContexttype
type StringParamsContext = Record<string, string>;
StringParamsProvidervariable
const StringParamsProvider: FunctionalComponent<StringParamsProviderProps>;
StyleDepsvariable
const StyleDeps: FunctionalComponent<StyleDepsProps>;
The <StyleDeps> component registers a component's CSS deps for injection into the page <head>, even when the component is imported dynamically.
Root normally collects CSS by walking a route's *static* import graph, so the .module.scss of a dynamically-imported (import()) component is never linked. Rendering <StyleDeps src="..."> alongside such a component tells Root to resolve that source file's CSS deps (via the asset map) and inject them, so a page loads only the CSS for the components it actually renders.
Usage:
<StyleDeps src="templates/Foo/Foo.tsx" />
testPathHasParamsfunction
function testPathHasParams(urlPath: string): boolean;
TranslationLanguagetype
type TranslationLanguage = string;
The language identifier used by translation systems (CSV/Sheets columns, translation services, CMS translations pages), mapped from a root locale via i18n.translationLanguages. Defaults to the root locale id.
TranslationMiddlewareProvidervariable
const TranslationMiddlewareProvider: FunctionalComponent<TranslationMiddlewareProviderProps>;
useAssetfunction
function useAsset(src: string): Asset;
Returns an asset from the project's module graph. Paths are relative to the project root and may optionally start with /.
useAssetMapfunction
function useAssetMap(): AssetMap;
Returns the asset map for the current render.
useAssetUrlfunction
function useAssetUrl(src: string): string;
Returns the serving URL for a file compiled from the project's module graph.
Usage:
const customJs = useAssetUrl('/bundles/foo.ts');
return <div data-custom-js={customJs} />;
useI18nContextfunction
function useI18nContext(): I18nContext;
A hook that returns information about the current i18n context, including the locale for the given route and a map of translations for that locale.
useRequestContextfunction
function useRequestContext(): RequestContext;
A hook that returns information about the current route.
Usage:
const ctx = useRequestContext();
ctx.route.src;
// => 'routes/index.tsx'
useStringParamsfunction
function useStringParams(): StringParamsContext;
A hook that returns a map of string params, configured via the StringParamsProvider context provider. These params are automatically applied to the useTranslations() hook.
Usage:
export default function Page() {
return (
<StringParamsProvider value={{name: 'Alice'}}>
<SayHello />
</StringParamsProvider>
);
}
function SayHello() {
const t = useTranslations();
return <h1>{t('Hello, {name}!')}</h1>;
}
This should render <h1>Hello, Alice!</h1>.
useTranslationMiddlewarefunction
function useTranslationMiddleware(): TranslationMiddlewareContext;
useTranslationsfunction
function useTranslations(): (str: string, params?: Record<string, string | number>) => string;
A hook that returns a function that can be used to translate a string, and optionally replace any parameterized values that are surrounded in curly braces.
Usage:
const t = useTranslations();
t('Hello {name}', {name: 'Bob'});
// => 'Bounjour Bob'
XFrameOptionsConfiginterface
interface XFrameOptionsConfig
Members (1)
action: 'DENY' | 'SAMEORIGIN';
@blinkk/root/cli
import {…} from '@blinkk/root/cli';
buildfunction
function build(rootProjectDir?: string, options?: BuildOptions): Promise<void>;
BuildOptionsinterface
interface BuildOptions
Members (7)
ssrOnly?: boolean;
mode?: string;
concurrency?: string | number;
filter?: string;
threads?: string | boolean;
Renders pages using worker threads. Pass a number to use exactly N workers, or pass without a value (or "auto") to pick a worker count automatically based on CPU cores and the number of pages to build.
log?: string;
Build log output mode: "progress" (default) shows a progress indicator and a final summary, "verbose" prints one line per output file, and "quiet" prints only the final summary.
quiet?: boolean;
Global -q, --quiet flag; equivalent to log: 'quiet'.
CliRunnerclass
class CliRunner
Members (1)
run(argv: string[]): Promise<void>;
createDevServerfunction
function createDevServer(options?: {
rootDir?: string;
port?: number;
}): Promise<Server>;
createPackagefunction
function createPackage(rootProjectDir?: string, options?: CreatePackageOptions): Promise<void>;
createPreviewServerfunction
function createPreviewServer(options: {
rootDir: string;
}): Promise<Server>;
createProdServerfunction
function createProdServer(options: {
rootDir: string;
}): Promise<Server>;
devfunction
function dev(rootProjectDir?: string, options?: DevOptions): Promise<void>;
previewfunction
function preview(rootProjectDir?: string, options?: PreviewOptions): Promise<void>;
startfunction
function start(rootProjectDir?: string, options?: StartOptions): Promise<void>;
@blinkk/root/functions
import {…} from '@blinkk/root/functions';
ProdServerOptionsinterface
interface ProdServerOptions
Members (3)
rootDir?: string;
mode?: 'preview' | 'production';
httpsOptions?: HttpsOptions;
serverfunction
function server(options?: ProdServerOptions): import("firebase-functions/https").HttpsFunction;
Firebase Function that runs a Root.js server running in SSR mode.
@blinkk/root/jsx
import {…} from '@blinkk/root/jsx';
Root.js server-side JSX renderer. A zero-dependency JSX runtime that replaces Preact for server-side rendering (SSR/SSG).
## Quick Start
Configure your tsconfig.json:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@blinkk/root/jsx"
}
}
Import hooks and utilities directly:
import {createContext, useContext, renderJsxToString} from '@blinkk/root/jsx';
## What's included
- jsx / jsxs / Fragment — Automatic JSX transform - createElement / h — Classic JSX transform - createContext / useContext — Context API for SSR - renderJsxToString — Render VNode trees to HTML strings - options — VNode lifecycle hook (for nonce injection, etc.) - Full TypeScript JSX type definitions
AriaAttributesinterface
interface AriaAttributes
Members (49)
role?: string;
'aria-activedescendant'?: string;
'aria-atomic'?: boolean | 'false' | 'true';
'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both';
'aria-busy'?: boolean | 'false' | 'true';
'aria-checked'?: boolean | 'false' | 'mixed' | 'true';
'aria-colcount'?: number;
'aria-colindex'?: number;
'aria-colspan'?: number;
'aria-controls'?: string;
'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time';
'aria-describedby'?: string;
'aria-details'?: string;
'aria-disabled'?: boolean | 'false' | 'true';
'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup';
'aria-errormessage'?: string;
'aria-expanded'?: boolean | 'false' | 'true';
'aria-flowto'?: string;
'aria-grabbed'?: boolean | 'false' | 'true';
'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
'aria-hidden'?: boolean | 'false' | 'true';
'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling';
'aria-keyshortcuts'?: string;
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-level'?: number;
'aria-live'?: 'off' | 'assertive' | 'polite';
'aria-modal'?: boolean | 'false' | 'true';
'aria-multiline'?: boolean | 'false' | 'true';
'aria-multiselectable'?: boolean | 'false' | 'true';
'aria-orientation'?: 'horizontal' | 'vertical';
'aria-owns'?: string;
'aria-placeholder'?: string;
'aria-posinset'?: number;
'aria-pressed'?: boolean | 'false' | 'mixed' | 'true';
'aria-readonly'?: boolean | 'false' | 'true';
'aria-relevant'?: string;
'aria-required'?: boolean | 'false' | 'true';
'aria-roledescription'?: string;
'aria-rowcount'?: number;
'aria-rowindex'?: number;
'aria-rowspan'?: number;
'aria-selected'?: boolean | 'false' | 'true';
'aria-setsize'?: number;
'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other';
'aria-valuemax'?: number;
'aria-valuemin'?: number;
'aria-valuenow'?: number;
'aria-valuetext'?: string;
ComponentChildtype
type ComponentChild = ComponentChildren;
ComponentChildrentype
type ComponentChildren = VNode<any> | string | number | bigint | boolean | null | undefined | ComponentChildren[];
Valid children types for JSX elements.
ComponentTypetype
type ComponentType<P = Record<string, unknown>> = FunctionalComponent<P>;
Generic component type (function components only for SSR).
Contextinterface
interface Context<T>
A context object created by createContext(). Provides a Provider component and can be read via useContext().
Members (3)
_defaultValue: T;
_stack: T[];
Provider: FunctionalComponent<{
value: T;
children?: ComponentChildren;
}>;
Provider component that supplies a context value to descendants.
createContextfunction
function createContext<T>(defaultValue: T): Context<T>;
Creates a new context with an optional default value. Returns a context object with a Provider component.
const ThemeContext = createContext('light');
// In a parent component:
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
// In a child component:
const theme = useContext(ThemeContext);
createElementfunction
function createElement(type: string | FunctionalComponent<any> | typeof Fragment, props?: Record<string, any> | null, ...children: any[]): VNode;
Creates a VNode. Compatible with the classic React.createElement API.
createElement('div', {className: 'foo'}, 'Hello', ' ', 'World');
CSSPropertiesinterface
interface CSSProperties extends Partial<Record<CSSPropertyName, string | number>>
Typed CSS style object accepted by the style prop. Each known CSS property maps to a string or number (a number is emitted verbatim, matching the renderer's styleToString), and CSS custom properties (--my-var) are also permitted.
DOMAttributesinterface
interface DOMAttributes
Members (43)
children?: ComponentChildren;
dangerouslySetInnerHTML?: {
__html: string;
};
onCopy?: EventHandler;
onCut?: EventHandler;
onPaste?: EventHandler;
onKeyDown?: EventHandler;
onKeyPress?: EventHandler;
onKeyUp?: EventHandler;
onFocus?: EventHandler;
onBlur?: EventHandler;
onChange?: EventHandler;
onInput?: EventHandler;
onSubmit?: EventHandler;
onReset?: EventHandler;
onClick?: EventHandler;
onContextMenu?: EventHandler;
onDoubleClick?: EventHandler;
onDrag?: EventHandler;
onDragEnd?: EventHandler;
onDragEnter?: EventHandler;
onDragExit?: EventHandler;
onDragLeave?: EventHandler;
onDragOver?: EventHandler;
onDragStart?: EventHandler;
onDrop?: EventHandler;
onMouseDown?: EventHandler;
onMouseEnter?: EventHandler;
onMouseLeave?: EventHandler;
onMouseMove?: EventHandler;
onMouseOut?: EventHandler;
onMouseOver?: EventHandler;
onMouseUp?: EventHandler;
onTouchCancel?: EventHandler;
onTouchEnd?: EventHandler;
onTouchMove?: EventHandler;
onTouchStart?: EventHandler;
onScroll?: EventHandler;
onAnimationStart?: EventHandler;
onAnimationEnd?: EventHandler;
onAnimationIteration?: EventHandler;
onTransitionEnd?: EventHandler;
onLoad?: EventHandler;
onError?: EventHandler;
Fragmentfunction
function Fragment(props: {
children?: ComponentChildren;
}): any;
Fragment component. Renders its children without a wrapper DOM element. Used as <>...</> or <Fragment>...</Fragment> in JSX.
FunctionalComponentinterface
interface FunctionalComponent<P = Record<string, unknown>>
A function component that receives props and returns a VNode or null.
Members (3)
displayName?: string;
_isProvider?: boolean;
_context?: Context<any>;
hfunction
function createElement(type: string | FunctionalComponent<any> | typeof Fragment, props?: Record<string, any> | null, ...children: any[]): VNode;
Creates a VNode. Compatible with the classic React.createElement API.
createElement('div', {className: 'foo'}, 'Hello', ' ', 'World');
HTMLAttributesinterface
interface HTMLAttributes<T = HTMLElement> extends DOMAttributes, AriaAttributes
Common HTML attributes shared by all HTML elements. The type parameter T is retained for API compatibility with Preact's HTMLAttributes<HTMLElement> pattern, but is unused at runtime since this is an SSR-only renderer.
Members (143)
accept?: string;
acceptCharset?: string;
accessKey?: string;
action?: string;
allow?: string;
allowFullScreen?: boolean;
allowTransparency?: boolean;
alt?: string;
as?: string;
async?: boolean;
autoComplete?: string;
autoCorrect?: string;
autoFocus?: boolean;
autoPlay?: boolean;
capture?: boolean | string;
cellPadding?: number | string;
cellSpacing?: number | string;
charSet?: string;
challenge?: string;
checked?: boolean;
cite?: string;
class?: string;
className?: string;
cols?: number;
colSpan?: number;
content?: string;
contentEditable?: boolean | 'true' | 'false' | 'inherit';
contextMenu?: string;
controls?: boolean;
controlsList?: string;
coords?: string;
crossOrigin?: boolean | 'anonymous' | 'use-credentials' | (string & {});
data?: string;
dateTime?: string;
default?: boolean;
defer?: boolean;
dir?: 'auto' | 'ltr' | 'rtl';
disabled?: boolean;
disableRemotePlayback?: boolean;
download?: string | boolean;
decoding?: 'sync' | 'async' | 'auto';
draggable?: boolean;
encType?: string;
enterKeyHint?: string;
for?: string;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
frameBorder?: number | string;
headers?: string;
height?: number | string;
hidden?: boolean | string;
high?: number;
href?: string;
hrefLang?: string;
htmlFor?: string;
httpEquiv?: string;
icon?: string;
id?: string;
importance?: 'auto' | 'high' | 'low';
inert?: boolean;
inputMode?: string;
integrity?: string;
is?: string;
key?: string | number;
kind?: string;
label?: string;
lang?: string;
list?: string;
loading?: 'eager' | 'lazy';
loop?: boolean;
low?: number;
manifest?: string;
marginHeight?: number;
marginWidth?: number;
max?: number | string;
maxLength?: number;
media?: string;
mediaGroup?: string;
method?: string;
min?: number | string;
minLength?: number;
multiple?: boolean;
muted?: boolean;
name?: string;
noModule?: boolean;
nonce?: string;
noValidate?: boolean;
open?: boolean;
optimum?: number;
part?: string;
pattern?: string;
placeholder?: string;
playsInline?: boolean;
poster?: string;
preload?: string;
radioGroup?: string;
readOnly?: boolean;
referrerPolicy?: string;
rel?: string;
required?: boolean;
reversed?: boolean;
rows?: number;
rowSpan?: number;
sandbox?: string;
scope?: string;
scoped?: boolean;
scrolling?: string;
seamless?: boolean;
selected?: boolean;
shape?: string;
size?: number;
sizes?: string;
slot?: string;
span?: number;
spellcheck?: boolean;
src?: string;
srcDoc?: string;
srcLang?: string;
srcSet?: string;
start?: number;
step?: number | string;
style?: string | CSSProperties;
summary?: string;
tabIndex?: number;
target?: string;
title?: string;
translate?: 'yes' | 'no';
type?: string;
useMap?: string;
value?: string | string[] | number;
volume?: number;
width?: number | string;
wmode?: string;
wrap?: string;
autocapitalize?: string;
disablePictureInPicture?: boolean;
results?: number;
security?: string;
unselectable?: 'on' | 'off';
jsxfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
JSXnamespace
namespace JSX
Exports (3)
type Element = VNode<any>;
interface ElementChildrenAttribute
interface IntrinsicElements
jsxsfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
Keytype
type Key = string | number | null;
optionsvariable
const options: {
vnode?: (vnode: VNode<any>) => void;
};
Global options object. The vnode callback is invoked for every VNode created via jsx(), jsxs(), or createElement(). This is used by the renderer to inject nonce values into script/style tags.
renderJsxToStringfunction
function renderJsxToString(vnode: VNode, options?: JsxRenderOptions): string;
Renders a Preact VNode tree to an HTML string.
ScriptHTMLAttributesinterface
interface ScriptHTMLAttributes<T = HTMLScriptElement> extends HTMLAttributes<T>
Script-specific HTML attributes (for the <Script> component).
Members (9)
async?: boolean;
crossOrigin?: boolean | 'anonymous' | 'use-credentials' | (string & {});
defer?: boolean;
integrity?: string;
noModule?: boolean;
nonce?: string;
referrerPolicy?: string;
src?: string;
type?: string;
SVGAttributesinterface
interface SVGAttributes<T = SVGElement> extends HTMLAttributes<T>
SVG-specific attributes.
Members (103)
accentHeight?: number | string;
accumulate?: 'none' | 'sum';
additive?: 'replace' | 'sum';
alignmentBaseline?: string;
allowReorder?: 'no' | 'yes';
clipPath?: string;
clipPathUnits?: string;
clipRule?: string;
colorInterpolation?: string;
colorInterpolationFilters?: string;
cursor?: string;
cx?: number | string;
cy?: number | string;
d?: string;
dominantBaseline?: string;
dx?: number | string;
dy?: number | string;
fill?: string;
fillOpacity?: number | string;
fillRule?: 'nonzero' | 'evenodd' | 'inherit';
filter?: string;
floodColor?: string;
floodOpacity?: number | string;
fontFamily?: string;
fontSize?: number | string;
fontStyle?: string;
fontVariant?: string;
fontWeight?: number | string;
fx?: number | string;
fy?: number | string;
gradientTransform?: string;
gradientUnits?: string;
imageRendering?: string;
in?: string;
in2?: string;
k1?: number;
k2?: number;
k3?: number;
k4?: number;
letterSpacing?: number | string;
lightingColor?: string;
markerEnd?: string;
markerHeight?: number | string;
markerMid?: string;
markerStart?: string;
markerUnits?: string;
markerWidth?: number | string;
mask?: string;
offset?: number | string;
opacity?: number | string;
operator?: string;
order?: number | string;
overflow?: string;
paintOrder?: string;
pathLength?: number;
patternContentUnits?: string;
patternTransform?: string;
patternUnits?: string;
pointerEvents?: string;
points?: string;
preserveAspectRatio?: string;
r?: number | string;
result?: string;
rx?: number | string;
ry?: number | string;
shapeRendering?: string;
stopColor?: string;
stopOpacity?: number | string;
stroke?: string;
strokeDasharray?: string | number;
strokeDashoffset?: string | number;
strokeLinecap?: 'butt' | 'round' | 'square';
strokeLinejoin?: 'miter' | 'round' | 'bevel';
strokeMiterlimit?: number | string;
strokeOpacity?: number | string;
strokeWidth?: number | string;
textAnchor?: string;
textDecoration?: string;
textRendering?: string;
transform?: string;
vectorEffect?: string;
version?: string;
viewBox?: string;
visibility?: string;
wordSpacing?: number | string;
writingMode?: string;
x?: number | string;
x1?: number | string;
x2?: number | string;
xlinkActuate?: string;
xlinkArcrole?: string;
xlinkHref?: string;
xlinkRole?: string;
xlinkShow?: string;
xlinkTitle?: string;
xlinkType?: string;
xmlns?: string;
xmlBase?: string;
xmlLang?: string;
xmlSpace?: string;
y?: number | string;
y1?: number | string;
y2?: number | string;
useContextfunction
function useContext<T>(context: Context<T>): T;
Reads the current value of a context. Must be called during the render of a function component that is a descendant of a matching Provider. Returns the default value if no Provider is found.
const theme = useContext(ThemeContext);
VNodeinterface
interface VNode<P = Record<string, unknown>>
A virtual DOM node representing an element, component, or fragment.
Members (3)
type: string | FunctionalComponent<P> | typeof Fragment | (new (...args: any[]) => any);
props: P;
key: Key;
@blinkk/root/jsx/jsx-runtime
import {…} from '@blinkk/root/jsx/jsx-runtime';
Server-side JSX runtime for Root.js. Replaces Preact as the JSX renderer for server-side rendering (SSR/SSG). This module provides the automatic JSX transform entry point (jsxImportSource).
Supports: - Automatic JSX transform (jsx, jsxs, Fragment) - Classic JSX transform (createElement / h) - Context API (createContext, useContext) - Server-side renderToString
ComponentChildtype
type ComponentChild = ComponentChildren;
ComponentChildrentype
type ComponentChildren = VNode<any> | string | number | bigint | boolean | null | undefined | ComponentChildren[];
Valid children types for JSX elements.
ComponentTypetype
type ComponentType<P = Record<string, unknown>> = FunctionalComponent<P>;
Generic component type (function components only for SSR).
Contextinterface
interface Context<T>
A context object created by createContext(). Provides a Provider component and can be read via useContext().
Members (3)
_defaultValue: T;
_stack: T[];
Provider: FunctionalComponent<{
value: T;
children?: ComponentChildren;
}>;
Provider component that supplies a context value to descendants.
createContextfunction
function createContext<T>(defaultValue: T): Context<T>;
Creates a new context with an optional default value. Returns a context object with a Provider component.
const ThemeContext = createContext('light');
// In a parent component:
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
// In a child component:
const theme = useContext(ThemeContext);
createElementfunction
function createElement(type: string | FunctionalComponent<any> | typeof Fragment, props?: Record<string, any> | null, ...children: any[]): VNode;
Creates a VNode. Compatible with the classic React.createElement API.
createElement('div', {className: 'foo'}, 'Hello', ' ', 'World');
Fragmentfunction
function Fragment(props: {
children?: ComponentChildren;
}): any;
Fragment component. Renders its children without a wrapper DOM element. Used as <>...</> or <Fragment>...</Fragment> in JSX.
FunctionalComponentinterface
interface FunctionalComponent<P = Record<string, unknown>>
A function component that receives props and returns a VNode or null.
Members (3)
displayName?: string;
_isProvider?: boolean;
_context?: Context<any>;
hfunction
function createElement(type: string | FunctionalComponent<any> | typeof Fragment, props?: Record<string, any> | null, ...children: any[]): VNode;
Creates a VNode. Compatible with the classic React.createElement API.
createElement('div', {className: 'foo'}, 'Hello', ' ', 'World');
jsxfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
JSXnamespace
namespace JSX
Exports (3)
type Element = VNode<any>;
interface ElementChildrenAttribute
interface IntrinsicElements
jsxsfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
Keytype
type Key = string | number | null;
optionsvariable
const options: {
vnode?: (vnode: VNode<any>) => void;
};
Global options object. The vnode callback is invoked for every VNode created via jsx(), jsxs(), or createElement(). This is used by the renderer to inject nonce values into script/style tags.
useContextfunction
function useContext<T>(context: Context<T>): T;
Reads the current value of a context. Must be called during the render of a function component that is a descendant of a matching Provider. Returns the default value if no Provider is found.
const theme = useContext(ThemeContext);
VNodeinterface
interface VNode<P = Record<string, unknown>>
A virtual DOM node representing an element, component, or fragment.
Members (3)
type: string | FunctionalComponent<P> | typeof Fragment | (new (...args: any[]) => any);
props: P;
key: Key;
@blinkk/root/jsx/jsx-dev-runtime
import {…} from '@blinkk/root/jsx/jsx-dev-runtime';
Development JSX runtime entry point. For SSR, this is identical to the production runtime since there is no client-side diffing or dev warnings to add. TypeScript / bundlers look for this module when jsxImportSource is configured and the build is in development mode.
Fragmentfunction
function Fragment(props: {
children?: ComponentChildren;
}): any;
Fragment component. Renders its children without a wrapper DOM element. Used as <>...</> or <Fragment>...</Fragment> in JSX.
jsxfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
JSXnamespace
namespace JSX
Exports (3)
type Element = VNode<any>;
interface ElementChildrenAttribute
interface IntrinsicElements
jsxDEVfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
jsxsfunction
function jsx(type: string | FunctionalComponent<any> | typeof Fragment, props: Record<string, any>, key?: Key): VNode;
Creates a VNode. Used by the automatic JSX transform for elements with a single child or no children.
@blinkk/root/middleware
import {…} from '@blinkk/root/middleware';
compressionMiddlewarefunction
function compressionMiddleware(): (req: Request, res: Response, next: NextFunction) => void;
Response compression middleware shared by the preview and prod servers.
Uses brotli when the client accepts it (Accept-Encoding: br), falling back to gzip. Brotli quality 4 is used as a balance between compression ratio and CPU cost for dynamically-rendered responses — it generally compresses better than gzip's default (level 6) at comparable speed. Pre-compressed static assets should still be served with higher quality settings by a CDN or static file server where possible.
headersMiddlewarefunction
function headersMiddleware(options: {
rootConfig: RootConfig;
}): (req: Request, res: Response, next: NextFunction) => void;
Middleware that injects HTTP headers from the server.headers config in root.config.ts.
multipartMiddlewarefunction
function multipartMiddleware(options?: {
maxFileSize?: number;
}): RequestHandler;
Middleware for parsing multipart file uploads that's compatible with the dev server and Firebase Functions.
Context: https://stackoverflow.com/questions/47242340/how-to-perform-an-http-file-upload-using-express-on-cloud-functions-for-firebase
rootProjectMiddlewarefunction
function rootProjectMiddleware(options: {
rootConfig: RootConfig;
}): (req: Request, _: Response, next: NextFunction) => void;
Middleware that injects the root.js project config into the request context.
SaveSessionOptionsinterface
interface SaveSessionOptions
Members (1)
sameSite?: 'strict' | 'lax' | 'none';
securityHeadersMiddlewarefunction
function securityHeadersMiddleware(options: {
rootConfig: RootConfig;
}): (req: Request, res: Response, next: NextFunction) => void;
Middleware that sets security-related HTTP headers (e.g. Strict-Transport-Security) on all responses using the server.security config in root.config.ts.
The renderer sets these headers on rendered HTML responses, but responses that bypass the renderer (e.g. redirects, static files, plugin-served responses, 404s) would otherwise be served without them. Per https://hstspreload.org, HSTS preload eligibility requires the HSTS header on redirects as well.
NOTE: Content-Security-Policy is excluded here since the CSP is document-specific and depends on a per-request nonce, which is generated by the renderer at render time.
Sessionclass
class Session
Members (6)
hasChanges: boolean;
static fromCookieValue(cookieValue: string): Session;
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
toString(): string;
SESSION_COOKIEvariable
const SESSION_COOKIE = "__session";
sessionMiddlewarefunction
function sessionMiddleware(options?: SessionMiddlewareOptions): (req: Request, res: Response, next: NextFunction) => void;
Middleware for storing session data stored in an http cookie called __session. This cookie is compatible with Firebase Hosting: https://firebase.google.com/docs/hosting/manage-cache#using_cookies
SessionMiddlewareOptionsinterface
interface SessionMiddlewareOptions
Members (1)
maxAge?: number;
trailingSlashMiddlewarefunction
function trailingSlashMiddleware(options: {
rootConfig: RootConfig;
}): (req: Request, res: Response, next: NextFunction) => void;
Trailing slash middleware. Handles trailing slash redirects (preserving any query params) using the server.trailingSlash config in root.config.ts.
@blinkk/root/node
import {…} from '@blinkk/root/node';
bundleRootConfigfunction
function bundleRootConfig(rootDir: string, outPath: string): Promise<void>;
Compiles a root.config.ts file to root.config.js.
collectPodsfunction
function collectPods(rootConfig: RootConfig): Promise<ResolvedPod[]>;
ConfigOptionsinterface
interface ConfigOptions
Members (1)
command: string;
createViteServerfunction
function createViteServer(rootConfig: RootConfig, options?: CreateViteServerOptions): Promise<ViteDevServer>;
Returns a vite dev server.
CreateViteServerOptionsinterface
interface CreateViteServerOptions
Members (3)
hmr?: boolean;
Override HMR settings.
port?: number;
The port the server will run on.
optimizeDeps?: string[];
List of files to include in the optimizeDeps.include config.
flattenPackageDepsFromMonorepofunction
function flattenPackageDepsFromMonorepo(rootDir: string, options?: {
ignore?: Set<string>;
}): Record<string, string>;
Flattens package.json deps from the root project dir, taking into account any deps from the monorepo root as well as any workspace: deps from within the monorepo.
getMonorepoPackageDepsfunction
function getMonorepoPackageDeps(rootDir: string): Record<string, string>;
Returns the top-level monorepo package's deps, if any.
invalidatePodCachefunction
function invalidatePodCache(): void;
loadBundledConfigfunction
function loadBundledConfig(rootDir: string, options: ConfigOptions): Promise<RootConfig>;
Loads a pre-bundled config file from dist/root.config.js.
loadPackageJsonfunction
function loadPackageJson(filepath: string): PackageInfo | null;
loadRootConfigfunction
function loadRootConfig(rootDir: string, options: ConfigOptions): Promise<RootConfig>;
loadRootConfigWithDepsfunction
function loadRootConfigWithDeps(rootDir: string, options: ConfigOptions): Promise<{
rootConfig: RootConfig;
dependencies: string[];
}>;
ResolvedPodinterface
interface ResolvedPod
Members (14)
name: string;
enabled: boolean;
mount: string;
priority: number;
routesDir?: string;
elementsDirs: string[];
bundlesDir?: string;
collectionsDir?: string;
translationsDir?: string;
routeFiles: ResolvedPodRoute[];
bundleFiles: string[];
collectionFiles: ResolvedPodCollection[];
translationFiles: Array<{
locale: string;
filePath: string;
}>;
config: PodConfig;
ResolvedPodCollectioninterface
interface ResolvedPodCollection
Members (3)
filePath: string;
relPath: string;
id: string;
ResolvedPodRouteinterface
interface ResolvedPodRoute
Members (3)
filePath: string;
relPath: string;
routePath: string;
viteSsrLoadModulefunction
function viteSsrLoadModule<T = Record<string, any>>(rootConfig: RootConfig, file: string): Promise<T>;
Shortcut viteServer.ssrLoadModule() without starting an actual dev server.
@blinkk/root/render
import {…} from '@blinkk/root/render';
Rendererclass
class Renderer
Members (11)
getRoute(url: string): [
Route | undefined,
Record<string, string>
];
Returns a route from the router.
getRouteMatches(url: string): Array<[
Route,
Record<string, string>
]>;
Returns all routes that match a given url path.
walkRoutes(cb: (urlPathFormat: string, route: Route) => void | Promise<void>): Promise<void>;
Walks all routes registered with the router.
handle(req: Request, res: Response, next: NextFunction): Promise<void>;
renderRoute(route: Route, options: {
routeParams: Record<string, string>;
}): Promise<{
html?: string;
notFound?: boolean;
}>;
SSG renders a route.
handleRoute(req: Request, res: Response, next: NextFunction, route: Route, options?: {
defaultStatusCode?: number;
routeParams?: Record<string, string>;
nextRouteHandler?: () => void | Promise<void>;
}): Promise<void>;
Handles the SSR rendering of a route.
getSitemap(): Promise<Sitemap>;
Constructs and returns the project's sitemap.
The sitemap is used to: - determine all paths to build in SSG mode - display links on the dev server's 404 page - construct alternates for localized URL paths
render404(options?: {
currentPath?: string;
}): Promise<{
html: string;
}>;
renderError(err: any, options?: {
currentPath?: string;
}): Promise<{
html: string;
}>;
renderDevServer404(req: Request): Promise<{
html: string;
}>;
renderDevServer500(req: Request, error: unknown): Promise<{
html: string;
}>;
@blinkk/root/utils
import {…} from '@blinkk/root/utils';
jsonStringifyfunction
function jsonStringify(value: unknown, options?: JsonStringifyOptions): string;
Serializes data to a JSON string with Unix (LF) line endings.
Unlike JSON.stringify(), this: - Recursively normalizes \r\n and \r to \n in string values, so round-tripping through JSON.parse won't yield CRLF line endings. - Normalizes line endings in the resulting JSON string itself.
JsonStringifyOptionsinterface
interface JsonStringifyOptions
Members (1)
indent?: number | string;
Indentation passed through to JSON.stringify. Accepts a number of spaces or an indent string.
normalizeLineEndingsfunction
function normalizeLineEndings(value: string): string;
Normalizes line endings in a string to LF (\n).
Converts CRLF (\r\n) and lone CR (\r) to LF.