owebjs 1.0.6 → 1.1.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.
@@ -0,0 +1,6 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ export {
5
+ __name
6
+ };
@@ -1 +1,34 @@
1
- import{a as e}from"../chunk-2HA4XQFN.js";import a from"jsonwebtoken";var f=e(({secret:r,onError:i})=>function(n){return class extends n{static{e(this,"JWT")}constructor(o,s){super();let t=o?.headers?.authorization;if(t&&(t=t.trim(),t=t.slice(Math.max(t.lastIndexOf(" "),0))),r)try{this.jwtResult=a.verify(t,r)}catch{i&&i(o,s)}else throw new Error("JWT Secret not provided!")}}},"JwtAuth");export{f as JwtAuth};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import jwt from "jsonwebtoken";
5
+ const JwtAuth = /* @__PURE__ */ __name(({ secret, onError }) => {
6
+ return function(Base) {
7
+ return class JWT extends Base {
8
+ static {
9
+ __name(this, "JWT");
10
+ }
11
+ constructor(req, res) {
12
+ super();
13
+ let token = req?.headers?.authorization;
14
+ if (token) {
15
+ token = token.trim();
16
+ token = token.slice(Math.max(token.lastIndexOf(" "), 0));
17
+ }
18
+ if (secret) {
19
+ try {
20
+ this.jwtResult = jwt.verify(token, secret);
21
+ } catch {
22
+ if (onError)
23
+ onError(req, res);
24
+ }
25
+ } else {
26
+ throw new Error("JWT Secret not provided!");
27
+ }
28
+ }
29
+ };
30
+ };
31
+ }, "JwtAuth");
32
+ export {
33
+ JwtAuth
34
+ };
@@ -1 +1,15 @@
1
- import{a as s}from"../chunk-2HA4XQFN.js";var r=s((e,t)=>t(e),"creator"),c=class{static{s(this,"BaseRequest")}constructor(){}},a=s((...e)=>e.reduce(r,c),"register");export{a as register};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ const creator = /* @__PURE__ */ __name((allPlugins, plugin) => plugin(allPlugins), "creator");
5
+ let BaseRequest = class BaseRequest2 {
6
+ static {
7
+ __name(this, "BaseRequest");
8
+ }
9
+ constructor() {
10
+ }
11
+ };
12
+ const register = /* @__PURE__ */ __name((...plugins) => plugins.reduce(creator, BaseRequest), "register");
13
+ export {
14
+ register
15
+ };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,19 @@
1
1
  import { FastifyServerOptions, FastifyRequest, FastifyReply, FastifyListenOptions, FastifyInstance } from 'fastify';
2
+ export * from 'fastify/types/instance';
3
+ export * from 'fastify/types/hooks';
4
+ export * from 'fastify/types/logger';
5
+ export * from 'fastify/types/request';
6
+ export * from 'fastify/types/reply';
7
+ export * from 'fastify/types/errors';
8
+ export * from 'fastify/types/register';
9
+ export * from 'fastify/types/plugin';
10
+ export * from 'fastify/types/route';
11
+ export * from 'fastify/types/schema';
12
+ export * from 'fastify/types/context';
13
+ export * from 'fastify/types/utils';
14
+ export * from 'fastify/types/serverFactory';
15
+ export * from 'fastify/types/type-provider';
16
+ export * from 'fastify/types/content-type-parser';
2
17
 
3
18
  interface OwebOptions extends FastifyServerOptions {
4
19
  uWebSocketsEnabled?: boolean;
@@ -14,13 +29,28 @@ declare class _FastifyInstance {
14
29
  declare class Oweb extends _FastifyInstance {
15
30
  _options: OwebOptions;
16
31
  constructor(options?: OwebOptions);
17
- setup(): Promise<unknown>;
32
+ setup(): Promise<Oweb>;
18
33
  loadRoutes({ directory }: LoadRoutesOptions): Promise<void>;
19
34
  setInternalErrorHandler(errorHandlerCallback: (request: FastifyRequest, reply: FastifyReply, error: Error) => void): void;
20
- start(listenOptions?: FastifyListenOptions): Promise<{
35
+ start(options?: FastifyListenOptions): Promise<{
21
36
  err: Error;
22
37
  address: string;
23
38
  }>;
24
39
  }
25
40
 
26
- export { LoadRoutesOptions, Oweb, OwebOptions, Oweb as default };
41
+ type Awaitable<T> = T | Promise<T>;
42
+
43
+ declare interface Route {
44
+ handle(req: FastifyRequest, res: FastifyReply): Awaitable<any>;
45
+ handleError?(req: FastifyRequest, res: FastifyReply, err: Error): Awaitable<any>;
46
+ }
47
+ declare abstract class Route {
48
+ }
49
+
50
+ declare interface Hook {
51
+ handle(req: FastifyRequest, res: FastifyReply, done: () => void): Awaitable<any>;
52
+ }
53
+ declare abstract class Hook {
54
+ }
55
+
56
+ export { Awaitable, Hook, LoadRoutesOptions, Oweb, OwebOptions, Route, Oweb as default };
package/dist/index.js CHANGED
@@ -1 +1,10 @@
1
- import{b as a}from"./chunk-FRG47WHC.js";import"./chunk-OR3GJT5E.js";import"./chunk-XR5MHIBF.js";import{a as r}from"./chunk-2HA4XQFN.js";import p from"fastify";var _=class{static{r(this,"_FastifyInstance")}},n=class extends _{static{r(this,"Oweb")}_options={};constructor(t={}){super();let s=t??{};this._options=s,this._options.OWEB_INTERNAL_ERROR_HANDLER=(e,o,i)=>o.status(500).send({error:i.message})}async setup(){return new Promise(async t=>{if(this._options.uWebSocketsEnabled){let s=(await import("./uwebsocket/server.js")).default,e=await s({});this._options.serverFactory=(o,i)=>(e.on("request",o),e),Object.assign(this,p(this._options)),t(!0)}else Object.assign(this,p(this._options)),t(!0)})}loadRoutes({directory:t}){return a(t,this)}setInternalErrorHandler(t){this._options.OWEB_INTERNAL_ERROR_HANDLER=t}start(t={port:3e3,host:"127.0.0.1"}){return new Promise(s=>{this.listen({port:+t.port},(e,o)=>s({err:e,address:o}))})}};export{n as Oweb,n as default};
1
+ import "./chunk-NH24FRB3.js";
2
+ import { Oweb } from './structures/Oweb.js';
3
+ var src_default = Oweb;
4
+ export * from './structures/Oweb.js';
5
+ export * from './structures/Route.js';
6
+ export * from './structures/Hook.js';
7
+ export * from './types.js';
8
+ export {
9
+ src_default as default
10
+ };
@@ -0,0 +1,14 @@
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ class Hook {
5
+ static {
6
+ __name(this, "Hook");
7
+ }
8
+ handle() {
9
+ throw new Error("Hook#handle must be implemented");
10
+ }
11
+ }
12
+ export {
13
+ Hook
14
+ };
@@ -0,0 +1,59 @@
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import Fastify from "fastify";
5
+ import { assignRoutes } from '../utils/assignRoutes.js';
6
+ let _FastifyInstance = class _FastifyInstance2 {
7
+ static {
8
+ __name(this, "_FastifyInstance");
9
+ }
10
+ };
11
+ class Oweb extends _FastifyInstance {
12
+ static {
13
+ __name(this, "Oweb");
14
+ }
15
+ _options = {};
16
+ constructor(options) {
17
+ super();
18
+ this._options = options ?? {};
19
+ this._options.uWebSocketsEnabled ??= false;
20
+ this._options.OWEB_INTERNAL_ERROR_HANDLER ??= (_, res, err) => {
21
+ return res.status(500).send({
22
+ error: err.message
23
+ });
24
+ };
25
+ }
26
+ async setup() {
27
+ if (this._options.uWebSocketsEnabled) {
28
+ const serverimp = (await import("../uwebsocket/server")).default;
29
+ const server = await serverimp({});
30
+ this._options.serverFactory = (handler, opts) => {
31
+ server.on("request", handler);
32
+ return server;
33
+ };
34
+ }
35
+ return Object.assign(this, Fastify(this._options));
36
+ }
37
+ loadRoutes({ directory }) {
38
+ return assignRoutes(directory, this);
39
+ }
40
+ setInternalErrorHandler(errorHandlerCallback) {
41
+ this._options.OWEB_INTERNAL_ERROR_HANDLER = errorHandlerCallback;
42
+ }
43
+ start(options = {
44
+ port: 3e3,
45
+ host: "127.0.0.1"
46
+ }) {
47
+ return new Promise((resolve) => {
48
+ this.listen({
49
+ port: +options.port
50
+ }, (err, address) => resolve({
51
+ err,
52
+ address
53
+ }));
54
+ });
55
+ }
56
+ }
57
+ export {
58
+ Oweb
59
+ };
@@ -0,0 +1,14 @@
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ class Route {
5
+ static {
6
+ __name(this, "Route");
7
+ }
8
+ handle() {
9
+ throw new Error("Route#handle must be implemented");
10
+ }
11
+ }
12
+ export {
13
+ Route
14
+ };
package/dist/types.js ADDED
File without changes
@@ -1 +1,82 @@
1
- import{a,b}from"../chunk-FRG47WHC.js";import"../chunk-OR3GJT5E.js";import"../chunk-XR5MHIBF.js";import"../chunk-2HA4XQFN.js";export{b as assignRoutes,a as generateRoutes};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import path from "node:path";
5
+ import { dirname } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { buildRoutePath, buildRouteURL } from './utils.js';
8
+ import { walk } from './walk.js';
9
+ const __dirname = dirname(fileURLToPath(import.meta.url));
10
+ const generateRoutes = /* @__PURE__ */ __name(async (files) => {
11
+ const routes = [];
12
+ for (const file of files) {
13
+ const parsedFile = path.parse(file.rel);
14
+ const filePath = file.filePath.replaceAll("\\", "/");
15
+ const packageURL = new URL(path.resolve(filePath), `file://${__dirname}`).pathname.replaceAll("\\", "/");
16
+ const routePath = buildRoutePath(parsedFile);
17
+ const route = buildRouteURL(routePath);
18
+ const def = await import(packageURL);
19
+ const routeFuncs = def.default;
20
+ routes.push({
21
+ url: route.url,
22
+ method: route.method,
23
+ fn: routeFuncs,
24
+ fileInfo: file
25
+ });
26
+ }
27
+ return routes;
28
+ }, "generateRoutes");
29
+ const assignRoutes = /* @__PURE__ */ __name(async (directory, oweb) => {
30
+ const files = await walk(directory);
31
+ const routes = await generateRoutes(files);
32
+ for (const route of routes) {
33
+ oweb[route.method](route.url, function(req, res) {
34
+ const routeFunc = new route.fn(...arguments);
35
+ const handle = /* @__PURE__ */ __name(() => {
36
+ if (routeFunc.handle.constructor.name == "AsyncFunction") {
37
+ routeFunc.handle(...arguments).catch((error) => {
38
+ const handleErrorArgs = [
39
+ ...arguments,
40
+ error
41
+ ];
42
+ if (routeFunc?.handleError) {
43
+ routeFunc.handleError(...handleErrorArgs);
44
+ } else {
45
+ oweb._options.OWEB_INTERNAL_ERROR_HANDLER(...handleErrorArgs);
46
+ }
47
+ });
48
+ } else {
49
+ try {
50
+ routeFunc.handle(...arguments);
51
+ } catch (error) {
52
+ const handleErrorArgs = [
53
+ ...arguments,
54
+ error
55
+ ];
56
+ if (routeFunc?.handleError) {
57
+ routeFunc.handleError(...handleErrorArgs);
58
+ } else {
59
+ oweb._options.OWEB_INTERNAL_ERROR_HANDLER(...handleErrorArgs);
60
+ }
61
+ }
62
+ }
63
+ }, "handle");
64
+ if (route.fileInfo.hooks.length) {
65
+ for (let index = 0; index < route.fileInfo.hooks.length; index++) {
66
+ const hookFun = route.fileInfo.hooks[index];
67
+ new hookFun().handle(req, res, () => {
68
+ if (index + 1 == route.fileInfo.hooks.length) {
69
+ handle();
70
+ }
71
+ });
72
+ }
73
+ } else {
74
+ handle();
75
+ }
76
+ });
77
+ }
78
+ }, "assignRoutes");
79
+ export {
80
+ assignRoutes,
81
+ generateRoutes
82
+ };
@@ -1 +1,48 @@
1
- import{a,b,c,d,e}from"../chunk-XR5MHIBF.js";import"../chunk-2HA4XQFN.js";export{d as buildRoutePath,e as buildRouteURL,c as convertCatchallSyntax,b as convertParamSyntax,a as mergePaths};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ const mergePaths = /* @__PURE__ */ __name((...paths) => "/" + paths.map((path) => path.replace(/^\/|\/$/g, "")).filter((path) => path !== "").join("/"), "mergePaths");
5
+ const regBackets = /\[([^}]*)\]/g;
6
+ const transformBrackets = /* @__PURE__ */ __name((value) => regBackets.test(value) ? value.replace(regBackets, (_, s) => `:${s}`) : value, "transformBrackets");
7
+ const convertParamSyntax = /* @__PURE__ */ __name((path) => {
8
+ const subpaths = [];
9
+ for (const subpath of path.split("/")) {
10
+ subpaths.push(transformBrackets(subpath));
11
+ }
12
+ return mergePaths(...subpaths);
13
+ }, "convertParamSyntax");
14
+ const convertCatchallSyntax = /* @__PURE__ */ __name((url) => url.replace(/:\.\.\.\w+/g, "*"), "convertCatchallSyntax");
15
+ const buildRoutePath = /* @__PURE__ */ __name((parsedFile) => {
16
+ const directory = parsedFile.dir === parsedFile.root ? "" : parsedFile.dir;
17
+ const name = parsedFile.name.startsWith("index") ? parsedFile.name.replace("index", "") : `/${parsedFile.name}`;
18
+ return directory + name;
19
+ }, "buildRoutePath");
20
+ const buildRouteURL = /* @__PURE__ */ __name((path) => {
21
+ let method = "get";
22
+ const paramURL = convertParamSyntax(path);
23
+ let url = convertCatchallSyntax(paramURL);
24
+ for (const m of [
25
+ ".DELETE",
26
+ ".POST",
27
+ ".PATCH",
28
+ ".GET",
29
+ ".PUT"
30
+ ]) {
31
+ if (path.endsWith(m) || path.endsWith(m.toLowerCase())) {
32
+ method = m.toLowerCase().slice(1);
33
+ url = url.slice(0, url.length - m.length);
34
+ break;
35
+ }
36
+ }
37
+ return {
38
+ url,
39
+ method
40
+ };
41
+ }, "buildRouteURL");
42
+ export {
43
+ buildRoutePath,
44
+ buildRouteURL,
45
+ convertCatchallSyntax,
46
+ convertParamSyntax,
47
+ mergePaths
48
+ };
@@ -1 +1,71 @@
1
- import{a}from"../chunk-OR3GJT5E.js";import"../chunk-XR5MHIBF.js";import"../chunk-2HA4XQFN.js";export{a as walk};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import { readdirSync, statSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import path from "node:path";
7
+ import { mergePaths } from './utils.js';
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const isParentOrGrandparent = /* @__PURE__ */ __name((parentFolderPath, childFolderPath) => {
10
+ if (childFolderPath.startsWith(parentFolderPath)) {
11
+ const relativePath = path.relative(parentFolderPath, childFolderPath);
12
+ const relativeSegments = relativePath.split(path.sep);
13
+ return relativeSegments.length > 2 || relativePath == "" || relativePath.length > 0;
14
+ }
15
+ return false;
16
+ }, "isParentOrGrandparent");
17
+ const hookPaths = /* @__PURE__ */ new Set();
18
+ const walk = /* @__PURE__ */ __name(async (directory, tree = []) => {
19
+ const results = [];
20
+ const readDirPriority = readdirSync(directory);
21
+ readDirPriority.sort((a, b) => {
22
+ if (a.startsWith("_") && !b.startsWith("_")) {
23
+ return -1;
24
+ } else if (!a.startsWith("_") && b.startsWith("_")) {
25
+ return 1;
26
+ } else {
27
+ return a.localeCompare(b);
28
+ }
29
+ });
30
+ for (const fileName of readDirPriority) {
31
+ const filePath = path.join(directory, fileName);
32
+ const directoryResolve = path.resolve(directory);
33
+ if (fileName == "_hooks.js" || fileName == "_hooks.ts") {
34
+ hookPaths.add(directoryResolve);
35
+ continue;
36
+ }
37
+ const fileStats = statSync(filePath);
38
+ if (fileStats.isDirectory()) {
39
+ results.push(...await walk(filePath, [
40
+ ...tree,
41
+ fileName
42
+ ]));
43
+ } else {
44
+ const spread = [
45
+ ...hookPaths
46
+ ];
47
+ const hooks = spread.filter((hookPath) => {
48
+ return isParentOrGrandparent(hookPath, directoryResolve);
49
+ });
50
+ const hooksImport = hooks.map((hookPath) => new URL(hookPath, `file://${__dirname}`).pathname.replaceAll("\\", "/") + "/_hooks.js");
51
+ const hookFunctions = [];
52
+ for (const importPath of hooksImport) {
53
+ const imp = await import(importPath);
54
+ if (imp?.default) {
55
+ hookFunctions.push(imp.default);
56
+ }
57
+ }
58
+ results.push({
59
+ name: fileName,
60
+ path: directory,
61
+ hooks: hookFunctions,
62
+ rel: mergePaths(...tree, fileName),
63
+ filePath
64
+ });
65
+ }
66
+ }
67
+ return results;
68
+ }, "walk");
69
+ export {
70
+ walk
71
+ };
@@ -1 +1,50 @@
1
- import{a}from"../chunk-2WXLF7QU.js";import"../chunk-2D3NDWTU.js";import"../chunk-2HA4XQFN.js";export{a as default};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import { Readable } from "stream";
5
+ import { forEach } from './utils/object.js';
6
+ class HttpRequest extends Readable {
7
+ static {
8
+ __name(this, "HttpRequest");
9
+ }
10
+ req;
11
+ res;
12
+ url;
13
+ method;
14
+ statusCode;
15
+ statusMessage;
16
+ body;
17
+ headers;
18
+ socket;
19
+ constructor(uRequest) {
20
+ super();
21
+ const q = uRequest.getQuery();
22
+ this.req = uRequest;
23
+ this.url = uRequest.getUrl() + (q ? "?" + q : "");
24
+ this.method = uRequest.getMethod().toUpperCase();
25
+ this.statusCode = null;
26
+ this.statusMessage = null;
27
+ this.body = {};
28
+ this.headers = {};
29
+ this.socket = {};
30
+ uRequest.forEach((header, value) => {
31
+ this.headers[header] = value;
32
+ });
33
+ }
34
+ getRawHeaders() {
35
+ const raw = [];
36
+ forEach(this.headers, (header, value) => {
37
+ raw.push(header, value);
38
+ });
39
+ return raw;
40
+ }
41
+ getRaw() {
42
+ return this.req;
43
+ }
44
+ _read(size) {
45
+ return this.slice(0, size);
46
+ }
47
+ }
48
+ export {
49
+ HttpRequest as default
50
+ };
@@ -1 +1,96 @@
1
- import{a}from"../chunk-Z23QA6PX.js";import"../chunk-7JAXN5IF.js";import"../chunk-ARAMBVQ3.js";import"../chunk-2HA4XQFN.js";export{a as default};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import { Writable } from "stream";
5
+ import { toLowerCase } from "./utils/string.js";
6
+ import HttpResponseSocket from './responseSocket.js';
7
+ class HttpResponse extends Writable {
8
+ static {
9
+ __name(this, "HttpResponse");
10
+ }
11
+ res;
12
+ req;
13
+ server;
14
+ statusCode;
15
+ statusMessage;
16
+ __headers;
17
+ headersSent;
18
+ socket;
19
+ finished;
20
+ constructor(uResponse, uServer) {
21
+ super();
22
+ this.res = uResponse;
23
+ this.server = uServer;
24
+ this.statusCode = 200;
25
+ this.statusMessage = "OK";
26
+ this.__headers = {};
27
+ this.headersSent = false;
28
+ this.socket = new HttpResponseSocket(uResponse);
29
+ this.res.onAborted(() => {
30
+ this.finished = this.res.finished = true;
31
+ });
32
+ }
33
+ setHeader(name, value) {
34
+ this.__headers[toLowerCase(name)] = value;
35
+ }
36
+ getHeaderNames() {
37
+ return Object.keys(this.__headers);
38
+ }
39
+ getHeaders() {
40
+ return Object.assign({}, this.__headers);
41
+ }
42
+ getHeader(name) {
43
+ return this.__headers[toLowerCase(name)];
44
+ }
45
+ hasHeader(name) {
46
+ return !!this.__headers[toLowerCase(name)];
47
+ }
48
+ removeHeader(name) {
49
+ delete this.__headers[toLowerCase(name)];
50
+ }
51
+ //@ts-ignore
52
+ write(data) {
53
+ if (this.finished)
54
+ return;
55
+ this.res.write(data);
56
+ }
57
+ writeHead(statusCode) {
58
+ if (this.finished)
59
+ return;
60
+ this.statusCode = statusCode;
61
+ let headers;
62
+ if (arguments.length === 2) {
63
+ headers = arguments[1];
64
+ } else if (arguments.length === 3) {
65
+ this.statusMessage = arguments[1];
66
+ headers = arguments[2];
67
+ } else {
68
+ headers = {};
69
+ }
70
+ Object.keys(headers).forEach((key) => {
71
+ this.setHeader(key, headers[key]);
72
+ });
73
+ }
74
+ //@ts-ignore
75
+ end(data) {
76
+ if (this.finished)
77
+ return;
78
+ function doWrite(res) {
79
+ res.res.writeStatus(`${res.statusCode} ${res.statusMessage}`);
80
+ res.finished = true;
81
+ res.res.end(data);
82
+ }
83
+ __name(doWrite, "doWrite");
84
+ if (!data) {
85
+ data = "";
86
+ return doWrite(this);
87
+ }
88
+ return doWrite(this);
89
+ }
90
+ getRaw() {
91
+ return this.res;
92
+ }
93
+ }
94
+ export {
95
+ HttpResponse as default
96
+ };
@@ -1 +1,21 @@
1
- import{a}from"../chunk-7JAXN5IF.js";import"../chunk-2HA4XQFN.js";export{a as default};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ class HttpResponseSocket {
5
+ static {
6
+ __name(this, "HttpResponseSocket");
7
+ }
8
+ uResponse;
9
+ constructor(uResponse) {
10
+ this.uResponse = uResponse;
11
+ }
12
+ get remoteAddress() {
13
+ return Buffer.from(this.uResponse.getRemoteAddressAsText()).toString();
14
+ }
15
+ destroy() {
16
+ return this.uResponse.end();
17
+ }
18
+ }
19
+ export {
20
+ HttpResponseSocket as default
21
+ };
@@ -1 +1,131 @@
1
- import{a as p}from"../chunk-2WXLF7QU.js";import"../chunk-2D3NDWTU.js";import{a as d}from"../chunk-Z23QA6PX.js";import"../chunk-7JAXN5IF.js";import"../chunk-ARAMBVQ3.js";import{a as u}from"../chunk-2HA4XQFN.js";import{EventEmitter as k}from"node:events";var q="request";async function v({cert_file_name:h,key_file_name:m}){let c;c=(await import("uWebSockets.js")).default;let S="App";h&&m&&(S="SSLApp");let l=u((i,n)=>{n.statusCode=404,n.statusMessage="Not Found",n.end()},"handler"),E={cert_file_name:h,key_file_name:m},o=c[S](E).any("/*",(i,n)=>{i.finished=!1;let e=new p(n),t=new d(i,o);e.res=t,t.req=e,e.socket=t.socket,e.method!=="HEAD"?i.onData((r,f)=>{let y=Buffer.from(r);return f?(e.push(y),e.push(null),i.finished?void 0:l(e,t)):e.push(y)}):i.finished||l(e,t)}),g=class extends k{static{u(this,"uServerClass")}constructor(){super();let n=this.on.bind(this),e=this.once.bind(this);this.once=function(t,s){return e(t,s)},this.on=function(t,s){if(t===q){l=s;return}return n(t,s)}}close(n){if(c.us_listen_socket_close(o._socket),!!n)return n()}start(n,e,t){let s,r=u(function(f){o._socket=f,t&&t(f)},"callbackFunction");return n&&e&&t&&(s=[n,e,r]),!t&&(!e||typeof e=="function")&&(t=e,e=n,s=[e,r]),o.listen(...s)}listen(n,e,t){if(typeof n=="object"){let s=n;return e=s.port,t=s.cb,n=s.host,this.start(n,e,r=>{o._socket=r,t&&t(r)})}else return(!e||typeof e=="function")&&!t?(t=e,e=n,this.start(e,t)):this.start(n,e,t)}get uwsApp(){return o}},a=new g;return a[Symbol("IncomingMessage")]=p,a[Symbol("ServerResponse")]=d,a}u(v,"default");export{v as default};
1
+ import {
2
+ __name
3
+ } from "../chunk-NH24FRB3.js";
4
+ import { EventEmitter } from "node:events";
5
+ const REQUEST_EVENT = "request";
6
+ import HttpRequest from './request.js';
7
+ import HttpResponse from './response.js';
8
+ async function server_default({ cert_file_name, key_file_name }) {
9
+ let uWS;
10
+ uWS = (await import("uWebSockets.js")).default;
11
+ let appType = "App";
12
+ if (cert_file_name && key_file_name) {
13
+ appType = "SSLApp";
14
+ }
15
+ let handler = /* @__PURE__ */ __name((req, res) => {
16
+ res.statusCode = 404;
17
+ res.statusMessage = "Not Found";
18
+ res.end();
19
+ }, "handler");
20
+ const config = {
21
+ cert_file_name,
22
+ key_file_name
23
+ };
24
+ const uServer = uWS[appType](config).any("/*", (res, req) => {
25
+ res.finished = false;
26
+ const reqWrapper = new HttpRequest(req);
27
+ const resWrapper = new HttpResponse(res, uServer);
28
+ reqWrapper.res = resWrapper;
29
+ resWrapper.req = reqWrapper;
30
+ reqWrapper.socket = resWrapper.socket;
31
+ const method = reqWrapper.method;
32
+ if (method !== "HEAD") {
33
+ res.onData((bytes, isLast) => {
34
+ const chunk = Buffer.from(bytes);
35
+ if (isLast) {
36
+ reqWrapper.push(chunk);
37
+ reqWrapper.push(null);
38
+ if (!res.finished) {
39
+ return handler(reqWrapper, resWrapper);
40
+ }
41
+ return;
42
+ }
43
+ return reqWrapper.push(chunk);
44
+ });
45
+ } else if (!res.finished) {
46
+ handler(reqWrapper, resWrapper);
47
+ }
48
+ });
49
+ let uServerClass = class uServerClass extends EventEmitter {
50
+ static {
51
+ __name(this, "uServerClass");
52
+ }
53
+ constructor() {
54
+ super();
55
+ const oldThisOn = this.on.bind(this);
56
+ const oldThisOnce = this.once.bind(this);
57
+ this.once = function(eventName, listener) {
58
+ return oldThisOnce(eventName, listener);
59
+ };
60
+ this.on = function(eventName, listener) {
61
+ if (eventName === REQUEST_EVENT) {
62
+ handler = listener;
63
+ return;
64
+ }
65
+ return oldThisOn(eventName, listener);
66
+ };
67
+ }
68
+ close(cb) {
69
+ uWS.us_listen_socket_close(uServer._socket);
70
+ if (!cb)
71
+ return;
72
+ return cb();
73
+ }
74
+ start(host, port, cb) {
75
+ let args;
76
+ const callbackFunction = /* @__PURE__ */ __name(function(socket) {
77
+ uServer._socket = socket;
78
+ if (cb)
79
+ cb(socket);
80
+ }, "callbackFunction");
81
+ if (host && port && cb) {
82
+ args = [
83
+ host,
84
+ port,
85
+ callbackFunction
86
+ ];
87
+ }
88
+ if (!cb && (!port || typeof port === "function")) {
89
+ cb = port;
90
+ port = host;
91
+ args = [
92
+ port,
93
+ callbackFunction
94
+ ];
95
+ }
96
+ return uServer.listen(...args);
97
+ }
98
+ listen(host, port, cb) {
99
+ if (typeof host === "object") {
100
+ const listenOptions = host;
101
+ port = listenOptions.port;
102
+ cb = listenOptions.cb;
103
+ host = listenOptions.host;
104
+ return this.start(host, port, (socket) => {
105
+ uServer._socket = socket;
106
+ if (cb)
107
+ cb(socket);
108
+ });
109
+ } else {
110
+ if ((!port || typeof port === "function") && !cb) {
111
+ cb = port;
112
+ port = host;
113
+ return this.start(port, cb);
114
+ } else {
115
+ return this.start(host, port, cb);
116
+ }
117
+ }
118
+ }
119
+ get uwsApp() {
120
+ return uServer;
121
+ }
122
+ };
123
+ const initUServer = new uServerClass();
124
+ initUServer[Symbol("IncomingMessage")] = HttpRequest;
125
+ initUServer[Symbol("ServerResponse")] = HttpResponse;
126
+ return initUServer;
127
+ }
128
+ __name(server_default, "default");
129
+ export {
130
+ server_default as default
131
+ };
@@ -1 +1,12 @@
1
- import{a}from"../../chunk-2D3NDWTU.js";import"../../chunk-2HA4XQFN.js";export{a as forEach};
1
+ import {
2
+ __name
3
+ } from "../../chunk-NH24FRB3.js";
4
+ const forEach = /* @__PURE__ */ __name((obj, cb) => {
5
+ const keys = Object.keys(obj);
6
+ for (let i = 0, length = keys.length; i < length; i++) {
7
+ cb(obj[keys[i]], keys[i]);
8
+ }
9
+ }, "forEach");
10
+ export {
11
+ forEach
12
+ };
@@ -1 +1,13 @@
1
- import{a,b}from"../../chunk-ARAMBVQ3.js";import"../../chunk-2HA4XQFN.js";export{b as toLowerCase,a as toString};
1
+ import {
2
+ __name
3
+ } from "../../chunk-NH24FRB3.js";
4
+ const toString = /* @__PURE__ */ __name((str) => {
5
+ return str + "";
6
+ }, "toString");
7
+ const toLowerCase = /* @__PURE__ */ __name((str) => {
8
+ return toString(str).toLowerCase();
9
+ }, "toLowerCase");
10
+ export {
11
+ toLowerCase,
12
+ toString
13
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "owebjs",
3
- "version": "1.0.6",
4
- "description": "",
3
+ "version": "1.1.0",
4
+ "description": "Flexible handler that built on top of Fastify",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
@@ -1 +0,0 @@
1
- import{a as n}from"./chunk-2HA4XQFN.js";var h=n((c,o)=>{let t=Object.keys(c);for(let e=0,s=t.length;e<s;e++)o(c[t[e]],t[e])},"forEach");export{h as a};
@@ -1 +0,0 @@
1
- var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};
@@ -1 +0,0 @@
1
- import{a as h}from"./chunk-2D3NDWTU.js";import{a}from"./chunk-2HA4XQFN.js";import{Readable as d}from"stream";var r=class extends d{static{a(this,"HttpRequest")}req;res;url;method;statusCode;statusMessage;body;headers;socket;constructor(s){super();let t=s.getQuery();this.req=s,this.url=s.getUrl()+(t?"?"+t:""),this.method=s.getMethod().toUpperCase(),this.statusCode=null,this.statusMessage=null,this.body={},this.headers={},this.socket={},s.forEach((e,o)=>{this.headers[e]=o})}getRawHeaders(){let s=[];return h(this.headers,(t,e)=>{s.push(t,e)}),s}getRaw(){return this.req}_read(s){return this.slice(0,s)}};export{r as a};
@@ -1 +0,0 @@
1
- import{a as s}from"./chunk-2HA4XQFN.js";var e=class{static{s(this,"HttpResponseSocket")}uResponse;constructor(r){this.uResponse=r}get remoteAddress(){return Buffer.from(this.uResponse.getRemoteAddressAsText()).toString()}destroy(){return this.uResponse.end()}};export{e as a};
@@ -1 +0,0 @@
1
- import{a as o}from"./chunk-2HA4XQFN.js";var r=o(t=>t+"","toString"),e=o(t=>r(t).toLowerCase(),"toLowerCase");export{r as a,e as b};
@@ -1 +0,0 @@
1
- import{a as d}from"./chunk-OR3GJT5E.js";import{d as u,e as m}from"./chunk-XR5MHIBF.js";import{a}from"./chunk-2HA4XQFN.js";import p from"node:path";import{dirname as R}from"node:path";import{fileURLToPath as E}from"node:url";var g=R(E(import.meta.url)),_=a(async l=>{let r=[];for(let s of l){let f=p.parse(s.rel),t=s.filePath.replaceAll("\\","/"),i=new URL(p.resolve(t),`file://${g}`).pathname.replaceAll("\\","/"),c=u(f),o=m(c),e=(await import(i)).default;r.push({url:o.url,method:o.method,fn:e,fileInfo:s})}return r},"generateRoutes"),w=a(async(l,r)=>{let s=await d(l),f=await _(s);for(let t of f)r[t.method](t.url,function(i,c){let o=new t.fn(...arguments),h=a(()=>{if(o.handle.constructor.name=="AsyncFunction")o.handle(...arguments).catch(e=>{let n=[...arguments,e];o?.handleError?o.handleError(...n):r._options.OWEB_INTERNAL_ERROR_HANDLER(...n)});else try{o.handle(...arguments)}catch(e){let n=[...arguments,e];o?.handleError?o.handleError(...n):r._options.OWEB_INTERNAL_ERROR_HANDLER(...n)}},"handle");if(t.fileInfo.hooks.length)for(let e=0;e<t.fileInfo.hooks.length;e++){let n=t.fileInfo.hooks[e];new n().handle(i,c,()=>{e+1==t.fileInfo.hooks.length&&h()})}else h()})},"assignRoutes");export{_ as a,w as b};
@@ -1 +0,0 @@
1
- import{a as c}from"./chunk-XR5MHIBF.js";import{a as l}from"./chunk-2HA4XQFN.js";import{readdirSync as k,statSync as _}from"node:fs";import a from"node:path";import{fileURLToPath as d}from"node:url";var S=a.dirname(d(import.meta.url)),v=l((s,r)=>{if(r.startsWith(s)){let e=a.relative(s,r);return e.split(a.sep).length>2||e==""||e.length>0}return!1},"isParentOrGrandparent"),p=new Set,P=l(async(s,r=[])=>{let e=[],i=k(s);i.sort((t,o)=>t.startsWith("_")&&!o.startsWith("_")?-1:!t.startsWith("_")&&o.startsWith("_")?1:t.localeCompare(o));for(let t of i){let o=a.join(s,t),h=a.resolve(s);if(t=="_hooks.js"||t=="_hooks.ts"){p.add(h);continue}if(_(o).isDirectory())e.push(...await P(o,[...r,t]));else{let u=[...p].filter(n=>v(n,h)).map(n=>new URL(n,`file://${S}`).pathname.replaceAll("\\","/")+"/_hooks.js"),f=[];for(let n of u){let m=await import(n);m?.default&&f.push(m.default)}e.push({name:t,path:s,hooks:f,rel:c(...r,t),filePath:o})}}return e},"walk");export{P as a};
@@ -1 +0,0 @@
1
- import{a as n}from"./chunk-2HA4XQFN.js";var a=n((...t)=>"/"+t.map(e=>e.replace(/^\/|\/$/g,"")).filter(e=>e!=="").join("/"),"mergePaths"),c=/\[([^}]*)\]/g,i=n(t=>c.test(t)?t.replace(c,(e,o)=>`:${o}`):t,"transformBrackets"),m=n(t=>{let e=[];for(let o of t.split("/"))e.push(i(o));return a(...e)},"convertParamSyntax"),h=n(t=>t.replace(/:\.\.\.\w+/g,"*"),"convertCatchallSyntax"),l=n(t=>{let e=t.dir===t.root?"":t.dir,o=t.name.startsWith("index")?t.name.replace("index",""):`/${t.name}`;return e+o},"buildRoutePath"),u=n(t=>{let e="get",o=m(t),r=h(o);for(let s of[".DELETE",".POST",".PATCH",".GET",".PUT"])if(t.endsWith(s)||t.endsWith(s.toLowerCase())){e=s.toLowerCase().slice(1),r=r.slice(0,r.length-s.length);break}return{url:r,method:e}},"buildRouteURL");export{a,m as b,h as c,l as d,u as e};
@@ -1 +0,0 @@
1
- import{a}from"./chunk-7JAXN5IF.js";import{b as r}from"./chunk-ARAMBVQ3.js";import{a as i}from"./chunk-2HA4XQFN.js";import{Writable as d}from"stream";var h=class extends d{static{i(this,"HttpResponse")}res;req;server;statusCode;statusMessage;__headers;headersSent;socket;finished;constructor(e,s){super(),this.res=e,this.server=s,this.statusCode=200,this.statusMessage="OK",this.__headers={},this.headersSent=!1,this.socket=new a(e),this.res.onAborted(()=>{this.finished=this.res.finished=!0})}setHeader(e,s){this.__headers[r(e)]=s}getHeaderNames(){return Object.keys(this.__headers)}getHeaders(){return Object.assign({},this.__headers)}getHeader(e){return this.__headers[r(e)]}hasHeader(e){return!!this.__headers[r(e)]}removeHeader(e){delete this.__headers[r(e)]}write(e){this.finished||this.res.write(e)}writeHead(e){if(this.finished)return;this.statusCode=e;let s;arguments.length===2?s=arguments[1]:arguments.length===3?(this.statusMessage=arguments[1],s=arguments[2]):s={},Object.keys(s).forEach(t=>{this.setHeader(t,s[t])})}end(e){if(this.finished)return;function s(t){t.res.writeStatus(`${t.statusCode} ${t.statusMessage}`),t.finished=!0,t.res.end(e)}return i(s,"doWrite"),e?s(this):(e="",s(this))}getRaw(){return this.res}};export{h as a};