@gravito/core 1.2.0 → 1.6.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,357 @@
1
+ /**
2
+ * @fileoverview Core HTTP Types for Gravito Framework
3
+ *
4
+ * These types provide a unified abstraction layer that decouples the framework
5
+ * from any specific HTTP engine (Photon, Express, custom, etc.).
6
+ *
7
+ * @module @gravito/core/http
8
+ * @since 2.0.0
9
+ */
10
+ declare global {
11
+ interface ExecutionContext {
12
+ waitUntil(promise: Promise<unknown>): void;
13
+ passThroughOnException(): void;
14
+ }
15
+ }
16
+ /**
17
+ * Standard HTTP methods supported by Gravito
18
+ */
19
+ type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
20
+ /**
21
+ * HTTP status codes
22
+ */
23
+ type StatusCode = number;
24
+ /**
25
+ * Content-bearing HTTP status codes (excludes 1xx, 204, 304)
26
+ */
27
+ type ContentfulStatusCode = Exclude<StatusCode, 100 | 101 | 102 | 103 | 204 | 304>;
28
+ /**
29
+ * Base context variables available in every request
30
+ * Orbits can extend this interface via module augmentation
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // Extending variables in your orbit:
35
+ * declare module '@gravito/core' {
36
+ * interface GravitoVariables {
37
+ * myService: MyService
38
+ * }
39
+ * }
40
+ * ```
41
+ */
42
+ interface GravitoVariables {
43
+ /**
44
+ * The PlanetCore instance
45
+ * @remarks Always available in PlanetCore-managed contexts
46
+ */
47
+ core?: unknown;
48
+ /**
49
+ * Logger instance
50
+ */
51
+ logger?: unknown;
52
+ /**
53
+ * Configuration manager
54
+ */
55
+ config?: unknown;
56
+ /**
57
+ * Cookie jar for managing response cookies
58
+ */
59
+ cookieJar?: unknown;
60
+ /**
61
+ * Middleware scope tracking for Orbit isolation
62
+ * Tracks which Orbit/scope this request belongs to
63
+ * Used to prevent cross-Orbit middleware contamination
64
+ * @since 2.3.0
65
+ */
66
+ middlewareScope?: string;
67
+ /** @deprecated Use ctx.route() instead */
68
+ route?: unknown;
69
+ [key: string]: unknown;
70
+ }
71
+ /**
72
+ * Validated request data targets
73
+ */
74
+ type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form' | 'cookie';
75
+ /**
76
+ * GravitoRequest - Unified request interface
77
+ *
78
+ * Provides a consistent API for accessing request data regardless of
79
+ * the underlying HTTP engine.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const userId = ctx.req.param('id')
84
+ * const search = ctx.req.query('q')
85
+ * const body = await ctx.req.json<CreateUserDto>()
86
+ * ```
87
+ */
88
+ interface GravitoRequest {
89
+ /** Full request URL */
90
+ readonly url: string;
91
+ /** HTTP method (uppercase) */
92
+ readonly method: string;
93
+ /** Request path without query string */
94
+ readonly path: string;
95
+ /**
96
+ * Route pattern (e.g., /users/:id) for the matched route
97
+ *
98
+ * This provides the parameterized route pattern instead of the concrete path,
99
+ * which is critical for preventing high cardinality issues in metrics systems.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * // For request: GET /users/123
104
+ * ctx.req.path // => "/users/123"
105
+ * ctx.req.routePattern // => "/users/:id"
106
+ * ```
107
+ */
108
+ readonly routePattern?: string;
109
+ /**
110
+ * Get a route parameter value
111
+ * @param name - Parameter name (e.g., 'id' for route '/users/:id')
112
+ */
113
+ param(name: string): string | undefined;
114
+ /**
115
+ * Get all route parameters
116
+ */
117
+ params(): Record<string, string>;
118
+ /**
119
+ * Get a query string parameter
120
+ * @param name - Query parameter name
121
+ */
122
+ query(name: string): string | undefined;
123
+ /**
124
+ * Get all query parameters
125
+ */
126
+ queries(): Record<string, string | string[]>;
127
+ /**
128
+ * Get a request header value
129
+ * @param name - Header name (case-insensitive)
130
+ */
131
+ header(name: string): string | undefined;
132
+ /**
133
+ * Get all request headers
134
+ */
135
+ header(): Record<string, string>;
136
+ /**
137
+ * Parse request body as JSON
138
+ * @throws {Error} If body is not valid JSON
139
+ */
140
+ json<T = unknown>(): Promise<T>;
141
+ /**
142
+ * Parse request body as text
143
+ */
144
+ text(): Promise<string>;
145
+ /**
146
+ * Parse request body as FormData
147
+ */
148
+ formData(): Promise<FormData>;
149
+ /**
150
+ * Parse request body as ArrayBuffer
151
+ */
152
+ arrayBuffer(): Promise<ArrayBuffer>;
153
+ /**
154
+ * Parse form data (urlencoded or multipart)
155
+ */
156
+ parseBody<T = unknown>(): Promise<T>;
157
+ /**
158
+ * Get the raw Request object
159
+ */
160
+ readonly raw: Request;
161
+ /**
162
+ * Get validated data from a specific source
163
+ * @param target - The validation target
164
+ * @throws {Error} If validation was not performed for this target
165
+ */
166
+ valid<T = unknown>(target: ValidationTarget): T;
167
+ }
168
+ /**
169
+ * Options for request forwarding (Proxy)
170
+ */
171
+ interface ProxyOptions {
172
+ /** Override or add request headers */
173
+ headers?: Record<string, string>;
174
+ /** Whether to keep the original Host header (default: false) */
175
+ preserveHost?: boolean;
176
+ /** Whether to add X-Forwarded-* headers (default: true) */
177
+ addForwardedHeaders?: boolean;
178
+ /** Path rewriting logic */
179
+ rewritePath?: (path: string) => string;
180
+ }
181
+ /**
182
+ * GravitoContext - Unified request context
183
+ *
184
+ * This interface encapsulates all HTTP request/response operations,
185
+ * enabling seamless replacement of the underlying HTTP engine.
186
+ *
187
+ * @typeParam V - Context variables type
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * // In a controller
192
+ * async show(ctx: GravitoContext) {
193
+ * const id = ctx.req.param('id')
194
+ * const user = await User.find(id)
195
+ * return ctx.json({ user })
196
+ * }
197
+ * ```
198
+ */
199
+ interface GravitoContext<V extends GravitoVariables = GravitoVariables> {
200
+ /** The incoming request */
201
+ readonly req: GravitoRequest;
202
+ /**
203
+ * Send a JSON response
204
+ * @param data - Data to serialize as JSON
205
+ * @param status - HTTP status code (default: 200)
206
+ */
207
+ json<T>(data: T, status?: ContentfulStatusCode): Response;
208
+ /**
209
+ * Send a plain text response
210
+ * @param text - Text content
211
+ * @param status - HTTP status code (default: 200)
212
+ */
213
+ text(text: string, status?: ContentfulStatusCode): Response;
214
+ /**
215
+ * Send an HTML response
216
+ * @param html - HTML content
217
+ * @param status - HTTP status code (default: 200)
218
+ */
219
+ html(html: string, status?: ContentfulStatusCode): Response;
220
+ /**
221
+ * Send a redirect response
222
+ * @param url - Target URL
223
+ * @param status - Redirect status code (default: 302)
224
+ */
225
+ redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
226
+ /**
227
+ * Create a Response with no body
228
+ * @param status - HTTP status code
229
+ */
230
+ body(data: BodyInit | null, status?: StatusCode): Response;
231
+ /**
232
+ * Stream a response
233
+ * @param stream - ReadableStream to send
234
+ * @param status - HTTP status code (default: 200)
235
+ */
236
+ stream(stream: ReadableStream, status?: ContentfulStatusCode): Response;
237
+ /**
238
+ * Send a 404 Not Found response
239
+ */
240
+ notFound(message?: string): Response;
241
+ /**
242
+ * Send a 403 Forbidden response
243
+ */
244
+ forbidden(message?: string): Response;
245
+ /**
246
+ * Send a 401 Unauthorized response
247
+ */
248
+ unauthorized(message?: string): Response;
249
+ /**
250
+ * Send a 400 Bad Request response
251
+ */
252
+ badRequest(message?: string): Response;
253
+ /**
254
+ * Forward the current request to another URL (Reverse Proxy)
255
+ * @param target - Target URL or base URL to forward to
256
+ * @param options - Optional proxy options
257
+ */
258
+ forward(target: string, options?: ProxyOptions): Promise<Response>;
259
+ /**
260
+ * Set a response header
261
+ * @param name - Header name
262
+ * @param value - Header value
263
+ * @param options - Options (append: true to add multiple values)
264
+ */
265
+ header(name: string, value: string, options?: {
266
+ append?: boolean;
267
+ }): void;
268
+ /**
269
+ * Get a request header
270
+ * @param name - Header name (case-insensitive)
271
+ */
272
+ header(name: string): string | undefined;
273
+ /**
274
+ * Set the response status code
275
+ * @param code - HTTP status code
276
+ */
277
+ status(code: StatusCode): void;
278
+ /**
279
+ * Get a context variable
280
+ * @param key - Variable key
281
+ */
282
+ get<K extends keyof V>(key: K): V[K];
283
+ /**
284
+ * Set a context variable
285
+ * @param key - Variable key
286
+ * @param value - Variable value
287
+ */
288
+ set<K extends keyof V>(key: K, value: V[K]): void;
289
+ /**
290
+ * Get the execution context (for Cloudflare Workers, etc.)
291
+ */
292
+ readonly executionCtx?: ExecutionContext;
293
+ /**
294
+ * Get environment bindings (for Cloudflare Workers, etc.)
295
+ */
296
+ readonly env?: Record<string, unknown>;
297
+ /**
298
+ * URL generator helper.
299
+ * Generates a URL for a named route.
300
+ */
301
+ route: (name: string, params?: Record<string, any>, query?: Record<string, any>) => string;
302
+ /**
303
+ * Access the native context object from the underlying HTTP engine.
304
+ *
305
+ * ⚠️ WARNING: Using this ties your code to a specific adapter.
306
+ * Prefer using the abstraction methods when possible.
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * // Only when absolutely necessary
311
+ * const photonCtx = ctx.native as Context // Photon Context
312
+ * ```
313
+ */
314
+ readonly native: unknown;
315
+ }
316
+ /**
317
+ * Next function for middleware chain
318
+ */
319
+ type GravitoNext = () => Promise<Response | undefined>;
320
+ /**
321
+ * GravitoHandler - Standard route handler type
322
+ *
323
+ * @typeParam V - Context variables type
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * const handler: GravitoHandler = async (ctx) => {
328
+ * return ctx.json({ message: 'Hello, World!' })
329
+ * }
330
+ * ```
331
+ */
332
+ type GravitoHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
333
+ /**
334
+ * GravitoMiddleware - Standard middleware type
335
+ *
336
+ * @typeParam V - Context variables type
337
+ *
338
+ * @example
339
+ * ```typescript
340
+ * const logger: GravitoMiddleware = async (ctx, next) => {
341
+ * console.log(`${ctx.req.method} ${ctx.req.path}`)
342
+ * await next()
343
+ * return undefined
344
+ * }
345
+ * ```
346
+ */
347
+ type GravitoMiddleware<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>, next: GravitoNext) => Response | undefined | Promise<Response | undefined | undefined>;
348
+ /**
349
+ * Error handler type
350
+ */
351
+ type GravitoErrorHandler<V extends GravitoVariables = GravitoVariables> = (error: Error, ctx: GravitoContext<V>) => Response | Promise<Response>;
352
+ /**
353
+ * Not found handler type
354
+ */
355
+ type GravitoNotFoundHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
356
+
357
+ export type { ContentfulStatusCode as C, GravitoVariables as G, HttpMethod as H, ProxyOptions as P, StatusCode as S, ValidationTarget as V, GravitoHandler as a, GravitoMiddleware as b, GravitoErrorHandler as c, GravitoNotFoundHandler as d, GravitoContext as e, GravitoRequest as f, GravitoNext as g };
package/dist/compat.d.cts CHANGED
@@ -1,314 +1 @@
1
- /**
2
- * @fileoverview Core HTTP Types for Gravito Framework
3
- *
4
- * These types provide a unified abstraction layer that decouples the framework
5
- * from any specific HTTP engine (Photon, Express, custom, etc.).
6
- *
7
- * @module @gravito/core/http
8
- * @since 2.0.0
9
- */
10
- declare global {
11
- interface ExecutionContext {
12
- waitUntil(promise: Promise<unknown>): void;
13
- passThroughOnException(): void;
14
- }
15
- }
16
- /**
17
- * Standard HTTP methods supported by Gravito
18
- */
19
- type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
20
- /**
21
- * HTTP status codes
22
- */
23
- type StatusCode = number;
24
- /**
25
- * Content-bearing HTTP status codes (excludes 1xx, 204, 304)
26
- */
27
- type ContentfulStatusCode = Exclude<StatusCode, 100 | 101 | 102 | 103 | 204 | 304>;
28
- /**
29
- * Base context variables available in every request
30
- * Orbits can extend this interface via module augmentation
31
- *
32
- * @example
33
- * ```typescript
34
- * // Extending variables in your orbit:
35
- * declare module '@gravito/core' {
36
- * interface GravitoVariables {
37
- * myService: MyService
38
- * }
39
- * }
40
- * ```
41
- */
42
- interface GravitoVariables {
43
- /**
44
- * The PlanetCore instance
45
- * @remarks Always available in PlanetCore-managed contexts
46
- */
47
- core?: unknown;
48
- /**
49
- * Logger instance
50
- */
51
- logger?: unknown;
52
- /**
53
- * Configuration manager
54
- */
55
- config?: unknown;
56
- /**
57
- * Cookie jar for managing response cookies
58
- */
59
- cookieJar?: unknown;
60
- /**
61
- * URL generator helper
62
- */
63
- route?: (name: string, params?: Record<string, unknown>, query?: Record<string, unknown>) => string;
64
- [key: string]: unknown;
65
- }
66
- /**
67
- * Validated request data targets
68
- */
69
- type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form' | 'cookie';
70
- /**
71
- * GravitoRequest - Unified request interface
72
- *
73
- * Provides a consistent API for accessing request data regardless of
74
- * the underlying HTTP engine.
75
- *
76
- * @example
77
- * ```typescript
78
- * const userId = ctx.req.param('id')
79
- * const search = ctx.req.query('q')
80
- * const body = await ctx.req.json<CreateUserDto>()
81
- * ```
82
- */
83
- interface GravitoRequest {
84
- /** Full request URL */
85
- readonly url: string;
86
- /** HTTP method (uppercase) */
87
- readonly method: string;
88
- /** Request path without query string */
89
- readonly path: string;
90
- /**
91
- * Get a route parameter value
92
- * @param name - Parameter name (e.g., 'id' for route '/users/:id')
93
- */
94
- param(name: string): string | undefined;
95
- /**
96
- * Get all route parameters
97
- */
98
- params(): Record<string, string>;
99
- /**
100
- * Get a query string parameter
101
- * @param name - Query parameter name
102
- */
103
- query(name: string): string | undefined;
104
- /**
105
- * Get all query parameters
106
- */
107
- queries(): Record<string, string | string[]>;
108
- /**
109
- * Get a request header value
110
- * @param name - Header name (case-insensitive)
111
- */
112
- header(name: string): string | undefined;
113
- /**
114
- * Get all request headers
115
- */
116
- header(): Record<string, string>;
117
- /**
118
- * Parse request body as JSON
119
- * @throws {Error} If body is not valid JSON
120
- */
121
- json<T = unknown>(): Promise<T>;
122
- /**
123
- * Parse request body as text
124
- */
125
- text(): Promise<string>;
126
- /**
127
- * Parse request body as FormData
128
- */
129
- formData(): Promise<FormData>;
130
- /**
131
- * Parse request body as ArrayBuffer
132
- */
133
- arrayBuffer(): Promise<ArrayBuffer>;
134
- /**
135
- * Parse form data (urlencoded or multipart)
136
- */
137
- parseBody<T = unknown>(): Promise<T>;
138
- /**
139
- * Get the raw Request object
140
- */
141
- readonly raw: Request;
142
- /**
143
- * Get validated data from a specific source
144
- * @param target - The validation target
145
- * @throws {Error} If validation was not performed for this target
146
- */
147
- valid<T = unknown>(target: ValidationTarget): T;
148
- }
149
- /**
150
- * GravitoContext - Unified request context
151
- *
152
- * This interface encapsulates all HTTP request/response operations,
153
- * enabling seamless replacement of the underlying HTTP engine.
154
- *
155
- * @typeParam V - Context variables type
156
- *
157
- * @example
158
- * ```typescript
159
- * // In a controller
160
- * async show(ctx: GravitoContext) {
161
- * const id = ctx.req.param('id')
162
- * const user = await User.find(id)
163
- * return ctx.json({ user })
164
- * }
165
- * ```
166
- */
167
- interface GravitoContext<V extends GravitoVariables = GravitoVariables> {
168
- /** The incoming request */
169
- readonly req: GravitoRequest;
170
- /**
171
- * Send a JSON response
172
- * @param data - Data to serialize as JSON
173
- * @param status - HTTP status code (default: 200)
174
- */
175
- json<T>(data: T, status?: ContentfulStatusCode): Response;
176
- /**
177
- * Send a plain text response
178
- * @param text - Text content
179
- * @param status - HTTP status code (default: 200)
180
- */
181
- text(text: string, status?: ContentfulStatusCode): Response;
182
- /**
183
- * Send an HTML response
184
- * @param html - HTML content
185
- * @param status - HTTP status code (default: 200)
186
- */
187
- html(html: string, status?: ContentfulStatusCode): Response;
188
- /**
189
- * Send a redirect response
190
- * @param url - Target URL
191
- * @param status - Redirect status code (default: 302)
192
- */
193
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
194
- /**
195
- * Create a Response with no body
196
- * @param status - HTTP status code
197
- */
198
- body(data: BodyInit | null, status?: StatusCode): Response;
199
- /**
200
- * Stream a response
201
- * @param stream - ReadableStream to send
202
- * @param status - HTTP status code (default: 200)
203
- */
204
- stream(stream: ReadableStream, status?: ContentfulStatusCode): Response;
205
- /**
206
- * Send a 404 Not Found response
207
- */
208
- notFound(message?: string): Response;
209
- /**
210
- * Send a 403 Forbidden response
211
- */
212
- forbidden(message?: string): Response;
213
- /**
214
- * Send a 401 Unauthorized response
215
- */
216
- unauthorized(message?: string): Response;
217
- /**
218
- * Send a 400 Bad Request response
219
- */
220
- badRequest(message?: string): Response;
221
- /**
222
- * Set a response header
223
- * @param name - Header name
224
- * @param value - Header value
225
- * @param options - Options (append: true to add multiple values)
226
- */
227
- header(name: string, value: string, options?: {
228
- append?: boolean;
229
- }): void;
230
- /**
231
- * Get a request header
232
- * @param name - Header name (case-insensitive)
233
- */
234
- header(name: string): string | undefined;
235
- /**
236
- * Set the response status code
237
- * @param code - HTTP status code
238
- */
239
- status(code: StatusCode): void;
240
- /**
241
- * Get a context variable
242
- * @param key - Variable key
243
- */
244
- get<K extends keyof V>(key: K): V[K];
245
- /**
246
- * Set a context variable
247
- * @param key - Variable key
248
- * @param value - Variable value
249
- */
250
- set<K extends keyof V>(key: K, value: V[K]): void;
251
- /**
252
- * Get the execution context (for Cloudflare Workers, etc.)
253
- */
254
- readonly executionCtx?: ExecutionContext;
255
- /**
256
- * Get environment bindings (for Cloudflare Workers, etc.)
257
- */
258
- readonly env?: Record<string, unknown>;
259
- /**
260
- * Access the native context object from the underlying HTTP engine.
261
- *
262
- * ⚠️ WARNING: Using this ties your code to a specific adapter.
263
- * Prefer using the abstraction methods when possible.
264
- *
265
- * @example
266
- * ```typescript
267
- * // Only when absolutely necessary
268
- * const photonCtx = ctx.native as Context // Photon Context
269
- * ```
270
- */
271
- readonly native: unknown;
272
- }
273
- /**
274
- * Next function for middleware chain
275
- */
276
- type GravitoNext = () => Promise<Response | undefined>;
277
- /**
278
- * GravitoHandler - Standard route handler type
279
- *
280
- * @typeParam V - Context variables type
281
- *
282
- * @example
283
- * ```typescript
284
- * const handler: GravitoHandler = async (ctx) => {
285
- * return ctx.json({ message: 'Hello, World!' })
286
- * }
287
- * ```
288
- */
289
- type GravitoHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
290
- /**
291
- * GravitoMiddleware - Standard middleware type
292
- *
293
- * @typeParam V - Context variables type
294
- *
295
- * @example
296
- * ```typescript
297
- * const logger: GravitoMiddleware = async (ctx, next) => {
298
- * console.log(`${ctx.req.method} ${ctx.req.path}`)
299
- * await next()
300
- * return undefined
301
- * }
302
- * ```
303
- */
304
- type GravitoMiddleware<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>, next: GravitoNext) => Response | undefined | Promise<Response | undefined | undefined>;
305
- /**
306
- * Error handler type
307
- */
308
- type GravitoErrorHandler<V extends GravitoVariables = GravitoVariables> = (error: Error, ctx: GravitoContext<V>) => Response | Promise<Response>;
309
- /**
310
- * Not found handler type
311
- */
312
- type GravitoNotFoundHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
313
-
314
- export type { ContentfulStatusCode, GravitoContext as Context, GravitoContext, GravitoErrorHandler, GravitoHandler, GravitoMiddleware, GravitoNext, GravitoNotFoundHandler, GravitoRequest, GravitoVariables, GravitoHandler as Handler, HttpMethod, GravitoMiddleware as MiddlewareHandler, GravitoNext as Next, StatusCode, ValidationTarget, GravitoVariables as Variables };
1
+ export { C as ContentfulStatusCode, e as Context, e as GravitoContext, c as GravitoErrorHandler, a as GravitoHandler, b as GravitoMiddleware, g as GravitoNext, d as GravitoNotFoundHandler, f as GravitoRequest, G as GravitoVariables, a as Handler, H as HttpMethod, b as MiddlewareHandler, g as Next, S as StatusCode, V as ValidationTarget, G as Variables } from './compat-C4Src6NN.cjs';