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.
- 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 +194 -189
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +194 -189
- 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 +8 -5
- package/dist/types/core/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +4 -0
- package/dist/types/edge.d.ts +2 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/security/validators.d.ts +1 -0
- package/dist/types/utils/cache.d.ts +26 -0
- package/dist/types/utils/etag.d.ts +12 -0
- package/dist/types/utils/file.d.ts +23 -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 +26 -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 +86 -8
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +37 -6
- package/src/edge.ts +2 -0
- package/src/index.ts +3 -0
- package/src/security/validators.ts +24 -4
- package/src/utils/cache.ts +128 -0
- package/src/utils/etag.ts +115 -0
- package/src/utils/file.ts +111 -0
- package/src/utils/html.ts +72 -0
- package/src/utils/jsx.ts +217 -0
- package/src/utils/openapi.ts +7 -0
- package/src/utils/ssg.ts +110 -0
|
@@ -0,0 +1,27 @@
|
|
|
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
|
+
|
|
10
|
+
interface FetchableEdgeApp {
|
|
11
|
+
fetch(req: Request, env?: any, executionCtx?: any): Response | Promise<Response>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Cloudflare Pages Functions adapter (`onRequest`).
|
|
16
|
+
* Usage: `export const onRequest = handle(app);`
|
|
17
|
+
*/
|
|
18
|
+
export const handle = <Env = Record<string, any>>(app: FetchableEdgeApp) => {
|
|
19
|
+
return (context: CloudflarePagesContext<Env>): Response | Promise<Response> => {
|
|
20
|
+
return app.fetch(context.request, context.env, {
|
|
21
|
+
waitUntil: (p: Promise<any>) => context.waitUntil(p),
|
|
22
|
+
passThroughOnException: () => {}
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const cloudflarePages = handle;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface NetlifyContext {
|
|
2
|
+
ip?: string;
|
|
3
|
+
requestId?: string;
|
|
4
|
+
site?: { id?: string; name?: string; url?: string };
|
|
5
|
+
geo?: { city?: string; country?: { code?: string; name?: string }; timezone?: string };
|
|
6
|
+
cookies?: { get(name: string): string | undefined };
|
|
7
|
+
waitUntil?(promise: Promise<any>): void;
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface FetchableApp {
|
|
12
|
+
fetch(req: Request, peerIpOrEnv?: any, executionCtx?: any): Response | Promise<Response>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Netlify Functions v2 adapter.
|
|
17
|
+
* Usage: `export default handle(app);`
|
|
18
|
+
*/
|
|
19
|
+
export const handle = (app: FetchableApp) => {
|
|
20
|
+
return (req: Request, context?: NetlifyContext): Response | Promise<Response> => {
|
|
21
|
+
const execCtx = context?.waitUntil
|
|
22
|
+
? { waitUntil: (p: Promise<any>) => context.waitUntil!(p) }
|
|
23
|
+
: undefined;
|
|
24
|
+
return app.fetch(req, context ?? {}, execCtx);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const netlify = handle;
|
package/src/core/bare.ts
CHANGED
|
@@ -121,6 +121,7 @@ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<an
|
|
|
121
121
|
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
122
122
|
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
123
123
|
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
124
|
+
cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
|
|
124
125
|
}
|
|
125
126
|
) => Res | Promise<Res>;
|
|
126
127
|
|
|
@@ -624,11 +625,29 @@ export class BareJS<
|
|
|
624
625
|
router: BareRouter<R2>
|
|
625
626
|
) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
626
627
|
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
628
|
+
public override use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
|
|
629
|
+
mw: BareJS<D2, R2, M2>
|
|
630
|
+
): BareJS<Derived & D2, Routes & R2, Macros & M2>;
|
|
631
|
+
public override use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
|
|
632
|
+
prefix: P,
|
|
633
|
+
mw: BareJS<D2, R2, M2>
|
|
634
|
+
): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
|
|
635
|
+
public override use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
|
|
636
|
+
public override use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
|
|
637
|
+
public override use(...mws: any[]): BareJS<Derived, Routes, Macros>;
|
|
638
|
+
public override use(prefixOrMw: any, ...rest: any[]): any {
|
|
639
|
+
const mergeMacrosFrom = (candidate: any) => {
|
|
640
|
+
if (candidate && typeof candidate === 'object' && candidate.macros && typeof candidate.macros === 'object') {
|
|
641
|
+
for (const [k, def] of Object.entries(candidate.macros)) {
|
|
642
|
+
if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
|
|
643
|
+
if (def && typeof def === 'object') this.macros[k] = def as any;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
mergeMacrosFrom(prefixOrMw);
|
|
648
|
+
for (let i = 0; i < rest.length; i++) mergeMacrosFrom(rest[i]);
|
|
649
|
+
return super.use(prefixOrMw, ...rest);
|
|
650
|
+
}
|
|
632
651
|
|
|
633
652
|
/**
|
|
634
653
|
* Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
|
|
@@ -698,7 +717,7 @@ export class BareJS<
|
|
|
698
717
|
}
|
|
699
718
|
// Only pass schemaValidator if any RouteSchemas key is present
|
|
700
719
|
const hasSchemaKey =
|
|
701
|
-
'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
|
|
720
|
+
'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'cookies' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
|
|
702
721
|
if (hasSchemaKey) expanded.push(h);
|
|
703
722
|
for (let j = 0; j < macroMws.length; j++) expanded.push(macroMws[j]);
|
|
704
723
|
} else {
|
|
@@ -788,6 +807,27 @@ export class BareJS<
|
|
|
788
807
|
};
|
|
789
808
|
}
|
|
790
809
|
|
|
810
|
+
const postIdx = pipeline.findIndex((fn) => fn?.__postResponse);
|
|
811
|
+
if (postIdx !== -1) {
|
|
812
|
+
const applyPost = pipeline[postIdx]!.__postResponse;
|
|
813
|
+
const innerPipeline = pipeline.filter((_, i) => i !== postIdx);
|
|
814
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
815
|
+
return async (ctx: Context, doLog?: any) => {
|
|
816
|
+
const res = await innerCompiled(ctx, doLog);
|
|
817
|
+
return applyPost(ctx, res);
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const wrapIdx = pipeline.findIndex((fn) => fn?.__wrapHandler);
|
|
822
|
+
if (wrapIdx !== -1) {
|
|
823
|
+
const applyWrap = pipeline[wrapIdx]!.__wrapHandler;
|
|
824
|
+
const innerPipeline = pipeline.filter((_, i) => i !== wrapIdx);
|
|
825
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
826
|
+
return async (ctx: Context, doLog?: any) => {
|
|
827
|
+
return applyWrap(ctx, () => innerCompiled(ctx, doLog));
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
|
|
791
831
|
const cbIdx = pipeline.findIndex((fn) => fn?.__circuitBreaker);
|
|
792
832
|
if (cbIdx !== -1) {
|
|
793
833
|
const cbMw = pipeline[cbIdx]!;
|
|
@@ -905,6 +945,40 @@ export class BareJS<
|
|
|
905
945
|
return res;
|
|
906
946
|
`;
|
|
907
947
|
|
|
948
|
+
const genEncoder = new TextEncoder();
|
|
949
|
+
const generatorToResponse = (gen: any, status: number, hdrs?: Record<string, string>): Response => {
|
|
950
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
951
|
+
async pull(controller) {
|
|
952
|
+
try {
|
|
953
|
+
const step = await gen.next();
|
|
954
|
+
if (step.done) {
|
|
955
|
+
controller.close();
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
const val = step.value;
|
|
959
|
+
if (val === undefined || val === null) return;
|
|
960
|
+
if (val instanceof Uint8Array) {
|
|
961
|
+
controller.enqueue(val);
|
|
962
|
+
} else if (typeof val === 'string') {
|
|
963
|
+
controller.enqueue(genEncoder.encode(val));
|
|
964
|
+
} else {
|
|
965
|
+
controller.enqueue(genEncoder.encode(JSON.stringify(val) + '\n'));
|
|
966
|
+
}
|
|
967
|
+
} catch (err) {
|
|
968
|
+
controller.error(err);
|
|
969
|
+
}
|
|
970
|
+
},
|
|
971
|
+
cancel() {
|
|
972
|
+
try { gen.return?.(); } catch {}
|
|
973
|
+
}
|
|
974
|
+
});
|
|
975
|
+
const outHeaders: Record<string, string> = hdrs ? { ...hdrs } : {};
|
|
976
|
+
if (!outHeaders['content-type'] && !outHeaders['Content-Type']) {
|
|
977
|
+
outHeaders['content-type'] = 'text/plain; charset=utf-8';
|
|
978
|
+
}
|
|
979
|
+
return new Response(stream, { status, headers: outHeaders });
|
|
980
|
+
};
|
|
981
|
+
|
|
908
982
|
const buildNonResFinalize = `
|
|
909
983
|
${logStatusCode}
|
|
910
984
|
let outRes;
|
|
@@ -917,6 +991,8 @@ export class BareJS<
|
|
|
917
991
|
headers: ctx._headers || text200.headers
|
|
918
992
|
});
|
|
919
993
|
}
|
|
994
|
+
} else if (res !== null && typeof res === 'object' && typeof res.next === 'function') {
|
|
995
|
+
outRes = genToRes(res, finalStatus, ctx._headers);
|
|
920
996
|
} else if (finalStatus === 200 && !ctx._headers) {
|
|
921
997
|
outRes = Response.json(res ?? null);
|
|
922
998
|
} else if (finalStatus === 200 && ctx._headers === lastHdrs) {
|
|
@@ -966,6 +1042,7 @@ export class BareJS<
|
|
|
966
1042
|
const extraNames = [
|
|
967
1043
|
'applyShortCircuit',
|
|
968
1044
|
'noop',
|
|
1045
|
+
'genToRes',
|
|
969
1046
|
...(rFilter ? ['rFilter'] : []),
|
|
970
1047
|
...(idemCommit ? ['idemCommit'] : []),
|
|
971
1048
|
...(idemRelease ? ['idemRelease'] : [])
|
|
@@ -973,6 +1050,7 @@ export class BareJS<
|
|
|
973
1050
|
const extraVals = [
|
|
974
1051
|
applyCtxHeadersToRes,
|
|
975
1052
|
noop,
|
|
1053
|
+
generatorToResponse,
|
|
976
1054
|
...(rFilter ? [rFilter] : []),
|
|
977
1055
|
...(idemCommit ? [idemCommit] : []),
|
|
978
1056
|
...(idemRelease ? [idemRelease] : [])
|
|
@@ -1657,7 +1735,7 @@ export class BareJS<
|
|
|
1657
1735
|
let count = 0;
|
|
1658
1736
|
for (const route of this.routes) {
|
|
1659
1737
|
if (route.method === 'ALL') continue;
|
|
1660
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1738
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1661
1739
|
if (route.handlers.length !== 1) continue;
|
|
1662
1740
|
|
|
1663
1741
|
const rawHandler = route.handlers[0] as any;
|
|
@@ -1790,7 +1868,7 @@ export class BareJS<
|
|
|
1790
1868
|
|
|
1791
1869
|
for (const route of this.routes) {
|
|
1792
1870
|
if (route.method !== 'GET' && route.method !== 'HEAD' && route.method !== 'DELETE' && route.method !== 'OPTIONS') continue;
|
|
1793
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1871
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1794
1872
|
if (route.handlers.length !== 1) continue;
|
|
1795
1873
|
|
|
1796
1874
|
const rawHandler = route.handlers[0] as any;
|
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
|
@@ -76,6 +76,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (
|
|
|
76
76
|
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
77
77
|
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
78
78
|
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
79
|
+
cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
|
|
79
80
|
}
|
|
80
81
|
) => Res | Promise<Res>;
|
|
81
82
|
|
|
@@ -110,6 +111,32 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
110
111
|
public groupMiddleware: any[] = []
|
|
111
112
|
) { }
|
|
112
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
|
+
|
|
113
140
|
protected _add(method: string, path: string, handlers: HandlersChain) {
|
|
114
141
|
let fullPath = (this.prefix + "/" + path)
|
|
115
142
|
.replace(/\/+/g, "/");
|
|
@@ -126,14 +153,18 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
126
153
|
}
|
|
127
154
|
}
|
|
128
155
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
+
}
|
|
134
165
|
this._onRouteMutate?.();
|
|
135
166
|
return this;
|
|
136
|
-
}
|
|
167
|
+
}
|
|
137
168
|
|
|
138
169
|
public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
|
|
139
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
|
@@ -84,9 +84,12 @@ export {
|
|
|
84
84
|
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
85
85
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
86
86
|
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
87
|
+
export { file, type FileResponseOptions } from './utils/file';
|
|
87
88
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
88
89
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
89
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';
|
|
90
93
|
|
|
91
94
|
// --- 6. Authentication (Bun Native) ---
|
|
92
95
|
// Always deploy using process.env [2026-01-06]
|
|
@@ -244,6 +244,7 @@ export interface RouteSchemas {
|
|
|
244
244
|
query?: any;
|
|
245
245
|
params?: any;
|
|
246
246
|
headers?: any;
|
|
247
|
+
cookies?: any;
|
|
247
248
|
response?: any;
|
|
248
249
|
/** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
|
|
249
250
|
stripUnknown?: boolean;
|
|
@@ -909,9 +910,11 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
909
910
|
const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
|
|
910
911
|
const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
|
|
911
912
|
const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
|
|
913
|
+
const cookiesCheck = schemas.cookies ? compileSingleSchema(schemas.cookies) : null;
|
|
912
914
|
const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
|
|
913
915
|
const queryProjector = schemas.stripUnknown && schemas.query ? compileProjector(schemas.query) : null;
|
|
914
916
|
const paramsProjector = schemas.stripUnknown && schemas.params ? compileProjector(schemas.params) : null;
|
|
917
|
+
const cookiesProjector = schemas.stripUnknown && schemas.cookies ? compileProjector(schemas.cookies) : null;
|
|
915
918
|
const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
|
|
916
919
|
const maxBodySize = schemas.maxBodySize ?? 1048576;
|
|
917
920
|
const queryArrayKeys: string[] = [];
|
|
@@ -942,11 +945,28 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
942
945
|
}
|
|
943
946
|
}
|
|
944
947
|
}
|
|
945
|
-
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
|
|
948
|
+
const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck || cookiesCheck);
|
|
946
949
|
|
|
947
950
|
const validateSyncParts = (ctx: Context): Response | undefined | Promise<Response | undefined> => {
|
|
951
|
+
const runCookies = (): Response | undefined | Promise<Response | undefined> => {
|
|
952
|
+
if (!cookiesCheck) return undefined;
|
|
953
|
+
const coerced = coerceFields(ctx.cookies, schemas.cookies);
|
|
954
|
+
const r = cookiesCheck(coerced);
|
|
955
|
+
if (r && typeof (r as any).then === 'function') {
|
|
956
|
+
return (r as Promise<CheckResult>).then((res) => {
|
|
957
|
+
if (!res.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: res.error });
|
|
958
|
+
ctx._cookies = cookiesProjector ? cookiesProjector(res.data) : res.data;
|
|
959
|
+
return undefined;
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
const syncR = r as CheckResult;
|
|
963
|
+
if (!syncR.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: syncR.error });
|
|
964
|
+
ctx._cookies = cookiesProjector ? cookiesProjector(syncR.data) : syncR.data;
|
|
965
|
+
return undefined;
|
|
966
|
+
};
|
|
967
|
+
|
|
948
968
|
const runHeaders = (): Response | undefined | Promise<Response | undefined> => {
|
|
949
|
-
if (!headersCheck) return
|
|
969
|
+
if (!headersCheck) return runCookies();
|
|
950
970
|
const hdrObj: Record<string, string> = {};
|
|
951
971
|
ctx.req.headers.forEach((v, k) => {
|
|
952
972
|
const lower = k.toLowerCase();
|
|
@@ -957,12 +977,12 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
957
977
|
const r = headersCheck(hdrObj);
|
|
958
978
|
if (r && typeof (r as any).then === 'function') {
|
|
959
979
|
return (r as Promise<CheckResult>).then((res) =>
|
|
960
|
-
res.ok ?
|
|
980
|
+
res.ok ? runCookies() : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
|
|
961
981
|
);
|
|
962
982
|
}
|
|
963
983
|
const syncR = r as CheckResult;
|
|
964
984
|
if (!syncR.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: syncR.error });
|
|
965
|
-
return
|
|
985
|
+
return runCookies();
|
|
966
986
|
};
|
|
967
987
|
|
|
968
988
|
const runQuery = (): Response | undefined | Promise<Response | undefined> => {
|
|
@@ -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
|
+
};
|