@lengkapp/edge 0.0.38 → 0.0.40
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 +795 -320
- package/dist/README.md +795 -320
- package/dist/client.js +1 -1
- package/dist/server.d.ts +161 -79
- package/dist/server.js +1 -1
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -26,4 +26,4 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
|
26
26
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
27
27
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
28
28
|
*/
|
|
29
|
-
(()=>{const e={loader:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',alert:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-triangle-alert"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>',refresh:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-refresh-cw"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>'},t=new WeakMap;function
|
|
29
|
+
(()=>{const e={loader:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',alert:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-triangle-alert"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>',refresh:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-refresh-cw"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>'},t=new WeakMap;function r(t){return e[t]||""}function n(){const e=document.querySelector('meta[name="_csrf"]');return e?e.content:""}var o=null;function i(e,t,r){const n=document.querySelector(e);if(!n)throw new Error("Target not found: "+e);const o=document.createElement("template");o.innerHTML="string"==typeof r?r:String(r);const i=o.content,c=[],s=[];i.querySelectorAll("script").forEach(e=>{const t=document.createComment("_edge-script");c.push(e),s.push(t),e.replaceWith(t)}),"in"===t?n.replaceChildren(i):"out"===t?(n.parentNode.insertBefore(i,n),n.remove()):"before"===t?n.parentNode.insertBefore(i,n):"after"===t?n.parentNode.insertBefore(i,n.nextSibling):n.replaceChildren(i),function(e,t){if(0===e.length)return;let r=Promise.resolve();for(let n=0;n<e.length;n++){const o=e[n],i=t[n];r=r.then(()=>a(o,i))}r.catch(()=>{})}(c,s)}function a(e,t){return new Promise(r=>{if(!t.parentNode)return void r();const n=document.createElement("script");for(let t=0;t<e.attributes.length;t++){const r=e.attributes[t];n.setAttribute(r.name,r.value)}const o=e.hasAttribute("src"),i=e.hasAttribute("async");if(!o)return n.textContent=e.textContent,t.parentNode.replaceChild(n,t),void r();if(i)return t.parentNode.replaceChild(n,t),void r();let a=!1;const c=()=>{a||(a=!0,r())};n.addEventListener("load",c,{once:!0}),n.addEventListener("error",c,{once:!0}),t.parentNode.replaceChild(n,t),setTimeout(c,3e4)})}async function c(e){const a=t.get(e);a&&a.abort&&a.abort.abort();const s=new AbortController;t.set(e,{abort:s,retry:()=>c(e)});const l=e.hasAttribute("_post")?"POST":"GET",u=e.getAttribute("POST"===l?"_post":"_get")||e.getAttribute("_go")||e.getAttribute("_open");if(!u)return;if(e.hasAttribute("_go"))return void(location.href=u);if(e.hasAttribute("_open"))return void window.open(u,"_blank","noopener");const f=e.getAttribute("_in")&&{sel:e.getAttribute("_in"),mode:"in"}||e.getAttribute("_out")&&{sel:e.getAttribute("_out"),mode:"out"}||e.getAttribute("_before")&&{sel:e.getAttribute("_before"),mode:"before"}||e.getAttribute("_after")&&{sel:e.getAttribute("_after"),mode:"after"};if(!f)return;const m=function(e,t){const n=document.querySelector(e);if(!n)return null;const o=document.createElement("span");return o.className="_edge-loader",o.innerHTML=r("loader"),"in"===t?(n.innerHTML="",n.appendChild(o)):"out"===t||"before"===t?n.parentNode.insertBefore(o,n):n.parentNode.insertBefore(o,n.nextSibling),o}(f.sel,f.mode);try{const t={"X-CSRF-Token":n()};let r;if(e.hasAttribute("_id")&&(t["X-DeviceId"]=(o||(o=function(){var e=[navigator.userAgent,navigator.language,screen.width,screen.height,screen.colorDepth,(new Date).getTimezoneOffset(),navigator.hardwareConcurrency||"?",navigator.deviceMemory||"?"].join("|"),t=d.createElement("canvas"),r="",n=t.getContext&&t.getContext("2d");if(n){n.textBaseline="top",n.font="14px Arial",n.fillStyle="#f60",n.fillRect(125,1,62,20),n.fillStyle="#069",n.fillText("FP",2,15),n.fillStyle="rgba(102,204,0,0.7)",n.fillText("FP",4,17);try{r=t.toDataURL()}catch{r=""}}var o="";try{var i=t.getContext("webgl")||t.getContext("experimental-webgl");if(i){var a=i.getExtension("WEBGL_debug_renderer_info");o=a?i.getParameter(a.UNMASKED_VENDOR_WEBGL)+"~"+i.getParameter(a.UNMASKED_RENDERER_WEBGL):i.getParameter(i.VERSION)+"~"+i.getParameter(i.RENDERER)}}catch{o=""}var c=["Arial","Courier New","Times New Roman","Helvetica","Georgia","Verdana","Comic Sans MS","Trebuchet MS","Impact","Lucida Console"],s="",l=d.body||d.documentElement;if(l){for(var u=[],f=0;f<c.length;f++){var m=d.createElement("span");m.style.cssText='position:absolute;left:-9999px;visibility:hidden;font:72px "'+c[f]+'",monospace',m.textContent="mmmmmmmmmmlli",l.appendChild(m),u.push(m.offsetWidth),l.removeChild(m)}s=u.join(",")}return function(){var e=w.OfflineAudioContext||w.webkitOfflineAudioContext;if(!e)return Promise.resolve("");try{var t=new e(1,44100,44100),r=t.createOscillator();r.type="triangle",r.frequency.value=1e4;var n=t.createDynamicsCompressor();return n.threshold.value=-50,n.knee.value=40,n.ratio.value=12,n.attack.value=0,n.release.value=.25,r.connect(n),n.connect(t.destination),r.start(0),t.startRendering().then(function(e){for(var t=e.getChannelData(0),r=0,n=4500;n<5e3;n++)r+=Math.abs(t[n]);return r.toString()}).catch(function(){return""})}catch{return Promise.resolve("")}}().then(function(t){return function(e){if(!w.crypto||!w.crypto.subtle||!w.TextEncoder){for(var t=5381,r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r);return Promise.resolve((t>>>0).toString(16))}var n=(new TextEncoder).encode(e);return w.crypto.subtle.digest("SHA-256",n).then(function(e){for(var t=new Uint8Array(e),r="",n=0;n<t.length;n++)r+=t[n].toString(16).padStart(2,"0");return r})}([e,r,o,s,t].join("||"))})}().catch(function(){return""})),o)),"POST"===l){const n=e.getAttribute("_form"),o=e.getAttribute("_json");if(n)r=function(e){const t=document.querySelector(e);if(!t)throw new Error("Form not found: "+e);return new FormData(t)}(n);else{if(!o)throw new Error("_post requires _form or _json");t["Content-Type"]="application/json",r=JSON.stringify(function(e){const t=e.split(",").map(e=>e.trim()).filter(Boolean),r={};for(const e of t){const t=document.querySelector(e);if(!t)continue;const n=t.name||t.id||e;"checkbox"===t.type?r[n]=t.checked:"radio"===t.type?t.checked&&(r[n]=t.value):t.multiple?r[n]=Array.from(t.selectedOptions).map(e=>e.value):r[n]=t.value}return r}(o))}}const a=await fetch(u,{method:l,headers:t,body:r,signal:s.signal}),c=await a.text();if(!a.ok){const t=e.getAttribute("_toast");if(t&&document.querySelector(t))return void i(t,"in",c);throw new Error("HTTP "+a.status)}i(f.sel,f.mode,c)}catch(t){if("AbortError"===t.name)return;!function(e,t,n,o){const i=document.querySelector(e);if(!i)return;const a=document.createElement("div");a.className="_edge-error",a.innerHTML=r("alert");const c=document.createElement("span");c.textContent=n.message||"Request failed",a.appendChild(c);const s=document.createElement("button");s.type="button",s.innerHTML=r("refresh")+" Retry",s.onclick=()=>{a.remove(),o()},a.appendChild(s),"in"===t?(i.innerHTML="",i.appendChild(a)):"out"===t||"before"===t?i.parentNode.insertBefore(a,i):i.parentNode.insertBefore(a,i.nextSibling)}(f.sel,f.mode,t,()=>c(e))}finally{m&&m.remove()}}function s(e){if(e.__edgeInit)return;e.__edgeInit=!0;const t=function(e){return e.getAttribute("_trigger")||"click"}(e);if("click"===t)e.addEventListener("click",t=>{t.preventDefault(),c(e)});else if("load"===t)c(e);else if("visible"===t){const t=new IntersectionObserver(r=>{r.some(e=>e.isIntersecting)&&(t.disconnect(),c(e))});t.observe(e)}}function l(e=document){(function(){if(document.getElementById("_edge-style"))return;const e=document.createElement("style");e.id="_edge-style",e.textContent="._edge-loader{display:inline-flex;align-items:center;gap:.35rem;opacity:.7}._edge-loader svg{animation:_edge-spin 1s linear infinite}._edge-error{display:flex;align-items:center;gap:.5rem;color:#b91c1c;background:#fef2f2;border:1px solid #fecaca;padding:.5rem .75rem;border-radius:.5rem;font:14px system-ui,sans-serif}._edge-error button{display:inline-flex;align-items:center;gap:.25rem;margin-left:auto;cursor:pointer;border:1px solid #fca5a5;background:#fff;color:#991b1b;border-radius:.35rem;padding:.25rem .5rem}@keyframes _edge-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)})(),e.querySelectorAll&&e.querySelectorAll("[_get], [_post], [_go], [_open]").forEach(s)}function u(){new MutationObserver(e=>{for(const t of e)t.addedNodes.forEach(e=>{1===e.nodeType&&(e.matches&&e.matches("[_get], [_post], [_go], [_open]")&&s(e),l(e))})}).observe(document.documentElement,{childList:!0,subtree:!0})}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{l(),u()}):(l(),u())})();
|
package/dist/server.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// server.d.ts
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
toString(): string;
|
|
7
|
-
}
|
|
3
|
+
/* ------------------------------------------------------------------ *
|
|
4
|
+
* JSX runtime *
|
|
5
|
+
* ------------------------------------------------------------------ */
|
|
8
6
|
|
|
9
7
|
/**
|
|
10
8
|
* Runtime value is `Symbol('Fragment')`. The function signature is a
|
|
@@ -14,108 +12,192 @@ export class Html {
|
|
|
14
12
|
*/
|
|
15
13
|
export const Fragment: (props: { children?: any }) => JSXNode;
|
|
16
14
|
|
|
17
|
-
export
|
|
18
|
-
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
| undefined
|
|
24
|
-
| JsxChild[];
|
|
15
|
+
export interface JSXNode {
|
|
16
|
+
type: string | symbol | ((props: any) => any);
|
|
17
|
+
props: Record<string, any>;
|
|
18
|
+
children: any[];
|
|
19
|
+
__isJSX: true;
|
|
20
|
+
}
|
|
25
21
|
|
|
26
|
-
export
|
|
27
|
-
|
|
28
|
-
|
|
|
29
|
-
|
|
22
|
+
export function jsx(
|
|
23
|
+
type: JSXNode['type'],
|
|
24
|
+
props: Record<string, any> | null,
|
|
25
|
+
...children: any[]
|
|
26
|
+
): JSXNode;
|
|
30
27
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Renders a JSX tree to an HTML string. Async because components may be
|
|
30
|
+
* `async`. Accepts `null`/boolean children, Promises, and arrays.
|
|
31
|
+
*
|
|
32
|
+
* The optional `ctx` is normally supplied by `Context.html`/`Context.page`;
|
|
33
|
+
* user code never needs to pass it.
|
|
34
|
+
*/
|
|
35
|
+
export function renderToString(node: any, ctx?: Context): Promise<string>;
|
|
36
|
+
|
|
37
|
+
/* ------------------------------------------------------------------ *
|
|
38
|
+
* Ambient context *
|
|
39
|
+
* ------------------------------------------------------------------ */
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Returns the Context of the request whose render is currently executing.
|
|
43
|
+
*
|
|
44
|
+
* MUST be called synchronously at the top of a component — before any
|
|
45
|
+
* `await`. After an `await`, use the captured local reference; the
|
|
46
|
+
* ambient slot is no longer guaranteed to belong to your request.
|
|
47
|
+
*
|
|
48
|
+
* Throws if called outside an active render (module top-level, scheduled
|
|
49
|
+
* handler, `waitUntil` callback, or after an `await`).
|
|
50
|
+
*/
|
|
51
|
+
export function useCtx(): Context;
|
|
34
52
|
|
|
35
|
-
/*
|
|
53
|
+
/* ------------------------------------------------------------------ *
|
|
54
|
+
* Context *
|
|
55
|
+
* ------------------------------------------------------------------ */
|
|
36
56
|
|
|
37
57
|
export interface CookieOptions {
|
|
38
58
|
path?: string;
|
|
39
59
|
domain?: string;
|
|
40
60
|
maxAge?: number;
|
|
41
|
-
expires?: Date
|
|
42
|
-
httpOnly?: boolean;
|
|
61
|
+
expires?: Date;
|
|
43
62
|
secure?: boolean;
|
|
44
|
-
|
|
45
|
-
|
|
63
|
+
httpOnly?: boolean;
|
|
64
|
+
sameSite?: 'Strict' | 'Lax' | 'None' | string;
|
|
46
65
|
}
|
|
47
66
|
|
|
48
|
-
|
|
67
|
+
export interface CorsOptions {
|
|
68
|
+
origin?: string | string[];
|
|
69
|
+
methods?: string;
|
|
70
|
+
headers?: string;
|
|
71
|
+
}
|
|
49
72
|
|
|
50
|
-
export interface
|
|
51
|
-
|
|
52
|
-
|
|
73
|
+
export interface CacheOptions {
|
|
74
|
+
/** TTL in seconds. Default: 3600 */
|
|
75
|
+
ttl?: number;
|
|
76
|
+
/** stale-while-revalidate in seconds. Default: 0 */
|
|
77
|
+
staleWhileRevalidate?: number;
|
|
53
78
|
}
|
|
54
79
|
|
|
55
|
-
export interface
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
param(key: string): string | undefined;
|
|
62
|
-
query(key: string): string | null;
|
|
63
|
-
header(key: string): string | null;
|
|
64
|
-
cookie(key: string): string | undefined;
|
|
65
|
-
json<T = any>(): Promise<T>;
|
|
66
|
-
text(): Promise<string>;
|
|
67
|
-
formData(): Promise<FormData>;
|
|
80
|
+
export interface RouteOptions {
|
|
81
|
+
cors?: boolean | CorsOptions;
|
|
82
|
+
cache?: boolean | CacheOptions;
|
|
83
|
+
compress?: boolean;
|
|
84
|
+
log?: boolean;
|
|
85
|
+
validate?: (ctx: Context) => boolean | Promise<boolean>;
|
|
68
86
|
}
|
|
69
87
|
|
|
70
|
-
export
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
88
|
+
export class Context {
|
|
89
|
+
constructor(
|
|
90
|
+
request: Request,
|
|
91
|
+
env: Record<string, any>,
|
|
92
|
+
executionCtx: ExecutionContext,
|
|
93
|
+
params?: Record<string, string>,
|
|
94
|
+
parsedUrl?: URL | null
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
req: Request;
|
|
98
|
+
env: Record<string, any>;
|
|
99
|
+
executionCtx: ExecutionContext;
|
|
100
|
+
params: Record<string, string>;
|
|
101
|
+
status: number;
|
|
102
|
+
headers: Headers;
|
|
103
|
+
url: URL;
|
|
104
|
+
|
|
105
|
+
getCookie(name: string): string | null;
|
|
106
|
+
readonly query: URLSearchParams;
|
|
76
107
|
setCookie(name: string, value: string, options?: CookieOptions): void;
|
|
77
108
|
deleteCookie(name: string, options?: CookieOptions): void;
|
|
78
|
-
redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
|
|
79
|
-
text(body: string | Html, status?: number, headers?: Record<string, string>): Response;
|
|
80
|
-
json(body: any, status?: number, headers?: Record<string, string>): Response;
|
|
81
|
-
html(body: string | Html, status?: number, headers?: Record<string, string>): Response;
|
|
82
|
-
page(body: string | Html, status?: number, headers?: Record<string, string>): Response;
|
|
83
|
-
}
|
|
84
109
|
|
|
85
|
-
|
|
86
|
-
|
|
110
|
+
text(data: string, status?: number, headers?: Record<string, string>): Response;
|
|
111
|
+
json(data: any, status?: number, headers?: Record<string, string>): Response;
|
|
112
|
+
|
|
113
|
+
/** Async — JSX trees may contain async components. */
|
|
114
|
+
html(
|
|
115
|
+
data: string | JSXNode | JSXNode[] | null | undefined,
|
|
116
|
+
status?: number,
|
|
117
|
+
headers?: Record<string, string>
|
|
118
|
+
): Promise<Response>;
|
|
87
119
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
120
|
+
/** Async — JSX trees may contain async components. */
|
|
121
|
+
page(
|
|
122
|
+
data: string | JSXNode | JSXNode[] | null | undefined,
|
|
123
|
+
status?: number,
|
|
124
|
+
headers?: Record<string, string>
|
|
125
|
+
): Promise<Response>;
|
|
126
|
+
|
|
127
|
+
redirect(location: string, status?: number): Response;
|
|
128
|
+
}
|
|
91
129
|
|
|
92
|
-
|
|
93
|
-
|
|
130
|
+
/* ------------------------------------------------------------------ *
|
|
131
|
+
* Edge router *
|
|
132
|
+
* ------------------------------------------------------------------ */
|
|
94
133
|
|
|
95
|
-
|
|
96
|
-
post(path: string, handler: Handler<E>): void;
|
|
134
|
+
export type RouteHandler = (ctx: Context) => any | Promise<any>;
|
|
97
135
|
|
|
98
|
-
|
|
99
|
-
|
|
136
|
+
export type ScheduledHandler = (
|
|
137
|
+
event: ScheduledEvent,
|
|
138
|
+
env: Record<string, any>,
|
|
139
|
+
ctx: ExecutionContext
|
|
140
|
+
) => void | Promise<void>;
|
|
100
141
|
|
|
101
|
-
|
|
102
|
-
|
|
142
|
+
export interface SecurityOptions {
|
|
143
|
+
logSecurityEvents?: boolean;
|
|
144
|
+
extraHeaders?: Record<string, string> | null;
|
|
145
|
+
trustedProxies?: string[] | null;
|
|
146
|
+
}
|
|
103
147
|
|
|
104
|
-
|
|
105
|
-
|
|
148
|
+
export interface EdgeDefaults {
|
|
149
|
+
cors: CorsOptions & { methods: string };
|
|
150
|
+
}
|
|
106
151
|
|
|
107
|
-
|
|
152
|
+
export class Edge {
|
|
153
|
+
constructor();
|
|
154
|
+
|
|
155
|
+
readonly staticRoutes: Map<string, Map<string, { handler: RouteHandler; options: RouteOptions }>>;
|
|
156
|
+
readonly dynamicTries: Record<string, any>;
|
|
157
|
+
defaults: EdgeDefaults;
|
|
158
|
+
scheduledHandler: ScheduledHandler | null;
|
|
159
|
+
security: SecurityOptions;
|
|
160
|
+
|
|
161
|
+
get(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
162
|
+
get(path: string, handler: RouteHandler): void;
|
|
163
|
+
post(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
164
|
+
post(path: string, handler: RouteHandler): void;
|
|
165
|
+
put(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
166
|
+
put(path: string, handler: RouteHandler): void;
|
|
167
|
+
delete(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
168
|
+
delete(path: string, handler: RouteHandler): void;
|
|
169
|
+
patch(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
170
|
+
patch(path: string, handler: RouteHandler): void;
|
|
171
|
+
options(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
172
|
+
options(path: string, handler: RouteHandler): void;
|
|
173
|
+
head(path: string, options: RouteOptions | boolean, handler: RouteHandler): void;
|
|
174
|
+
head(path: string, handler: RouteHandler): void;
|
|
175
|
+
|
|
176
|
+
scheduled(handler: ScheduledHandler): void;
|
|
177
|
+
|
|
178
|
+
fetch(
|
|
179
|
+
request: Request,
|
|
180
|
+
env: Record<string, any>,
|
|
181
|
+
executionCtx: ExecutionContext
|
|
182
|
+
): Promise<Response>;
|
|
108
183
|
}
|
|
109
184
|
|
|
110
|
-
/*
|
|
185
|
+
/* ---------------- JSX typing for this runtime ---------------- */
|
|
186
|
+
type ComponentReturn =
|
|
187
|
+
| JSXNode
|
|
188
|
+
| string
|
|
189
|
+
| number
|
|
190
|
+
| boolean
|
|
191
|
+
| null
|
|
192
|
+
| undefined
|
|
193
|
+
| ComponentReturn[]
|
|
194
|
+
| Promise<ComponentReturn>;
|
|
195
|
+
|
|
111
196
|
declare global {
|
|
112
197
|
namespace JSX {
|
|
113
|
-
type Element =
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
interface IntrinsicElements {
|
|
118
|
-
[elemName: string]: Record<string, any>;
|
|
119
|
-
}
|
|
198
|
+
type Element = any;
|
|
199
|
+
type ElementType = string | symbol | ((props: any) => ComponentReturn);
|
|
200
|
+
interface IntrinsicElements { [elemName: string]: any; }
|
|
201
|
+
interface ElementChildrenAttribute { children: {}; }
|
|
120
202
|
}
|
|
121
203
|
}
|
package/dist/server.js
CHANGED
|
@@ -26,4 +26,4 @@ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
|
26
26
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
27
27
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
28
28
|
*/
|
|
29
|
-
const e=Symbol("Fragment");class t{constructor(e){this.value=String(e)}toString(){return this.value}}const s=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function n(n,r,...o){if(n===e)return new t(o.flat(1/0).map(i).join(""));if("function"==typeof n){const e=n({...r||{},children:o});return e instanceof t?e:new t(null==e?"":String(e))}const h=[];if(r)for(const[e,t]of Object.entries(r)){if("children"===e||null==t||!1===t||"dangerouslySetInnerHTML"===e)continue;let s=e;if("className"===e?s="class":"htmlFor"===e?s="for":e.startsWith("on")&&e.length>2&&(s=e.toLowerCase()),"style"===e&&"object"==typeof t){const e=Object.entries(t).map(([e,t])=>`${c(e)}:${a(String(t))}`).join(";");h.push(`style="${e}"`)}else!0===t?h.push(s):h.push(`${s}="${a(String(t))}"`)}let u;u=r&&r.dangerouslySetInnerHTML&&null!=r.dangerouslySetInnerHTML.__html?String(r.dangerouslySetInnerHTML.__html):o.flat(1/0).map(i).join("");const l=h.length?" "+h.join(" "):"";return s.has(n)?new t(`<${n}${l} />`):new t(`<${n}${l}>${u}</${n}>`)}const r=n,o=n;function i(e){return null==e||!1===e||!0===e?"":e instanceof t?e.value:Array.isArray(e)?e.flat(1/0).map(i).join(""):String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function a(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function c(e){return e.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}const h=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;class u{constructor(){this.routes=[],this.cors=["*"],this.headers={}}add(e,t,s,n){"function"==typeof s&&(n=s,s={});const r=[],o=t.replace(/:([A-Za-z0-9_]+)/g,(e,t)=>(r.push(t),"([^/]+)")),i=new RegExp(`^${o}$`);this.routes.push({method:e,regex:i,keys:r,config:s||{},handler:n})}get(e,t,s){this.add("GET",e,t,s)}post(e,t,s){this.add("POST",e,t,s)}put(e,t,s){this.add("PUT",e,t,s)}delete(e,t,s){this.add("DELETE",e,t,s)}options(e,t,s){this.add("OPTIONS",e,t,s)}async fetch(e,t,s){const n=new URL(e.url),r=e.headers.get("Origin")||"",o=this.corsHeaders(r);if("OPTIONS"===e.method)return new Response(null,{status:204,headers:o});for(const r of this.routes){if(r.method!==e.method)continue;const i=r.regex.exec(n.pathname);if(!i)continue;const a={};r.keys.forEach((e,t)=>{a[e]=decodeURIComponent(i[t+1])});const c=new l(e,t,s,a,this);if(r.config.valid&&!await this.validCsrf(c))return this.withHeaders(c.text("Invalid CSRF",403),o,c);if(r.config.auth&&!this.auth(c))return this.withHeaders(c.text("Unauthorized",401),o,c);try{const e=await r.handler(c),t=e instanceof Response?e:c.text(null==e?"":String(e));return this.withHeaders(t,o,c)}catch(e){return this.withHeaders(c.text(e.message||"Internal Error",500),o,c)}}return this.withHeaders(new Response("Not Found",{status:404}),o)}corsHeaders(e){const t={};return!this.cors||this.cors.includes("*")?t["Access-Control-Allow-Origin"]="*":e&&this.cors.some(t=>function(e,t){try{const s=new URL(e).host;if(t===s)return!0;if(t.startsWith("*.")){const e=t.slice(2);return s===e||s.endsWith("."+e)}return!1}catch{return!1}}(e,t))&&(t["Access-Control-Allow-Origin"]=e,t.Vary="Origin"),t["Access-Control-Allow-Methods"]="GET,POST,PUT,DELETE,OPTIONS",t["Access-Control-Allow-Headers"]="Content-Type, X-CSRF-Token, X-DeviceId",t}withHeaders(e,t={},s=null){const n=function(e){const t=new Headers,s="function"==typeof e.getSetCookie?e.getSetCookie():[];let n=null;for(const[s,r]of e)"set-cookie"!==s.toLowerCase()?t.set(s,r):n=r;if(s.length)for(const e of s)t.append("Set-Cookie",e);else n&&t.append("Set-Cookie",n);return t}(e.headers);for(const[e,t]of Object.entries(this.headers))n.set(e,t);for(const[e,s]of Object.entries(t))n.set(e,s);if(s&&s._setCookies.length)for(const e of s._setCookies)n.append("Set-Cookie",e);const r=101===e.status||204===e.status||205===e.status||304===e.status;return new Response(r?null:e.body,{status:e.status,statusText:e.statusText,headers:n})}async validCsrf(e){const t=e.req.cookie("_csrf"),s=e.req.header("x-csrf-token");return!(!t||!s||t!==s)}auth(e){return!!e.req.cookie("_auth")}}class l{constructor(e,t,s,n,r){this.req=new p(e,n),this.env=t,this.ctx=s,this.app=r,this._setCookies=[]}get cookies(){return this.req.cookies}getCookie(e){return this.req.cookie(e)}setCookie(e,t,s={}){this._setCookies.push(function(e,t,s={}){if(!h.test(e))throw new TypeError(`Invalid cookie name: ${JSON.stringify(e)}`);const n=[`${e}=${encodeURIComponent(null==t?"":String(t))}`];if(null!=s.maxAge&&n.push(`Max-Age=${Math.floor(Number(s.maxAge))}`),s.domain&&n.push(`Domain=${s.domain}`),s.path&&n.push(`Path=${s.path}`),null!=s.expires){const e=s.expires instanceof Date?s.expires:new Date(s.expires);n.push(`Expires=${e.toUTCString()}`)}if(s.httpOnly&&n.push("HttpOnly"),s.secure&&n.push("Secure"),s.sameSite){const e=!0===s.sameSite?"strict":String(s.sameSite);n.push(`SameSite=${e.charAt(0).toUpperCase()}${e.slice(1).toLowerCase()}`)}return s.partitioned&&n.push("Partitioned"),n.join("; ")}(e,t,s))}deleteCookie(e,t={}){this.setCookie(e,"",{...t,maxAge:0,expires:new Date(0)})}redirect(e,t=302){return Response.redirect(new URL(e,this.req.url),t)}text(e,t=200,s={}){return new Response(String(e),{status:t,headers:{"Content-Type":"text/plain; charset=utf-8",...s}})}json(e,t=200,s={}){const n="string"==typeof e?e:JSON.stringify(e);return new Response(n,{status:t,headers:{"Content-Type":"application/json; charset=utf-8",...s}})}html(e,t=200,s={}){return new Response(String(e),{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...s}})}page(e,t=200,s={}){const n=String(e),r=n.startsWith("<!DOCTYPE html>")?n:"<!DOCTYPE html>"+n;return new Response(r,{status:t,headers:{"Content-Type":"text/html; charset=utf-8",...s}})}}class p{constructor(e,t){this.raw=e,this.url=e.url,this.method=e.method,this.params=t,this._url=new URL(e.url),this._cookies=null}param(e){return this.params[e]}query(e){return this._url.searchParams.get(e)}header(e){return this.raw.headers.get(e)}get cookies(){return this._cookies||(this._cookies=function(e){const t=Object.create(null);if(!e)return t;for(const s of e.split(";")){const e=s.indexOf("=");if(e<0)continue;const n=s.slice(0,e).trim();if(!n||"__proto__"===n||n in t)continue;const r=s.slice(e+1).trim();try{t[n]=decodeURIComponent(r)}catch{t[n]=r}}return t}(this.raw.headers.get("Cookie"))),this._cookies}cookie(e){return this.cookies[e]}json(){return this.raw.json()}text(){return this.raw.text()}formData(){return this.raw.formData()}}export{u as Edge,e as Fragment,t as Html,n as jsx,o as jsxDEV,r as jsxs};
|
|
29
|
+
function e(e){const t=[],s=e.length;let n=1;for(let r=1;r<=s;r++)(r===s||47===e.charCodeAt(r))&&(r>n&&t.push(e.slice(n,r)),n=r+1);return t}function t(e){const t=e.length;return t>1&&47===e.charCodeAt(t-1)?e.slice(0,-1):e}const s=new Set(["__proto__","constructor","prototype"]);function n(e){return"string"==typeof e&&!s.has(e)}function r(e){const t=e.length;let s=0;for(;s<t;){const t=e.charCodeAt(s);if(38===t||60===t||62===t||34===t||39===t)break;s++}if(s===t)return e;let n=e.slice(0,s),r=s;for(;s<t;s++){const t=e.charCodeAt(s);let o;if(38===t)o="&";else if(60===t)o="<";else if(62===t)o=">";else if(34===t)o=""";else{if(39!==t)continue;o="'"}s>r&&(n+=e.slice(r,s)),n+=o,r=s+1}return r<t&&(n+=e.slice(r)),n}function o(e){return e>=65&&e<=90||e>=97&&e<=122}function i(e){return e>=48&&e<=57}function a(e){const t=e.length;if(0===t)return!1;const s=e.charCodeAt(0);if(!o(s)&&95!==s&&58!==s)return!1;for(let s=1;s<t;s++){const t=e.charCodeAt(s);if(!o(t)&&!i(t)&&95!==t&&58!==t&&46!==t&&45!==t)return!1}return!0}function c(e){const t=e.charCodeAt(0),s=e.charCodeAt(1);return!(111!==t&&79!==t||110!==s&&78!==s)}const l=Symbol("Fragment");function h(e,t,...s){return{type:e,props:t||{},children:s,__isJSX:!0}}const u=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),d=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),f=new Set(["animation-iteration-count","border-image-outset","border-image-slice","border-image-width","box-flex","box-flex-group","box-ordinal-group","column-count","columns","flex","flex-grow","flex-positive","flex-shrink","flex-negative","flex-order","grid-row","grid-row-end","grid-row-span","grid-row-start","grid-column","grid-column-end","grid-column-span","grid-column-start","font-weight","line-clamp","line-height","opacity","order","orphans","tab-size","widows","z-index","zoom","fill-opacity","flood-opacity","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-miterlimit","stroke-opacity","stroke-width"]),p=new Map;function g(e){const t=p.get(e);if(void 0!==t)return t;const s=e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"");return p.size>=2e3&&p.clear(),p.set(e,s),s}function y(e){if(!e||"object"!=typeof e)return"";let t="";for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;const n=g(s);let r=e[s];"number"==typeof r&&!f.has(n)&&(r+="px"),t&&(t+=";"),t+=n+":"+r}return t}const m=new Set(["href","src","xlink:href","action","formaction"]),w=[];function C(){const e=w[w.length-1];if(!e)throw new Error("useCtx() must be called synchronously at the top of a component (before any await). It is not available after an await, nor outside a render.");return e}async function _(e,t){if(void 0===t&&(t=w[w.length-1]),null==e||"boolean"==typeof e)return"";const s=typeof e;if("string"===s)return r(e);if("number"===s)return r(String(e));if("object"===s&&"function"==typeof e.then)return _(await e,t);if(Array.isArray(e)){let s="";for(let n=0;n<e.length;n++)s+=await _(e[n],t);return s}if(!e.__isJSX)return r(String(e));const{type:h,props:f,children:p}=e;if(h===l){let e="";for(let s=0;s<p.length;s++)e+=await _(p[s],t);return e}if("symbol"==typeof h)return"";if("function"==typeof h){let e;if(t){w.push(t);try{e=h({...f,children:p})}finally{w.pop()}}else e=h({...f,children:p});return _(await e,t)}if("string"!=typeof h||!function(e){const t=e.length;if(0===t||!o(e.charCodeAt(0)))return!1;for(let s=1;s<t;s++){const t=e.charCodeAt(s);if(!o(t)&&!i(t)&&45!==t)return!1}return!0}(h))return"";const g=u.has(h);let C="";for(const e in f){if(!Object.prototype.hasOwnProperty.call(f,e)||"children"===e||"key"===e||"ref"===e)continue;const t=f[e];if(null==t||!1===t||"dangerouslySetInnerHTML"===e)continue;let s=e;if("className"===e||"class"===e?s="class":("htmlFor"===e||"for"===e)&&(s="for"),n(s)&&!c(s)&&a(s)){if(m.has(s)){const e=String(t).replace(/[\u0000-\u0020]/g,"").toLowerCase();if(e.startsWith("javascript:")||e.startsWith("vbscript:")||e.startsWith("data:text/html"))continue}if(d.has(s)){!0===t&&(C+=" "+s);continue}if(!0===t){C+=" "+s+'="true"';continue}if("style"===s&&"object"==typeof t){const e=y(t);e&&(C+=' style="'+r(e)+'"');continue}C+=" "+s+'="'+r(String(t))+'"'}}let x="";const A=f.dangerouslySetInnerHTML;if(A&&null!=A.__html)x=A.__html;else for(let e=0;e<p.length;e++)x+=await _(p[e],t);return g?"<"+h+C+"/>":"<"+h+C+">"+x+"</"+h+">"}const x=Object.freeze([["X-Content-Type-Options","nosniff"],["X-Frame-Options","DENY"],["Referrer-Policy","strict-origin-when-cross-origin"],["Permissions-Policy","geolocation=(), microphone=(), camera=()"]]),A=Object.freeze(Object.create(null));class T{constructor(e,t,s,n={},r=null){this.req=e,this.env=t,this.executionCtx=s,this.params=n,this.status=200,this.headers=new Headers(x),this._cookies=null,this.url=r||new URL(e.url)}_ensureCookies(){if(null!==this._cookies)return this._cookies;const e=this.req.headers.get("Cookie");if(!e)return this._cookies=A,A;const t=Object.create(null);let s=0;const r=e.length;for(;s<r;){let o=e.indexOf(";",s);-1===o&&(o=r);let i=s,a=o;for(;i<a&&32===e.charCodeAt(i);)i++;for(;a>i&&32===e.charCodeAt(a-1);)a--;if(a>i){const s=e.indexOf("=",i);if(s>i&&s<a)try{const r=decodeURIComponent(e.slice(i,s));n(r)&&(t[r]=decodeURIComponent(e.slice(s+1,a)))}catch{}}s=o+1}return this._cookies=t,t}getCookie(e){const t=this._ensureCookies()[e];return void 0===t?null:t}get query(){return this.url.searchParams}setCookie(e,t,s={}){if("string"!=typeof e||!n(e)||/[\r\n;=]/.test(e))return;let r=encodeURIComponent(e)+"="+encodeURIComponent(t);s.path&&(r+="; Path="+s.path),s.domain&&(r+="; Domain="+s.domain),void 0!==s.maxAge&&(r+="; Max-Age="+s.maxAge),s.expires&&(r+="; Expires="+s.expires.toUTCString()),s.secure&&(r+="; Secure"),s.httpOnly&&(r+="; HttpOnly"),s.sameSite&&(r+="; SameSite="+s.sameSite),this.headers.append("Set-Cookie",r)}deleteCookie(e,t={}){this.setCookie(e,"",{...t,maxAge:0,expires:new Date(0)})}_buildHeaders(e){if(!e)return this.headers;const t=Object.keys(e);if(0===t.length)return this.headers;const s=new Headers(this.headers);for(let n=0;n<t.length;n++)s.set(t[n],e[t[n]]);return s}text(e,t=this.status,s={}){const n=this._buildHeaders(s);return n.has("Content-Type")||n.set("Content-Type","text/plain; charset=utf-8"),new Response(e,{status:t,headers:n})}json(e,t=this.status,s={}){const n=this._buildHeaders(s);return n.has("Content-Type")||n.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),{status:t,headers:n})}async html(e,t=this.status,s={}){const n=this._buildHeaders(s);let r;return n.has("Content-Type")||n.set("Content-Type","text/html; charset=utf-8"),r="string"==typeof e?e:e&&e.__isJSX||Array.isArray(e)?await _(e,this):null==e?"":String(e),new Response(r,{status:t,headers:n})}async page(e,t=this.status,s={}){const n=this._buildHeaders(s);let r;return n.has("Content-Type")||n.set("Content-Type","text/html; charset=utf-8"),r="string"==typeof e?e:e&&e.__isJSX||Array.isArray(e)?await _(e,this):null==e?"":String(e),/^\s*<!doctype\s/i.test(r)||(r="<!DOCTYPE html>"+r),new Response(r,{status:t,headers:n})}redirect(e,t=302){const s=new Headers(this.headers);return s.set("Location",String(e)),s.delete("Content-Type"),new Response(null,{status:t,headers:s})}}class S{constructor(){this.children=null,this.paramChild=null,this.handler=null}}class b{constructor(){this.root=new S}add(e,t,s){let r=this.root;const o=[];for(let t=0;t<e.length;t++){const s=e[t];if(58===s.charCodeAt(0)){const e=s.slice(1);o.push(n(e)?e:"_p"+t),r.paramChild||(r.paramChild=new S),r=r.paramChild}else{r.children||(r.children=new Map);let e=r.children.get(s);e||(e=new S,r.children.set(s,e)),r=e}}r.handler={handler:t,options:s,paramNames:o}}match(e){const t=[],s=this._walk(this.root,e,0,t);if(!s)return null;const{handler:n,options:r,paramNames:o}=s,i=Object.create(null);for(let e=0;e<o.length;e++)i[o[e]]=t[e];return{handler:n,options:r,params:i}}_walk(e,t,s,n){if(s===t.length)return e.handler;const r=t[s],o=e.children;if(o){const e=o.get(r);if(e){const r=this._walk(e,t,s+1,n);if(r)return r}}const i=e.paramChild;if(i){n.push(r);const e=this._walk(i,t,s+1,n);if(e)return e;n.pop()}return null}}const O=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"],E=["text/","application/json","application/xml","application/javascript","application/xhtml","application/ld+json","application/manifest+json","image/svg"],k=new Map;let R=0;class v{constructor(){this.staticRoutes=new Map;for(let e=0;e<O.length;e++)this.staticRoutes.set(O[e],new Map);this.dynamicTries={};for(let e=0;e<O.length;e++)this.dynamicTries[O[e]]=new b;this.defaults={cors:{origin:"*",methods:"GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD"}},this.scheduledHandler=null,this.security={logSecurityEvents:!0,extraHeaders:null,trustedProxies:null}}_addRoute(s,n,r,o){if("boolean"==typeof r?r={}:"function"==typeof r&&(o=r,r={}),"function"!=typeof o)throw new Error("Handler for "+s+" "+n+" must be a function");const i={...this.defaults,...r||{}};-1===n.indexOf(":")?this.staticRoutes.get(s).set(t(n),{handler:o,options:i}):this.dynamicTries[s].add(e(n),o,i)}get(e,t,s){this._addRoute("GET",e,t,s)}post(e,t,s){this._addRoute("POST",e,t,s)}put(e,t,s){this._addRoute("PUT",e,t,s)}delete(e,t,s){this._addRoute("DELETE",e,t,s)}patch(e,t,s){this._addRoute("PATCH",e,t,s)}options(e,t,s){this._addRoute("OPTIONS",e,t,s)}head(e,t,s){this._addRoute("HEAD",e,t,s)}scheduled(e){this.scheduledHandler=e}_logSecurityEvent(e,t,s){if(this.security.logSecurityEvents)try{const n=e.req.headers.get("CF-Connecting-IP")||"",r=e.url?e.url.pathname:"";if(!function(e,t,s){const n=e+"|"+(t||"")+"|"+(s||""),r=Date.now(),o=k.get(n);if(o&&r-o<6e4)return!1;if(k.set(n,r),r-R>3e4){R=r;for(const[e,t]of k)r-t>6e4&&k.delete(e)}return!0}(t,n,r))return;console.log(JSON.stringify({ts:(new Date).toISOString(),kind:"security",event:t,detail:"string"==typeof s?s:void 0,ip:n||void 0,method:e.req.method,path:r,ua:e.req.headers.get("User-Agent")||void 0}))}catch{}}_processCors(e,t){if(!t)return;const s="object"==typeof t?t:this.defaults.cors,n=e.req.headers.get("Origin"),r=s.origin;"*"===r?e.headers.set("Access-Control-Allow-Origin","*"):Array.isArray(r)?n&&-1!==r.indexOf(n)&&(e.headers.set("Access-Control-Allow-Origin",n),e.headers.set("Vary","Origin"),e.headers.set("Access-Control-Allow-Credentials","true")):"string"==typeof r&&n===r&&(e.headers.set("Access-Control-Allow-Origin",n),e.headers.set("Vary","Origin"),e.headers.set("Access-Control-Allow-Credentials","true")),e.headers.set("Access-Control-Allow-Methods",s.methods||"GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD"),e.headers.set("Access-Control-Allow-Headers",s.headers||"Content-Type, Authorization, X-CSRF-Token"),e.headers.set("Access-Control-Max-Age","86400")}_processLog(e,t){t&&console.log(e.req.method+" "+e.req.url+" - "+e.status)}_processCompress(e,t){if(!function(e){if(!e)return!0;const t=e.toLowerCase();for(let e=0;e<E.length;e++)if(t.startsWith(E[e]))return!0;return!1}(t.headers.get("Content-Type")))return t;const s=t.headers.get("Content-Length");if(null!==s&&+s<1024)return t;const n=e.headers.get("Accept-Encoding")||"";let r=null;if(-1!==n.indexOf("gzip")?r="gzip":-1!==n.indexOf("deflate")&&(r="deflate"),!r||!t.body)return t;const o=t.body.pipeThrough(new CompressionStream(r)),i=new Headers(t.headers);return i.set("Content-Encoding",r),i.set("Vary","Accept-Encoding"),i.delete("Content-Length"),new Response(o,{status:t.status,statusText:t.statusText,headers:i})}async _validate(e,t){return!t||"function"!=typeof t||!!await t(e)}async _cacheGet(e){return await caches.default.match(e)||null}async _cachePut(e,t,s){if(!s)return;const n=!0===s?{}:s,r=n.ttl??3600,o=n.staleWhileRevalidate??0,i=new Headers(t.headers);i.set("Cache-Control","max-age="+r+(o>0?", stale-while-revalidate="+o:"")),i.delete("Set-Cookie"),await caches.default.put(e,new Response(t.body,{status:t.status,statusText:t.statusText,headers:i}))}async fetch(s,n,r){const o=new URL(s.url),i=t(o.pathname),a=s.method,c=this.staticRoutes.get(a);if(c){const e=c.get(i);if(e)return this._handleRoute(e.handler,e.options,s,n,r,Object.create(null),o)}const l=this.dynamicTries[a];if(l){const t=l.match(e(i));if(t)return this._handleRoute(t.handler,t.options,s,n,r,t.params,o)}return new Response("Not Found",{status:404})}async _handleRoute(e,t,s,n,r,o,i){const a=new T(s,n,r,o,i),c=this.security.extraHeaders;if(c)for(const e in c)Object.prototype.hasOwnProperty.call(c,e)&&a.headers.set(e,c[e]);let l,h=!1;try{h=await this._validate(a,t.validate)}catch(e){this._logSecurityEvent(a,"validation_error",e&&e.message),h=!1}if(!h)return a.text("Validation failed",400);if(t.cache&&"GET"===s.method){const e=await this._cacheGet(s);if(e)return this._processCors(a,t.cors),this._processLog(a,t.log),e}this._processCors(a,t.cors);try{const t=await e(a);l=t instanceof Response?t:t&&t.__isJSX?await a.html(t):a.text("OK")}catch(e){this._logSecurityEvent(a,"handler_error",e&&e.message),l=a.text("Internal Server Error",500)}return t.cache&&"GET"===s.method&&200===l.status&&a.executionCtx.waitUntil(this._cachePut(s,l.clone(),t.cache)),t.compress&&(l=this._processCompress(s,l)),this._processLog(a,t.log),l}}export{T as Context,v as Edge,l as Fragment,h as jsx,_ as renderToString,C as useCtx};
|