barejs 0.2.7 → 0.2.9
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.
- package/README.md +139 -126
- package/dist/aws-lambda.js +1 -0
- package/dist/cache.js +1 -0
- package/dist/cloudflare-pages.js +1 -0
- package/dist/edge.js +28 -28
- package/dist/etag.js +1 -0
- package/dist/html.js +1 -0
- package/dist/index.js +146 -144
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +146 -144
- package/dist/ssg.js +1 -0
- package/dist/types/adapters/aws-lambda.d.ts +43 -0
- package/dist/types/adapters/cloudflare-pages.d.ts +18 -0
- package/dist/types/adapters/netlify.d.ts +32 -0
- package/dist/types/core/bare.d.ts +15 -3
- package/dist/types/core/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +2 -0
- package/dist/types/edge.d.ts +13 -0
- package/dist/types/index.d.ts +3 -1
- package/dist/types/utils/cache.d.ts +26 -0
- package/dist/types/utils/etag.d.ts +12 -0
- package/dist/types/utils/html.d.ts +22 -0
- package/dist/types/utils/jsx.d.ts +34 -0
- package/dist/types/utils/ssg.d.ts +36 -0
- package/llms.txt +24 -3
- package/package.json +42 -2
- package/src/adapters/aws-lambda.ts +166 -0
- package/src/adapters/cloudflare-pages.ts +27 -0
- package/src/adapters/netlify.ts +28 -0
- package/src/core/bare.ts +78 -22
- package/src/core/context.ts +1 -1
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +41 -7
- package/src/edge.ts +28 -1
- package/src/index.ts +3 -1
- package/src/utils/cache.ts +128 -0
- package/src/utils/etag.ts +115 -0
- package/src/utils/html.ts +72 -0
- package/src/utils/jsx.ts +217 -0
- package/src/utils/ssg.ts +110 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface EtagOptions {
|
|
4
|
+
/** Emit weak ETags `W/"..."` (default: `true`, fast zero-async FNV-1a 64-bit) */
|
|
5
|
+
weak?: boolean;
|
|
6
|
+
/** Retain these headers on 304 Not Modified responses */
|
|
7
|
+
retainedHeaders?: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const DEFAULT_RETAINED = ['cache-control', 'content-location', 'date', 'etag', 'expires', 'vary'];
|
|
11
|
+
|
|
12
|
+
/** Fast 64-bit FNV-1a pair (zero-async, works on Bun, Node, Deno, and Edge) */
|
|
13
|
+
const fastHashHex = (bytes: Uint8Array): string => {
|
|
14
|
+
let h1 = 0x811c9dc5;
|
|
15
|
+
let h2 = 0x01000193;
|
|
16
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
17
|
+
const b = bytes[i]!;
|
|
18
|
+
h1 ^= b;
|
|
19
|
+
h1 = Math.imul(h1, 0x01000193);
|
|
20
|
+
h2 ^= b ^ (i & 0xff);
|
|
21
|
+
h2 = Math.imul(h2, 0x01000193);
|
|
22
|
+
}
|
|
23
|
+
return `${bytes.length.toString(16)}-${(h1 >>> 0).toString(16).padStart(8, '0')}${(h2 >>> 0).toString(16).padStart(8, '0')}`;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const strongSha256Hex = async (bytes: Uint8Array): Promise<string> => {
|
|
27
|
+
const buf = await crypto.subtle.digest('SHA-256', bytes as any);
|
|
28
|
+
const arr = new Uint8Array(buf);
|
|
29
|
+
let hex = '';
|
|
30
|
+
for (let i = 0; i < 16; i++) hex += arr[i]!.toString(16).padStart(2, '0');
|
|
31
|
+
return hex;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const stripWeak = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
|
|
35
|
+
|
|
36
|
+
const matchesIfNoneMatch = (ifNoneMatch: string, etag: string): boolean => {
|
|
37
|
+
const trimmed = ifNoneMatch.trim();
|
|
38
|
+
if (trimmed === '*') return true;
|
|
39
|
+
const target = stripWeak(etag);
|
|
40
|
+
const parts = trimmed.split(',');
|
|
41
|
+
for (let i = 0; i < parts.length; i++) {
|
|
42
|
+
if (stripWeak(parts[i]!.trim()) === target) return true;
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Dynamic API ETag middleware (`304 Not Modified` support).
|
|
49
|
+
* Edge-safe, zero dependencies, skips streaming/SSE and non-200 responses.
|
|
50
|
+
*/
|
|
51
|
+
export const etag = (options: EtagOptions = {}): Middleware => {
|
|
52
|
+
const weak = options.weak ?? true;
|
|
53
|
+
const retained = options.retainedHeaders ?? DEFAULT_RETAINED;
|
|
54
|
+
|
|
55
|
+
const applyEtag = async (ctx: Context, res: any): Promise<any> => {
|
|
56
|
+
const method = ctx.req.method;
|
|
57
|
+
if (method !== 'GET' && method !== 'HEAD') return res;
|
|
58
|
+
|
|
59
|
+
let response: Response;
|
|
60
|
+
if (res instanceof Response) {
|
|
61
|
+
response = res;
|
|
62
|
+
} else if (typeof res === 'string') {
|
|
63
|
+
response = new Response(res, {
|
|
64
|
+
status: ctx._status || 200,
|
|
65
|
+
headers: ctx._headers || { 'content-type': 'text/plain; charset=utf-8' }
|
|
66
|
+
});
|
|
67
|
+
} else if (res !== undefined && res !== null) {
|
|
68
|
+
response = Response.json(res, {
|
|
69
|
+
status: ctx._status || 200,
|
|
70
|
+
headers: ctx._headers
|
|
71
|
+
});
|
|
72
|
+
} else {
|
|
73
|
+
return res;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (response.status !== 200) return response;
|
|
77
|
+
if (response.headers.has('etag')) return response;
|
|
78
|
+
const ct = (response.headers.get('content-type') || '').toLowerCase();
|
|
79
|
+
if (ct.includes('text/event-stream')) return response;
|
|
80
|
+
|
|
81
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
82
|
+
if (bytes.byteLength === 0) {
|
|
83
|
+
return new Response(bytes, { status: response.status, headers: response.headers });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const digest = weak ? fastHashHex(bytes) : await strongSha256Hex(bytes);
|
|
87
|
+
const tag = weak ? `W/"${digest}"` : `"${digest}"`;
|
|
88
|
+
|
|
89
|
+
const inm = ctx.req.headers.get('if-none-match');
|
|
90
|
+
if (inm && matchesIfNoneMatch(inm, tag)) {
|
|
91
|
+
const h = new Headers();
|
|
92
|
+
for (let i = 0; i < retained.length; i++) {
|
|
93
|
+
const k = retained[i]!;
|
|
94
|
+
const v = response.headers.get(k);
|
|
95
|
+
if (v !== null) h.set(k, v);
|
|
96
|
+
}
|
|
97
|
+
h.set('etag', tag);
|
|
98
|
+
return new Response(null, { status: 304, headers: h });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const outHeaders = new Headers(response.headers);
|
|
102
|
+
outHeaders.set('etag', tag);
|
|
103
|
+
return new Response(method === 'HEAD' ? null : bytes, {
|
|
104
|
+
status: response.status,
|
|
105
|
+
headers: outHeaders
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
110
|
+
const res = await (next ? next() : undefined);
|
|
111
|
+
return applyEtag(ctx, res);
|
|
112
|
+
};
|
|
113
|
+
(mw as any).__postResponse = applyEtag;
|
|
114
|
+
return mw;
|
|
115
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const RAW_BRAND = Symbol('BareRawHtml');
|
|
2
|
+
|
|
3
|
+
export interface HtmlString {
|
|
4
|
+
readonly [RAW_BRAND]: true;
|
|
5
|
+
readonly value: string;
|
|
6
|
+
toString(): string;
|
|
7
|
+
toResponse(status?: number, headers?: Record<string, string>): Response;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const ESC_MAP: Record<string, string> = {
|
|
11
|
+
'&': '&',
|
|
12
|
+
'<': '<',
|
|
13
|
+
'>': '>',
|
|
14
|
+
'"': '"',
|
|
15
|
+
"'": '''
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const ESC_RE = /[&<>"']/g;
|
|
19
|
+
|
|
20
|
+
export const escapeHtml = (input: string): string =>
|
|
21
|
+
input.replace(ESC_RE, (ch) => ESC_MAP[ch]!);
|
|
22
|
+
|
|
23
|
+
const makeHtmlString = (value: string): HtmlString => ({
|
|
24
|
+
[RAW_BRAND]: true,
|
|
25
|
+
value,
|
|
26
|
+
toString() {
|
|
27
|
+
return value;
|
|
28
|
+
},
|
|
29
|
+
toResponse(status = 200, headers?: Record<string, string>): Response {
|
|
30
|
+
return new Response(value, {
|
|
31
|
+
status,
|
|
32
|
+
headers: {
|
|
33
|
+
'content-type': 'text/html; charset=utf-8',
|
|
34
|
+
...(headers || {})
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Marks a trusted HTML string so `html` tagged templates will not double-escape it.
|
|
42
|
+
* Only pass sanitized or static trusted markup.
|
|
43
|
+
*/
|
|
44
|
+
export const raw = (trustedHtml: string): HtmlString => makeHtmlString(String(trustedHtml));
|
|
45
|
+
|
|
46
|
+
const renderPart = (part: unknown): string => {
|
|
47
|
+
if (part === null || part === undefined || part === false) return '';
|
|
48
|
+
if (typeof part === 'object' && (part as any)[RAW_BRAND] === true) {
|
|
49
|
+
return (part as HtmlString).value;
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(part)) {
|
|
52
|
+
let out = '';
|
|
53
|
+
for (let i = 0; i < part.length; i++) out += renderPart(part[i]);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
return escapeHtml(String(part));
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* XSS-safe HTML tagged template literal (Edge-safe, zero dependencies).
|
|
61
|
+
*
|
|
62
|
+
* Example:
|
|
63
|
+
* `app.get('/hi', (ctx) => html\`<h1>Hello ${ctx.query.name}</h1>\`.toResponse())`
|
|
64
|
+
* `app.get('/hi', (ctx) => ctx.html(String(html\`<h1>Hello ${ctx.query.name}</h1>\`)))`
|
|
65
|
+
*/
|
|
66
|
+
export const html = (strings: TemplateStringsArray, ...values: unknown[]): HtmlString => {
|
|
67
|
+
let out = strings[0] ?? '';
|
|
68
|
+
for (let i = 0; i < values.length; i++) {
|
|
69
|
+
out += renderPart(values[i]) + (strings[i + 1] ?? '');
|
|
70
|
+
}
|
|
71
|
+
return makeHtmlString(out);
|
|
72
|
+
};
|
package/src/utils/jsx.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { escapeHtml, raw, type HtmlString } from './html';
|
|
2
|
+
|
|
3
|
+
export { escapeHtml, raw, type HtmlString };
|
|
4
|
+
|
|
5
|
+
export type JSXChild =
|
|
6
|
+
| JSXNode
|
|
7
|
+
| HtmlString
|
|
8
|
+
| string
|
|
9
|
+
| number
|
|
10
|
+
| boolean
|
|
11
|
+
| null
|
|
12
|
+
| undefined
|
|
13
|
+
| JSXChild[];
|
|
14
|
+
|
|
15
|
+
export type Component<P = any> = (props: P) => JSXChild | Promise<JSXChild>;
|
|
16
|
+
|
|
17
|
+
export interface JSXNode {
|
|
18
|
+
readonly $$bareJsx: true;
|
|
19
|
+
type: string | typeof Fragment | typeof Suspense | Component<any>;
|
|
20
|
+
props: Record<string, any>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const Fragment = Symbol.for('barejs.jsx.Fragment');
|
|
24
|
+
export const Suspense = Symbol.for('barejs.jsx.Suspense');
|
|
25
|
+
|
|
26
|
+
const VOID_ELEMENTS = new Set([
|
|
27
|
+
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
|
28
|
+
'link', 'meta', 'param', 'source', 'track', 'wbr'
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const BOOLEAN_ATTRS = new Set([
|
|
32
|
+
'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls',
|
|
33
|
+
'default', 'defer', 'disabled', 'formnovalidate', 'hidden', 'inert', 'ismap',
|
|
34
|
+
'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline',
|
|
35
|
+
'readonly', 'required', 'reversed', 'selected'
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
export const jsx = (
|
|
39
|
+
type: JSXNode['type'],
|
|
40
|
+
props: Record<string, any> | null
|
|
41
|
+
): JSXNode => ({
|
|
42
|
+
$$bareJsx: true,
|
|
43
|
+
type,
|
|
44
|
+
props: props ?? {}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export const jsxs = jsx;
|
|
48
|
+
export const jsxDEV = jsx;
|
|
49
|
+
|
|
50
|
+
const isJsxNode = (v: unknown): v is JSXNode =>
|
|
51
|
+
typeof v === 'object' && v !== null && (v as any).$$bareJsx === true;
|
|
52
|
+
|
|
53
|
+
const isHtmlString = (v: unknown): v is HtmlString =>
|
|
54
|
+
typeof v === 'object' && v !== null && (v as any).__bareHtml === true;
|
|
55
|
+
|
|
56
|
+
const styleToString = (style: Record<string, any>): string => {
|
|
57
|
+
let out = '';
|
|
58
|
+
for (const [k, v] of Object.entries(style)) {
|
|
59
|
+
if (v === null || v === undefined || v === false) continue;
|
|
60
|
+
const prop = k.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
|
|
61
|
+
out += `${prop}:${String(v)};`;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const renderAttrs = (props: Record<string, any>): string => {
|
|
67
|
+
let out = '';
|
|
68
|
+
for (const [rawKey, val] of Object.entries(props)) {
|
|
69
|
+
if (rawKey === 'children' || rawKey === 'key' || rawKey === 'dangerouslySetInnerHTML') continue;
|
|
70
|
+
if (val === null || val === undefined || val === false) continue;
|
|
71
|
+
const key = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey;
|
|
72
|
+
if (key === 'style' && typeof val === 'object') {
|
|
73
|
+
const css = styleToString(val);
|
|
74
|
+
if (css) out += ` style="${escapeHtml(css)}"`;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (val === true) {
|
|
78
|
+
out += BOOLEAN_ATTRS.has(key.toLowerCase()) ? ` ${key}` : ` ${key}="true"`;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
out += ` ${key}="${escapeHtml(String(val))}"`;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
interface PendingSuspense {
|
|
87
|
+
id: number;
|
|
88
|
+
promise: Promise<string>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const renderNodeInternal = async (
|
|
92
|
+
node: JSXChild | Promise<JSXChild>,
|
|
93
|
+
pending?: PendingSuspense[]
|
|
94
|
+
): Promise<string> => {
|
|
95
|
+
const resolved = node instanceof Promise ? await node : node;
|
|
96
|
+
if (resolved === null || resolved === undefined || typeof resolved === 'boolean') return '';
|
|
97
|
+
if (typeof resolved === 'string') return escapeHtml(resolved);
|
|
98
|
+
if (typeof resolved === 'number') return String(resolved);
|
|
99
|
+
if (isHtmlString(resolved)) return resolved.value;
|
|
100
|
+
if (Array.isArray(resolved)) {
|
|
101
|
+
let out = '';
|
|
102
|
+
for (let i = 0; i < resolved.length; i++) {
|
|
103
|
+
out += await renderNodeInternal(resolved[i], pending);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
if (!isJsxNode(resolved)) return escapeHtml(String(resolved));
|
|
108
|
+
|
|
109
|
+
const { type, props } = resolved;
|
|
110
|
+
|
|
111
|
+
if (type === Fragment) {
|
|
112
|
+
return renderNodeInternal(props.children, pending);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (type === Suspense) {
|
|
116
|
+
if (pending) {
|
|
117
|
+
const id = pending.length;
|
|
118
|
+
const fallbackHtml = await renderNodeInternal(props.fallback ?? '', undefined);
|
|
119
|
+
const childPromise = renderNodeInternal(props.children, pending);
|
|
120
|
+
pending.push({ id, promise: childPromise });
|
|
121
|
+
return `<template id="B:${id}"></template>${fallbackHtml}<!--/B:${id}-->`;
|
|
122
|
+
}
|
|
123
|
+
return renderNodeInternal(props.children, undefined);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (typeof type === 'function') {
|
|
127
|
+
const out = type(props);
|
|
128
|
+
return renderNodeInternal(out, pending);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const tag = String(type);
|
|
132
|
+
const attrs = renderAttrs(props);
|
|
133
|
+
if (VOID_ELEMENTS.has(tag.toLowerCase())) {
|
|
134
|
+
return `<${tag}${attrs}>`;
|
|
135
|
+
}
|
|
136
|
+
if (props.dangerouslySetInnerHTML && typeof props.dangerouslySetInnerHTML.__html === 'string') {
|
|
137
|
+
return `<${tag}${attrs}>${props.dangerouslySetInnerHTML.__html}</${tag}>`;
|
|
138
|
+
}
|
|
139
|
+
const inner = await renderNodeInternal(props.children, pending);
|
|
140
|
+
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** Renders a JSX tree (including async components) to an HTML string. */
|
|
144
|
+
export const renderToString = async (node: JSXChild): Promise<string> => {
|
|
145
|
+
return renderNodeInternal(node, undefined);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const SWAP_SCRIPT_FN =
|
|
149
|
+
'<script>function $B(i,t){var a=document.getElementById("B:"+i),b=document.getElementById("S:"+i);if(!a||!b)return;var p=a.parentNode,n=a.nextSibling;while(n&&!(n.nodeType===8&&n.data==="/B:"+i)){var x=n.nextSibling;p.removeChild(n);n=x;}p.insertBefore(b.content,n);p.removeChild(a);if(n)p.removeChild(n);b.remove();}</script>';
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Streams a JSX tree as a Web `ReadableStream<Uint8Array>`, flushing `<Suspense fallback>`
|
|
153
|
+
* immediately and streaming out-of-order `<template>` replacement chunks as async children resolve.
|
|
154
|
+
*/
|
|
155
|
+
export const renderToReadableStream = (node: JSXChild): ReadableStream<Uint8Array> => {
|
|
156
|
+
const encoder = new TextEncoder();
|
|
157
|
+
return new ReadableStream<Uint8Array>({
|
|
158
|
+
async start(controller) {
|
|
159
|
+
try {
|
|
160
|
+
const pending: PendingSuspense[] = [];
|
|
161
|
+
const shell = await renderNodeInternal(node, pending);
|
|
162
|
+
controller.enqueue(encoder.encode(shell));
|
|
163
|
+
|
|
164
|
+
if (pending.length > 0) {
|
|
165
|
+
controller.enqueue(encoder.encode(SWAP_SCRIPT_FN));
|
|
166
|
+
const settled = new Set<number>();
|
|
167
|
+
while (settled.size < pending.length) {
|
|
168
|
+
const batch = pending.filter((p) => !settled.has(p.id));
|
|
169
|
+
await Promise.all(
|
|
170
|
+
batch.map(async (item) => {
|
|
171
|
+
settled.add(item.id);
|
|
172
|
+
const html = await item.promise;
|
|
173
|
+
const chunk = `<template id="S:${item.id}">${html}</template><script>$B(${item.id})</script>`;
|
|
174
|
+
controller.enqueue(encoder.encode(chunk));
|
|
175
|
+
})
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
controller.close();
|
|
180
|
+
} catch (err) {
|
|
181
|
+
controller.error(err);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/** Convenience helper returning a `text/html; charset=utf-8` Response from a JSX tree. */
|
|
188
|
+
export const htmlResponse = async (
|
|
189
|
+
node: JSXChild,
|
|
190
|
+
status = 200,
|
|
191
|
+
headers?: Record<string, string> | Headers
|
|
192
|
+
): Promise<Response> => {
|
|
193
|
+
const h = new Headers(headers as any);
|
|
194
|
+
if (!h.has('content-type')) h.set('content-type', 'text/html; charset=utf-8');
|
|
195
|
+
return new Response(await renderToString(node), { status, headers: h });
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
/** Convenience helper returning a streaming `text/html; charset=utf-8` Response with `<Suspense>` support. */
|
|
199
|
+
export const streamResponse = (
|
|
200
|
+
node: JSXChild,
|
|
201
|
+
status = 200,
|
|
202
|
+
headers?: Record<string, string> | Headers
|
|
203
|
+
): Response => {
|
|
204
|
+
const h = new Headers(headers as any);
|
|
205
|
+
if (!h.has('content-type')) h.set('content-type', 'text/html; charset=utf-8');
|
|
206
|
+
return new Response(renderToReadableStream(node), { status, headers: h });
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
export namespace JSX {
|
|
210
|
+
export type Element = JSXNode;
|
|
211
|
+
export interface ElementChildrenAttribute {
|
|
212
|
+
children: {};
|
|
213
|
+
}
|
|
214
|
+
export interface IntrinsicElements {
|
|
215
|
+
[elemName: string]: Record<string, any>;
|
|
216
|
+
}
|
|
217
|
+
}
|
package/src/utils/ssg.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
export interface SSGFileWriter {
|
|
2
|
+
mkdir(path: string, opts?: { recursive?: boolean }): Promise<any>;
|
|
3
|
+
writeFile(path: string, data: Uint8Array | string): Promise<any>;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface ToSSGOptions {
|
|
7
|
+
/** Output directory on disk (default: `'./static'`). */
|
|
8
|
+
dir?: string;
|
|
9
|
+
/** Additional concrete routes to pre-render (useful for parameterized routes like `['/posts/hello']`). */
|
|
10
|
+
routes?: string[];
|
|
11
|
+
/** Emit `/about` as `/about/index.html` instead of `/about.html` (default: `false`). */
|
|
12
|
+
dirIndex?: boolean;
|
|
13
|
+
/** Optional custom filesystem writer (useful for testing or non-Node runtimes). */
|
|
14
|
+
fs?: SSGFileWriter;
|
|
15
|
+
/** Base origin used when invoking `app.fetch` (default: `'http://localhost'`). */
|
|
16
|
+
origin?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ToSSGResult {
|
|
20
|
+
success: boolean;
|
|
21
|
+
files: string[];
|
|
22
|
+
error?: Error;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface FetchableApp {
|
|
26
|
+
fetch(req: Request): Response | Promise<Response>;
|
|
27
|
+
routes?: Array<{ method: string; path: string }>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const routeToFilePath = (dir: string, routePath: string, contentType: string, dirIndex: boolean): string => {
|
|
31
|
+
const cleanDir = dir.replace(/\/+$/, '');
|
|
32
|
+
const norm = routePath.startsWith('/') ? routePath : '/' + routePath;
|
|
33
|
+
if (norm === '/' || norm === '') return `${cleanDir}/index.html`;
|
|
34
|
+
|
|
35
|
+
const lastSeg = norm.slice(norm.lastIndexOf('/') + 1);
|
|
36
|
+
if (lastSeg.includes('.')) {
|
|
37
|
+
return `${cleanDir}${norm}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const ct = contentType.toLowerCase();
|
|
41
|
+
if (ct.includes('application/json')) return `${cleanDir}${norm}.json`;
|
|
42
|
+
if (ct.includes('text/plain')) return `${cleanDir}${norm}.txt`;
|
|
43
|
+
if (ct.includes('application/xml') || ct.includes('text/xml')) return `${cleanDir}${norm}.xml`;
|
|
44
|
+
|
|
45
|
+
return dirIndex ? `${cleanDir}${norm}/index.html` : `${cleanDir}${norm}.html`;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Build-time Static Site Generator (`toSSG`).
|
|
50
|
+
* Pre-renders static `GET` routes (plus any explicit `options.routes`) into static files.
|
|
51
|
+
*/
|
|
52
|
+
export const toSSG = async (app: FetchableApp, options: ToSSGOptions = {}): Promise<ToSSGResult> => {
|
|
53
|
+
const dir = options.dir ?? './static';
|
|
54
|
+
const dirIndex = options.dirIndex ?? false;
|
|
55
|
+
const origin = (options.origin ?? 'http://localhost').replace(/\/+$/, '');
|
|
56
|
+
const files: string[] = [];
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
let writer: SSGFileWriter;
|
|
60
|
+
if (options.fs) {
|
|
61
|
+
writer = options.fs;
|
|
62
|
+
} else {
|
|
63
|
+
const nodeFs = await import('node:fs/promises');
|
|
64
|
+
writer = {
|
|
65
|
+
mkdir: (p, o) => nodeFs.mkdir(p, o),
|
|
66
|
+
writeFile: (p, d) => nodeFs.writeFile(p, d)
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const targets = new Set<string>();
|
|
71
|
+
if (Array.isArray(app.routes)) {
|
|
72
|
+
for (let i = 0; i < app.routes.length; i++) {
|
|
73
|
+
const r = app.routes[i]!;
|
|
74
|
+
if (r.method !== 'GET') continue;
|
|
75
|
+
const p = r.path || '/';
|
|
76
|
+
if (p.includes(':') || p.includes('*')) continue;
|
|
77
|
+
targets.add(p.startsWith('/') ? p : '/' + p);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (options.routes) {
|
|
81
|
+
for (let i = 0; i < options.routes.length; i++) {
|
|
82
|
+
const p = options.routes[i]!;
|
|
83
|
+
targets.add(p.startsWith('/') ? p : '/' + p);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
for (const routePath of targets) {
|
|
88
|
+
const res = await app.fetch(new Request(`${origin}${routePath}`, { method: 'GET' }));
|
|
89
|
+
if (res.status < 200 || res.status >= 300) continue;
|
|
90
|
+
|
|
91
|
+
const ct = res.headers.get('content-type') ?? 'text/html';
|
|
92
|
+
const outPath = routeToFilePath(dir, routePath, ct, dirIndex);
|
|
93
|
+
const parentDir = outPath.slice(0, outPath.lastIndexOf('/'));
|
|
94
|
+
if (parentDir) {
|
|
95
|
+
await writer.mkdir(parentDir, { recursive: true });
|
|
96
|
+
}
|
|
97
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
98
|
+
await writer.writeFile(outPath, bytes);
|
|
99
|
+
files.push(outPath);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { success: true, files };
|
|
103
|
+
} catch (err) {
|
|
104
|
+
return {
|
|
105
|
+
success: false,
|
|
106
|
+
files,
|
|
107
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
};
|