diesel-core 1.6.9 → 1.7.0
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/dist/ctx.d.ts +6 -6
- package/dist/ctx.js +39 -222
- package/dist/handleRequest.d.ts +2 -2
- package/dist/handleRequest.js +5 -6
- package/dist/main.d.ts +1 -1
- package/dist/main.js +12 -4
- package/dist/middlewares/cors/index.test.js +42 -42
- package/dist/middlewares/filesave/index.test.js +1 -1
- package/dist/middlewares/filesave/savefile.js +1 -1
- package/dist/middlewares/jwt/index.js +1 -1
- package/dist/middlewares/powered-by/index.js +1 -1
- package/dist/src/constant.js +1 -0
- package/dist/src/ctx.js +54 -0
- package/dist/src/handleRequest.js +54 -0
- package/dist/src/http-exception.js +1 -0
- package/dist/src/main.js +266 -0
- package/dist/src/request_pipeline.js +163 -0
- package/dist/src/router/find-my-way.js +102 -0
- package/dist/src/router/interface.js +102 -0
- package/dist/src/router/trie.js +1 -0
- package/dist/types.d.ts +6 -6
- package/dist/utils/jwt.js +1 -1
- package/dist/utils/request.util.d.ts +5 -4
- package/dist/utils/request.util.js +1 -1
- package/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/ctx.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server } from "bun";
|
|
2
|
-
import type {
|
|
3
|
-
export declare class Context
|
|
2
|
+
import type { CookieOptions } from "./types";
|
|
3
|
+
export declare class Context {
|
|
4
4
|
req: Request;
|
|
5
5
|
server?: Server | undefined;
|
|
6
6
|
path?: string | undefined;
|
|
@@ -25,10 +25,10 @@ export declare class Context implements ContextType {
|
|
|
25
25
|
get query(): Record<string, string>;
|
|
26
26
|
get params(): Record<string, string>;
|
|
27
27
|
get body(): Promise<any>;
|
|
28
|
-
text(data: string, status?: number): Response;
|
|
29
|
-
send<T>(data: T, status?: number): Response;
|
|
30
|
-
json<T>(object: T, status?: number): Response;
|
|
31
|
-
file(filePath: string,
|
|
28
|
+
text(data: string, status?: number, customHeaders?: HeadersInit): Response;
|
|
29
|
+
send<T>(data: T, status?: number, customHeaders?: HeadersInit): Response;
|
|
30
|
+
json<T>(object: T, status?: number, customHeaders?: HeadersInit): Response;
|
|
31
|
+
file(filePath: string, mimeType?: string, status?: number, customHeaders?: HeadersInit): Response;
|
|
32
32
|
ejs(viewPath: string, data?: {}, status?: number): Promise<Response>;
|
|
33
33
|
redirect(path: string, status?: number): Response;
|
|
34
34
|
setCookie(name: string, value: string, options?: CookieOptions): this;
|
package/dist/ctx.js
CHANGED
|
@@ -94,6 +94,7 @@ export class Context {
|
|
|
94
94
|
}
|
|
95
95
|
get body() {
|
|
96
96
|
if (this.req.method === "GET") {
|
|
97
|
+
console.error(`you are trying to access body in GET method ${this.path}`);
|
|
97
98
|
return Promise.resolve({});
|
|
98
99
|
}
|
|
99
100
|
if (!this.parsedBody) {
|
|
@@ -114,47 +115,60 @@ export class Context {
|
|
|
114
115
|
}
|
|
115
116
|
return this.parsedBody;
|
|
116
117
|
}
|
|
117
|
-
text(data, status = 200) {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
118
|
+
text(data, status = 200, customHeaders) {
|
|
119
|
+
if (customHeaders) {
|
|
120
|
+
for (const [key, value] of Object.entries(customHeaders)) {
|
|
121
|
+
this.headers.set(key, value);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (!this.headers.has("Content-Type")) {
|
|
125
|
+
this.headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
126
|
+
}
|
|
127
|
+
return new Response(data, { status, headers: this.headers });
|
|
125
128
|
}
|
|
126
|
-
send(data, status = 200) {
|
|
127
|
-
// this.status = status;
|
|
129
|
+
send(data, status = 200, customHeaders) {
|
|
128
130
|
var _a;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
131
|
+
if (customHeaders) {
|
|
132
|
+
for (const [key, value] of Object.entries(customHeaders)) {
|
|
133
|
+
this.headers.set(key, value);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
132
136
|
let dataType;
|
|
133
137
|
if (data instanceof Uint8Array)
|
|
134
138
|
dataType = "Uint8Array";
|
|
135
139
|
else if (data instanceof ArrayBuffer)
|
|
136
|
-
dataType =
|
|
140
|
+
dataType = "ArrayBuffer";
|
|
137
141
|
else
|
|
138
142
|
dataType = typeof data;
|
|
139
143
|
if (!this.headers.has("Content-Type")) {
|
|
140
144
|
this.headers.set("Content-Type", (_a = typeMap[dataType]) !== null && _a !== void 0 ? _a : "text/plain; charset=utf-8");
|
|
141
145
|
}
|
|
142
|
-
const responseData = dataType === "object" && data !== null
|
|
146
|
+
const responseData = dataType === "object" && data !== null
|
|
147
|
+
? JSON.stringify(data)
|
|
148
|
+
: data;
|
|
143
149
|
return new Response(responseData, { status, headers: this.headers });
|
|
144
150
|
}
|
|
145
|
-
json(object, status = 200) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
+
json(object, status = 200, customHeaders) {
|
|
152
|
+
if (customHeaders) {
|
|
153
|
+
for (const [key, value] of Object.entries(customHeaders)) {
|
|
154
|
+
this.headers.set(key, value);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (!this.headers.has("Content-Type")) {
|
|
158
|
+
this.headers.set("Content-Type", "application/json; charset=utf-8");
|
|
159
|
+
}
|
|
160
|
+
return new Response(JSON.stringify(object), { status, headers: this.headers });
|
|
151
161
|
}
|
|
152
|
-
file(filePath,
|
|
153
|
-
|
|
154
|
-
|
|
162
|
+
file(filePath, mimeType, status = 200, customHeaders) {
|
|
163
|
+
if (customHeaders) {
|
|
164
|
+
for (const [key, value] of Object.entries(customHeaders)) {
|
|
165
|
+
this.headers.set(key, value);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
155
168
|
if (!this.headers.has("Content-Type")) {
|
|
156
|
-
this.headers.set("Content-Type",
|
|
169
|
+
this.headers.set("Content-Type", mimeType !== null && mimeType !== void 0 ? mimeType : getMimeType(filePath));
|
|
157
170
|
}
|
|
171
|
+
const file = Bun.file(filePath);
|
|
158
172
|
return new Response(file, { status, headers: this.headers });
|
|
159
173
|
}
|
|
160
174
|
ejs(viewPath_1) {
|
|
@@ -174,7 +188,6 @@ export class Context {
|
|
|
174
188
|
});
|
|
175
189
|
}
|
|
176
190
|
redirect(path, status = 302) {
|
|
177
|
-
// this.status = status
|
|
178
191
|
this.headers.set("Location", path);
|
|
179
192
|
return new Response(null, { status, headers: this.headers });
|
|
180
193
|
}
|
|
@@ -311,199 +324,3 @@ function parseBody(req) {
|
|
|
311
324
|
return { error: "Unknown request body type" };
|
|
312
325
|
});
|
|
313
326
|
}
|
|
314
|
-
// Deprecated
|
|
315
|
-
// export default function createCtx(
|
|
316
|
-
// req: Request,
|
|
317
|
-
// server: Server,
|
|
318
|
-
// pathname: string,
|
|
319
|
-
// // onn: (event: string | symbol, listener: EventListener) => void,
|
|
320
|
-
// // emitter: (event: string | symbol, ...args: any) => void,
|
|
321
|
-
// routePattern: string | undefined
|
|
322
|
-
// ): ContextType {
|
|
323
|
-
// let parsedQuery: Record<string, string> | null = null;
|
|
324
|
-
// let parsedParams: Record<string, string> | null = null;
|
|
325
|
-
// let parsedCookies: Record<string, string> | null = null;
|
|
326
|
-
// let parsedBody: Promise<any> | null = null;
|
|
327
|
-
// let contextData: Record<string, any> = {};
|
|
328
|
-
// let urlObject: URL | null = null
|
|
329
|
-
// return {
|
|
330
|
-
// req,
|
|
331
|
-
// server,
|
|
332
|
-
// pathname,
|
|
333
|
-
// // status: 200,
|
|
334
|
-
// headers: new Headers(),
|
|
335
|
-
// // on(event: string | symbol, listener: EventListener) {
|
|
336
|
-
// // onn(event, listener)
|
|
337
|
-
// // },
|
|
338
|
-
// // emit(event: string | symbol, ...args: any) {
|
|
339
|
-
// // emitter(event, ...args)
|
|
340
|
-
// // },
|
|
341
|
-
// setHeader(key: string, value: string): ContextType {
|
|
342
|
-
// this.headers.set(key, value);
|
|
343
|
-
// return this;
|
|
344
|
-
// },
|
|
345
|
-
// removeHeader(key: string): ContextType {
|
|
346
|
-
// this.headers.delete(key)
|
|
347
|
-
// return this
|
|
348
|
-
// },
|
|
349
|
-
// set<T>(key: string, value: T): ContextType {
|
|
350
|
-
// contextData[key] = value;
|
|
351
|
-
// return this;
|
|
352
|
-
// },
|
|
353
|
-
// get<T>(key: string): T | undefined {
|
|
354
|
-
// return contextData[key];
|
|
355
|
-
// },
|
|
356
|
-
// get ip(): string | null {
|
|
357
|
-
// return this.server.requestIP(req)?.address ?? null;
|
|
358
|
-
// },
|
|
359
|
-
// get url(): URL {
|
|
360
|
-
// if (!urlObject) {
|
|
361
|
-
// urlObject = new URL(req.url)
|
|
362
|
-
// }
|
|
363
|
-
// return urlObject
|
|
364
|
-
// },
|
|
365
|
-
// get query(): Record<string, string> {
|
|
366
|
-
// if (!parsedQuery) {
|
|
367
|
-
// if (!this.url.search) return {};
|
|
368
|
-
// parsedQuery = Object.fromEntries(this.url.searchParams);
|
|
369
|
-
// }
|
|
370
|
-
// return parsedQuery;
|
|
371
|
-
// },
|
|
372
|
-
// get params(): Record<string, string> {
|
|
373
|
-
// if (!parsedParams && routePattern) {
|
|
374
|
-
// try {
|
|
375
|
-
// parsedParams = extractDynamicParams(routePattern, pathname);
|
|
376
|
-
// } catch (error) {
|
|
377
|
-
// const message = error instanceof Error ? error.message : String(error)
|
|
378
|
-
// throw new Error(`Failed to extract route parameters: ${message}`);
|
|
379
|
-
// }
|
|
380
|
-
// }
|
|
381
|
-
// return parsedParams ?? {};
|
|
382
|
-
// },
|
|
383
|
-
// get body(): Promise<any> {
|
|
384
|
-
// if (req.method === "GET") {
|
|
385
|
-
// return Promise.resolve({});
|
|
386
|
-
// }
|
|
387
|
-
// if (!parsedBody) {
|
|
388
|
-
// parsedBody = (async () => {
|
|
389
|
-
// try {
|
|
390
|
-
// const result = await parseBody(req);
|
|
391
|
-
// if (result.error) {
|
|
392
|
-
// throw new Error(result.error);
|
|
393
|
-
// }
|
|
394
|
-
// return Object.keys(result).length === 0 ? null : result;
|
|
395
|
-
// } catch (error) {
|
|
396
|
-
// throw new Error("Invalid request body format");
|
|
397
|
-
// // const message = error instanceof Error ? error.message : String(error);
|
|
398
|
-
// // throw new Error(`Failed to parse request body: ${message}`);
|
|
399
|
-
// }
|
|
400
|
-
// })();
|
|
401
|
-
// }
|
|
402
|
-
// return parsedBody;
|
|
403
|
-
// },
|
|
404
|
-
// text(data: string, status: number = 200) {
|
|
405
|
-
// return new Response(data, {
|
|
406
|
-
// status,
|
|
407
|
-
// headers: this.headers
|
|
408
|
-
// });
|
|
409
|
-
// },
|
|
410
|
-
// send<T>(data: T, status: number = 200): Response {
|
|
411
|
-
// // this.status = status;
|
|
412
|
-
// // const dataType = data instanceof Uint8Array ? "Uint8Array"
|
|
413
|
-
// // : data instanceof ArrayBuffer ? "ArrayBuffer"
|
|
414
|
-
// // : typeof data;
|
|
415
|
-
// let dataType: string
|
|
416
|
-
// if (data instanceof Uint8Array) dataType = "Uint8Array"
|
|
417
|
-
// else if (data instanceof ArrayBuffer) dataType = 'ArrayBuffer'
|
|
418
|
-
// else dataType = typeof data
|
|
419
|
-
// // if (!this.headers.has("Content-Type")) {
|
|
420
|
-
// // this.headers.set("Content-Type", typeMap[dataType] ?? "text/plain; charset=utf-8");
|
|
421
|
-
// // }
|
|
422
|
-
// const responseData =
|
|
423
|
-
// dataType === "object" && data !== null ? JSON.stringify(data) : (data as any);
|
|
424
|
-
// return new Response(responseData, { status, headers: this.headers });
|
|
425
|
-
// },
|
|
426
|
-
// json<T>(object: T, status: number = 200): Response {
|
|
427
|
-
// // this.status = status;
|
|
428
|
-
// // if (!this.headers.has("Content-Type")) {
|
|
429
|
-
// // this.headers.set("Content-Type", "application/json; charset=utf-8");
|
|
430
|
-
// // }
|
|
431
|
-
// return Response.json(object, { status, headers: this.headers })
|
|
432
|
-
// },
|
|
433
|
-
// file(filePath: string, mime_Type?: string, status: number = 200): Response {
|
|
434
|
-
// // this.status = status;
|
|
435
|
-
// const file = Bun.file(filePath);
|
|
436
|
-
// if (!this.headers.has("Content-Type")) {
|
|
437
|
-
// this.headers.set("Content-Type", mime_Type ?? getMimeType(filePath));
|
|
438
|
-
// }
|
|
439
|
-
// return new Response(file, { status, headers: this.headers });
|
|
440
|
-
// },
|
|
441
|
-
// async ejs(viewPath: string, data = {}, status: number = 200): Promise<Response> {
|
|
442
|
-
// // this.status = status;
|
|
443
|
-
// const ejs = await getEjs();
|
|
444
|
-
// try {
|
|
445
|
-
// const template = await Bun.file(viewPath).text()
|
|
446
|
-
// const rendered = ejs.render(template, data)
|
|
447
|
-
// const headers = new Headers({ "Content-Type": "text/html; charset=utf-8" });
|
|
448
|
-
// return new Response(rendered, { status, headers });
|
|
449
|
-
// } catch (error) {
|
|
450
|
-
// console.error("EJS Rendering Error:", error);
|
|
451
|
-
// return new Response("Error rendering template", { status: 500 });
|
|
452
|
-
// }
|
|
453
|
-
// },
|
|
454
|
-
// redirect(path: string, status: number = 302): Response {
|
|
455
|
-
// // this.status = status
|
|
456
|
-
// this.headers.set("Location", path);
|
|
457
|
-
// return new Response(null, { status, headers: this.headers });
|
|
458
|
-
// },
|
|
459
|
-
// stream(callback: (controller: ReadableStreamDefaultController) => void) {
|
|
460
|
-
// const headers = new Headers(this.headers)
|
|
461
|
-
// const stream = new ReadableStream({
|
|
462
|
-
// async start(controller) {
|
|
463
|
-
// await callback(controller);
|
|
464
|
-
// controller.close();
|
|
465
|
-
// },
|
|
466
|
-
// });
|
|
467
|
-
// return new Response(stream, {
|
|
468
|
-
// headers
|
|
469
|
-
// });
|
|
470
|
-
// },
|
|
471
|
-
// yieldStream(callback: () => AsyncIterable<any>): Response {
|
|
472
|
-
// return new Response("not working stream yet.")
|
|
473
|
-
// // return new Response(
|
|
474
|
-
// // {
|
|
475
|
-
// // async *[Symbol.asyncIterator ]() {
|
|
476
|
-
// // yield* callback();
|
|
477
|
-
// // },
|
|
478
|
-
// // },
|
|
479
|
-
// // { headers: this.headers }
|
|
480
|
-
// // );
|
|
481
|
-
// },
|
|
482
|
-
// setCookie(
|
|
483
|
-
// name: string,
|
|
484
|
-
// value: string,
|
|
485
|
-
// options: CookieOptions = {}
|
|
486
|
-
// ): ContextType {
|
|
487
|
-
// let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(
|
|
488
|
-
// value
|
|
489
|
-
// )}`;
|
|
490
|
-
// if (options.maxAge) cookieString += `; Max-Age=${options.maxAge}`;
|
|
491
|
-
// if (options.expires)
|
|
492
|
-
// cookieString += `; Expires=${options.expires.toUTCString()}`;
|
|
493
|
-
// if (options.path) cookieString += `; Path=${options.path}`;
|
|
494
|
-
// if (options.domain) cookieString += `; Domain=${options.domain}`;
|
|
495
|
-
// if (options.secure) cookieString += `; Secure`;
|
|
496
|
-
// if (options.httpOnly) cookieString += `; HttpOnly`;
|
|
497
|
-
// if (options.sameSite) cookieString += `; SameSite=${options.sameSite}`;
|
|
498
|
-
// this.headers.append("Set-Cookie", cookieString);
|
|
499
|
-
// return this;
|
|
500
|
-
// },
|
|
501
|
-
// get cookies(): Record<string, string> {
|
|
502
|
-
// if (!parsedCookies) {
|
|
503
|
-
// const cookieHeader = this.req.headers.get("cookie");
|
|
504
|
-
// parsedCookies = cookieHeader ? parseCookie(cookieHeader) : {};
|
|
505
|
-
// }
|
|
506
|
-
// return parsedCookies;
|
|
507
|
-
// },
|
|
508
|
-
// };
|
|
509
|
-
// }
|
package/dist/handleRequest.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { Server } from "bun";
|
|
2
|
-
import
|
|
3
|
-
export default function handleRequest(req: Request, server: Server, diesel:
|
|
2
|
+
import Diesel from "./main";
|
|
3
|
+
export default function handleRequest(req: Request, server: Server, diesel: Diesel, env?: Record<string, any>, executionContext?: any): Promise<Response | undefined>;
|
package/dist/handleRequest.js
CHANGED
|
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
};
|
|
10
10
|
import { Context } from "./ctx";
|
|
11
11
|
import { tryDecodeURI } from "./utils/urls";
|
|
12
|
-
import { generateErrorResponse, handleRouteNotFound, runFilter, runHooks
|
|
12
|
+
import { generateErrorResponse, handleRouteNotFound, runFilter, runHooks } from "./utils/request.util";
|
|
13
13
|
import { isPromise } from "./utils/promise";
|
|
14
14
|
export default function handleRequest(req, server, diesel, env, executionContext) {
|
|
15
15
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -38,11 +38,10 @@ export default function handleRequest(req, server, diesel, env, executionContext
|
|
|
38
38
|
// if (diesel.hasOnReqHook)
|
|
39
39
|
// await runHooks('onRequest', diesel.hooks.onRequest, [req, pathname, server])
|
|
40
40
|
// middleware execution
|
|
41
|
-
if (diesel.hasMiddleware) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
41
|
+
// if (diesel.hasMiddleware) {
|
|
42
|
+
// const mwResult = await runMiddlewares(diesel, pathname, ctx);
|
|
43
|
+
// if (mwResult) return mwResult;
|
|
44
|
+
// }
|
|
46
45
|
// filter execution
|
|
47
46
|
if (diesel.hasFilterEnabled) {
|
|
48
47
|
const filterResponse = yield runFilter(diesel, pathname, ctx);
|
package/dist/main.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export default class Diesel {
|
|
|
20
20
|
FilterRoutes: string[] | null | undefined;
|
|
21
21
|
filters: Set<string>;
|
|
22
22
|
filterFunction: Function[];
|
|
23
|
-
|
|
23
|
+
hasFilterEnabled: boolean;
|
|
24
24
|
private serverInstance;
|
|
25
25
|
staticFiles: any;
|
|
26
26
|
user_jwt_secret: string;
|
package/dist/main.js
CHANGED
|
@@ -114,8 +114,17 @@ class Diesel {
|
|
|
114
114
|
return new Proxy(this.instance, {
|
|
115
115
|
get(target, prop, reciever) {
|
|
116
116
|
return (path, handler) => {
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
let givenHandler = handler;
|
|
118
|
+
let givenPath = '';
|
|
119
|
+
if (typeof path === 'string')
|
|
120
|
+
givenPath = path;
|
|
121
|
+
else if (typeof path === 'function')
|
|
122
|
+
givenHandler = path;
|
|
123
|
+
else if (typeof path !== 'string')
|
|
124
|
+
givenPath = '';
|
|
125
|
+
const fullPath = prefix + givenPath;
|
|
126
|
+
// console.log(fullPath)
|
|
127
|
+
return target[prop](fullPath, givenHandler);
|
|
119
128
|
// if (typeof path === 'string') return (target as any)[prop](fullPath, handler)
|
|
120
129
|
// else if (typeof path === 'function') return (target as any)[prop](path)
|
|
121
130
|
};
|
|
@@ -394,7 +403,7 @@ class Diesel {
|
|
|
394
403
|
mount(prefix, fetch) {
|
|
395
404
|
const cleanPrefix = prefix.endsWith("/*") ? prefix.slice(0, -1) : prefix;
|
|
396
405
|
const prefixLength = cleanPrefix === '/' ? 0 : cleanPrefix.length;
|
|
397
|
-
this.
|
|
406
|
+
this.use(prefix, (ctx) => {
|
|
398
407
|
// build new url for fetch
|
|
399
408
|
const url = new URL(ctx.req.url);
|
|
400
409
|
// here we slice orgininal coming url like /hono/hello so we have to slice /hono
|
|
@@ -642,7 +651,6 @@ _Diesel_newPipelineArchitecture = new WeakMap(), _Diesel_instances = new WeakSet
|
|
|
642
651
|
if (result)
|
|
643
652
|
return result;
|
|
644
653
|
}
|
|
645
|
-
// console.log('routeHandlers ',routeHandler)
|
|
646
654
|
let finalResult;
|
|
647
655
|
const handlers = matchedRouteHandler === null || matchedRouteHandler === void 0 ? void 0 : matchedRouteHandler.handler;
|
|
648
656
|
if (handlers.length === 1) {
|
|
@@ -34,30 +34,30 @@ describe("CORS Middleware", () => {
|
|
|
34
34
|
afterAll(() => {
|
|
35
35
|
app.close();
|
|
36
36
|
});
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
37
|
+
it("should allow any origin for public route", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
38
|
+
const res = yield fetch("http://localhost:3005/public/test", {
|
|
39
|
+
headers: { origin: "http://random.com" },
|
|
40
|
+
});
|
|
41
|
+
const data = yield res.json();
|
|
42
|
+
expect(res.status).toBe(200);
|
|
43
|
+
expect(data.message).toBe("Public route");
|
|
44
|
+
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
|
|
45
|
+
}));
|
|
46
|
+
it("should allow specific origin", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
47
|
+
const res = yield fetch("http://localhost:3005/single-origin/test", {
|
|
48
|
+
headers: { origin: "http://localhost:3000" },
|
|
49
|
+
});
|
|
50
|
+
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("http://localhost:3000");
|
|
51
|
+
expect(res.headers.get("Access-Control-Allow-Credentials")).toBe("true");
|
|
52
|
+
}));
|
|
53
|
+
it("should reject request from disallowed origin", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
54
|
+
const res = yield fetch("http://localhost:3005/single-origin/test", {
|
|
55
|
+
headers: { origin: "http://evil.com" },
|
|
56
|
+
});
|
|
57
|
+
expect(res.status).toBe(403);
|
|
58
|
+
const data = yield res.json();
|
|
59
|
+
expect(data.message).toBe("CORS not allowed");
|
|
60
|
+
}));
|
|
61
61
|
it("should handle preflight with allowed headers and methods", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
62
62
|
const res = yield fetch("http://localhost:3005/single-origin/test", {
|
|
63
63
|
method: "OPTIONS",
|
|
@@ -73,22 +73,22 @@ describe("CORS Middleware", () => {
|
|
|
73
73
|
expect(res.headers.get("Access-Control-Allow-Methods")).toBe("GET,POST");
|
|
74
74
|
expect(res.headers.get("Access-Control-Max-Age")).toBe("86400");
|
|
75
75
|
}));
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
76
|
+
it("should allow multiple origins", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
77
|
+
const req = yield fetch("http://localhost:3005/multi-origin/test", {
|
|
78
|
+
headers: {
|
|
79
|
+
origin: "http://site2.com",
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
expect(req.headers.get("Access-Control-Allow-Origin")).toBe("http://site2.com");
|
|
83
|
+
}));
|
|
84
|
+
it("should reject disallowed origin in multiple origins", () => __awaiter(void 0, void 0, void 0, function* () {
|
|
85
|
+
const req = yield fetch("http://localhost:3005/multi-origin/test", {
|
|
86
|
+
headers: {
|
|
87
|
+
origin: "http://evil.com",
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
expect(req.status).toBe(403);
|
|
91
|
+
const body = yield req.json();
|
|
92
|
+
expect(body.message).toBe("CORS not allowed");
|
|
93
|
+
}));
|
|
94
94
|
});
|
|
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
import { afterAll, beforeAll, describe, expect, it } from "bun:test";
|
|
11
11
|
import Diesel from "../../main";
|
|
12
12
|
import { fileSaveMiddleware } from "./savefile";
|
|
13
|
-
import fs from 'fs';
|
|
13
|
+
import * as fs from 'fs';
|
|
14
14
|
describe("FileSaveMidlleware", () => {
|
|
15
15
|
const app = new Diesel();
|
|
16
16
|
app.post("/upload", fileSaveMiddleware({ fields: ["file"] }), (ctx) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function g(e){if(typeof e!=="string")throw
|
|
1
|
+
function g(e){if(typeof e!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(e))}function x(e,r){var n="",i=0,l=-1,t=0,f;for(var o=0;o<=e.length;++o){if(o<e.length)f=e.charCodeAt(o);else if(f===47)break;else f=47;if(f===47){if(l===o-1||t===1);else if(l!==o-1&&t===2){if(n.length<2||i!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var a=n.lastIndexOf("/");if(a!==n.length-1){if(a===-1)n="",i=0;else n=n.slice(0,a),i=n.length-1-n.lastIndexOf("/");l=o,t=0;continue}}else if(n.length===2||n.length===1){n="",i=0,l=o,t=0;continue}}if(r){if(n.length>0)n+="/..";else n="..";i=2}}else{if(n.length>0)n+="/"+e.slice(l+1,o);else n=e.slice(l+1,o);i=o-l-1}l=o,t=0}else if(f===46&&t!==-1)++t;else t=-1}return n}function T(e,r){var n=r.dir||r.root,i=r.base||(r.name||"")+(r.ext||"");if(!n)return i;if(n===r.root)return n+i;return n+e+i}function A(){var e="",r=!1,n;for(var i=arguments.length-1;i>=-1&&!r;i--){var l;if(i>=0)l=arguments[i];else{if(n===void 0)n=process.cwd();l=n}if(g(l),l.length===0)continue;e=l+"/"+e,r=l.charCodeAt(0)===47}if(e=x(e,!r),r)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function k(e){if(g(e),e.length===0)return".";var r=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;if(e=x(e,!r),e.length===0&&!r)e=".";if(e.length>0&&n)e+="/";if(r)return"/"+e;return e}function E(e){return g(e),e.length>0&&e.charCodeAt(0)===47}function V(){if(arguments.length===0)return".";var e;for(var r=0;r<arguments.length;++r){var n=arguments[r];if(g(n),n.length>0)if(e===void 0)e=n;else e+="/"+n}if(e===void 0)return".";return k(e)}function I(e,r){if(g(e),g(r),e===r)return"";if(e=A(e),r=A(r),e===r)return"";var n=1;for(;n<e.length;++n)if(e.charCodeAt(n)!==47)break;var i=e.length,l=i-n,t=1;for(;t<r.length;++t)if(r.charCodeAt(t)!==47)break;var f=r.length,o=f-t,a=l<o?l:o,d=-1,s=0;for(;s<=a;++s){if(s===a){if(o>a){if(r.charCodeAt(t+s)===47)return r.slice(t+s+1);else if(s===0)return r.slice(t+s)}else if(l>a){if(e.charCodeAt(n+s)===47)d=s;else if(s===0)d=0}break}var S=e.charCodeAt(n+s),R=r.charCodeAt(t+s);if(S!==R)break;else if(S===47)d=s}var c="";for(s=n+d+1;s<=i;++s)if(s===i||e.charCodeAt(s)===47)if(c.length===0)c+="..";else c+="/..";if(c.length>0)return c+r.slice(t+d);else{if(t+=d,r.charCodeAt(t)===47)++t;return r.slice(t)}}function L(e){return e}function P(e){if(g(e),e.length===0)return".";var r=e.charCodeAt(0),n=r===47,i=-1,l=!0;for(var t=e.length-1;t>=1;--t)if(r=e.charCodeAt(t),r===47){if(!l){i=t;break}}else l=!1;if(i===-1)return n?"/":".";if(n&&i===1)return"//";return e.slice(0,i)}function z(e,r){if(r!==void 0&&typeof r!=="string")throw TypeError('"ext" argument must be a string');g(e);var n=0,i=-1,l=!0,t;if(r!==void 0&&r.length>0&&r.length<=e.length){if(r.length===e.length&&r===e)return"";var f=r.length-1,o=-1;for(t=e.length-1;t>=0;--t){var a=e.charCodeAt(t);if(a===47){if(!l){n=t+1;break}}else{if(o===-1)l=!1,o=t+1;if(f>=0)if(a===r.charCodeAt(f)){if(--f===-1)i=t}else f=-1,i=o}}if(n===i)i=o;else if(i===-1)i=e.length;return e.slice(n,i)}else{for(t=e.length-1;t>=0;--t)if(e.charCodeAt(t)===47){if(!l){n=t+1;break}}else if(i===-1)l=!1,i=t+1;if(i===-1)return"";return e.slice(n,i)}}function $(e){g(e);var r=-1,n=0,i=-1,l=!0,t=0;for(var f=e.length-1;f>=0;--f){var o=e.charCodeAt(f);if(o===47){if(!l){n=f+1;break}continue}if(i===-1)l=!1,i=f+1;if(o===46){if(r===-1)r=f;else if(t!==1)t=1}else if(r!==-1)t=-1}if(r===-1||i===-1||t===0||t===1&&r===i-1&&r===n+1)return"";return e.slice(r,i)}function H(e){if(e===null||typeof e!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return T("/",e)}function J(e){g(e);var r={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return r;var n=e.charCodeAt(0),i=n===47,l;if(i)r.root="/",l=1;else l=0;var t=-1,f=0,o=-1,a=!0,d=e.length-1,s=0;for(;d>=l;--d){if(n=e.charCodeAt(d),n===47){if(!a){f=d+1;break}continue}if(o===-1)a=!1,o=d+1;if(n===46){if(t===-1)t=d;else if(s!==1)s=1}else if(t!==-1)s=-1}if(t===-1||o===-1||s===0||s===1&&t===o-1&&t===f+1){if(o!==-1)if(f===0&&i)r.base=r.name=e.slice(1,o);else r.base=r.name=e.slice(f,o)}else{if(f===0&&i)r.name=e.slice(1,t),r.base=e.slice(1,o);else r.name=e.slice(f,t),r.base=e.slice(f,o);r.ext=e.slice(t,o)}if(f>0)r.dir=e.slice(0,f-1);else if(i)r.dir="/";return r}var M="/",X=":",q=((e)=>(e.posix=e,e))({resolve:A,normalize:k,isAbsolute:E,join:V,relative:I,_makeLong:L,dirname:P,basename:z,extname:$,format:H,parse:J,sep:M,delimiter:X,win32:null,posix:null}),m=q;var u=[];for(let e=0;e<256;++e)u.push((e+256).toString(16).slice(1));function U(e,r=0){return(u[e[r+0]]+u[e[r+1]]+u[e[r+2]]+u[e[r+3]]+"-"+u[e[r+4]]+u[e[r+5]]+"-"+u[e[r+6]]+u[e[r+7]]+"-"+u[e[r+8]]+u[e[r+9]]+"-"+u[e[r+10]]+u[e[r+11]]+u[e[r+12]]+u[e[r+13]]+u[e[r+14]]+u[e[r+15]]).toLowerCase()}var y,F=new Uint8Array(16);function b(){if(!y){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");y=crypto.getRandomValues.bind(crypto)}return y(F)}var G=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),C={randomUUID:G};function K(e,r,n){if(C.randomUUID&&!r&&!e)return C.randomUUID();e=e||{};let i=e.random??e.rng?.()??b();if(i.length<16)throw Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,r){if(n=n||0,n<0||n+16>r.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let l=0;l<16;++l)r[n+l]=i[l];return r}return U(i)}var h=K;var v=(()=>({}));var D=import.meta.dir,w=m.resolve(D,"../../public/uploaded");if(!v.existsSync(w))v.mkdirSync(w,{recursive:!0});var ne=(e={})=>{let r=e.dest?m.resolve(D,e.dest):w;return async(n)=>{try{let i=await n.body;n.req.files??={};for(let l of e?.fields??[]){let t=i[l];if(!t.name)continue;let f=`${l}_${h()}${m.extname(t?.name)}`,o=m.join(r,f);await Bun.write(o,await t.arrayBuffer()),n.req.files[l]=o}}catch(i){return console.error("File upload error:",i),n.json({status:500,message:"Error uploading files"},500)}}};export{ne as fileSaveMiddleware};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function G(q,E){if(!q)throw
|
|
1
|
+
function G(q,E){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(B)=>{try{let z=B.cookies?.accessToken??B.req?.headers?.get("Authorization");if(!z)return B.json({message:"Unauthorized",error:"No token provided"},401);if(z.startsWith("Bearer "))z=z.slice(7);let A=q?.verify(z,E);if(!A)return B.json({message:"Unauthorized",error:"Token could not be decoded"},401);B.set("user",A)}catch(z){let A="Invalid token";if(z.name==="TokenExpiredError")A="Token expired";else if(z.name==="JsonWebTokenError")A="Malformed or tampered token";return B.json({message:"Unauthorized",error:A},401)}}}function H(q,E,B){if(!q)throw Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!E)throw Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(z)=>{try{let A=z.cookies?.accessToken??z.req?.headers?.get("Authorization");if(!A)return z.json({message:"Unauthorized",error:"No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let C=q?.verify(A,B);if(!C)return z.json({message:"Unauthorized",error:"Token could not be decoded"},401);let F=await E.findById(C._id).select("-password -refreshToken");if(!F)return z.json({message:"Unauthorized: User not found"},404);z.set("user",F);return}catch(A){let C="Invalid token";if(A.name==="TokenExpiredError")C="Token expired";else if(A.name==="JsonWebTokenError")C="Malformed or tampered token";return z.json({message:"Unauthorized",error:C},401)}}}var L=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z}=q,A=G(B,z);return(C)=>{if(!E?.length||E?.includes(C.url.pathname))return A(C)}},N=(q)=>{if(!q.app)throw Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!q.userModel)throw Error("User model is not defined, please provide userModel to authenticateJwt Function");if(!q.jwt)throw Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!q.jwtSecret)q.jwtSecret=q.app.user_jwt_secret;let{routes:E,jwt:B,jwtSecret:z,userModel:A}=q,C=H(B,A,z);return(F)=>{if(E?.length===0||E?.includes(F.url.pathname))return C(F)}};export{N as authenticateJwtDB,L as authenticateJwt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=(g)=>{return async function
|
|
1
|
+
var q=(g)=>{return async function(j){j.setHeader("X-Powered-By",g?.serverName??"Diesel")}};export{q as poweredBy};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var A=Object.create;var{getPrototypeOf:D,defineProperty:t,getOwnPropertyNames:p,getOwnPropertyDescriptor:N}=Object,s=Object.prototype.hasOwnProperty;var d=(P,T,E)=>{E=P!=null?A(D(P)):{};let o=T||!P||!P.__esModule?t(E,"default",{value:P,enumerable:!0}):E;for(let O of p(P))if(!s.call(o,O))t(o,O,{get:()=>P[O],enumerable:!0});return o},e=new WeakMap,r=(P)=>{var T=e.get(P),E;if(T)return T;if(T=t({},"__esModule",{value:!0}),P&&typeof P==="object"||typeof P==="function")p(P).map((o)=>!s.call(T,o)&&t(T,o,{get:()=>P[o],enumerable:!(E=N(P,o))||E.enumerable}));return e.set(P,T),T},H=(P,T)=>()=>(T||P((T={exports:{}}).exports,T),T.exports);var I=(P,T)=>{for(var E in T)t(P,E,{get:T[E],enumerable:!0,configurable:!0,set:(o)=>T[E]=()=>o})};var S=(P,T)=>()=>(P&&(T=P(P=0)),T);var c=((P)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(P,{get:(T,E)=>(typeof require<"u"?require:T)[E]}):P)(function(P){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+P+'" is not supported')});var n=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];export{n as supportedMethods};
|