barejs 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +132 -125
  2. package/dist/aws-lambda.js +1 -0
  3. package/dist/cache.js +1 -0
  4. package/dist/cloudflare-pages.js +1 -0
  5. package/dist/edge.js +29 -29
  6. package/dist/etag.js +1 -0
  7. package/dist/html.js +1 -0
  8. package/dist/index.js +194 -189
  9. package/dist/jsx.js +1 -0
  10. package/dist/netlify.js +1 -0
  11. package/dist/node.js +194 -189
  12. package/dist/ssg.js +1 -0
  13. package/dist/types/adapters/aws-lambda.d.ts +43 -0
  14. package/dist/types/adapters/cloudflare-pages.d.ts +18 -0
  15. package/dist/types/adapters/netlify.d.ts +32 -0
  16. package/dist/types/core/bare.d.ts +8 -5
  17. package/dist/types/core/radix.d.ts +5 -0
  18. package/dist/types/core/router.d.ts +4 -0
  19. package/dist/types/edge.d.ts +2 -0
  20. package/dist/types/index.d.ts +3 -0
  21. package/dist/types/security/validators.d.ts +1 -0
  22. package/dist/types/utils/cache.d.ts +26 -0
  23. package/dist/types/utils/etag.d.ts +12 -0
  24. package/dist/types/utils/file.d.ts +23 -0
  25. package/dist/types/utils/html.d.ts +22 -0
  26. package/dist/types/utils/jsx.d.ts +34 -0
  27. package/dist/types/utils/ssg.d.ts +36 -0
  28. package/llms.txt +26 -3
  29. package/package.json +42 -2
  30. package/src/adapters/aws-lambda.ts +166 -0
  31. package/src/adapters/cloudflare-pages.ts +27 -0
  32. package/src/adapters/netlify.ts +28 -0
  33. package/src/core/bare.ts +86 -8
  34. package/src/core/radix.ts +46 -10
  35. package/src/core/router.ts +37 -6
  36. package/src/edge.ts +2 -0
  37. package/src/index.ts +3 -0
  38. package/src/security/validators.ts +24 -4
  39. package/src/utils/cache.ts +128 -0
  40. package/src/utils/etag.ts +115 -0
  41. package/src/utils/file.ts +111 -0
  42. package/src/utils/html.ts +72 -0
  43. package/src/utils/jsx.ts +217 -0
  44. package/src/utils/openapi.ts +7 -0
  45. package/src/utils/ssg.ts +110 -0
package/dist/ssg.js ADDED
@@ -0,0 +1 @@
1
+ var R=Object.create;var{getPrototypeOf:U,defineProperty:O,getOwnPropertyNames:V}=Object;var W=Object.prototype.hasOwnProperty;var X=(j,k,H)=>{H=j!=null?R(U(j)):{};let L=k||!j||!j.__esModule?O(H,"default",{value:j,enumerable:!0}):H;for(let z of V(j))if(!W.call(L,z))O(L,z,{get:()=>j[z],enumerable:!0});return L};var Y=((j)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(j,{get:(k,H)=>(typeof require!=="undefined"?require:k)[H]}):j)(function(j){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});var Z=(j,k,H,L)=>{let z=j.replace(/\/+$/,""),v=k.startsWith("/")?k:"/"+k;if(v==="/"||v==="")return`${z}/index.html`;if(v.slice(v.lastIndexOf("/")+1).includes("."))return`${z}${v}`;let K=H.toLowerCase();if(K.includes("application/json"))return`${z}${v}.json`;if(K.includes("text/plain"))return`${z}${v}.txt`;if(K.includes("application/xml")||K.includes("text/xml"))return`${z}${v}.xml`;return L?`${z}${v}/index.html`:`${z}${v}.html`},$=async(j,k={})=>{let H=k.dir??"./static",L=k.dirIndex??!1,z=(k.origin??"http://localhost").replace(/\/+$/,""),v=[];try{let J;if(k.fs)J=k.fs;else{let A=await import("node:fs/promises");J={mkdir:(q,C)=>A.mkdir(q,C),writeFile:(q,C)=>A.writeFile(q,C)}}let K=new Set;if(Array.isArray(j.routes))for(let A=0;A<j.routes.length;A++){let q=j.routes[A];if(q.method!=="GET")continue;let C=q.path||"/";if(C.includes(":")||C.includes("*"))continue;K.add(C.startsWith("/")?C:"/"+C)}if(k.routes)for(let A=0;A<k.routes.length;A++){let q=k.routes[A];K.add(q.startsWith("/")?q:"/"+q)}for(let A of K){let q=await j.fetch(new Request(`${z}${A}`,{method:"GET"}));if(q.status<200||q.status>=300)continue;let C=q.headers.get("content-type")??"text/html",M=Z(H,A,C,L),N=M.slice(0,M.lastIndexOf("/"));if(N)await J.mkdir(N,{recursive:!0});let Q=new Uint8Array(await q.arrayBuffer());await J.writeFile(M,Q),v.push(M)}return{success:!0,files:v}}catch(J){return{success:!1,files:v,error:J instanceof Error?J:new Error(String(J))}}};export{$ as toSSG};
@@ -0,0 +1,43 @@
1
+ export interface LambdaEvent {
2
+ version?: string;
3
+ rawPath?: string;
4
+ rawQueryString?: string;
5
+ cookies?: string[];
6
+ requestContext?: {
7
+ http?: {
8
+ method?: string;
9
+ path?: string;
10
+ sourceIp?: string;
11
+ };
12
+ identity?: {
13
+ sourceIp?: string;
14
+ };
15
+ domainName?: string;
16
+ };
17
+ httpMethod?: string;
18
+ path?: string;
19
+ queryStringParameters?: Record<string, string | undefined> | null;
20
+ multiValueQueryStringParameters?: Record<string, string[] | undefined> | null;
21
+ headers?: Record<string, string | undefined> | null;
22
+ multiValueHeaders?: Record<string, string[] | undefined> | null;
23
+ body?: string | null;
24
+ isBase64Encoded?: boolean;
25
+ }
26
+ export interface LambdaResult {
27
+ statusCode: number;
28
+ headers: Record<string, string>;
29
+ cookies?: string[];
30
+ multiValueHeaders?: Record<string, string[]>;
31
+ body: string;
32
+ isBase64Encoded: boolean;
33
+ }
34
+ export interface FetchableApp {
35
+ fetch(req: Request, peerIp?: string): Response | Promise<Response>;
36
+ }
37
+ /**
38
+ * Optional AWS Lambda adapter for BareJS (`import { awsLambda, handle } from 'barejs/aws-lambda'`).
39
+ * Supports API Gateway HTTP API (v2), REST API (v1), and Application Load Balancer (ALB) events
40
+ * with zero dependencies and zero impact on core bundle size.
41
+ */
42
+ export declare const awsLambda: (app: FetchableApp) => (event: LambdaEvent) => Promise<LambdaResult>;
43
+ export declare const handle: (app: FetchableApp) => (event: LambdaEvent) => Promise<LambdaResult>;
@@ -0,0 +1,18 @@
1
+ export interface CloudflarePagesContext<Env = Record<string, any>> {
2
+ request: Request;
3
+ env: Env;
4
+ params: Record<string, string | string[]>;
5
+ waitUntil(promise: Promise<any>): void;
6
+ next(input?: Request | string, init?: RequestInit): Promise<Response>;
7
+ data: Record<string, unknown>;
8
+ }
9
+ interface FetchableEdgeApp {
10
+ fetch(req: Request, env?: any, executionCtx?: any): Response | Promise<Response>;
11
+ }
12
+ /**
13
+ * Cloudflare Pages Functions adapter (`onRequest`).
14
+ * Usage: `export const onRequest = handle(app);`
15
+ */
16
+ export declare const handle: <Env = Record<string, any>>(app: FetchableEdgeApp) => (context: CloudflarePagesContext<Env>) => Response | Promise<Response>;
17
+ export declare const cloudflarePages: <Env = Record<string, any>>(app: FetchableEdgeApp) => (context: CloudflarePagesContext<Env>) => Response | Promise<Response>;
18
+ export {};
@@ -0,0 +1,32 @@
1
+ export interface NetlifyContext {
2
+ ip?: string;
3
+ requestId?: string;
4
+ site?: {
5
+ id?: string;
6
+ name?: string;
7
+ url?: string;
8
+ };
9
+ geo?: {
10
+ city?: string;
11
+ country?: {
12
+ code?: string;
13
+ name?: string;
14
+ };
15
+ timezone?: string;
16
+ };
17
+ cookies?: {
18
+ get(name: string): string | undefined;
19
+ };
20
+ waitUntil?(promise: Promise<any>): void;
21
+ [key: string]: any;
22
+ }
23
+ interface FetchableApp {
24
+ fetch(req: Request, peerIpOrEnv?: any, executionCtx?: any): Response | Promise<Response>;
25
+ }
26
+ /**
27
+ * Netlify Functions v2 adapter.
28
+ * Usage: `export default handle(app);`
29
+ */
30
+ export declare const handle: (app: FetchableApp) => (req: Request, context?: NetlifyContext) => Response | Promise<Response>;
31
+ export declare const netlify: (app: FetchableApp) => (req: Request, context?: NetlifyContext) => Response | Promise<Response>;
32
+ export {};
@@ -58,6 +58,9 @@ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<an
58
58
  params: S extends {
59
59
  params: infer Pa;
60
60
  } ? InferSchema<Pa> : Record<string, any>;
61
+ cookies: S extends {
62
+ cookies: infer C;
63
+ } ? InferSchema<C> : Record<string, string>;
61
64
  }) => Res | Promise<Res>;
62
65
  type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> = {
63
66
  <P extends string, S extends RouteSchemas & MacroOptions<Macros>, Res = S extends {
@@ -169,11 +172,11 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
169
172
  head: AddRoute<Derived, Routes, 'HEAD', Macros>;
170
173
  all: AddRoute<Derived, Routes, 'ALL', Macros>;
171
174
  route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
172
- use: {
173
- <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
174
- <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
175
- (mw: any): BareJS<Derived, Routes, Macros>;
176
- };
175
+ use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & R2, Macros & M2>;
176
+ use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(prefix: P, mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
177
+ use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
178
+ use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
179
+ use(...mws: any[]): BareJS<Derived, Routes, Macros>;
177
180
  /**
178
181
  * Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
179
182
  * Zero overhead on routes that do not opt into a macro.
@@ -4,6 +4,11 @@ export declare class RadixNode {
4
4
  staticKeys: string[];
5
5
  paramNode: RadixNode | null;
6
6
  paramName: string | null;
7
+ regexParamNodes: Array<{
8
+ regex: RegExp;
9
+ pattern: string;
10
+ node: RadixNode;
11
+ }>;
7
12
  wildcardNode: RadixNode | null;
8
13
  handlers: Record<string, Function>;
9
14
  handlerParams: Record<string, string[]>;
@@ -47,6 +47,9 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
47
47
  params: S extends {
48
48
  params: infer Pa;
49
49
  } ? InferSchema<Pa> : Record<string, any>;
50
+ cookies: S extends {
51
+ cookies: infer C;
52
+ } ? InferSchema<C> : Record<string, string>;
50
53
  }) => Res | Promise<Res>;
51
54
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
52
55
  <P extends string, S extends RouteSchemas, Res = S extends {
@@ -87,6 +90,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
87
90
  routes: any[];
88
91
  protected _onRouteMutate?(): void;
89
92
  constructor(prefix?: string, groupMiddleware?: any[]);
93
+ private static expandOptionalPaths;
90
94
  protected _add(method: string, path: string, handlers: HandlersChain): this;
91
95
  get: AddRouterRoute<Routes, 'GET'>;
92
96
  post: AddRouterRoute<Routes, 'POST'>;
@@ -96,4 +96,6 @@ export declare function createSingleflight(): {
96
96
  size(): number;
97
97
  };
98
98
  export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
99
+ export { html, raw, escapeHtml, type HtmlString } from './utils/html';
100
+ export { etag, type EtagOptions } from './utils/etag';
99
101
  export { BareEdge as BareJS, BareRouter, Type, t, Z, z, native, standard, bareClient, bareTreaty, cors, securityHeaders, rateLimit, timeout, circuitBreaker, redisStore, healthcheck, logger, generateOpenAPISpec, renderDocsHTML };
@@ -29,9 +29,12 @@ export { redisStore, type BareStore, type RateLimitStore, type IdempotencyStore,
29
29
  export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
30
30
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
31
31
  export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
32
+ export { file, type FileResponseOptions } from './utils/file';
32
33
  export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
33
34
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
34
35
  export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
36
+ export { html, raw, escapeHtml, type HtmlString } from './utils/html';
37
+ export { etag, type EtagOptions } from './utils/etag';
35
38
  export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
36
39
  export { Hash as Password, Hash } from './security/hash';
37
40
  export { bareClient, bareTreaty, type BareClient, type BareSafeClient, type BareTreatyNode, type TreatyTree, type BareClientResult, type BareWsClient, type BareClientOptions, type ClientRequestOptions, type RouteEndpoint, type RouteSchema } from './client/index';
@@ -67,6 +67,7 @@ export interface RouteSchemas {
67
67
  query?: any;
68
68
  params?: any;
69
69
  headers?: any;
70
+ cookies?: any;
70
71
  response?: any;
71
72
  /** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
72
73
  stripUnknown?: boolean;
@@ -0,0 +1,26 @@
1
+ import type { Context, Middleware } from '../core/context';
2
+ export interface CacheLike {
3
+ match(request: Request | string): Promise<Response | undefined>;
4
+ put(request: Request | string, response: Response): Promise<void>;
5
+ }
6
+ export interface CacheOptions {
7
+ /** Cache name for Web Cache API (`caches.open(cacheName)`). Falls back to `caches.default` on Cloudflare Workers. */
8
+ cacheName?: string;
9
+ /** Optional custom `Cache`-compatible store (overrides `globalThis.caches`, useful for testing or custom stores). */
10
+ cache?: CacheLike;
11
+ /** `Cache-Control` header value applied to cacheable 200 OK responses (e.g. `'public, max-age=60, stale-while-revalidate=30'`). */
12
+ cacheControl?: string;
13
+ /** Optional `Vary` header(s) appended to responses (e.g. `'Accept-Encoding'` or `['Accept', 'Accept-Language']`). */
14
+ vary?: string | string[];
15
+ /** Custom cache key generator (defaults to `ctx.req.url`). */
16
+ keyGenerator?: (ctx: Context) => string;
17
+ /** Await `cache.put()` before returning the response (default: `false`; uses `executionCtx.waitUntil` when available). */
18
+ wait?: boolean;
19
+ /** HTTP status codes eligible for caching (default: `[200]`). */
20
+ cacheableStatuses?: number[];
21
+ }
22
+ /**
23
+ * Zero-dependency HTTP `Cache-Control` + Web Cache API (`caches.default` / `caches.open`) middleware.
24
+ * Edge-safe (Cloudflare Workers, Deno Deploy, Bun, Node.js). Caches GET/HEAD responses only.
25
+ */
26
+ export declare const cache: (options?: CacheOptions) => Middleware;
@@ -0,0 +1,12 @@
1
+ import type { Middleware } from '../core/context';
2
+ export interface EtagOptions {
3
+ /** Emit weak ETags `W/"..."` (default: `true`, fast zero-async FNV-1a 64-bit) */
4
+ weak?: boolean;
5
+ /** Retain these headers on 304 Not Modified responses */
6
+ retainedHeaders?: string[];
7
+ }
8
+ /**
9
+ * Dynamic API ETag middleware (`304 Not Modified` support).
10
+ * Edge-safe, zero dependencies, skips streaming/SSE and non-200 responses.
11
+ */
12
+ export declare const etag: (options?: EtagOptions) => Middleware;
@@ -0,0 +1,23 @@
1
+ export interface FileResponseOptions {
2
+ /** Optional root directory jail — blocks path traversal and symlinks escaping `root` (403) */
3
+ root?: string;
4
+ /** Override Content-Type header */
5
+ type?: string;
6
+ /** Set Content-Disposition: attachment (pass `true` for basename or a custom filename) */
7
+ download?: boolean | string;
8
+ /** Optional Cache-Control header value */
9
+ cacheControl?: string;
10
+ /** Additional custom response headers */
11
+ headers?: Record<string, string>;
12
+ /** HTTP status code (default: 200) */
13
+ status?: number;
14
+ }
15
+ /**
16
+ * Ergonomic 1-liner file response helper:
17
+ * `app.get('/logo', () => file('public/logo.png'))`
18
+ * `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))`
19
+ *
20
+ * Uses zero-copy `Bun.file` on Bun and streaming `fs.createReadStream` on Node.js.
21
+ * Enforces null-byte rejection and optional `root` directory/symlink containment.
22
+ */
23
+ export declare const file: (filePath: string, options?: FileResponseOptions) => Response;
@@ -0,0 +1,22 @@
1
+ declare const RAW_BRAND: unique symbol;
2
+ export interface HtmlString {
3
+ readonly [RAW_BRAND]: true;
4
+ readonly value: string;
5
+ toString(): string;
6
+ toResponse(status?: number, headers?: Record<string, string>): Response;
7
+ }
8
+ export declare const escapeHtml: (input: string) => string;
9
+ /**
10
+ * Marks a trusted HTML string so `html` tagged templates will not double-escape it.
11
+ * Only pass sanitized or static trusted markup.
12
+ */
13
+ export declare const raw: (trustedHtml: string) => HtmlString;
14
+ /**
15
+ * XSS-safe HTML tagged template literal (Edge-safe, zero dependencies).
16
+ *
17
+ * Example:
18
+ * `app.get('/hi', (ctx) => html\`<h1>Hello ${ctx.query.name}</h1>\`.toResponse())`
19
+ * `app.get('/hi', (ctx) => ctx.html(String(html\`<h1>Hello ${ctx.query.name}</h1>\`)))`
20
+ */
21
+ export declare const html: (strings: TemplateStringsArray, ...values: unknown[]) => HtmlString;
22
+ export {};
@@ -0,0 +1,34 @@
1
+ import { escapeHtml, raw, type HtmlString } from './html';
2
+ export { escapeHtml, raw, type HtmlString };
3
+ export type JSXChild = JSXNode | HtmlString | string | number | boolean | null | undefined | JSXChild[];
4
+ export type Component<P = any> = (props: P) => JSXChild | Promise<JSXChild>;
5
+ export interface JSXNode {
6
+ readonly $$bareJsx: true;
7
+ type: string | typeof Fragment | typeof Suspense | Component<any>;
8
+ props: Record<string, any>;
9
+ }
10
+ export declare const Fragment: unique symbol;
11
+ export declare const Suspense: unique symbol;
12
+ export declare const jsx: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
13
+ export declare const jsxs: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
14
+ export declare const jsxDEV: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
15
+ /** Renders a JSX tree (including async components) to an HTML string. */
16
+ export declare const renderToString: (node: JSXChild) => Promise<string>;
17
+ /**
18
+ * Streams a JSX tree as a Web `ReadableStream<Uint8Array>`, flushing `<Suspense fallback>`
19
+ * immediately and streaming out-of-order `<template>` replacement chunks as async children resolve.
20
+ */
21
+ export declare const renderToReadableStream: (node: JSXChild) => ReadableStream<Uint8Array>;
22
+ /** Convenience helper returning a `text/html; charset=utf-8` Response from a JSX tree. */
23
+ export declare const htmlResponse: (node: JSXChild, status?: number, headers?: Record<string, string> | Headers) => Promise<Response>;
24
+ /** Convenience helper returning a streaming `text/html; charset=utf-8` Response with `<Suspense>` support. */
25
+ export declare const streamResponse: (node: JSXChild, status?: number, headers?: Record<string, string> | Headers) => Response;
26
+ export declare namespace JSX {
27
+ type Element = JSXNode;
28
+ interface ElementChildrenAttribute {
29
+ children: {};
30
+ }
31
+ interface IntrinsicElements {
32
+ [elemName: string]: Record<string, any>;
33
+ }
34
+ }
@@ -0,0 +1,36 @@
1
+ export interface SSGFileWriter {
2
+ mkdir(path: string, opts?: {
3
+ recursive?: boolean;
4
+ }): Promise<any>;
5
+ writeFile(path: string, data: Uint8Array | string): Promise<any>;
6
+ }
7
+ export interface ToSSGOptions {
8
+ /** Output directory on disk (default: `'./static'`). */
9
+ dir?: string;
10
+ /** Additional concrete routes to pre-render (useful for parameterized routes like `['/posts/hello']`). */
11
+ routes?: string[];
12
+ /** Emit `/about` as `/about/index.html` instead of `/about.html` (default: `false`). */
13
+ dirIndex?: boolean;
14
+ /** Optional custom filesystem writer (useful for testing or non-Node runtimes). */
15
+ fs?: SSGFileWriter;
16
+ /** Base origin used when invoking `app.fetch` (default: `'http://localhost'`). */
17
+ origin?: string;
18
+ }
19
+ export interface ToSSGResult {
20
+ success: boolean;
21
+ files: string[];
22
+ error?: Error;
23
+ }
24
+ interface FetchableApp {
25
+ fetch(req: Request): Response | Promise<Response>;
26
+ routes?: Array<{
27
+ method: string;
28
+ path: string;
29
+ }>;
30
+ }
31
+ /**
32
+ * Build-time Static Site Generator (`toSSG`).
33
+ * Pre-renders static `GET` routes (plus any explicit `options.routes`) into static files.
34
+ */
35
+ export declare const toSSG: (app: FetchableApp, options?: ToSSGOptions) => Promise<ToSSGResult>;
36
+ export {};
package/llms.txt CHANGED
@@ -1,6 +1,19 @@
1
1
  # BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
2
2
 
3
- > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, and **Edge Workers** (`barejs/edge` — zero `node:*` imports) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** (`bun create barejs my-app [--bun|--node|--node-uws|--deno]`), built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (487 tests / 6,772 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
3
+ > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `53 KB`, zero `node:*` imports), **AWS Lambda**, **Cloudflare Pages**, and **Netlify** with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** and **502 tests across 37 files verified in CI (Bun, Node.js 20/22, Deno 2)**.
4
+
5
+ ## 0. Complete Export & Subpath Index (Check Here First!)
6
+ - `barejs` (core): `BareJS`, `BareRouter`, `Context`, `Type`/`T`/`TypeBox`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `isTokenRevoked`, `Hash`/`Password`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck`, `generateOpenAPISpec`, `renderDocsHTML` (router supports `:param`, optional `:param?`, regex `:id{[0-9]+}`, and `*` wildcards)
7
+ - `barejs/node`: Node.js `>= 20` build (same exports + native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` / `ws` / `@node-rs/argon2`)
8
+ - `barejs/edge` (`53 KB`): Zero-`node:*` Edge build (Cloudflare Workers, Vercel Edge, Deno Deploy)
9
+ - `barejs/html` (`1.3 KB`): `html`, `raw`, `escapeHtml`, `type HtmlString`
10
+ - `barejs/etag` (`2.4 KB`): `etag`, `type EtagOptions`
11
+ - `barejs/cache` (`2.2 KB`): `cache`, `type CacheOptions`
12
+ - `barejs/jsx` / `barejs/jsx-runtime` (`4.5 KB`): `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse`
13
+ - `barejs/ssg` (`2.1 KB`): `toSSG`, `type ToSSGOptions`, `type ToSSGResult`
14
+ - `barejs/aws-lambda` (`3.0 KB`): `awsLambda`, `handle`, `type AwsLambdaEvent`, `type AwsLambdaResult`
15
+ - `barejs/cloudflare-pages` (`768 B`): `handle`, `cloudflarePages` (`export const onRequest = handle(app)`)
16
+ - `barejs/netlify` (`752 B`): `handle`, `netlify` (`export default handle(app)`)
4
17
 
5
18
  ## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge)
6
19
  ```bash
@@ -8,14 +21,16 @@ bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebS
8
21
  bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
9
22
  ```
10
23
  ```ts
11
- import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
24
+ import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
12
25
 
13
26
  // Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool with in-flight slot clearing, shared state across JIT recompiles, & dev-mode UAF guard (0 overhead in prod)
14
27
  const app = new BareJS();
15
28
 
16
- // Direct return (Elysia style — auto-detects JSON, text, or Response)
29
+ // Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams)
17
30
  app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name }));
18
31
  app.get('/ping', () => 'pong');
32
+ app.get('/logo', () => file('public/logo.png')); // Or file(ctx.params.name, { root: './uploads', download: true })
33
+ app.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; }); // Pull-based ReadableStream backpressure
19
34
 
20
35
  // Wildcard catch-all route (`ctx.params['*']`)
21
36
  app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
@@ -146,3 +161,11 @@ app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
146
161
  await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners
147
162
  ```
148
163
  > **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`).
164
+
165
+ ## 8. Optional Subpaths, Macros & Observability
166
+ - **HTML Templates (`barejs/html`, `649 B`)**: `html\`<h1>Hello ${name}</h1>${raw('<span>✓</span>')}\`.toResponse()` — auto-escapes XSS, supports nested `html`, arrays, and falsy values.
167
+ - **Dynamic ETag (`barejs/etag`, `1.8 KB`)**: `app.use(etag())` (weak FNV-1a 64-bit default) or `etag({ weak: false })` (strong SHA-256) with `304 Not Modified`.
168
+ - **AWS Lambda (`barejs/aws-lambda`, `2.4 KB`)**: `export const handler = awsLambda(app)` (alias `handle`) — supports API Gateway v1, v2, ALB, `Set-Cookie`, and binary base64.
169
+ - **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro('auth', { beforeHandle, resolve }); app.use(plugin).get('/me', { auth: 'admin' }, handler);`
170
+ - **Cookie & Per-Status Response Schemas**: `RouteSchemas` supports `cookies` validation and `response: { 200: OkSchema, 404: ErrSchema }` (reflected in OpenAPI 3.1 & `bareTreaty`).
171
+ - **Observability (`tracing`, `serverTiming`)**: `app.use(tracing({ serverTiming: 'app', onSpan }))` — zero-dep W3C `traceparent` + `Server-Timing` header.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "author": "xarhang",
5
- "description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
5
+ "description": "Batteries-included, zero-bloat TypeScript web framework for Bun, Node.js (uWebSockets.js), Deno, Edge & AWS Lambda — O(1) JIT routing, Standard Schema/TypeBox/Zod, bareTreaty RPC, OpenAPI 3.1, WebSockets, JSX SSR, and built-in zero-trust security.",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "types": "./dist/types/index.d.ts",
@@ -21,6 +21,46 @@
21
21
  "./edge": {
22
22
  "types": "./dist/types/edge.d.ts",
23
23
  "import": "./dist/edge.js"
24
+ },
25
+ "./html": {
26
+ "types": "./dist/types/utils/html.d.ts",
27
+ "import": "./dist/html.js"
28
+ },
29
+ "./etag": {
30
+ "types": "./dist/types/utils/etag.d.ts",
31
+ "import": "./dist/etag.js"
32
+ },
33
+ "./cache": {
34
+ "types": "./dist/types/utils/cache.d.ts",
35
+ "import": "./dist/cache.js"
36
+ },
37
+ "./jsx": {
38
+ "types": "./dist/types/utils/jsx.d.ts",
39
+ "import": "./dist/jsx.js"
40
+ },
41
+ "./jsx-runtime": {
42
+ "types": "./dist/types/utils/jsx.d.ts",
43
+ "import": "./dist/jsx.js"
44
+ },
45
+ "./jsx-dev-runtime": {
46
+ "types": "./dist/types/utils/jsx.d.ts",
47
+ "import": "./dist/jsx.js"
48
+ },
49
+ "./ssg": {
50
+ "types": "./dist/types/utils/ssg.d.ts",
51
+ "import": "./dist/ssg.js"
52
+ },
53
+ "./aws-lambda": {
54
+ "types": "./dist/types/adapters/aws-lambda.d.ts",
55
+ "import": "./dist/aws-lambda.js"
56
+ },
57
+ "./cloudflare-pages": {
58
+ "types": "./dist/types/adapters/cloudflare-pages.d.ts",
59
+ "import": "./dist/cloudflare-pages.js"
60
+ },
61
+ "./netlify": {
62
+ "types": "./dist/types/adapters/netlify.d.ts",
63
+ "import": "./dist/netlify.js"
24
64
  }
25
65
  },
26
66
  "engines": {
@@ -0,0 +1,166 @@
1
+ export interface LambdaEvent {
2
+ // API Gateway HTTP API v2
3
+ version?: string;
4
+ rawPath?: string;
5
+ rawQueryString?: string;
6
+ cookies?: string[];
7
+ requestContext?: {
8
+ http?: { method?: string; path?: string; sourceIp?: string };
9
+ identity?: { sourceIp?: string };
10
+ domainName?: string;
11
+ };
12
+ // API Gateway REST API v1 & ALB
13
+ httpMethod?: string;
14
+ path?: string;
15
+ queryStringParameters?: Record<string, string | undefined> | null;
16
+ multiValueQueryStringParameters?: Record<string, string[] | undefined> | null;
17
+ headers?: Record<string, string | undefined> | null;
18
+ multiValueHeaders?: Record<string, string[] | undefined> | null;
19
+ body?: string | null;
20
+ isBase64Encoded?: boolean;
21
+ }
22
+
23
+ export interface LambdaResult {
24
+ statusCode: number;
25
+ headers: Record<string, string>;
26
+ cookies?: string[];
27
+ multiValueHeaders?: Record<string, string[]>;
28
+ body: string;
29
+ isBase64Encoded: boolean;
30
+ }
31
+
32
+ export interface FetchableApp {
33
+ fetch(req: Request, peerIp?: string): Response | Promise<Response>;
34
+ }
35
+
36
+ const TEXT_MIME_RE = /^(text\/|application\/(json|xml|javascript|xhtml\+xml|x-www-form-urlencoded)|.*\+(json|xml))/i;
37
+
38
+ const isBinaryResponse = (headers: Headers): boolean => {
39
+ const enc = headers.get('content-encoding');
40
+ if (enc && enc !== 'identity') return true;
41
+ const ct = (headers.get('content-type') || '').split(';', 1)[0]!.trim();
42
+ if (!ct) return false;
43
+ return !TEXT_MIME_RE.test(ct);
44
+ };
45
+
46
+ const toBase64 = (bytes: Uint8Array): string => {
47
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
48
+ let bin = '';
49
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
50
+ return btoa(bin);
51
+ };
52
+
53
+ const fromBase64 = (b64: string): Uint8Array => {
54
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
55
+ const bin = atob(b64);
56
+ const out = new Uint8Array(bin.length);
57
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
58
+ return out;
59
+ };
60
+
61
+ /**
62
+ * Optional AWS Lambda adapter for BareJS (`import { awsLambda, handle } from 'barejs/aws-lambda'`).
63
+ * Supports API Gateway HTTP API (v2), REST API (v1), and Application Load Balancer (ALB) events
64
+ * with zero dependencies and zero impact on core bundle size.
65
+ */
66
+ export const awsLambda = (app: FetchableApp) => {
67
+ return async (event: LambdaEvent): Promise<LambdaResult> => {
68
+ const isV2 = event.version === '2.0' || Boolean(event.requestContext?.http);
69
+ const method = (event.requestContext?.http?.method || event.httpMethod || 'GET').toUpperCase();
70
+ const path = event.rawPath || event.requestContext?.http?.path || event.path || '/';
71
+
72
+ let queryString = event.rawQueryString ?? '';
73
+ if (!queryString) {
74
+ const sp = new URLSearchParams();
75
+ if (event.multiValueQueryStringParameters) {
76
+ for (const [k, vals] of Object.entries(event.multiValueQueryStringParameters)) {
77
+ if (!vals) continue;
78
+ for (const v of vals) sp.append(k, v);
79
+ }
80
+ } else if (event.queryStringParameters) {
81
+ for (const [k, v] of Object.entries(event.queryStringParameters)) {
82
+ if (v !== undefined) sp.append(k, v);
83
+ }
84
+ }
85
+ queryString = sp.toString();
86
+ }
87
+
88
+ const headers = new Headers();
89
+ if (event.multiValueHeaders) {
90
+ for (const [k, vals] of Object.entries(event.multiValueHeaders)) {
91
+ if (!vals) continue;
92
+ for (const v of vals) headers.append(k, v);
93
+ }
94
+ } else if (event.headers) {
95
+ for (const [k, v] of Object.entries(event.headers)) {
96
+ if (v !== undefined) headers.set(k, v);
97
+ }
98
+ }
99
+ if (event.cookies && event.cookies.length > 0 && !headers.has('cookie')) {
100
+ headers.set('cookie', event.cookies.join('; '));
101
+ }
102
+
103
+ const host = headers.get('host') || event.requestContext?.domainName || 'localhost';
104
+ const proto = headers.get('x-forwarded-proto') || 'https';
105
+ const url = `${proto}://${host}${path.startsWith('/') ? path : '/' + path}${queryString ? '?' + queryString : ''}`;
106
+
107
+ const init: RequestInit = { method, headers };
108
+ if (event.body != null && method !== 'GET' && method !== 'HEAD') {
109
+ init.body = event.isBase64Encoded ? (fromBase64(event.body) as any) : event.body;
110
+ }
111
+
112
+ const sourceIp =
113
+ event.requestContext?.http?.sourceIp ||
114
+ event.requestContext?.identity?.sourceIp ||
115
+ undefined;
116
+
117
+ const res = await app.fetch(new Request(url, init), sourceIp);
118
+
119
+ const outHeaders: Record<string, string> = {};
120
+ const cookies: string[] = [];
121
+ const multiValueHeaders: Record<string, string[]> = {};
122
+
123
+ const rawSetCookies = typeof (res.headers as any).getSetCookie === 'function'
124
+ ? ((res.headers as any).getSetCookie() as string[])
125
+ : [];
126
+
127
+ res.headers.forEach((v, k) => {
128
+ const lower = k.toLowerCase();
129
+ if (lower === 'set-cookie') {
130
+ if (rawSetCookies.length === 0) cookies.push(v);
131
+ return;
132
+ }
133
+ outHeaders[lower] = v;
134
+ if (!isV2) multiValueHeaders[lower] = [v];
135
+ });
136
+ if (rawSetCookies.length > 0) cookies.push(...rawSetCookies);
137
+
138
+ const binary = isBinaryResponse(res.headers);
139
+ const body = binary
140
+ ? toBase64(new Uint8Array(await res.arrayBuffer()))
141
+ : await res.text();
142
+
143
+ if (isV2) {
144
+ return {
145
+ statusCode: res.status,
146
+ headers: outHeaders,
147
+ ...(cookies.length > 0 ? { cookies } : {}),
148
+ body,
149
+ isBase64Encoded: binary
150
+ };
151
+ }
152
+
153
+ if (cookies.length > 0) {
154
+ multiValueHeaders['set-cookie'] = cookies;
155
+ }
156
+ return {
157
+ statusCode: res.status,
158
+ headers: outHeaders,
159
+ multiValueHeaders,
160
+ body,
161
+ isBase64Encoded: binary
162
+ };
163
+ };
164
+ };
165
+
166
+ export const handle = awsLambda;