barejs 0.2.7 → 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.
- package/README.md +132 -125
- package/dist/aws-lambda.js +1 -0
- package/dist/cache.js +1 -0
- package/dist/cloudflare-pages.js +1 -0
- package/dist/edge.js +29 -29
- package/dist/etag.js +1 -0
- package/dist/html.js +1 -0
- package/dist/index.js +152 -150
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +152 -150
- 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/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/edge.d.ts +2 -0
- package/dist/types/index.d.ts +2 -0
- 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 +22 -1
- 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 +23 -2
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +36 -6
- package/src/edge.ts +2 -0
- package/src/index.ts +2 -0
- 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
package/src/core/radix.ts
CHANGED
|
@@ -5,6 +5,7 @@ export class RadixNode {
|
|
|
5
5
|
public staticKeys: string[] = [];
|
|
6
6
|
public paramNode: RadixNode | null = null;
|
|
7
7
|
public paramName: string | null = null;
|
|
8
|
+
public regexParamNodes: Array<{ regex: RegExp; pattern: string; node: RadixNode }> = [];
|
|
8
9
|
public wildcardNode: RadixNode | null = null;
|
|
9
10
|
public handlers: Record<string, Function> = Object.create(null);
|
|
10
11
|
public handlerParams: Record<string, string[]> = Object.create(null);
|
|
@@ -19,11 +20,24 @@ export class RadixNode {
|
|
|
19
20
|
node = node.wildcardNode;
|
|
20
21
|
break;
|
|
21
22
|
} else if (part.startsWith(':')) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
const braceIdx = part.indexOf('{');
|
|
24
|
+
if (braceIdx !== -1 && part.endsWith('}')) {
|
|
25
|
+
const pName = part.slice(1, braceIdx);
|
|
26
|
+
const pattern = part.slice(braceIdx + 1, -1);
|
|
27
|
+
let entry = node.regexParamNodes.find((e) => e.pattern === pattern);
|
|
28
|
+
if (!entry) {
|
|
29
|
+
entry = { regex: new RegExp(`^(?:${pattern})$`), pattern, node: new RadixNode() };
|
|
30
|
+
node.regexParamNodes.push(entry);
|
|
31
|
+
}
|
|
32
|
+
paramNames.push(pName);
|
|
33
|
+
node = entry.node;
|
|
34
|
+
} else {
|
|
35
|
+
if (!node.paramNode) node.paramNode = new RadixNode();
|
|
36
|
+
const pName = part.slice(1);
|
|
37
|
+
if (!node.paramName) node.paramName = pName;
|
|
38
|
+
paramNames.push(pName);
|
|
39
|
+
node = node.paramNode;
|
|
40
|
+
}
|
|
27
41
|
} else {
|
|
28
42
|
if (!node.children[part]) {
|
|
29
43
|
node.children[part] = new RadixNode();
|
|
@@ -101,6 +115,19 @@ export class RadixNode {
|
|
|
101
115
|
if (res) return res;
|
|
102
116
|
}
|
|
103
117
|
|
|
118
|
+
if (node.regexParamNodes.length > 0 && segmentLen > 0) {
|
|
119
|
+
const seg = url.slice(pos, j);
|
|
120
|
+
for (let r = 0; r < node.regexParamNodes.length; r++) {
|
|
121
|
+
const entry = node.regexParamNodes[r]!;
|
|
122
|
+
if (entry.regex.test(seg)) {
|
|
123
|
+
pVals.push(seg);
|
|
124
|
+
const res = matchNode(entry.node, j + 1, pVals);
|
|
125
|
+
if (res) return res;
|
|
126
|
+
pVals.pop();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
104
131
|
if (node.paramNode && segmentLen > 0) {
|
|
105
132
|
pVals.push(url.slice(pos, j));
|
|
106
133
|
const res = matchNode(node.paramNode, j + 1, pVals);
|
|
@@ -157,7 +184,7 @@ export class RadixNode {
|
|
|
157
184
|
code += `${indent}}\n`;
|
|
158
185
|
}
|
|
159
186
|
|
|
160
|
-
const hasChildren = this.staticKeys.length > 0 || this.paramNode !== null;
|
|
187
|
+
const hasChildren = this.staticKeys.length > 0 || this.regexParamNodes.length > 0 || this.paramNode !== null;
|
|
161
188
|
if (hasChildren) {
|
|
162
189
|
const innerIndent = indent + ' ';
|
|
163
190
|
code += `${indent}if (${idxPrefix} < urlLen) {\n`;
|
|
@@ -291,8 +318,7 @@ export class RadixNode {
|
|
|
291
318
|
}
|
|
292
319
|
}
|
|
293
320
|
|
|
294
|
-
if (this.paramNode) {
|
|
295
|
-
const pNode = this.paramNode;
|
|
321
|
+
if (this.regexParamNodes.length > 0 || this.paramNode) {
|
|
296
322
|
if (this.staticKeys.length <= 1) {
|
|
297
323
|
code += `${innerIndent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
|
|
298
324
|
code += `${innerIndent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
|
|
@@ -301,9 +327,19 @@ export class RadixNode {
|
|
|
301
327
|
const pVar = `pL${level}`;
|
|
302
328
|
code += `${innerIndent}if (slash${level} > ${idxPrefix}) {\n`;
|
|
303
329
|
code += `${innerIndent} const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
|
|
304
|
-
|
|
305
330
|
const newVars = [...paramVars, pVar];
|
|
306
|
-
|
|
331
|
+
|
|
332
|
+
for (let r = 0; r < this.regexParamNodes.length; r++) {
|
|
333
|
+
const entry = this.regexParamNodes[r]!;
|
|
334
|
+
const reVar = register(entry.regex as any);
|
|
335
|
+
code += `${innerIndent} if (${reVar}.test(${pVar})) {\n`;
|
|
336
|
+
code += entry.node.jitCompile(register, level + 2, pathPrefix, `slash${level} + 1`, newVars, emitCall);
|
|
337
|
+
code += `${innerIndent} }\n`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (this.paramNode) {
|
|
341
|
+
code += this.paramNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newVars, emitCall);
|
|
342
|
+
}
|
|
307
343
|
code += `${innerIndent}}\n`;
|
|
308
344
|
}
|
|
309
345
|
|
package/src/core/router.ts
CHANGED
|
@@ -111,6 +111,32 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
111
111
|
public groupMiddleware: any[] = []
|
|
112
112
|
) { }
|
|
113
113
|
|
|
114
|
+
private static expandOptionalPaths(fullPath: string): string[] {
|
|
115
|
+
if (!fullPath.includes('?')) return [fullPath];
|
|
116
|
+
const parts = fullPath.split('/').filter(Boolean);
|
|
117
|
+
const hasOptParam = parts.some((p) => p.startsWith(':') && p.endsWith('?'));
|
|
118
|
+
if (!hasOptParam) return [fullPath];
|
|
119
|
+
|
|
120
|
+
let paths: string[] = [''];
|
|
121
|
+
for (let i = 0; i < parts.length; i++) {
|
|
122
|
+
const part = parts[i]!;
|
|
123
|
+
if (part.startsWith(':') && part.endsWith('?')) {
|
|
124
|
+
const concrete = part.slice(0, -1);
|
|
125
|
+
const next: string[] = [];
|
|
126
|
+
for (let j = 0; j < paths.length; j++) {
|
|
127
|
+
next.push(paths[j]!); // omitted
|
|
128
|
+
next.push(paths[j]! + '/' + concrete); // included
|
|
129
|
+
}
|
|
130
|
+
paths = next;
|
|
131
|
+
} else {
|
|
132
|
+
for (let j = 0; j < paths.length; j++) {
|
|
133
|
+
paths[j] = paths[j]! + '/' + part;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return Array.from(new Set(paths));
|
|
138
|
+
}
|
|
139
|
+
|
|
114
140
|
protected _add(method: string, path: string, handlers: HandlersChain) {
|
|
115
141
|
let fullPath = (this.prefix + "/" + path)
|
|
116
142
|
.replace(/\/+/g, "/");
|
|
@@ -127,14 +153,18 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
127
153
|
}
|
|
128
154
|
}
|
|
129
155
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
156
|
+
const expanded = BareRouter.expandOptionalPaths(fullPath || "");
|
|
157
|
+
const upperMethod = method.toUpperCase();
|
|
158
|
+
for (let i = 0; i < expanded.length; i++) {
|
|
159
|
+
this.routes.push({
|
|
160
|
+
method: upperMethod,
|
|
161
|
+
path: expanded[i]!,
|
|
162
|
+
handlers: [...this.groupMiddleware, ...resolvedHandlers]
|
|
163
|
+
});
|
|
164
|
+
}
|
|
135
165
|
this._onRouteMutate?.();
|
|
136
166
|
return this;
|
|
137
|
-
}
|
|
167
|
+
}
|
|
138
168
|
|
|
139
169
|
public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
|
|
140
170
|
public post: AddRouterRoute<Routes, 'POST'> = ((path: string, ...h: HandlersChain) => this._add("POST", path, h)) as any;
|
package/src/edge.ts
CHANGED
|
@@ -469,6 +469,8 @@ export function createSingleflight() {
|
|
|
469
469
|
}
|
|
470
470
|
|
|
471
471
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
472
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
473
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
472
474
|
|
|
473
475
|
export {
|
|
474
476
|
BareEdge as BareJS,
|
package/src/index.ts
CHANGED
|
@@ -88,6 +88,8 @@ export { file, type FileResponseOptions } from './utils/file';
|
|
|
88
88
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
89
89
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
90
90
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
91
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
92
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
91
93
|
|
|
92
94
|
// --- 6. Authentication (Bun Native) ---
|
|
93
95
|
// Always deploy using process.env [2026-01-06]
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface CacheLike {
|
|
4
|
+
match(request: Request | string): Promise<Response | undefined>;
|
|
5
|
+
put(request: Request | string, response: Response): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CacheOptions {
|
|
9
|
+
/** Cache name for Web Cache API (`caches.open(cacheName)`). Falls back to `caches.default` on Cloudflare Workers. */
|
|
10
|
+
cacheName?: string;
|
|
11
|
+
/** Optional custom `Cache`-compatible store (overrides `globalThis.caches`, useful for testing or custom stores). */
|
|
12
|
+
cache?: CacheLike;
|
|
13
|
+
/** `Cache-Control` header value applied to cacheable 200 OK responses (e.g. `'public, max-age=60, stale-while-revalidate=30'`). */
|
|
14
|
+
cacheControl?: string;
|
|
15
|
+
/** Optional `Vary` header(s) appended to responses (e.g. `'Accept-Encoding'` or `['Accept', 'Accept-Language']`). */
|
|
16
|
+
vary?: string | string[];
|
|
17
|
+
/** Custom cache key generator (defaults to `ctx.req.url`). */
|
|
18
|
+
keyGenerator?: (ctx: Context) => string;
|
|
19
|
+
/** Await `cache.put()` before returning the response (default: `false`; uses `executionCtx.waitUntil` when available). */
|
|
20
|
+
wait?: boolean;
|
|
21
|
+
/** HTTP status codes eligible for caching (default: `[200]`). */
|
|
22
|
+
cacheableStatuses?: number[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const resolveWebCache = async (cacheName?: string): Promise<CacheLike | null> => {
|
|
26
|
+
const g = globalThis as any;
|
|
27
|
+
const storage = g.caches;
|
|
28
|
+
if (!storage) return null;
|
|
29
|
+
if (cacheName && typeof storage.open === 'function') {
|
|
30
|
+
return await storage.open(cacheName);
|
|
31
|
+
}
|
|
32
|
+
if (storage.default && typeof storage.default.match === 'function') {
|
|
33
|
+
return storage.default as CacheLike;
|
|
34
|
+
}
|
|
35
|
+
if (typeof storage.open === 'function') {
|
|
36
|
+
return await storage.open('barejs-default');
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const mergeVary = (headers: Headers, vary: string | string[]) => {
|
|
42
|
+
const incoming = Array.isArray(vary) ? vary : [vary];
|
|
43
|
+
const existing = headers.get('vary');
|
|
44
|
+
const set = new Set<string>(
|
|
45
|
+
existing ? existing.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean) : []
|
|
46
|
+
);
|
|
47
|
+
const out = existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : [];
|
|
48
|
+
for (let i = 0; i < incoming.length; i++) {
|
|
49
|
+
const v = incoming[i]!.trim();
|
|
50
|
+
if (!v) continue;
|
|
51
|
+
const lower = v.toLowerCase();
|
|
52
|
+
if (!set.has(lower)) {
|
|
53
|
+
set.add(lower);
|
|
54
|
+
out.push(v);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (out.length > 0) headers.set('vary', out.join(', '));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Zero-dependency HTTP `Cache-Control` + Web Cache API (`caches.default` / `caches.open`) middleware.
|
|
62
|
+
* Edge-safe (Cloudflare Workers, Deno Deploy, Bun, Node.js). Caches GET/HEAD responses only.
|
|
63
|
+
*/
|
|
64
|
+
export const cache = (options: CacheOptions = {}): Middleware => {
|
|
65
|
+
const cacheName = options.cacheName;
|
|
66
|
+
const customCache = options.cache;
|
|
67
|
+
const cacheControl = options.cacheControl;
|
|
68
|
+
const vary = options.vary;
|
|
69
|
+
const keyGenerator = options.keyGenerator;
|
|
70
|
+
const wait = options.wait ?? false;
|
|
71
|
+
const allowedStatuses = new Set<number>(options.cacheableStatuses ?? [200]);
|
|
72
|
+
|
|
73
|
+
const wrapCache = async (ctx: Context, next: () => Promise<any>): Promise<any> => {
|
|
74
|
+
const method = ctx.req.method;
|
|
75
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
76
|
+
return next();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const webCache = customCache ?? (await resolveWebCache(cacheName));
|
|
80
|
+
const cacheKey = keyGenerator ? keyGenerator(ctx) : ctx.req.url;
|
|
81
|
+
const cacheReq = new Request(cacheKey, { method: 'GET' });
|
|
82
|
+
|
|
83
|
+
if (webCache) {
|
|
84
|
+
const hit = await webCache.match(cacheReq);
|
|
85
|
+
if (hit) {
|
|
86
|
+
if (method === 'HEAD') {
|
|
87
|
+
return new Response(null, { status: hit.status, headers: hit.headers });
|
|
88
|
+
}
|
|
89
|
+
return hit;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const res = await next();
|
|
94
|
+
if (!(res instanceof Response)) return res;
|
|
95
|
+
|
|
96
|
+
const ct = (res.headers.get('content-type') || '').toLowerCase();
|
|
97
|
+
if (ct.includes('text/event-stream')) return res;
|
|
98
|
+
if (!allowedStatuses.has(res.status)) return res;
|
|
99
|
+
|
|
100
|
+
let out = res;
|
|
101
|
+
if (cacheControl || vary) {
|
|
102
|
+
const headers = new Headers(res.headers);
|
|
103
|
+
if (cacheControl && !headers.has('cache-control')) {
|
|
104
|
+
headers.set('cache-control', cacheControl);
|
|
105
|
+
}
|
|
106
|
+
if (vary) mergeVary(headers, vary);
|
|
107
|
+
out = new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (webCache && method === 'GET') {
|
|
111
|
+
const putPromise = webCache.put(cacheReq, out.clone() as any).catch(() => {});
|
|
112
|
+
const execCtx = (ctx as any).executionCtx;
|
|
113
|
+
if (wait) {
|
|
114
|
+
await putPromise;
|
|
115
|
+
} else if (execCtx && typeof execCtx.waitUntil === 'function') {
|
|
116
|
+
execCtx.waitUntil(putPromise);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
124
|
+
return wrapCache(ctx, () => Promise.resolve(next ? next() : undefined));
|
|
125
|
+
};
|
|
126
|
+
(mw as any).__wrapHandler = wrapCache;
|
|
127
|
+
return mw;
|
|
128
|
+
};
|
|
@@ -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
|
+
};
|