zero-http 0.2.5 → 0.3.1

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.
Files changed (89) hide show
  1. package/README.md +1250 -283
  2. package/documentation/config/db.js +25 -0
  3. package/documentation/config/middleware.js +44 -0
  4. package/documentation/config/tls.js +12 -0
  5. package/documentation/controllers/cookies.js +34 -0
  6. package/documentation/controllers/tasks.js +108 -0
  7. package/documentation/full-server.js +25 -184
  8. package/documentation/models/Task.js +21 -0
  9. package/documentation/public/data/api.json +404 -24
  10. package/documentation/public/data/docs.json +1139 -0
  11. package/documentation/public/data/examples.json +80 -2
  12. package/documentation/public/data/options.json +23 -8
  13. package/documentation/public/index.html +138 -99
  14. package/documentation/public/scripts/app.js +1 -3
  15. package/documentation/public/scripts/custom-select.js +189 -0
  16. package/documentation/public/scripts/data-sections.js +233 -250
  17. package/documentation/public/scripts/playground.js +270 -0
  18. package/documentation/public/scripts/ui.js +4 -3
  19. package/documentation/public/styles.css +56 -5
  20. package/documentation/public/vendor/icons/compress.svg +17 -17
  21. package/documentation/public/vendor/icons/database.svg +21 -0
  22. package/documentation/public/vendor/icons/env.svg +21 -0
  23. package/documentation/public/vendor/icons/fetch.svg +11 -14
  24. package/documentation/public/vendor/icons/security.svg +15 -0
  25. package/documentation/public/vendor/icons/sse.svg +12 -13
  26. package/documentation/public/vendor/icons/static.svg +12 -26
  27. package/documentation/public/vendor/icons/stream.svg +7 -13
  28. package/documentation/public/vendor/icons/validate.svg +17 -0
  29. package/documentation/routes/api.js +41 -0
  30. package/documentation/routes/core.js +20 -0
  31. package/documentation/routes/playground.js +29 -0
  32. package/documentation/routes/realtime.js +49 -0
  33. package/documentation/routes/uploads.js +71 -0
  34. package/index.js +62 -1
  35. package/lib/app.js +200 -8
  36. package/lib/body/json.js +28 -5
  37. package/lib/body/multipart.js +29 -1
  38. package/lib/body/raw.js +1 -1
  39. package/lib/body/sendError.js +1 -0
  40. package/lib/body/text.js +1 -1
  41. package/lib/body/typeMatch.js +6 -2
  42. package/lib/body/urlencoded.js +5 -2
  43. package/lib/debug.js +345 -0
  44. package/lib/env/index.js +440 -0
  45. package/lib/errors.js +231 -0
  46. package/lib/http/request.js +219 -1
  47. package/lib/http/response.js +410 -6
  48. package/lib/middleware/compress.js +39 -6
  49. package/lib/middleware/cookieParser.js +237 -0
  50. package/lib/middleware/cors.js +13 -2
  51. package/lib/middleware/csrf.js +135 -0
  52. package/lib/middleware/errorHandler.js +90 -0
  53. package/lib/middleware/helmet.js +176 -0
  54. package/lib/middleware/index.js +7 -2
  55. package/lib/middleware/rateLimit.js +12 -1
  56. package/lib/middleware/requestId.js +54 -0
  57. package/lib/middleware/static.js +95 -11
  58. package/lib/middleware/timeout.js +72 -0
  59. package/lib/middleware/validator.js +257 -0
  60. package/lib/orm/adapters/json.js +215 -0
  61. package/lib/orm/adapters/memory.js +383 -0
  62. package/lib/orm/adapters/mongo.js +444 -0
  63. package/lib/orm/adapters/mysql.js +272 -0
  64. package/lib/orm/adapters/postgres.js +394 -0
  65. package/lib/orm/adapters/sql-base.js +142 -0
  66. package/lib/orm/adapters/sqlite.js +311 -0
  67. package/lib/orm/index.js +276 -0
  68. package/lib/orm/model.js +895 -0
  69. package/lib/orm/query.js +807 -0
  70. package/lib/orm/schema.js +172 -0
  71. package/lib/router/index.js +136 -47
  72. package/lib/sse/stream.js +15 -3
  73. package/lib/ws/connection.js +19 -3
  74. package/lib/ws/handshake.js +3 -0
  75. package/lib/ws/index.js +3 -1
  76. package/lib/ws/room.js +222 -0
  77. package/package.json +15 -5
  78. package/types/app.d.ts +120 -0
  79. package/types/env.d.ts +80 -0
  80. package/types/errors.d.ts +147 -0
  81. package/types/fetch.d.ts +43 -0
  82. package/types/index.d.ts +135 -0
  83. package/types/middleware.d.ts +292 -0
  84. package/types/orm.d.ts +610 -0
  85. package/types/request.d.ts +99 -0
  86. package/types/response.d.ts +142 -0
  87. package/types/router.d.ts +78 -0
  88. package/types/sse.d.ts +78 -0
  89. package/types/websocket.d.ts +119 -0
@@ -0,0 +1,135 @@
1
+ // Type definitions for zero-http
2
+ // Project: https://github.com/tonywied17/zero-http
3
+ // Definitions by: zero-http contributors
4
+
5
+ /// <reference types="node" />
6
+
7
+ // --- Re-exports from individual type modules ---------------------
8
+
9
+ export { App } from './app';
10
+ export { RouterInstance, RouteChain, RouteEntry, RouteInfo, RouteOptions, RouteHandler } from './router';
11
+ export { Request, RangeResult } from './request';
12
+ export { Response, SendFileOptions, CookieOptions } from './response';
13
+ export { SSEOptions, SSEStream } from './sse';
14
+ export { WebSocketOptions, WebSocketHandler, WebSocketConnection, WebSocketPool } from './websocket';
15
+ export {
16
+ NextFunction, MiddlewareFunction, ErrorHandlerFunction,
17
+ CorsOptions, cors,
18
+ BodyParserOptions, JsonParserOptions, UrlencodedParserOptions, TextParserOptions,
19
+ MultipartOptions, MultipartFile,
20
+ json, urlencoded, text, raw, multipart,
21
+ RateLimitOptions, rateLimit,
22
+ LoggerOptions, logger,
23
+ CompressOptions, compress,
24
+ HelmetOptions, helmet,
25
+ TimeoutOptions, timeout,
26
+ RequestIdOptions, requestId,
27
+ CookieParserStatic, cookieParser,
28
+ StaticOptions,
29
+ CsrfOptions, csrf,
30
+ ValidationRule, ValidatorSchema, ValidatorOptions, ValidateFunction, validate,
31
+ } from './middleware';
32
+ export { static } from './middleware';
33
+ export {
34
+ FetchOptions, FetchResponse, FetchHeaders, fetch,
35
+ } from './fetch';
36
+ export { Env, EnvFieldDef, EnvSchema, EnvLoadOptions, env } from './env';
37
+ export {
38
+ TYPES, SchemaColumnDef, validateValue,
39
+ Query, Model, ModelHooks, FindOrCreateResult,
40
+ Database, AdapterType,
41
+ } from './orm';
42
+ // Re-export validate from orm as schemaValidate to avoid collision with middleware validate
43
+ export { validate as schemaValidate } from './orm';
44
+ export {
45
+ HttpError, HttpErrorOptions,
46
+ BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError,
47
+ MethodNotAllowedError, ConflictError, GoneError, PayloadTooLargeError,
48
+ UnprocessableEntityError, ValidationError, TooManyRequestsError,
49
+ InternalError, NotImplementedError, BadGatewayError, ServiceUnavailableError,
50
+ createError, isHttpError,
51
+ ErrorHandlerOptions, errorHandler,
52
+ Debug, DebugLogger, DebugLevels, debug,
53
+ } from './errors';
54
+
55
+ // --- Module Exports ----------------------------------------------
56
+
57
+ import { App } from './app';
58
+ import { RouterInstance } from './router';
59
+ import { WebSocketConnection, WebSocketPool } from './websocket';
60
+ import { SSEStream } from './sse';
61
+ import {
62
+ cors, json, urlencoded, text, raw, multipart,
63
+ rateLimit, logger, compress, helmet, timeout, requestId,
64
+ CookieParserStatic, csrf, ValidateFunction,
65
+ } from './middleware';
66
+ import { fetch } from './fetch';
67
+ import { Env } from './env';
68
+ import { Database, Model, Query } from './orm';
69
+ import { TYPES } from './orm';
70
+ import {
71
+ HttpError, BadRequestError, UnauthorizedError, ForbiddenError,
72
+ NotFoundError, MethodNotAllowedError, ConflictError, GoneError,
73
+ PayloadTooLargeError, UnprocessableEntityError, ValidationError,
74
+ TooManyRequestsError, InternalError, NotImplementedError,
75
+ BadGatewayError, ServiceUnavailableError,
76
+ createError, isHttpError, errorHandler, debug,
77
+ } from './errors';
78
+
79
+ declare function serveStatic(root: string, options?: import('./middleware').StaticOptions): import('./middleware').MiddlewareFunction;
80
+
81
+ declare const zeroServer: {
82
+ createApp(): App;
83
+ Router(): RouterInstance;
84
+ cors: typeof cors;
85
+ fetch: typeof fetch;
86
+ json: typeof json;
87
+ urlencoded: typeof urlencoded;
88
+ text: typeof text;
89
+ raw: typeof raw;
90
+ multipart: typeof multipart;
91
+ static: typeof serveStatic;
92
+ rateLimit: typeof rateLimit;
93
+ logger: typeof logger;
94
+ compress: typeof compress;
95
+ helmet: typeof helmet;
96
+ timeout: typeof timeout;
97
+ requestId: typeof requestId;
98
+ cookieParser: CookieParserStatic;
99
+ csrf: typeof csrf;
100
+ validate: ValidateFunction;
101
+ env: Env;
102
+ Database: typeof Database;
103
+ Model: typeof Model;
104
+ TYPES: typeof TYPES;
105
+ Query: typeof Query;
106
+ // Error handling & debugging
107
+ HttpError: typeof HttpError;
108
+ BadRequestError: typeof BadRequestError;
109
+ UnauthorizedError: typeof UnauthorizedError;
110
+ ForbiddenError: typeof ForbiddenError;
111
+ NotFoundError: typeof NotFoundError;
112
+ MethodNotAllowedError: typeof MethodNotAllowedError;
113
+ ConflictError: typeof ConflictError;
114
+ GoneError: typeof GoneError;
115
+ PayloadTooLargeError: typeof PayloadTooLargeError;
116
+ UnprocessableEntityError: typeof UnprocessableEntityError;
117
+ ValidationError: typeof ValidationError;
118
+ TooManyRequestsError: typeof TooManyRequestsError;
119
+ InternalError: typeof InternalError;
120
+ NotImplementedError: typeof NotImplementedError;
121
+ BadGatewayError: typeof BadGatewayError;
122
+ ServiceUnavailableError: typeof ServiceUnavailableError;
123
+ createError: typeof createError;
124
+ isHttpError: typeof isHttpError;
125
+ errorHandler: typeof errorHandler;
126
+ debug: typeof debug;
127
+ // classes
128
+ WebSocketConnection: WebSocketConnection;
129
+ WebSocketPool: {
130
+ new(): WebSocketPool;
131
+ };
132
+ SSEStream: SSEStream;
133
+ };
134
+
135
+ export = zeroServer;
@@ -0,0 +1,292 @@
1
+ import { Request } from './request';
2
+ import { Response } from './response';
3
+
4
+ // --- Core Types --------------------------------------------------
5
+
6
+ export type NextFunction = (err?: any) => void;
7
+ export type MiddlewareFunction = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
8
+ export type ErrorHandlerFunction = (err: any, req: Request, res: Response, next: NextFunction) => void;
9
+
10
+ // --- CORS --------------------------------------------------------
11
+
12
+ export interface CorsOptions {
13
+ origin?: string | string[];
14
+ methods?: string;
15
+ allowedHeaders?: string;
16
+ exposedHeaders?: string;
17
+ credentials?: boolean;
18
+ maxAge?: number;
19
+ }
20
+
21
+ export function cors(options?: CorsOptions): MiddlewareFunction;
22
+
23
+ // --- Body Parsers ------------------------------------------------
24
+
25
+ export interface BodyParserOptions {
26
+ /** Max body size (e.g. '10kb', '1mb'). Default: '1mb'. */
27
+ limit?: string | number;
28
+ /** Content-Type to match. */
29
+ type?: string | ((ct: string) => boolean);
30
+ /** Reject non-HTTPS requests with 403. */
31
+ requireSecure?: boolean;
32
+ }
33
+
34
+ export interface JsonParserOptions extends BodyParserOptions {
35
+ /** JSON.parse reviver function. */
36
+ reviver?: (key: string, value: any) => any;
37
+ /** Reject non-object/array roots. Default: true. */
38
+ strict?: boolean;
39
+ }
40
+
41
+ export interface UrlencodedParserOptions extends BodyParserOptions {
42
+ /** Enable nested bracket parsing. Default: false. */
43
+ extended?: boolean;
44
+ }
45
+
46
+ export interface TextParserOptions extends BodyParserOptions {
47
+ /** Character encoding. Default: 'utf8'. */
48
+ encoding?: BufferEncoding;
49
+ }
50
+
51
+ export interface MultipartOptions {
52
+ /** Upload directory (default: OS temp). */
53
+ dir?: string;
54
+ /** Maximum file size in bytes. */
55
+ maxFileSize?: number;
56
+ /** Reject non-HTTPS requests with 403. */
57
+ requireSecure?: boolean;
58
+ }
59
+
60
+ export interface MultipartFile {
61
+ originalFilename: string;
62
+ storedName: string;
63
+ path: string;
64
+ contentType: string;
65
+ size: number;
66
+ }
67
+
68
+ export function json(options?: JsonParserOptions): MiddlewareFunction;
69
+ export function urlencoded(options?: UrlencodedParserOptions): MiddlewareFunction;
70
+ export function text(options?: TextParserOptions): MiddlewareFunction;
71
+ export function raw(options?: BodyParserOptions): MiddlewareFunction;
72
+ export function multipart(options?: MultipartOptions): MiddlewareFunction;
73
+
74
+ // --- Rate Limiting -----------------------------------------------
75
+
76
+ export interface RateLimitOptions {
77
+ /** Time window in ms. Default: 60000. */
78
+ windowMs?: number;
79
+ /** Max requests per window per IP. Default: 100. */
80
+ max?: number;
81
+ /** Custom error message. */
82
+ message?: string;
83
+ /** HTTP status for rate-limited responses. Default: 429. */
84
+ statusCode?: number;
85
+ /** Custom key extraction function. */
86
+ keyGenerator?: (req: Request) => string;
87
+ }
88
+
89
+ export function rateLimit(opts?: RateLimitOptions): MiddlewareFunction;
90
+
91
+ // --- Logger ------------------------------------------------------
92
+
93
+ export interface LoggerOptions {
94
+ /** Custom log function. Default: console.log. */
95
+ logger?: (...args: any[]) => void;
96
+ /** Colorize output. Default: true when TTY. */
97
+ colors?: boolean;
98
+ /** Format: 'tiny' | 'short' | 'dev'. Default: 'dev'. */
99
+ format?: 'tiny' | 'short' | 'dev';
100
+ }
101
+
102
+ export function logger(opts?: LoggerOptions): MiddlewareFunction;
103
+
104
+ // --- Compression -------------------------------------------------
105
+
106
+ export interface CompressOptions {
107
+ /** Minimum body size to compress. Default: 1024. */
108
+ threshold?: number;
109
+ /** Compression level. */
110
+ level?: number;
111
+ /** Force specific encoding(s). */
112
+ encoding?: string | string[];
113
+ /** Filter function — return false to skip compression. */
114
+ filter?: (req: Request, res: Response) => boolean;
115
+ }
116
+
117
+ export function compress(opts?: CompressOptions): MiddlewareFunction;
118
+
119
+ // --- Helmet (Security Headers) ----------------------------------
120
+
121
+ export interface HelmetOptions {
122
+ /** CSP directive object or `false` to disable. */
123
+ contentSecurityPolicy?: { directives?: Record<string, string[]> } | false;
124
+ /** Set COEP header. Default: false. */
125
+ crossOriginEmbedderPolicy?: boolean;
126
+ /** COOP value. Default: 'same-origin'. */
127
+ crossOriginOpenerPolicy?: string | false;
128
+ /** CORP value. Default: 'same-origin'. */
129
+ crossOriginResourcePolicy?: string | false;
130
+ /** Set X-DNS-Prefetch-Control. Default: true. */
131
+ dnsPrefetchControl?: boolean | false;
132
+ /** X-Frame-Options value. Default: 'deny'. */
133
+ frameguard?: 'deny' | 'sameorigin' | false;
134
+ /** Remove X-Powered-By. Default: true. */
135
+ hidePoweredBy?: boolean;
136
+ /** Set HSTS. Default: true. */
137
+ hsts?: boolean | false;
138
+ /** HSTS max-age in seconds. Default: 15552000. */
139
+ hstsMaxAge?: number;
140
+ /** HSTS includeSubDomains. Default: true. */
141
+ hstsIncludeSubDomains?: boolean;
142
+ /** HSTS preload. Default: false. */
143
+ hstsPreload?: boolean;
144
+ /** Set X-Download-Options. Default: true. */
145
+ ieNoOpen?: boolean;
146
+ /** Set X-Content-Type-Options: nosniff. Default: true. */
147
+ noSniff?: boolean;
148
+ /** X-Permitted-Cross-Domain-Policies. Default: 'none'. */
149
+ permittedCrossDomainPolicies?: string | false;
150
+ /** Referrer-Policy value. Default: 'no-referrer'. */
151
+ referrerPolicy?: string | false;
152
+ /** Set legacy X-XSS-Protection. Default: false. */
153
+ xssFilter?: boolean;
154
+ }
155
+
156
+ export function helmet(opts?: HelmetOptions): MiddlewareFunction;
157
+
158
+ // --- Timeout -----------------------------------------------------
159
+
160
+ export interface TimeoutOptions {
161
+ /** HTTP status code for timeout responses. Default: 408. */
162
+ status?: number;
163
+ /** Error message body. Default: 'Request Timeout'. */
164
+ message?: string;
165
+ }
166
+
167
+ export function timeout(ms?: number, opts?: TimeoutOptions): MiddlewareFunction;
168
+
169
+ // --- Request ID --------------------------------------------------
170
+
171
+ export interface RequestIdOptions {
172
+ /** Response header name. Default: 'X-Request-Id'. */
173
+ header?: string;
174
+ /** Custom ID generator. */
175
+ generator?: () => string;
176
+ /** Trust incoming X-Request-Id. Default: false. */
177
+ trustProxy?: boolean;
178
+ }
179
+
180
+ export function requestId(opts?: RequestIdOptions): MiddlewareFunction;
181
+
182
+ // --- Cookie Parser -----------------------------------------------
183
+
184
+ export interface CookieParserStatic {
185
+ (secret?: string | string[], opts?: { decode?: boolean }): MiddlewareFunction;
186
+ /** Sign a value with a secret. */
187
+ sign(val: string, secret: string): string;
188
+ /** Unsign a signed value against one or more secrets. Returns the original value or false. */
189
+ unsign(val: string, secrets: string | string[]): string | false;
190
+ /** Parse a single JSON cookie value (j: prefix). Returns parsed object or original string. */
191
+ jsonCookie(str: string): any;
192
+ /** Parse all string values in an object as JSON cookies. */
193
+ parseJSON(obj: Record<string, any>): Record<string, any>;
194
+ }
195
+
196
+ export const cookieParser: CookieParserStatic;
197
+
198
+ // --- Static File Serving -----------------------------------------
199
+
200
+ export interface StaticOptions {
201
+ /** Default file for directories. Default: 'index.html'. */
202
+ index?: string | false;
203
+ /** Cache-Control max-age in ms. Default: 0. */
204
+ maxAge?: number;
205
+ /** Dotfile policy: 'allow' | 'deny' | 'ignore'. Default: 'ignore'. */
206
+ dotfiles?: 'allow' | 'deny' | 'ignore';
207
+ /** Fallback extensions. */
208
+ extensions?: string[];
209
+ /** Custom header hook. */
210
+ setHeaders?: (res: Response, filePath: string) => void;
211
+ }
212
+
213
+ declare function serveStatic(root: string, options?: StaticOptions): MiddlewareFunction;
214
+ export { serveStatic as static };
215
+
216
+ // --- CSRF Protection ---------------------------------------------
217
+
218
+ export interface CsrfOptions {
219
+ /** Double-submit cookie name. Default: '_csrf'. */
220
+ cookie?: string;
221
+ /** Request header name for the token. Default: 'x-csrf-token'. */
222
+ header?: string;
223
+ /** Bytes of randomness for token generation. Default: 18. */
224
+ saltLength?: number;
225
+ /** HMAC secret. Auto-generated if not provided. */
226
+ secret?: string;
227
+ /** HTTP methods to skip CSRF checks. Default: ['GET', 'HEAD', 'OPTIONS']. */
228
+ ignoreMethods?: string[];
229
+ /** Path prefixes to skip CSRF checks. */
230
+ ignorePaths?: string[];
231
+ /** Custom error handler. Default: sends 403 JSON. */
232
+ onError?: (req: Request, res: Response) => void;
233
+ }
234
+
235
+ export function csrf(options?: CsrfOptions): MiddlewareFunction;
236
+
237
+ // --- Request Validator -------------------------------------------
238
+
239
+ export interface ValidationRule {
240
+ /** Type with coercion. */
241
+ type?: 'string' | 'integer' | 'number' | 'float' | 'boolean' | 'array' | 'json' | 'date' | 'uuid' | 'email' | 'url';
242
+ /** Field is required. */
243
+ required?: boolean;
244
+ /** Default value or factory function. */
245
+ default?: any | (() => any);
246
+ /** Minimum string length. */
247
+ minLength?: number;
248
+ /** Maximum string length. */
249
+ maxLength?: number;
250
+ /** Minimum numeric value. */
251
+ min?: number;
252
+ /** Maximum numeric value. */
253
+ max?: number;
254
+ /** Pattern match constraint. */
255
+ match?: RegExp;
256
+ /** Allowed values. */
257
+ enum?: any[];
258
+ /** Minimum array length. */
259
+ minItems?: number;
260
+ /** Maximum array length. */
261
+ maxItems?: number;
262
+ /** Custom validation function. Return a string to indicate an error. */
263
+ validate?: (value: any) => string | void;
264
+ }
265
+
266
+ export interface ValidatorSchema {
267
+ /** Rules for `req.body` fields. */
268
+ body?: Record<string, ValidationRule>;
269
+ /** Rules for `req.query` fields. */
270
+ query?: Record<string, ValidationRule>;
271
+ /** Rules for `req.params` fields. */
272
+ params?: Record<string, ValidationRule>;
273
+ }
274
+
275
+ export interface ValidatorOptions {
276
+ /** Remove fields not in schema. Default: true. */
277
+ stripUnknown?: boolean;
278
+ /** Custom error handler. Default: sends 422 JSON. */
279
+ onError?: (errors: string[], req: Request, res: Response) => void;
280
+ }
281
+
282
+ export interface ValidateFunction {
283
+ (schema: ValidatorSchema, options?: ValidatorOptions): MiddlewareFunction;
284
+
285
+ /** Validate a single field value against a rule. */
286
+ field(value: any, rule: ValidationRule, field: string): { value: any; error: string | null };
287
+
288
+ /** Validate an object against a schema. */
289
+ object(data: object, schema: Record<string, ValidationRule>, opts?: { stripUnknown?: boolean }): { sanitized: object; errors: string[] };
290
+ }
291
+
292
+ export const validate: ValidateFunction;