@adonisjs/http-server
Advanced tools
Sorry, the diff of this file is too big to display
| var __defProp = Object.defineProperty; | ||
| var __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| // src/helpers.ts | ||
| import cookie from "cookie"; | ||
| import matchit from "@poppinss/matchit"; | ||
| import string from "@poppinss/utils/string"; | ||
| import { parseBindingReference } from "@adonisjs/fold"; | ||
| import { default as default2 } from "encodeurl"; | ||
| import { default as default3 } from "mime-types"; | ||
| function parseRoute(pattern, matchers) { | ||
| const tokens = matchit.parse(pattern, matchers); | ||
| return tokens; | ||
| } | ||
| function createURL(pattern, tokens, searchParamsStringifier, params, options) { | ||
| const uriSegments = []; | ||
| const paramsArray = Array.isArray(params) ? params : null; | ||
| const paramsObject = !Array.isArray(params) ? params ?? {} : {}; | ||
| let paramsIndex = 0; | ||
| for (const token of tokens) { | ||
| if (token.type === 0) { | ||
| uriSegments.push(token.val === "/" ? "" : `${token.val}${token.end}`); | ||
| continue; | ||
| } | ||
| if (token.type === 2) { | ||
| const values = paramsArray ? paramsArray.slice(paramsIndex) : paramsObject["*"]; | ||
| if (!Array.isArray(values) || !values.length) { | ||
| throw new Error( | ||
| `Cannot make URL for "${pattern}". Invalid value provided for the wildcard param` | ||
| ); | ||
| } | ||
| uriSegments.push(`${values.join("/")}${token.end}`); | ||
| break; | ||
| } | ||
| const paramName = token.val; | ||
| const value = paramsArray ? paramsArray[paramsIndex] : paramsObject[paramName]; | ||
| const isDefined = value !== void 0 && value !== null; | ||
| if (token.type === 1 && !isDefined) { | ||
| throw new Error( | ||
| `Cannot make URL for "${pattern}". Missing value for the "${paramName}" param` | ||
| ); | ||
| } | ||
| if (isDefined) { | ||
| uriSegments.push(`${value}${token.end}`); | ||
| } | ||
| paramsIndex++; | ||
| } | ||
| let URI = `/${uriSegments.join("/")}`; | ||
| if (options?.prefixUrl) { | ||
| URI = `${options?.prefixUrl.replace(/\/$/, "")}${URI}`; | ||
| } | ||
| if (options?.qs) { | ||
| const queryString = searchParamsStringifier(options?.qs); | ||
| URI = queryString ? `${URI}?${queryString}` : URI; | ||
| } | ||
| return URI; | ||
| } | ||
| function createSignedURL(identifier, tokens, searchParamsStringifier, encryption, params, options) { | ||
| const signature = encryption.verifier.sign( | ||
| createURL(identifier, tokens, searchParamsStringifier, params, { | ||
| ...options, | ||
| prefixUrl: void 0 | ||
| }), | ||
| options?.expiresIn, | ||
| options?.purpose | ||
| ); | ||
| return createURL(identifier, tokens, searchParamsStringifier, params, { | ||
| ...options, | ||
| qs: { ...options?.qs, signature } | ||
| }); | ||
| } | ||
| function matchRoute(url, patterns) { | ||
| const tokensBucket = patterns.map((pattern) => parseRoute(pattern)); | ||
| const match = matchit.match(url, tokensBucket); | ||
| if (!match.length) { | ||
| return null; | ||
| } | ||
| return matchit.exec(url, match); | ||
| } | ||
| function serializeCookie(key, value, options) { | ||
| let expires; | ||
| let maxAge; | ||
| if (options) { | ||
| expires = typeof options.expires === "function" ? options.expires() : options.expires; | ||
| maxAge = options.maxAge ? string.seconds.parse(options.maxAge) : void 0; | ||
| } | ||
| return cookie.serialize(key, value, { ...options, maxAge, expires }); | ||
| } | ||
| async function middlewareInfo(middleware) { | ||
| if (typeof middleware === "function") { | ||
| return { | ||
| type: "closure", | ||
| name: middleware.name || "closure" | ||
| }; | ||
| } | ||
| if ("args" in middleware) { | ||
| return { | ||
| type: "named", | ||
| name: middleware.name, | ||
| args: middleware.args, | ||
| ...await parseBindingReference([middleware.reference]) | ||
| }; | ||
| } | ||
| return { | ||
| type: "global", | ||
| name: middleware.name, | ||
| ...await parseBindingReference([middleware.reference]) | ||
| }; | ||
| } | ||
| async function routeInfo(route) { | ||
| return "reference" in route.handler ? { | ||
| type: "controller", | ||
| ...await parseBindingReference(route.handler.reference) | ||
| } : { | ||
| type: "closure", | ||
| name: route.handler.name || "closure", | ||
| args: "listArgs" in route.handler ? String(route.handler.listArgs) : void 0 | ||
| }; | ||
| } | ||
| export { | ||
| __export, | ||
| parseRoute, | ||
| createURL, | ||
| createSignedURL, | ||
| matchRoute, | ||
| serializeCookie, | ||
| middlewareInfo, | ||
| routeInfo, | ||
| default2 as default, | ||
| default3 as default2 | ||
| }; |
@@ -18,6 +18,7 @@ import type { Logger } from '@adonisjs/logger'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
| merge(params: Partial<FactoryParameters>): this; | ||
| /** | ||
| * Create request | ||
| * Create HTTP context instance | ||
| */ | ||
@@ -24,0 +25,0 @@ create(): HttpContext; |
| import { type IncomingMessage, type Server, type ServerResponse } from 'node:http'; | ||
| /** | ||
| * HTTP server factory for testing purposes | ||
| */ | ||
| export declare const httpServer: { | ||
| /** | ||
| * Creates a new HTTP server for testing with automatic cleanup | ||
| * @param handler - The request handler function | ||
| */ | ||
| create(handler: (req: IncomingMessage, res: ServerResponse) => any | Promise<any>): Promise<{ | ||
@@ -4,0 +11,0 @@ server: Server; |
@@ -9,4 +9,4 @@ import { | ||
| defineConfig | ||
| } from "../chunk-BFGF3A5X.js"; | ||
| import "../chunk-ASX56VAK.js"; | ||
| } from "../chunk-7ROFCP6L.js"; | ||
| import "../chunk-NQNHMINZ.js"; | ||
@@ -19,2 +19,5 @@ // factories/router.ts | ||
| var QsParserFactory = class { | ||
| /** | ||
| * Default configuration options for the QS parser | ||
| */ | ||
| #options = { | ||
@@ -36,3 +39,4 @@ parse: { | ||
| /** | ||
| * Merge encryption factory options | ||
| * Merge QS parser factory options | ||
| * @param options - Partial options to merge with existing configuration | ||
| */ | ||
@@ -45,3 +49,3 @@ merge(options) { | ||
| /** | ||
| * Create instance of the logger class | ||
| * Create instance of the QS parser class | ||
| */ | ||
@@ -55,2 +59,5 @@ create() { | ||
| var RouterFactory = class { | ||
| /** | ||
| * Factory parameters for creating router instances | ||
| */ | ||
| #parameters = {}; | ||
@@ -72,2 +79,3 @@ /** | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -93,2 +101,5 @@ merge(params) { | ||
| var RequestFactory = class { | ||
| /** | ||
| * Factory parameters for creating request instances | ||
| */ | ||
| #parameters = {}; | ||
@@ -125,2 +136,3 @@ /** | ||
| * Returns the HTTP res object | ||
| * @param req - The incoming message request object | ||
| */ | ||
@@ -139,2 +151,3 @@ #createResponse(req) { | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -165,2 +178,5 @@ merge(params) { | ||
| var ResponseFactory = class { | ||
| /** | ||
| * Factory parameters for creating response instances | ||
| */ | ||
| #parameters = {}; | ||
@@ -198,2 +214,3 @@ /** | ||
| * Returns the HTTP res object | ||
| * @param req - The incoming message request object | ||
| */ | ||
@@ -212,2 +229,3 @@ #createResponse(req) { | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -240,2 +258,5 @@ merge(params) { | ||
| var ServerFactory = class { | ||
| /** | ||
| * Factory parameters for creating server instances | ||
| */ | ||
| #parameters = {}; | ||
@@ -275,2 +296,3 @@ /** | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -299,2 +321,5 @@ merge(params) { | ||
| var HttpContextFactory = class { | ||
| /** | ||
| * Factory parameters for creating HTTP context instances | ||
| */ | ||
| #parameters = {}; | ||
@@ -321,2 +346,3 @@ /** | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -328,3 +354,3 @@ merge(params) { | ||
| /** | ||
| * Create request | ||
| * Create HTTP context instance | ||
| */ | ||
@@ -331,0 +357,0 @@ create() { |
@@ -10,3 +10,4 @@ import { Qs } from '../src/qs.ts'; | ||
| /** | ||
| * Merge encryption factory options | ||
| * Merge QS parser factory options | ||
| * @param options - Partial options to merge with existing configuration | ||
| */ | ||
@@ -18,5 +19,5 @@ merge(options: Partial<{ | ||
| /** | ||
| * Create instance of the logger class | ||
| * Create instance of the QS parser class | ||
| */ | ||
| create(): Qs; | ||
| } |
@@ -21,2 +21,3 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -23,0 +24,0 @@ merge(params: Partial<FactoryParameters>): this; |
@@ -21,2 +21,3 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -23,0 +24,0 @@ merge(params: Partial<FactoryParameters>): this; |
@@ -16,2 +16,3 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -18,0 +19,0 @@ merge(params: Partial<FactoryParameters>): this; |
@@ -22,2 +22,3 @@ import { Logger } from '@adonisjs/logger'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -24,0 +25,0 @@ merge(params: Partial<FactoryParameters>): this; |
@@ -15,2 +15,3 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| * Merge factory params | ||
| * @param params - Partial factory parameters to merge | ||
| */ | ||
@@ -17,0 +18,0 @@ merge(params: Partial<FactoryParameters>): this; |
+3
-1
@@ -12,6 +12,8 @@ export * as errors from './src/errors.ts'; | ||
| export { CookieClient } from './src/cookies/client.ts'; | ||
| export { CookieParser } from './src/cookies/parser.ts'; | ||
| export { HttpContext } from './src/http_context/main.ts'; | ||
| export { RouteResource } from './src/router/resource.ts'; | ||
| export { ResponseStatus } from './src/response_status.ts'; | ||
| export * as tracingChannels from './src/tracing_channels.ts'; | ||
| export { ExceptionHandler } from './src/exception_handler.ts'; | ||
| export * as tracingChannels from './src/tracing_channels.ts'; | ||
| export { CookieSerializer } from './src/cookies/serializer.ts'; |
+87
-37
| import { | ||
| BriskRoute, | ||
| CookieClient, | ||
| CookieParser, | ||
| CookieSerializer, | ||
| E_CANNOT_LOOKUP_ROUTE, | ||
@@ -23,4 +25,4 @@ E_HTTP_EXCEPTION, | ||
| tracing_channels_exports | ||
| } from "./chunk-BFGF3A5X.js"; | ||
| import "./chunk-ASX56VAK.js"; | ||
| } from "./chunk-7ROFCP6L.js"; | ||
| import "./chunk-NQNHMINZ.js"; | ||
@@ -32,27 +34,31 @@ // src/exception_handler.ts | ||
| /** | ||
| * Computed from the status pages property | ||
| * Cached expanded status pages mapping individual status codes to their renderers | ||
| * Computed from the statusPages property when first accessed | ||
| */ | ||
| #expandedStatusPages; | ||
| /** | ||
| * Whether or not to render debug info. When set to true, the errors | ||
| * will have the complete error stack. | ||
| * Controls whether to include debug information in error responses | ||
| * When enabled, errors include complete stack traces and detailed debugging info | ||
| * Defaults to true in non-production environments | ||
| */ | ||
| debug = process.env.NODE_ENV !== "production"; | ||
| /** | ||
| * Whether or not to render status pages. When set to true, the unhandled | ||
| * errors with matching status codes will be rendered using a status | ||
| * page. | ||
| * Controls whether to render custom status pages for unhandled errors | ||
| * When enabled, errors with matching status codes use configured status page renderers | ||
| * Defaults to true in production environments | ||
| */ | ||
| renderStatusPages = process.env.NODE_ENV === "production"; | ||
| /** | ||
| * A collection of error status code range and the view to render. | ||
| * Mapping of HTTP status code ranges to their corresponding page renderers | ||
| * Supports ranges like '400-499' or individual codes like '404' | ||
| */ | ||
| statusPages = {}; | ||
| /** | ||
| * Enable/disable errors reporting | ||
| * Controls whether errors should be reported to logging systems | ||
| * When disabled, errors are handled but not logged or reported | ||
| */ | ||
| reportErrors = true; | ||
| /** | ||
| * An array of exception classes to ignore when | ||
| * reporting an error | ||
| * Array of exception class constructors to exclude from error reporting | ||
| * These exceptions are handled but not logged or reported to external systems | ||
| */ | ||
@@ -66,13 +72,15 @@ ignoreExceptions = [ | ||
| /** | ||
| * An array of HTTP status codes to ignore when reporting | ||
| * an error | ||
| * Array of HTTP status codes to exclude from error reporting | ||
| * Errors with these status codes are handled but not logged | ||
| */ | ||
| ignoreStatuses = [400, 422, 401]; | ||
| /** | ||
| * An array of error codes to ignore when reporting | ||
| * an error | ||
| * Array of custom error codes to exclude from error reporting | ||
| * Errors with these codes are handled but not logged | ||
| */ | ||
| ignoreCodes = []; | ||
| /** | ||
| * Expands status pages | ||
| * Expands status page ranges into individual status code mappings | ||
| * Creates a cached lookup table for faster status page resolution | ||
| * @returns Mapping of status codes to renderers | ||
| */ | ||
@@ -93,4 +101,6 @@ #expandStatusPages() { | ||
| /** | ||
| * Forcefully tweaking the type of the error object to | ||
| * have known properties. | ||
| * Normalizes any thrown value into a standardized HttpError object | ||
| * Ensures the error has required properties like message and status | ||
| * @param error - Any thrown value (Error, string, object, etc.) | ||
| * @returns {HttpError} Normalized error object with status and message | ||
| */ | ||
@@ -108,3 +118,6 @@ #toHttpError(error) { | ||
| /** | ||
| * Error reporting context | ||
| * Provides additional context information for error reporting | ||
| * Includes request ID when available for correlation across logs | ||
| * @param ctx - HTTP context containing request information | ||
| * @returns Additional context data for error reporting | ||
| */ | ||
@@ -118,4 +131,6 @@ context(ctx) { | ||
| /** | ||
| * Returns the log level for an error based upon the error | ||
| * status code. | ||
| * Determines the appropriate log level based on HTTP status code | ||
| * 5xx errors are logged as 'error', 4xx as 'warn', others as 'info' | ||
| * @param error - HTTP error object with status code | ||
| * @returns {Level} Appropriate logging level for the error | ||
| */ | ||
@@ -132,4 +147,6 @@ getErrorLogLevel(error) { | ||
| /** | ||
| * A boolean to control if errors should be rendered with | ||
| * all the available debugging info. | ||
| * Determines whether debug information should be included in error responses | ||
| * Override this method to implement context-specific debug control | ||
| * @param _ - HTTP context (unused in base implementation) | ||
| * @returns {boolean} True if debugging should be enabled | ||
| */ | ||
@@ -140,3 +157,6 @@ isDebuggingEnabled(_) { | ||
| /** | ||
| * Returns a boolean by checking if an error should be reported. | ||
| * Determines whether an error should be reported to logging systems | ||
| * Checks against ignore lists for exceptions, status codes, and error codes | ||
| * @param error - HTTP error to evaluate for reporting | ||
| * @returns {boolean} True if the error should be reported | ||
| */ | ||
@@ -159,3 +179,6 @@ shouldReport(error) { | ||
| /** | ||
| * Renders an error to JSON response | ||
| * Renders an error as a JSON response | ||
| * In debug mode, includes full stack trace using Youch | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -172,3 +195,6 @@ async renderErrorAsJSON(error, ctx) { | ||
| /** | ||
| * Renders an error to JSON API response | ||
| * Renders an error as a JSON API compliant response | ||
| * Follows JSON API specification for error objects | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -193,3 +219,6 @@ async renderErrorAsJSONAPI(error, ctx) { | ||
| /** | ||
| * Renders an error to HTML response | ||
| * Renders an error as an HTML response | ||
| * Uses status pages if configured, otherwise shows debug info or simple message | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -217,4 +246,6 @@ async renderErrorAsHTML(error, ctx) { | ||
| /** | ||
| * Renders the validation error message to a JSON | ||
| * response | ||
| * Renders validation error messages as a JSON response | ||
| * Returns errors in a simple format with field-specific messages | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -227,4 +258,6 @@ async renderValidationErrorAsJSON(error, ctx) { | ||
| /** | ||
| * Renders the validation error message as per JSON API | ||
| * spec | ||
| * Renders validation error messages as JSON API compliant response | ||
| * Transforms validation messages to JSON API error object format | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -246,3 +279,6 @@ async renderValidationErrorAsJSONAPI(error, ctx) { | ||
| /** | ||
| * Renders the validation error as an HTML string | ||
| * Renders validation error messages as an HTML response | ||
| * Creates simple HTML list of field errors separated by line breaks | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -257,3 +293,6 @@ async renderValidationErrorAsHTML(error, ctx) { | ||
| /** | ||
| * Renders the error to response | ||
| * Renders an error to the appropriate response format based on content negotiation | ||
| * Supports HTML, JSON API, and JSON formats based on Accept headers | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -272,3 +311,6 @@ renderError(error, ctx) { | ||
| /** | ||
| * Renders the validation error to response | ||
| * Renders validation errors to the appropriate response format based on content negotiation | ||
| * Supports HTML, JSON API, and JSON formats for validation error messages | ||
| * @param error - Validation error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
@@ -287,3 +329,6 @@ renderValidationError(error, ctx) { | ||
| /** | ||
| * Reports an error during an HTTP request | ||
| * Reports an error to logging systems if reporting is enabled | ||
| * Allows errors to self-report via their own report method if available | ||
| * @param error - Any error object to report | ||
| * @param ctx - HTTP context for additional reporting context | ||
| */ | ||
@@ -310,3 +355,6 @@ async report(error, ctx) { | ||
| /** | ||
| * Handles the error during the HTTP request. | ||
| * Handles errors during HTTP request processing | ||
| * Delegates to error's own handle method if available, otherwise renders response | ||
| * @param error - Any error object to handle | ||
| * @param ctx - HTTP context for error handling | ||
| */ | ||
@@ -327,2 +375,4 @@ async handle(error, ctx) { | ||
| CookieClient, | ||
| CookieParser, | ||
| CookieSerializer, | ||
| ExceptionHandler, | ||
@@ -329,0 +379,0 @@ HttpContext, |
@@ -8,5 +8,14 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| #private; | ||
| /** | ||
| * Create a new instance of CookieClient | ||
| * | ||
| * @param encryption - The encryption instance for cookie operations | ||
| */ | ||
| constructor(encryption: Encryption); | ||
| /** | ||
| * Encrypt a key value pair to be sent in the cookie header | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The value to encrypt | ||
| * @returns The encrypted cookie string or null if encryption fails | ||
| */ | ||
@@ -16,2 +25,6 @@ encrypt(key: string, value: any): string | null; | ||
| * Sign a key value pair to be sent in the cookie header | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The value to sign | ||
| * @returns The signed cookie string or null if signing fails | ||
| */ | ||
@@ -21,2 +34,7 @@ sign(key: string, value: any): string | null; | ||
| * Encode a key value pair to be sent in the cookie header | ||
| * | ||
| * @param _ - Unused key parameter | ||
| * @param value - The value to encode | ||
| * @param stringify - Whether to stringify the value before encoding | ||
| * @returns The encoded cookie string or null if encoding fails | ||
| */ | ||
@@ -26,2 +44,6 @@ encode(_: string, value: any, stringify?: boolean): string | null; | ||
| * Unsign a signed cookie value | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The signed cookie value to unsign | ||
| * @returns The original value if valid signature, null otherwise | ||
| */ | ||
@@ -31,2 +53,6 @@ unsign(key: string, value: string): any; | ||
| * Decrypt an encrypted cookie value | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The encrypted cookie value to decrypt | ||
| * @returns The decrypted value or null if decryption fails | ||
| */ | ||
@@ -36,2 +62,7 @@ decrypt(key: string, value: string): any; | ||
| * Decode an encoded cookie value | ||
| * | ||
| * @param _ - Unused key parameter | ||
| * @param value - The encoded cookie value to decode | ||
| * @param stringified - Whether the value was stringified during encoding | ||
| * @returns The decoded value or null if decoding fails | ||
| */ | ||
@@ -41,4 +72,8 @@ decode(_: string, value: string, stringified?: boolean): any; | ||
| * Parse response cookie | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The cookie value to parse | ||
| * @returns The parsed value or undefined if parsing fails | ||
| */ | ||
| parse(key: string, value: any): any; | ||
| } |
| import type { Encryption } from '@adonisjs/encryption'; | ||
| /** | ||
| * Encrypt a value to be set as cookie | ||
| * | ||
| * @param key - The cookie key used for encryption | ||
| * @param value - The value to encrypt | ||
| * @param encryption - The encryption instance | ||
| * @returns The encrypted cookie string or null if value is null/undefined | ||
| */ | ||
@@ -9,2 +14,5 @@ export declare function pack(key: string, value: any, encryption: Encryption): null | string; | ||
| * to unpack encrypted value. | ||
| * | ||
| * @param encryptedValue - The encrypted value to check | ||
| * @returns True if the value can be unpacked by this module | ||
| */ | ||
@@ -16,3 +24,8 @@ export declare function canUnpack(encryptedValue: string): boolean; | ||
| * exceptions can be raised. | ||
| * | ||
| * @param key - The cookie key used for decryption | ||
| * @param encryptedValue - The encrypted value to decrypt | ||
| * @param encryption - The encryption instance | ||
| * @returns The decrypted value or null if decryption fails | ||
| */ | ||
| export declare function unpack(key: string, encryptedValue: string, encryption: Encryption): null | any; |
| /** | ||
| * Encodes a value into a base64 url encoded string to | ||
| * be set as cookie | ||
| * | ||
| * @param value - The value to encode | ||
| * @returns The encoded cookie string or null if value is null/undefined | ||
| */ | ||
@@ -9,2 +12,5 @@ export declare function pack(value: any): null | string; | ||
| * to unpack the encode value. | ||
| * | ||
| * @param encodedValue - The encoded value to check | ||
| * @returns True if the value can be unpacked by this module | ||
| */ | ||
@@ -15,3 +21,6 @@ export declare function canUnpack(encodedValue: string): boolean; | ||
| * before calling this method | ||
| * | ||
| * @param encodedValue - The encoded value to decode | ||
| * @returns The decoded value or null if decoding fails | ||
| */ | ||
| export declare function unpack(encodedValue: string): null | any; |
@@ -5,2 +5,7 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| * hash to verify tampering with the original value | ||
| * | ||
| * @param key - The cookie key used for signing | ||
| * @param value - The value to sign | ||
| * @param encryption - The encryption instance | ||
| * @returns The signed cookie string or null if value is null/undefined | ||
| */ | ||
@@ -11,2 +16,5 @@ export declare function pack(key: string, value: any, encryption: Encryption): null | string; | ||
| * to unpack the signed value. | ||
| * | ||
| * @param signedValue - The signed value to check | ||
| * @returns True if the value can be unpacked by this module | ||
| */ | ||
@@ -17,3 +25,8 @@ export declare function canUnpack(signedValue: string): boolean; | ||
| * calling this method. | ||
| * | ||
| * @param key - The cookie key used for verification | ||
| * @param signedValue - The signed value to verify and unpack | ||
| * @param encryption - The encryption instance | ||
| * @returns The original value or null if verification fails | ||
| */ | ||
| export declare function unpack(key: string, signedValue: string, encryption: Encryption): null | any; |
@@ -14,2 +14,8 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| #private; | ||
| /** | ||
| * Create a new instance of CookieParser | ||
| * | ||
| * @param cookieHeader - The raw cookie header string from the request | ||
| * @param encryption - The encryption instance for cookie operations | ||
| */ | ||
| constructor(cookieHeader: string, encryption: Encryption); | ||
@@ -20,2 +26,6 @@ /** | ||
| * place and not signed or encrypted. | ||
| * | ||
| * @param key - The cookie key to decode | ||
| * @param stringified - Whether the cookie value was stringified | ||
| * @returns The decoded cookie value or null if decoding fails | ||
| */ | ||
@@ -26,2 +36,5 @@ decode(key: string, stringified?: boolean): any | null; | ||
| * you are assuming that the cookie was signed in the first place. | ||
| * | ||
| * @param key - The cookie key to unsign | ||
| * @returns The original cookie value or null if unsigning fails | ||
| */ | ||
@@ -32,2 +45,5 @@ unsign(key: string): null | any; | ||
| * you are assuming that the cookie was encrypted in the first place. | ||
| * | ||
| * @param key - The cookie key to decrypt | ||
| * @returns The decrypted cookie value or null if decryption fails | ||
| */ | ||
@@ -39,4 +55,6 @@ decrypt(key: string): null | any; | ||
| * list. | ||
| * | ||
| * @returns Raw cookies as key-value pairs | ||
| */ | ||
| list(): Record<string, any>; | ||
| } |
@@ -10,2 +10,7 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| #private; | ||
| /** | ||
| * Create a new instance of CookieSerializer | ||
| * | ||
| * @param encryption - The encryption instance for cookie operations | ||
| */ | ||
| constructor(encryption: Encryption); | ||
@@ -22,2 +27,7 @@ /** | ||
| * ``` | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The value to encode | ||
| * @param options - Cookie encoding options | ||
| * @returns The serialized cookie string or null if encoding fails | ||
| */ | ||
@@ -35,2 +45,7 @@ encode(key: string, value: any, options?: Partial<CookieOptions & { | ||
| * verification hash attached to it to detect data tampering. | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The value to sign | ||
| * @param options - Cookie options | ||
| * @returns The serialized signed cookie string or null if signing fails | ||
| */ | ||
@@ -40,4 +55,9 @@ sign(key: string, value: any, options?: Partial<CookieOptions>): string | null; | ||
| * Encrypts a key-value pair to an encrypted cookie. | ||
| * | ||
| * @param key - The cookie key | ||
| * @param value - The value to encrypt | ||
| * @param options - Cookie options | ||
| * @returns The serialized encrypted cookie string or null if encryption fails | ||
| */ | ||
| encrypt(key: string, value: any, options?: Partial<CookieOptions>): string | null; | ||
| } |
@@ -0,5 +1,3 @@ | ||
| import { type DeepPartial } from '@poppinss/utils/types'; | ||
| import type { ServerConfig } from './types/server.ts'; | ||
| type DeepPartial<T> = { | ||
| [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]; | ||
| }; | ||
| type UserDefinedServerConfig = DeepPartial<Omit<ServerConfig, 'trustProxy'> & { | ||
@@ -6,0 +4,0 @@ trustProxy: ((address: string, distance: number) => boolean) | boolean | string; |
| import type { LazyImport, UnWrapLazyImport } from '@poppinss/utils/types'; | ||
| import type { GetMiddlewareArgs, MiddlewareAsClass, ParsedGlobalMiddleware } from './types/middleware.ts'; | ||
| import type { MiddlewareAsClass, GetMiddlewareArgs, ParsedGlobalMiddleware } from './types/middleware.ts'; | ||
| /** | ||
@@ -4,0 +4,0 @@ * Define an collection of named middleware. The collection gets converted |
@@ -20,95 +20,136 @@ import Macroable from '@poppinss/macroable'; | ||
| /** | ||
| * Whether or not to render debug info. When set to true, the errors | ||
| * will have the complete error stack. | ||
| * Controls whether to include debug information in error responses | ||
| * When enabled, errors include complete stack traces and detailed debugging info | ||
| * Defaults to true in non-production environments | ||
| */ | ||
| protected debug: boolean; | ||
| /** | ||
| * Whether or not to render status pages. When set to true, the unhandled | ||
| * errors with matching status codes will be rendered using a status | ||
| * page. | ||
| * Controls whether to render custom status pages for unhandled errors | ||
| * When enabled, errors with matching status codes use configured status page renderers | ||
| * Defaults to true in production environments | ||
| */ | ||
| protected renderStatusPages: boolean; | ||
| /** | ||
| * A collection of error status code range and the view to render. | ||
| * Mapping of HTTP status code ranges to their corresponding page renderers | ||
| * Supports ranges like '400-499' or individual codes like '404' | ||
| */ | ||
| protected statusPages: Record<StatusPageRange, StatusPageRenderer>; | ||
| /** | ||
| * Enable/disable errors reporting | ||
| * Controls whether errors should be reported to logging systems | ||
| * When disabled, errors are handled but not logged or reported | ||
| */ | ||
| protected reportErrors: boolean; | ||
| /** | ||
| * An array of exception classes to ignore when | ||
| * reporting an error | ||
| * Array of exception class constructors to exclude from error reporting | ||
| * These exceptions are handled but not logged or reported to external systems | ||
| */ | ||
| protected ignoreExceptions: any[]; | ||
| /** | ||
| * An array of HTTP status codes to ignore when reporting | ||
| * an error | ||
| * Array of HTTP status codes to exclude from error reporting | ||
| * Errors with these status codes are handled but not logged | ||
| */ | ||
| protected ignoreStatuses: number[]; | ||
| /** | ||
| * An array of error codes to ignore when reporting | ||
| * an error | ||
| * Array of custom error codes to exclude from error reporting | ||
| * Errors with these codes are handled but not logged | ||
| */ | ||
| protected ignoreCodes: string[]; | ||
| /** | ||
| * Error reporting context | ||
| * Provides additional context information for error reporting | ||
| * Includes request ID when available for correlation across logs | ||
| * @param ctx - HTTP context containing request information | ||
| * @returns Additional context data for error reporting | ||
| */ | ||
| protected context(ctx: HttpContext): any; | ||
| /** | ||
| * Returns the log level for an error based upon the error | ||
| * status code. | ||
| * Determines the appropriate log level based on HTTP status code | ||
| * 5xx errors are logged as 'error', 4xx as 'warn', others as 'info' | ||
| * @param error - HTTP error object with status code | ||
| * @returns {Level} Appropriate logging level for the error | ||
| */ | ||
| protected getErrorLogLevel(error: HttpError): Level; | ||
| /** | ||
| * A boolean to control if errors should be rendered with | ||
| * all the available debugging info. | ||
| * Determines whether debug information should be included in error responses | ||
| * Override this method to implement context-specific debug control | ||
| * @param _ - HTTP context (unused in base implementation) | ||
| * @returns {boolean} True if debugging should be enabled | ||
| */ | ||
| protected isDebuggingEnabled(_: HttpContext): boolean; | ||
| /** | ||
| * Returns a boolean by checking if an error should be reported. | ||
| * Determines whether an error should be reported to logging systems | ||
| * Checks against ignore lists for exceptions, status codes, and error codes | ||
| * @param error - HTTP error to evaluate for reporting | ||
| * @returns {boolean} True if the error should be reported | ||
| */ | ||
| protected shouldReport(error: HttpError): boolean; | ||
| /** | ||
| * Renders an error to JSON response | ||
| * Renders an error as a JSON response | ||
| * In debug mode, includes full stack trace using Youch | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderErrorAsJSON(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Renders an error to JSON API response | ||
| * Renders an error as a JSON API compliant response | ||
| * Follows JSON API specification for error objects | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderErrorAsJSONAPI(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Renders an error to HTML response | ||
| * Renders an error as an HTML response | ||
| * Uses status pages if configured, otherwise shows debug info or simple message | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderErrorAsHTML(error: HttpError, ctx: HttpContext): Promise<any>; | ||
| /** | ||
| * Renders the validation error message to a JSON | ||
| * response | ||
| * Renders validation error messages as a JSON response | ||
| * Returns errors in a simple format with field-specific messages | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderValidationErrorAsJSON(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Renders the validation error message as per JSON API | ||
| * spec | ||
| * Renders validation error messages as JSON API compliant response | ||
| * Transforms validation messages to JSON API error object format | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderValidationErrorAsJSONAPI(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Renders the validation error as an HTML string | ||
| * Renders validation error messages as an HTML response | ||
| * Creates simple HTML list of field errors separated by line breaks | ||
| * @param error - Validation error containing messages array | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderValidationErrorAsHTML(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Renders the error to response | ||
| * Renders an error to the appropriate response format based on content negotiation | ||
| * Supports HTML, JSON API, and JSON formats based on Accept headers | ||
| * @param error - HTTP error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderError(error: HttpError, ctx: HttpContext): Promise<any>; | ||
| /** | ||
| * Renders the validation error to response | ||
| * Renders validation errors to the appropriate response format based on content negotiation | ||
| * Supports HTML, JSON API, and JSON formats for validation error messages | ||
| * @param error - Validation error to render | ||
| * @param ctx - HTTP context for the request | ||
| */ | ||
| renderValidationError(error: HttpError, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Reports an error during an HTTP request | ||
| * Reports an error to logging systems if reporting is enabled | ||
| * Allows errors to self-report via their own report method if available | ||
| * @param error - Any error object to report | ||
| * @param ctx - HTTP context for additional reporting context | ||
| */ | ||
| report(error: unknown, ctx: HttpContext): Promise<void>; | ||
| /** | ||
| * Handles the error during the HTTP request. | ||
| * Handles errors during HTTP request processing | ||
| * Delegates to error's own handle method if available, otherwise renders response | ||
| * @param error - Any error object to handle | ||
| * @param ctx - HTTP context for error handling | ||
| */ | ||
| handle(error: unknown, ctx: HttpContext): Promise<any>; | ||
| } |
@@ -0,2 +1,4 @@ | ||
| import { type Encryption } from '@adonisjs/encryption'; | ||
| import { type CookieOptions } from './types/response.ts'; | ||
| import { type SignedURLOptions, type URLOptions } from './types/url_builder.ts'; | ||
| import type { RouteMatchers, RouteJSON, MatchItRouteToken } from './types/route.ts'; | ||
@@ -37,7 +39,44 @@ import { type MiddlewareFn, type RouteHandlerInfo, type MiddlewareHandlerInfo, type ParsedGlobalMiddleware, type ParsedNamedMiddleware } from './types/middleware.ts'; | ||
| * end refers to be the suffix or the segment (if any) | ||
| * | ||
| * @param pattern - The route pattern to parse | ||
| * @param matchers - Optional route matchers | ||
| * @returns {MatchItRouteToken[]} Array of parsed route tokens | ||
| */ | ||
| export declare function parseRoute(pattern: string, matchers?: RouteMatchers): MatchItRouteToken[]; | ||
| /** | ||
| * Makes URL for a given route pattern using its parsed tokens. The | ||
| * tokens could be generated using the "parseRoute" method. | ||
| * | ||
| * @param pattern - The route pattern | ||
| * @param tokens - Array of parsed route tokens | ||
| * @param searchParamsStringifier - Function to stringify query parameters | ||
| * @param params - Route parameters as array or object | ||
| * @param options - URL options | ||
| * @returns {string} The generated URL | ||
| */ | ||
| export declare function createURL(pattern: string, tokens: Pick<MatchItRouteToken, 'val' | 'type' | 'end'>[], searchParamsStringifier: (qs: Record<string, any>) => string, params?: any[] | { | ||
| [param: string]: any; | ||
| }, options?: URLOptions): string; | ||
| /** | ||
| * Makes signed URL for a given route pattern using its parsed tokens. The | ||
| * tokens could be generated using the "parseRoute" method. | ||
| * | ||
| * @param identifier - Route identifier | ||
| * @param tokens - Array of parsed route tokens | ||
| * @param searchParamsStringifier - Function to stringify query parameters | ||
| * @param encryption - Encryption instance for signing | ||
| * @param params - Route parameters as array or object | ||
| * @param options - Signed URL options | ||
| * @returns {string} The generated signed URL | ||
| */ | ||
| export declare function createSignedURL(identifier: string, tokens: MatchItRouteToken[], searchParamsStringifier: (qs: Record<string, any>) => string, encryption: Encryption, params?: any[] | { | ||
| [param: string]: any; | ||
| }, options?: SignedURLOptions): string; | ||
| /** | ||
| * Match a given URI with an array of patterns and extract the params | ||
| * from the URL. Null value is returned in case of no match | ||
| * | ||
| * @param url - The URL to match | ||
| * @param patterns - Array of route patterns to match against | ||
| * @returns {null | Record<string, string>} Extracted parameters or null if no match | ||
| */ | ||
@@ -48,2 +87,7 @@ export declare function matchRoute(url: string, patterns: string[]): null | Record<string, string>; | ||
| * set-cookie response header. | ||
| * | ||
| * @param key - Cookie name | ||
| * @param value - Cookie value | ||
| * @param options - Cookie options | ||
| * @returns {string} Serialized cookie string | ||
| */ | ||
@@ -54,2 +98,5 @@ export declare function serializeCookie(key: string, value: string, options?: Partial<CookieOptions>): string; | ||
| * will return the import path | ||
| * | ||
| * @param middleware - The middleware function or parsed middleware | ||
| * @returns {Promise<MiddlewareHandlerInfo>} Promise resolving to middleware handler information | ||
| */ | ||
@@ -60,3 +107,6 @@ export declare function middlewareInfo(middleware: MiddlewareFn | ParsedGlobalMiddleware | ParsedNamedMiddleware): Promise<MiddlewareHandlerInfo>; | ||
| * will return the import path. | ||
| * | ||
| * @param route - The route JSON object | ||
| * @returns {Promise<RouteHandlerInfo>} Promise resolving to route handler information | ||
| */ | ||
| export declare function routeInfo(route: RouteJSON): Promise<RouteHandlerInfo>; |
| import { | ||
| createSignedURL, | ||
| createURL, | ||
| default as default2, | ||
@@ -9,4 +11,6 @@ default2 as default3, | ||
| serializeCookie | ||
| } from "../chunk-ASX56VAK.js"; | ||
| } from "../chunk-NQNHMINZ.js"; | ||
| export { | ||
| createSignedURL, | ||
| createURL, | ||
| default2 as encodeUrl, | ||
@@ -13,0 +17,0 @@ matchRoute, |
@@ -6,7 +6,24 @@ import { AsyncLocalStorage } from 'node:async_hooks'; | ||
| */ | ||
| /** | ||
| * Async local storage for HTTP context | ||
| */ | ||
| export declare const asyncLocalStorage: { | ||
| /** | ||
| * Check if the async local storage for the HTTP context is enabled or not | ||
| */ | ||
| isEnabled: boolean; | ||
| /** | ||
| * HTTP context storage instance for the current scope | ||
| */ | ||
| storage: null | AsyncLocalStorage<HttpContext>; | ||
| /** | ||
| * Create the storage instance. This method must be called only once. | ||
| * | ||
| * @returns {AsyncLocalStorage<HttpContext>} The created storage instance | ||
| */ | ||
| create(): AsyncLocalStorage<HttpContext>; | ||
| /** | ||
| * Destroy the create storage instance | ||
| */ | ||
| destroy(): void; | ||
| }; |
@@ -53,2 +53,10 @@ import Macroable from '@poppinss/macroable'; | ||
| subdomains: Record<string, any>; | ||
| /** | ||
| * Creates a new HttpContext instance | ||
| * | ||
| * @param {Request} request - The HTTP request instance | ||
| * @param {Response} response - The HTTP response instance | ||
| * @param {Logger} logger - The logger instance | ||
| * @param {ContainerResolver<any>} containerResolver - The IoC container resolver | ||
| */ | ||
| constructor(request: Request, response: Response, logger: Logger, containerResolver: ContainerResolver<any>); | ||
@@ -55,0 +63,0 @@ /** |
+14
-0
@@ -8,5 +8,19 @@ import { type QSParserConfig } from './types/qs.ts'; | ||
| #private; | ||
| /** | ||
| * Creates a new query string parser instance with the provided configuration | ||
| * @param config - Configuration object with parse and stringify options | ||
| */ | ||
| constructor(config: QSParserConfig); | ||
| /** | ||
| * Parses a query string into a JavaScript object using the configured options | ||
| * @param value - Query string to parse (e.g., "foo=bar&baz=qux") | ||
| * @returns Parsed object representation of the query string | ||
| */ | ||
| parse: (value: string) => import("qs").ParsedQs; | ||
| /** | ||
| * Converts a JavaScript object into a query string using the configured options | ||
| * @param value - Object to convert to query string | ||
| * @returns Stringified query string representation of the object | ||
| */ | ||
| stringify: (value: any) => string; | ||
| } |
@@ -11,16 +11,29 @@ import type { IncomingMessage } from 'node:http'; | ||
| #private; | ||
| /** | ||
| * Creates a new Redirect instance for handling HTTP redirects | ||
| * @param request - Node.js incoming HTTP request | ||
| * @param response - AdonisJS response instance | ||
| * @param router - AdonisJS router instance | ||
| * @param qs - Query string parser instance | ||
| */ | ||
| constructor(request: IncomingMessage, response: Response, router: Router, qs: Qs); | ||
| /** | ||
| * Set a custom status code. | ||
| * Sets a custom HTTP status code for the redirect response | ||
| * @param statusCode - HTTP status code to use (e.g., 301, 302, 307) | ||
| * @returns {this} The Redirect instance for method chaining | ||
| */ | ||
| status(statusCode: number): this; | ||
| /** | ||
| * Clearing query string values added using the | ||
| * "withQs" method | ||
| * Clears any query string values previously added using the withQs method | ||
| * @returns {this} The Redirect instance for method chaining | ||
| */ | ||
| clearQs(): this; | ||
| /** | ||
| * Define query string for the redirect. Not passing | ||
| * any value will forward the current request query | ||
| * string. | ||
| * Defines query string parameters for the redirect URL | ||
| * - No arguments: forwards current request query string | ||
| * - Object argument: adds multiple key-value pairs | ||
| * - String arguments: adds single key-value pair | ||
| * @param name - Query parameter name or object of parameters | ||
| * @param value - Value for the query parameter (when name is string) | ||
| * @returns {this} The Redirect instance for method chaining | ||
| */ | ||
@@ -31,13 +44,16 @@ withQs(): this; | ||
| /** | ||
| * Redirect to the previous path. | ||
| * Redirects to the previous path using the Referer header | ||
| * Falls back to '/' if no referrer is found | ||
| */ | ||
| back(): void; | ||
| /** | ||
| * Redirect the request using a route identifier. | ||
| * Redirects to a route using its identifier (name, pattern, or handler reference) | ||
| * @param args - Route identifier, parameters, and options for URL building | ||
| */ | ||
| toRoute<Identifier extends keyof GetRoutesForMethod<RoutesList, 'GET'> & string>(...args: RoutesList extends LookupList ? RouteBuilderArguments<Identifier, RoutesList['GET'][Identifier], URLOptions> : []): void; | ||
| /** | ||
| * Redirect the request using a path. | ||
| * Redirects to a specific URL path | ||
| * @param url - Target URL path for redirection | ||
| */ | ||
| toPath(url: string): void; | ||
| } |
+109
-10
@@ -18,21 +18,38 @@ import Macroable from '@poppinss/macroable'; | ||
| #private; | ||
| /** Native Node.js incoming message instance */ | ||
| request: IncomingMessage; | ||
| /** Native Node.js server response instance */ | ||
| response: ServerResponse; | ||
| /** | ||
| * Parsed URL with query string stored as a string. | ||
| * Parsed URL with query string stored as a string and decode flag | ||
| */ | ||
| parsedUrl: { | ||
| /** The pathname portion of the URL */ | ||
| pathname: string; | ||
| /** The query string portion of the URL */ | ||
| query: string; | ||
| /** Flag indicating whether parameters should be decoded */ | ||
| shouldDecodeParam: boolean; | ||
| }; | ||
| /** | ||
| * The ctx will be set by the context itself. It creates a circular | ||
| * reference | ||
| * HTTP context reference - creates a circular reference when set by the context | ||
| */ | ||
| ctx?: HttpContext; | ||
| constructor(request: IncomingMessage, response: ServerResponse, encryption: Encryption, config: RequestConfig, qsParser: Qs); | ||
| /** | ||
| * Creates a new Request instance wrapping the native Node.js HTTP request | ||
| * @param request - Native Node.js incoming message instance | ||
| * @param response - Native Node.js server response instance | ||
| * @param encryption - Encryption module for cookie and URL signing | ||
| * @param config - Request configuration options | ||
| * @param qsParser - Query string parser instance | ||
| */ | ||
| constructor( | ||
| /** Native Node.js incoming message instance */ | ||
| request: IncomingMessage, | ||
| /** Native Node.js server response instance */ | ||
| response: ServerResponse, encryption: Encryption, config: RequestConfig, qsParser: Qs); | ||
| /** | ||
| * Returns the request id from the `x-request-id` header. The | ||
| * header is untouched, if it already exists. | ||
| * @returns The request ID or undefined if not found/generated | ||
| */ | ||
@@ -47,2 +64,4 @@ id(): string | undefined; | ||
| * once. For further mutations make use of `updateBody` method. | ||
| * @param body - Parsed request body data | ||
| * @returns {void} | ||
| */ | ||
@@ -54,2 +73,4 @@ setInitialBody(body: Record<string, any>): void; | ||
| * body. | ||
| * @param body - New request body data to set | ||
| * @returns {void} | ||
| */ | ||
@@ -60,2 +81,4 @@ updateBody(body: Record<string, any>): void; | ||
| * the request body or when request is multipart/form-data. | ||
| * @param rawBody - Raw request body as string | ||
| * @returns {void} | ||
| */ | ||
@@ -66,2 +89,4 @@ updateRawBody(rawBody: string): void; | ||
| * will be re-computed by merging the query and the request body. | ||
| * @param data - New query string data to set | ||
| * @returns {void} | ||
| */ | ||
@@ -71,2 +96,3 @@ updateQs(data: Record<string, any>): void; | ||
| * Returns route params | ||
| * @returns {Record<string, any>} Object containing route parameters | ||
| */ | ||
@@ -76,2 +102,3 @@ params(): Record<string, any>; | ||
| * Returns the query string object by reference | ||
| * @returns {Record<string, any>} Object containing parsed query string parameters | ||
| */ | ||
@@ -81,2 +108,3 @@ qs(): Record<string, any>; | ||
| * Returns reference to the request body | ||
| * @returns {Record<string, any>} Object containing parsed request body | ||
| */ | ||
@@ -87,2 +115,3 @@ body(): Record<string, any>; | ||
| * and query string | ||
| * @returns {Record<string, any>} Object containing merged request body and query parameters | ||
| */ | ||
@@ -93,2 +122,3 @@ all(): Record<string, any>; | ||
| * query string and body | ||
| * @returns {Record<string, any>} Object containing original merged request data | ||
| */ | ||
@@ -101,2 +131,3 @@ original(): Record<string, any>; | ||
| * [[post]] methods. The `raw` body is always a string. | ||
| * @returns {string | null} Raw request body as string or null if not set | ||
| */ | ||
@@ -115,2 +146,5 @@ raw(): string | null; | ||
| * ``` | ||
| * @param key - Key to lookup in request data | ||
| * @param defaultValue - Default value when key is not found | ||
| * @returns Value from request data or default value | ||
| */ | ||
@@ -128,2 +162,5 @@ input(key: string, defaultValue?: any): any; | ||
| * ``` | ||
| * @param key - Parameter key to lookup | ||
| * @param defaultValue - Default value when parameter is not found | ||
| * @returns Value from route parameters or default value | ||
| */ | ||
@@ -138,2 +175,4 @@ param(key: string, defaultValue?: any): any; | ||
| * ``` | ||
| * @param keys - Array of keys to exclude from the result | ||
| * @returns {Record<string, any>} Object with all request data except specified keys | ||
| */ | ||
@@ -148,2 +187,4 @@ except(keys: string[]): Record<string, any>; | ||
| * ``` | ||
| * @param keys - Array of keys to include in the result | ||
| * @returns {{ [K in T]: any }} Object with only the specified keys from request data | ||
| */ | ||
@@ -162,2 +203,3 @@ only<T extends string>(keys: T[]): { | ||
| * ``` | ||
| * @returns {string} Original HTTP method from the request | ||
| */ | ||
@@ -178,2 +220,3 @@ intended(): string; | ||
| * ``` | ||
| * @returns {string} HTTP method (potentially spoofed) | ||
| */ | ||
@@ -183,2 +226,3 @@ method(): string; | ||
| * Returns a copy of headers as an object | ||
| * @returns {IncomingHttpHeaders} Object containing all HTTP headers | ||
| */ | ||
@@ -189,2 +233,5 @@ headers(): IncomingHttpHeaders; | ||
| * used when original value is `undefined`. | ||
| * @param key - Header name to lookup | ||
| * @param defaultValue - Default value when header is not found | ||
| * @returns {string | undefined} Header value or default value if not found | ||
| */ | ||
@@ -222,2 +269,3 @@ header(key: string, defaultValue?: any): string | undefined; | ||
| * The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr) | ||
| * @returns {string} Client IP address | ||
| */ | ||
@@ -242,2 +290,3 @@ ip(): string; | ||
| * The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr) | ||
| * @returns {string[]} Array of IP addresses from most to least trusted | ||
| */ | ||
@@ -264,2 +313,3 @@ ips(): string[]; | ||
| * The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr) | ||
| * @returns {string} Request protocol ('http' or 'https') | ||
| */ | ||
@@ -271,2 +321,3 @@ protocol(): string; | ||
| * fetched. | ||
| * @returns {boolean} True if request is served over HTTPS | ||
| */ | ||
@@ -290,2 +341,3 @@ secure(): boolean; | ||
| * The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr) | ||
| * @returns {string | null} Request host or null if not found | ||
| */ | ||
@@ -309,2 +361,3 @@ host(): string | null; | ||
| * The value of trustProxy is passed directly to [proxy-addr](https://www.npmjs.com/package/proxy-addr) | ||
| * @returns {string | null} Request hostname (without port) or null if not found | ||
| */ | ||
@@ -317,2 +370,3 @@ hostname(): string | null; | ||
| * Also `www` is not considered as a subdomain | ||
| * @returns {string[]} Array of subdomains (excluding www) | ||
| */ | ||
@@ -323,2 +377,3 @@ subdomains(): string[]; | ||
| * or not. | ||
| * @returns {boolean} True if request is an AJAX request | ||
| */ | ||
@@ -329,2 +384,3 @@ ajax(): boolean; | ||
| * set or not | ||
| * @returns {boolean} True if request is a PJAX request | ||
| */ | ||
@@ -342,2 +398,4 @@ pjax(): boolean; | ||
| * ``` | ||
| * @param includeQueryString - Whether to include query string in the URL | ||
| * @returns {string} Request pathname, optionally with query string | ||
| */ | ||
@@ -356,2 +414,4 @@ url(includeQueryString?: boolean): string; | ||
| * ``` | ||
| * @param includeQueryString - Whether to include query string in the URL | ||
| * @returns {string} Complete URL including protocol and host | ||
| */ | ||
@@ -361,2 +421,4 @@ completeUrl(includeQueryString?: boolean): string; | ||
| * Find if the current HTTP request is for the given route or the routes | ||
| * @param routeIdentifier - Route name, pattern, or handler reference to match | ||
| * @returns {boolean} True if the request matches any of the given route identifiers | ||
| */ | ||
@@ -391,2 +453,4 @@ matchesRoute(routeIdentifier: string | string[]): boolean; | ||
| * ``` | ||
| * @param types - Array of content types to match against | ||
| * @returns {string | null} Best matching content type or null if no match | ||
| */ | ||
@@ -414,2 +478,4 @@ is(types: string[]): string | null; | ||
| * ``` | ||
| * @param types - Array of types to match against Accept header | ||
| * @returns {T | null} Best matching accept type or null if no match | ||
| */ | ||
@@ -423,2 +489,3 @@ accepts<T extends string>(types: T[]): T | null; | ||
| * docs too. | ||
| * @returns {string[]} Array of accepted types in preference order | ||
| */ | ||
@@ -446,2 +513,4 @@ types(): string[]; | ||
| * ``` | ||
| * @param languages - Array of languages to match against Accept-Language header | ||
| * @returns {T | null} Best matching language or null if no match | ||
| */ | ||
@@ -455,2 +524,3 @@ language<T extends string>(languages: T[]): T | null; | ||
| * docs too. | ||
| * @returns {string[]} Array of accepted languages in preference order | ||
| */ | ||
@@ -476,2 +546,4 @@ languages(): string[]; | ||
| * ``` | ||
| * @param charsets - Array of charsets to match against Accept-Charset header | ||
| * @returns {T | null} Best matching charset or null if no match | ||
| */ | ||
@@ -485,2 +557,3 @@ charset<T extends string>(charsets: T[]): T | null; | ||
| * docs too. | ||
| * @returns {string[]} Array of accepted charsets in preference order | ||
| */ | ||
@@ -496,6 +569,8 @@ charsets(): string[]; | ||
| * docs too. | ||
| * @param encodings - Array of encodings to match against Accept-Encoding header | ||
| * @returns {T | null} Best matching encoding or null if no match | ||
| */ | ||
| encoding<T extends string>(encodings: T[]): T | null; | ||
| /** | ||
| * Return the charsets that the request accepts, in the order of the | ||
| * Return the encodings that the request accepts, in the order of the | ||
| * client's preference (most preferred first). | ||
@@ -505,2 +580,3 @@ * | ||
| * docs too. | ||
| * @returns {string[]} Array of accepted encodings in preference order | ||
| */ | ||
@@ -510,2 +586,3 @@ encodings(): string[]; | ||
| * Returns a boolean telling if request has body | ||
| * @returns {boolean} True if request contains a body | ||
| */ | ||
@@ -536,2 +613,3 @@ hasBody(): boolean; | ||
| * ``` | ||
| * @returns {boolean} True if client cache is fresh (should return 304) | ||
| */ | ||
@@ -541,2 +619,3 @@ fresh(): boolean; | ||
| * Opposite of [[fresh]] | ||
| * @returns {boolean} True if client cache is stale (should send new response) | ||
| */ | ||
@@ -547,12 +626,21 @@ stale(): boolean; | ||
| * that their value isn't tampered. | ||
| * @returns {{ [key: string]: any }} Object containing all parsed cookies | ||
| */ | ||
| cookiesList(): Record<string, any>; | ||
| cookiesList(): { | ||
| [key: string]: any; | ||
| }; | ||
| /** | ||
| * Returns value for a given key from signed cookies. Optional | ||
| * defaultValue is returned when actual value is undefined. | ||
| * @param key - Cookie name to lookup | ||
| * @param defaultValue - Default value when cookie is not found | ||
| * @returns Cookie value or default value if not found | ||
| */ | ||
| cookie(key: string, defaultValue?: string): any; | ||
| /** | ||
| * Returns value for a given key from signed cookies. Optional | ||
| * Returns value for a given key from encrypted cookies. Optional | ||
| * defaultValue is returned when actual value is undefined. | ||
| * @param key - Cookie name to lookup | ||
| * @param defaultValue - Default value when cookie is not found | ||
| * @returns Decrypted cookie value or default value if not found | ||
| */ | ||
@@ -563,2 +651,5 @@ encryptedCookie(key: string, defaultValue?: string): any; | ||
| * defaultValue is returned when actual value is undefined. | ||
| * @param key - Cookie name to lookup | ||
| * @param options - Options object with defaultValue and encoded flag | ||
| * @returns Plain cookie value or default value if not found | ||
| */ | ||
@@ -571,4 +662,6 @@ plainCookie(key: string, options?: { | ||
| /** | ||
| * Returns a boolean telling if a signed url as a valid signature | ||
| * Returns a boolean telling if a signed url has a valid signature | ||
| * or not. | ||
| * @param purpose - Optional purpose for signature verification | ||
| * @returns {boolean} True if the signed URL has a valid signature | ||
| */ | ||
@@ -578,2 +671,3 @@ hasValidSignature(purpose?: string): boolean; | ||
| * Serializes request to JSON format | ||
| * @returns Object representation of the request | ||
| */ | ||
@@ -589,3 +683,5 @@ serialize(): { | ||
| protocol: string; | ||
| cookies: Record<string, any>; | ||
| cookies: { | ||
| [key: string]: any; | ||
| }; | ||
| hostname: string | null; | ||
@@ -597,2 +693,3 @@ ip: string; | ||
| * toJSON copy of the request | ||
| * @returns JSON representation of the request | ||
| */ | ||
@@ -608,3 +705,5 @@ toJSON(): { | ||
| protocol: string; | ||
| cookies: Record<string, any>; | ||
| cookies: { | ||
| [key: string]: any; | ||
| }; | ||
| hostname: string | null; | ||
@@ -611,0 +710,0 @@ ip: string; |
+399
-203
@@ -10,4 +10,13 @@ import Macroable from '@poppinss/macroable'; | ||
| /** | ||
| * The response is a wrapper over [ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) | ||
| * streamlining the process of writing response body and automatically setting up appropriate headers. | ||
| * The Response class provides a fluent API for constructing HTTP responses. | ||
| * | ||
| * It wraps Node.js ServerResponse and streamlines the process of writing | ||
| * response body, setting headers, handling cookies, redirects, and streaming. | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * response.status(200).json({ message: 'Hello World' }) | ||
| * response.redirect('/dashboard') | ||
| * response.download('/path/to/file.pdf') | ||
| * ``` | ||
| */ | ||
@@ -19,33 +28,27 @@ export declare class Response extends Macroable { | ||
| /** | ||
| * Does response has body set that will written to the | ||
| * response socket at the end of the request | ||
| * Indicates whether the response has any content (body, stream, or file) ready to be sent | ||
| */ | ||
| get hasLazyBody(): boolean; | ||
| /** | ||
| * Find if the response has non-stream content | ||
| * Indicates whether the response has non-stream content set | ||
| */ | ||
| get hasContent(): boolean; | ||
| /** | ||
| * Returns true when response body is set using "response.stream" | ||
| * method | ||
| * Indicates whether the response body is set as a readable stream | ||
| */ | ||
| get hasStream(): boolean; | ||
| /** | ||
| * Returns true when response body is set using "response.download" | ||
| * or "response.attachment" methods | ||
| * Indicates whether the response is configured to stream a file | ||
| */ | ||
| get hasFileToStream(): boolean; | ||
| /** | ||
| * Returns the response content. Check if the response | ||
| * has content using the "hasContent" method | ||
| * The response content data | ||
| */ | ||
| get content(): [any, boolean, (string | undefined)?] | undefined; | ||
| /** | ||
| * Returns reference to the stream set using "response.stream" | ||
| * method | ||
| * The readable stream instance configured for the response | ||
| */ | ||
| get outgoingStream(): import("stream").Readable | undefined; | ||
| /** | ||
| * Returns reference to the file path set using "response.stream" | ||
| * method. | ||
| * Configuration for file streaming including path and etag generation flag | ||
| */ | ||
@@ -57,5 +60,4 @@ get fileToStream(): { | ||
| /** | ||
| * Lazy body is used to set the response body. However, do not | ||
| * write it on the socket immediately unless `response.finish` | ||
| * is called. | ||
| * Lazy body container that holds response content until ready to send. | ||
| * Contains different types of response data: content, stream, or fileToStream. | ||
| */ | ||
@@ -68,64 +70,102 @@ lazyBody: Partial<{ | ||
| /** | ||
| * The ctx will be set by the context itself. It creates a circular | ||
| * reference | ||
| * HTTP context reference (creates circular dependency with HttpContext) | ||
| */ | ||
| ctx?: HttpContext; | ||
| /** | ||
| * Creates a new Response instance | ||
| * | ||
| * @param request - Node.js IncomingMessage instance | ||
| * @param response - Node.js ServerResponse instance | ||
| * @param encryption - Encryption service for cookie handling | ||
| * @param config - Response configuration settings | ||
| * @param router - Router instance for URL generation | ||
| * @param qs - Query string parser | ||
| */ | ||
| constructor(request: IncomingMessage, response: ServerResponse, encryption: Encryption, config: ResponseConfig, router: Router, qs: Qs); | ||
| /** | ||
| * Returns a boolean telling if response is finished or not. | ||
| * Any more attempts to update headers or body will result | ||
| * in raised exceptions. | ||
| * Indicates whether the response has been completely sent | ||
| */ | ||
| get finished(): boolean; | ||
| /** | ||
| * Returns a boolean telling if response headers has been sent or not. | ||
| * Any more attempts to update headers will result in raised | ||
| * exceptions. | ||
| * Indicates whether response headers have been sent to the client | ||
| */ | ||
| get headersSent(): boolean; | ||
| /** | ||
| * Returns a boolean telling if response headers and body is written | ||
| * or not. When value is `true`, you can feel free to write headers | ||
| * and body. | ||
| * Indicates whether the response is still pending (headers and body can still be modified) | ||
| */ | ||
| get isPending(): boolean; | ||
| /** | ||
| * Writes the body with appropriate response headers. Etag header is set | ||
| * when `generateEtag` is set to `true`. | ||
| * Writes the response body with appropriate headers and content type detection | ||
| * | ||
| * Empty body results in `204`. | ||
| * Automatically sets: | ||
| * - Content-Type based on content analysis | ||
| * - Content-Length header | ||
| * - ETag header (if enabled) | ||
| * - Status code 204 for empty bodies | ||
| * | ||
| * @param content - The response content | ||
| * @param generateEtag - Whether to generate ETag header | ||
| * @param jsonpCallbackName - Optional JSONP callback name | ||
| */ | ||
| protected writeBody(content: any, generateEtag: boolean, jsonpCallbackName?: string): void; | ||
| /** | ||
| * Stream the body to the response and handles cleaning up the stream | ||
| * Streams the response body and handles error cleanup | ||
| * | ||
| * Manages stream lifecycle including: | ||
| * - Error handling with custom callbacks | ||
| * - Proper stream cleanup to prevent memory leaks | ||
| * - Response finalization | ||
| * | ||
| * @param body - The readable stream to pipe | ||
| * @param errorCallback - Optional custom error handler | ||
| * @returns Promise that resolves when streaming is complete | ||
| */ | ||
| protected streamBody(body: ResponseStream, errorCallback?: (error: NodeJS.ErrnoException) => [string, number?]): Promise<void>; | ||
| /** | ||
| * Downloads a file by streaming it to the response | ||
| * Streams a file for download with proper headers and caching support | ||
| * | ||
| * Sets appropriate headers: | ||
| * - Last-Modified based on file stats | ||
| * - Content-Type based on file extension | ||
| * - Content-Length from file size | ||
| * - ETag (if enabled) | ||
| * | ||
| * Handles HEAD requests and cache validation (304 responses). | ||
| * | ||
| * @param filePath - Path to the file to stream | ||
| * @param generateEtag - Whether to generate ETag header | ||
| * @param errorCallback - Optional custom error handler | ||
| */ | ||
| protected streamFileForDownload(filePath: string, generateEtag: boolean, errorCallback?: (error: NodeJS.ErrnoException) => [string, number?]): Promise<void>; | ||
| /** | ||
| * Listen for the event the response is written | ||
| * to the TCP socket. | ||
| * Registers a callback to be called when the response is finished | ||
| * | ||
| * Under the hood the callback is registered with | ||
| * the "https://github.com/jshttp/on-finished" package | ||
| * The callback is executed when the response has been completely sent. | ||
| * Uses the "on-finished" package internally. | ||
| * | ||
| * @param callback - Function to call when response is finished | ||
| */ | ||
| onFinish(callback: (err: Error | null, response: ServerResponse) => void): void; | ||
| /** | ||
| * Writes headers with the Node.js res object using the | ||
| * response.setHeader method | ||
| * Transfers all buffered headers to the underlying Node.js response object | ||
| */ | ||
| relayHeaders(): void; | ||
| /** | ||
| * Calls res.writeHead on the Node.js res object. | ||
| * Writes the response status code and headers | ||
| * | ||
| * @param statusCode - Optional status code to set | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| writeHead(statusCode?: number): this; | ||
| /** | ||
| * Returns the existing value for a given HTTP response | ||
| * header. | ||
| * Gets the value of a response header | ||
| * | ||
| * @param key - Header name | ||
| * @returns The header value | ||
| */ | ||
| getHeader(key: string): import("http").OutgoingHttpHeader | undefined; | ||
| /** | ||
| * Get response headers | ||
| * Gets all response headers as an object | ||
| * | ||
| * @returns Object containing all headers | ||
| */ | ||
@@ -216,10 +256,11 @@ getHeaders(): { | ||
| /** | ||
| * Set header on the response. To `append` values to the existing header, we suggest | ||
| * using [[append]] method. | ||
| * Sets a response header (replaces existing value) | ||
| * | ||
| * If `value` is non existy, then header won't be set. | ||
| * @param key - Header name | ||
| * @param value - Header value (ignored if null/undefined) | ||
| * @returns The Response instance for chaining | ||
| * | ||
| * @example | ||
| * ```js | ||
| * response.header('content-type', 'application/json') | ||
| * ```ts | ||
| * response.header('Content-Type', 'application/json') | ||
| * ``` | ||
@@ -229,10 +270,11 @@ */ | ||
| /** | ||
| * Append value to an existing header. To replace the value, we suggest using | ||
| * [[header]] method. | ||
| * Appends a value to an existing response header | ||
| * | ||
| * If `value` is not existy, then header won't be set. | ||
| * @param key - Header name | ||
| * @param value - Header value to append (ignored if null/undefined) | ||
| * @returns The Response instance for chaining | ||
| * | ||
| * @example | ||
| * ```js | ||
| * response.append('set-cookie', 'username=virk') | ||
| * ```ts | ||
| * response.append('Set-Cookie', 'session=abc123') | ||
| * ``` | ||
@@ -242,32 +284,47 @@ */ | ||
| /** | ||
| * Adds HTTP response header, when it doesn't exists already. | ||
| * Sets a header only if it doesn't already exist | ||
| * | ||
| * @param key - Header name | ||
| * @param value - Header value | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| safeHeader(key: string, value: CastableHeader): this; | ||
| /** | ||
| * Removes the existing response header from being sent. | ||
| * Removes a response header | ||
| * | ||
| * @param key - Header name to remove | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| removeHeader(key: string): this; | ||
| /** | ||
| * Returns the status code for the response | ||
| * Gets the current response status code | ||
| * | ||
| * @returns The HTTP status code | ||
| */ | ||
| getStatus(): number; | ||
| /** | ||
| * Set HTTP status code | ||
| * Sets the response status code | ||
| * | ||
| * @param code - HTTP status code | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| status(code: number): this; | ||
| /** | ||
| * Set's status code only when it's not explictly | ||
| * set | ||
| * Sets the status code only if not explicitly set already | ||
| * | ||
| * @param code - HTTP status code | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| safeStatus(code: number): this; | ||
| /** | ||
| * Set response type by looking up for the mime-type using | ||
| * partial types like file extensions. | ||
| * Sets the Content-Type header based on mime type lookup | ||
| * | ||
| * Make sure to read [mime-types](https://www.npmjs.com/package/mime-types) docs | ||
| * too. | ||
| * @param type - File extension or mime type | ||
| * @param charset - Optional character encoding | ||
| * @returns The Response instance for chaining | ||
| * | ||
| * @example | ||
| * ```js | ||
| * response.type('.json') // Content-type: application/json | ||
| * ```ts | ||
| * response.type('.json') // Content-Type: application/json | ||
| * response.type('html', 'utf-8') // Content-Type: text/html; charset=utf-8 | ||
| * ``` | ||
@@ -277,39 +334,37 @@ */ | ||
| /** | ||
| * Set the Vary HTTP header | ||
| * Sets the Vary HTTP header for cache control | ||
| * | ||
| * @param field - Header field name(s) to vary on | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| vary(field: string | string[]): this; | ||
| /** | ||
| * Set etag by computing hash from the body. This class will set the etag automatically | ||
| * when `etag = true` in the defined config object. | ||
| * Sets the ETag header by computing a hash from the response body | ||
| * | ||
| * Use this function, when you want to compute etag manually for some other resons. | ||
| * @param body - The response body to hash | ||
| * @param weak - Whether to generate a weak ETag | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| setEtag(body: any, weak?: boolean): this; | ||
| /** | ||
| * Set X-Request-Id header by copying the header value from the request if it exists. | ||
| * Sets the X-Request-Id header by copying from the incoming request | ||
| * | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| setRequestId(): this; | ||
| /** | ||
| * Returns a boolean telling if the new response etag evaluates same | ||
| * as the request header `if-none-match`. In case of `true`, the | ||
| * server must return `304` response, telling the browser to | ||
| * use the client cache. | ||
| * Checks if the response is fresh (client cache is valid) | ||
| * | ||
| * You won't have to deal with this method directly, since AdonisJs will | ||
| * handle this for you when `http.etag = true` inside `config/app.js` file. | ||
| * Compares ETags and modified dates between request and response | ||
| * to determine if a 304 Not Modified response should be sent. | ||
| * | ||
| * However, this is how you can use it manually. | ||
| * @returns True if client cache is fresh, false otherwise | ||
| * | ||
| * @example | ||
| * ```js | ||
| * const responseBody = view.render('some-view') | ||
| * | ||
| * // sets the HTTP etag header for response | ||
| * response.setEtag(responseBody) | ||
| * | ||
| * ```ts | ||
| * response.setEtag(content) | ||
| * if (response.fresh()) { | ||
| * response.sendStatus(304) | ||
| * response.status(304).send(null) | ||
| * } else { | ||
| * response.send(responseBody) | ||
| * response.send(content) | ||
| * } | ||
@@ -320,53 +375,50 @@ * ``` | ||
| /** | ||
| * Returns the response body. Returns null when response | ||
| * body is a stream | ||
| * Gets the response body content | ||
| * | ||
| * @returns The response body or null if not set or is a stream | ||
| */ | ||
| getBody(): any; | ||
| /** | ||
| * Send the body as response and optionally generate etag. The default value | ||
| * is read from `config/app.js` file, using `http.etag` property. | ||
| * Sends the response body with optional ETag generation | ||
| * | ||
| * This method buffers the body if `explicitEnd = true`, which is the default | ||
| * behavior and do not change, unless you know what you are doing. | ||
| * @param body - The response body | ||
| * @param generateEtag - Whether to generate ETag header (defaults to config) | ||
| */ | ||
| send(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Alias of [[send]] | ||
| * Sends a JSON response (alias for send) | ||
| * | ||
| * @param body - The response body to serialize as JSON | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| json(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Writes response as JSONP. The callback name is resolved as follows, with priority | ||
| * from top to bottom. | ||
| * Sends a JSONP response with callback wrapping | ||
| * | ||
| * 1. Explicitly defined as 2nd Param. | ||
| * 2. Fetch from request query string. | ||
| * 3. Use the config value `http.jsonpCallbackName` from `config/app.js`. | ||
| * 4. Fallback to `callback`. | ||
| * Callback name resolution priority: | ||
| * 1. Explicit callbackName parameter | ||
| * 2. Query string parameter | ||
| * 3. Config value | ||
| * 4. Default "callback" | ||
| * | ||
| * This method buffers the body if `explicitEnd = true`, which is the default | ||
| * behavior and do not change, unless you know what you are doing. | ||
| * @param body - The response body | ||
| * @param callbackName - JSONP callback function name | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| jsonp(body: any, callbackName?: string, generateEtag?: boolean): void; | ||
| /** | ||
| * Pipe stream to the response. This method will gracefully destroy | ||
| * the stream, avoiding memory leaks. | ||
| * Pipes a readable stream to the response with graceful error handling | ||
| * | ||
| * If `raiseErrors=false`, then this method will self handle all the exceptions by | ||
| * writing a generic HTTP response. To have more control over the error, it is | ||
| * recommended to set `raiseErrors=true` and wrap this function inside a | ||
| * `try/catch` statement. | ||
| * @param body - The readable stream to pipe | ||
| * @param errorCallback - Optional custom error handler | ||
| * | ||
| * Streaming a file from the disk and showing 404 when file is missing. | ||
| * | ||
| * @example | ||
| * ```js | ||
| * // Errors handled automatically with generic HTTP response | ||
| * ```ts | ||
| * // Auto error handling | ||
| * response.stream(fs.createReadStream('file.txt')) | ||
| * | ||
| * // Manually handle (note the await call) | ||
| * try { | ||
| * await response.stream(fs.createReadStream('file.txt')) | ||
| * } catch () { | ||
| * response.status(404).send('File not found') | ||
| * } | ||
| * // Custom error handling | ||
| * response.stream(stream, (error) => { | ||
| * return error.code === 'ENOENT' ? ['Not found', 404] : ['Error', 500] | ||
| * }) | ||
| * ``` | ||
@@ -376,24 +428,18 @@ */ | ||
| /** | ||
| * Download file by streaming it from the file path. This method will setup | ||
| * appropriate `Content-type`, `Content-type` and `Last-modified` headers. | ||
| * Downloads a file by streaming it with appropriate headers | ||
| * | ||
| * Unexpected stream errors are handled gracefully to avoid memory leaks. | ||
| * Automatically sets: | ||
| * - Content-Type from file extension | ||
| * - Content-Length from file size | ||
| * - Last-Modified from file stats | ||
| * - ETag (if enabled) | ||
| * | ||
| * If `raiseErrors=false`, then this method will self handle all the exceptions by | ||
| * writing a generic HTTP response. To have more control over the error, it is | ||
| * recommended to set `raiseErrors=true` and wrap this function inside a | ||
| * `try/catch` statement. | ||
| * @param filePath - Path to the file to download | ||
| * @param generateEtag - Whether to generate ETag header | ||
| * @param errorCallback - Optional custom error handler | ||
| * | ||
| * @example | ||
| * ```js | ||
| * // Errors handled automatically with generic HTTP response | ||
| * response.download('somefile.jpg') | ||
| * | ||
| * // Manually handle (note the await call) | ||
| * try { | ||
| * await response.download('somefile.jpg') | ||
| * } catch (error) { | ||
| * response.status(error.code === 'ENOENT' ? 404 : 500) | ||
| * response.send('Cannot process file') | ||
| * } | ||
| * ```ts | ||
| * response.download('/path/to/file.pdf') | ||
| * response.download('/images/photo.jpg', true, (err) => ['Custom error', 500]) | ||
| * ``` | ||
@@ -403,14 +449,20 @@ */ | ||
| /** | ||
| * Download the file by forcing the user to save the file vs displaying it | ||
| * within the browser. | ||
| * Forces file download by setting Content-Disposition header | ||
| * | ||
| * Internally calls [[download]] | ||
| * @param filePath - Path to the file to download | ||
| * @param name - Optional filename for download (defaults to original filename) | ||
| * @param disposition - Content-Disposition type (defaults to 'attachment') | ||
| * @param generateEtag - Whether to generate ETag header | ||
| * @param errorCallback - Optional custom error handler | ||
| */ | ||
| attachment(filePath: string, name?: string, disposition?: string, generateEtag?: boolean, errorCallback?: (error: NodeJS.ErrnoException) => [string, number?]): void; | ||
| /** | ||
| * Set the location header. | ||
| * Sets the Location header for redirects | ||
| * | ||
| * @param url - The URL to redirect to | ||
| * @returns The Response instance for chaining | ||
| * | ||
| * @example | ||
| * ```js | ||
| * response.location('/login') | ||
| * ```ts | ||
| * response.location('/dashboard') | ||
| * ``` | ||
@@ -420,8 +472,13 @@ */ | ||
| /** | ||
| * Redirect the request. | ||
| * Redirects the request to a different URL | ||
| * | ||
| * @param path - Optional path to redirect to | ||
| * @param forwardQueryString - Whether to forward current query string | ||
| * @param statusCode - HTTP status code for redirect (default: 302) | ||
| * @returns Redirect instance when called without path, void when redirecting | ||
| * | ||
| * @example | ||
| * ```js | ||
| * response.redirect('/foo') | ||
| * response.redirect().toRoute('foo.bar') | ||
| * ```ts | ||
| * response.redirect('/dashboard') | ||
| * response.redirect().toRoute('users.show', { id: 1 }) | ||
| * response.redirect().back() | ||
@@ -433,29 +490,50 @@ * ``` | ||
| /** | ||
| * Abort the request with custom body and a status code. 400 is | ||
| * used when status is not defined | ||
| * Aborts the request with a custom response body and status code | ||
| * | ||
| * @param body - Response body for the aborted request | ||
| * @param status - HTTP status code (defaults to 400) | ||
| * @throws Always throws an HTTP exception | ||
| */ | ||
| abort(body: any, status?: number): never; | ||
| /** | ||
| * Abort the request with custom body and a status code when | ||
| * passed condition returns `true` | ||
| * Conditionally aborts the request if the condition is truthy | ||
| * | ||
| * @param condition - Condition to evaluate | ||
| * @param body - Response body for the aborted request | ||
| * @param status - HTTP status code (defaults to 400) | ||
| */ | ||
| abortIf(condition: unknown, body: any, status?: number): asserts condition is undefined | null | false; | ||
| /** | ||
| * Abort the request with custom body and a status code when | ||
| * passed condition returns `false` | ||
| * Conditionally aborts the request if the condition is falsy | ||
| * | ||
| * @param condition - Condition to evaluate | ||
| * @param body - Response body for the aborted request | ||
| * @param status - HTTP status code (defaults to 400) | ||
| */ | ||
| abortUnless<T>(condition: T, body: any, status?: number): asserts condition is Exclude<T, undefined | null | false>; | ||
| /** | ||
| * Set signed cookie as the response header. The inline options overrides | ||
| * all options from the config. | ||
| * Sets a signed cookie in the response | ||
| * | ||
| * @param key - Cookie name | ||
| * @param value - Cookie value | ||
| * @param options - Cookie options (overrides config defaults) | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| cookie(key: string, value: any, options?: Partial<CookieOptions>): this; | ||
| /** | ||
| * Set encrypted cookie as the response header. The inline options overrides | ||
| * all options from the config. | ||
| * Sets an encrypted cookie in the response | ||
| * | ||
| * @param key - Cookie name | ||
| * @param value - Cookie value | ||
| * @param options - Cookie options (overrides config defaults) | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| encryptedCookie(key: string, value: any, options?: Partial<CookieOptions>): this; | ||
| /** | ||
| * Set unsigned cookie as the response header. The inline options overrides | ||
| * all options from the config. | ||
| * Sets a plain (unsigned/unencrypted) cookie in the response | ||
| * | ||
| * @param key - Cookie name | ||
| * @param value - Cookie value | ||
| * @param options - Cookie options including encode flag | ||
| * @returns The Response instance for chaining | ||
| */ | ||
@@ -466,180 +544,298 @@ plainCookie(key: string, value: any, options?: Partial<CookieOptions & { | ||
| /** | ||
| * Clear existing cookie. | ||
| * Clears an existing cookie by setting it to expire | ||
| * | ||
| * @param key - Cookie name to clear | ||
| * @param options - Cookie options (should match original cookie options) | ||
| * @returns The Response instance for chaining | ||
| */ | ||
| clearCookie(key: string, options?: Partial<CookieOptions>): this; | ||
| /** | ||
| * Finishes the response by writing the lazy body, when `explicitEnd = true` | ||
| * and response is already pending. | ||
| * Finalizes and sends the response | ||
| * | ||
| * Calling this method twice or when `explicitEnd = false` is noop. | ||
| * Writes the buffered body (content, stream, or file) to the client. | ||
| * This method is idempotent - calling it multiple times has no effect. | ||
| */ | ||
| finish(): void; | ||
| /** | ||
| * Shorthand method to finish request with "100" status code | ||
| * Sends a 100 Continue response | ||
| */ | ||
| continue(): void; | ||
| /** | ||
| * Shorthand method to finish request with "101" status code | ||
| * Sends a 101 Switching Protocols response | ||
| */ | ||
| switchingProtocols(): void; | ||
| /** | ||
| * Shorthand method to finish request with "200" status code | ||
| * Sends a 200 OK response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| ok(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "201" status code | ||
| * Sends a 201 Created response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| created(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "202" status code | ||
| * Sends a 202 Accepted response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| accepted(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "203" status code | ||
| * Sends a 203 Non-Authoritative Information response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| nonAuthoritativeInformation(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "204" status code | ||
| * Sends a 204 No Content response | ||
| */ | ||
| noContent(): void; | ||
| /** | ||
| * Shorthand method to finish request with "205" status code | ||
| * Sends a 205 Reset Content response | ||
| */ | ||
| resetContent(): void; | ||
| /** | ||
| * Shorthand method to finish request with "206" status code | ||
| * Sends a 206 Partial Content response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| partialContent(body: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "300" status code | ||
| * Sends a 300 Multiple Choices response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| multipleChoices(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "301" status code | ||
| * Sends a 301 Moved Permanently response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| movedPermanently(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "302" status code | ||
| * Sends a 302 Found (Moved Temporarily) response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| movedTemporarily(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "303" status code | ||
| * Sends a 303 See Other response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| seeOther(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "304" status code | ||
| * Sends a 304 Not Modified response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| notModified(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "305" status code | ||
| * Sends a 305 Use Proxy response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| useProxy(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "307" status code | ||
| * Sends a 307 Temporary Redirect response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| temporaryRedirect(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "400" status code | ||
| * Sends a 400 Bad Request response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| badRequest(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "401" status code | ||
| * Sends a 401 Unauthorized response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| unauthorized(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "402" status code | ||
| * Sends a 402 Payment Required response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| paymentRequired(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "403" status code | ||
| * Sends a 403 Forbidden response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| forbidden(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "404" status code | ||
| * Sends a 404 Not Found response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| notFound(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "405" status code | ||
| * Sends a 405 Method Not Allowed response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| methodNotAllowed(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "406" status code | ||
| * Sends a 406 Not Acceptable response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| notAcceptable(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "407" status code | ||
| * Sends a 407 Proxy Authentication Required response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| proxyAuthenticationRequired(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "408" status code | ||
| * Sends a 408 Request Timeout response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| requestTimeout(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "409" status code | ||
| * Sends a 409 Conflict response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| conflict(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "401" status code | ||
| * Sends a 410 Gone response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| gone(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "411" status code | ||
| * Sends a 411 Length Required response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| lengthRequired(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "412" status code | ||
| * Sends a 412 Precondition Failed response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| preconditionFailed(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "413" status code | ||
| * Sends a 413 Payload Too Large response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| requestEntityTooLarge(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "414" status code | ||
| * Sends a 414 URI Too Long response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| requestUriTooLong(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "415" status code | ||
| * Sends a 415 Unsupported Media Type response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| unsupportedMediaType(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "416" status code | ||
| * Sends a 416 Range Not Satisfiable response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| requestedRangeNotSatisfiable(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "417" status code | ||
| * Sends a 417 Expectation Failed response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| expectationFailed(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "422" status code | ||
| * Sends a 422 Unprocessable Entity response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| unprocessableEntity(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "429" status code | ||
| * Sends a 429 Too Many Requests response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| tooManyRequests(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "500" status code | ||
| * Sends a 500 Internal Server Error response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| internalServerError(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "501" status code | ||
| * Sends a 501 Not Implemented response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| notImplemented(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "502" status code | ||
| * Sends a 502 Bad Gateway response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| badGateway(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "503" status code | ||
| * Sends a 503 Service Unavailable response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| serviceUnavailable(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "504" status code | ||
| * Sends a 504 Gateway Timeout response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| gatewayTimeout(body?: any, generateEtag?: boolean): void; | ||
| /** | ||
| * Shorthand method to finish request with "505" status code | ||
| * Sends a 505 HTTP Version Not Supported response | ||
| * | ||
| * @param body - Response body | ||
| * @param generateEtag - Whether to generate ETag header | ||
| */ | ||
| httpVersionNotSupported(body?: any, generateEtag?: boolean): void; | ||
| } |
@@ -22,2 +22,8 @@ import Macroable from '@poppinss/macroable'; | ||
| route: null | Route; | ||
| /** | ||
| * Creates a new BriskRoute instance | ||
| * @param app - The AdonisJS application instance | ||
| * @param routerMiddleware - Array of global middleware registered on the router | ||
| * @param options - Configuration options for the brisk route | ||
| */ | ||
| constructor(app: Application<any>, routerMiddleware: ParsedGlobalMiddleware[], options: { | ||
@@ -29,2 +35,4 @@ pattern: string; | ||
| * Set handler for the brisk route | ||
| * @param handler - The route handler function | ||
| * @returns The created route instance | ||
| */ | ||
@@ -35,2 +43,4 @@ setHandler(handler: RouteFn): Route; | ||
| * be used when no custom params are defined. | ||
| * @param args - Route identifier, parameters, and options for building the redirect URL | ||
| * @returns The created route instance | ||
| */ | ||
@@ -40,2 +50,5 @@ redirect<Identifier extends keyof GetRoutesForMethod<RoutesList, 'GET'> & string>(...args: RoutesList extends LookupList ? RouteBuilderArguments<Identifier, RoutesList['GET'][Identifier], URLOptions> : []): Route; | ||
| * Redirect request to a fixed URL | ||
| * @param url - The URL to redirect to | ||
| * @param options - Optional redirect options including HTTP status code | ||
| * @returns The created route instance | ||
| */ | ||
@@ -42,0 +55,0 @@ redirectToPath(url: string, options?: { |
@@ -8,3 +8,7 @@ import type { ContainerResolver } from '@adonisjs/fold'; | ||
| * handler | ||
| * @param route - The route JSON object containing route information | ||
| * @param resolver - Container resolver for dependency injection | ||
| * @param ctx - The HTTP context instance | ||
| * @param errorResponder - Error handler function for handling errors | ||
| */ | ||
| export declare function execute(route: RouteJSON, resolver: ContainerResolver<any>, ctx: HttpContext, errorResponder: ServerErrorHandler['handle']): Promise<void>; |
@@ -5,2 +5,5 @@ import { type HttpContext } from '../../http_context/main.ts'; | ||
| * false when the response body has already been set | ||
| * @param value - The value to check | ||
| * @param ctx - The HTTP context instance | ||
| * @returns True if value can be used for response body | ||
| */ | ||
@@ -11,3 +14,5 @@ export declare function canWriteResponseBody(value: any, ctx: HttpContext): boolean; | ||
| * pipeline as the response | ||
| * @param ctx - The HTTP context instance | ||
| * @returns Function that handles return values | ||
| */ | ||
| export declare function useReturnValue(ctx: HttpContext): (value: any) => void; |
@@ -15,2 +15,6 @@ import Macroable from '@poppinss/macroable'; | ||
| routes: (Route | RouteGroup | RouteResource | BriskRoute)[]; | ||
| /** | ||
| * Creates a new RouteGroup instance | ||
| * @param routes - Array of routes that belong to this group | ||
| */ | ||
| constructor(routes: (Route | RouteGroup | RouteResource | BriskRoute)[]); | ||
@@ -24,2 +28,5 @@ /** | ||
| * ``` | ||
| * @param param - The parameter name to match | ||
| * @param matcher - The matcher pattern (RegExp, string, or RouteMatcher) | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
@@ -34,2 +41,4 @@ where(param: string, matcher: RouteMatcher | string | RegExp): this; | ||
| * ``` | ||
| * @param prefix - The prefix to add to all routes in the group | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
@@ -44,2 +53,4 @@ prefix(prefix: string): this; | ||
| * ``` | ||
| * @param domain - The domain pattern for all routes in the group | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
@@ -54,2 +65,4 @@ domain(domain: string): this; | ||
| * ``` | ||
| * @param name - The name to prepend to all route names in the group | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
@@ -64,2 +77,4 @@ as(name: string): this; | ||
| * ``` | ||
| * @param middleware - Middleware function(s) to apply to all routes in the group | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
@@ -69,4 +84,6 @@ use(middleware: OneOrMore<MiddlewareFn | ParsedNamedMiddleware>): this; | ||
| * @alias use | ||
| * @param middleware - Middleware function(s) to apply to all routes in the group | ||
| * @returns Current RouteGroup instance for method chaining | ||
| */ | ||
| middleware(middleware: OneOrMore<MiddlewareFn | ParsedNamedMiddleware>): this; | ||
| } |
@@ -20,2 +20,7 @@ import { type Router } from '../main.ts'; | ||
| #private; | ||
| /** | ||
| * Creates a new UrlBuilder instance | ||
| * @param router - The router instance | ||
| * @param domain - Optional domain for URL generation | ||
| */ | ||
| constructor(router: Router, domain?: string); | ||
@@ -54,2 +59,4 @@ /** | ||
| * Instead use "@adonisjs/core/services/url_builder" instead | ||
| * @param identifier - Route identifier to generate URL for | ||
| * @returns Generated URL string | ||
| */ | ||
@@ -56,0 +63,0 @@ make(identifier: string): string; |
@@ -12,3 +12,3 @@ import type { Encryption } from '@adonisjs/encryption'; | ||
| import type { MiddlewareAsClass, ParsedGlobalMiddleware } from '../types/middleware.ts'; | ||
| import type { RouteFn, RouteJSON, MatchedRoute, RouteMatchers, MakeUrlOptions, MakeSignedUrlOptions, GetControllerHandlers, RouteMatcher } from '../types/route.ts'; | ||
| import type { RouteFn, RouteJSON, MatchedRoute, RouteMatcher, RouteMatchers, MakeUrlOptions, MakeSignedUrlOptions, GetControllerHandlers } from '../types/route.ts'; | ||
| import { type UrlFor, type LookupList, type RoutesList, type SignedURLOptions } from '../types/url_builder.ts'; | ||
@@ -65,2 +65,8 @@ /** | ||
| }; | ||
| /** | ||
| * Creates a new Router instance | ||
| * @param app - The AdonisJS application instance | ||
| * @param encryption - Encryption service for signed URLs | ||
| * @param qsParser - Query string parser for URL generation | ||
| */ | ||
| constructor(app: Application<any>, encryption: Encryption, qsParser: Qs); | ||
@@ -73,2 +79,4 @@ /** | ||
| * Parses the route pattern | ||
| * @param pattern - The route pattern to parse | ||
| * @param matchers - Optional route matchers | ||
| */ | ||
@@ -80,2 +88,4 @@ parsePattern(pattern: string, matchers?: RouteMatchers): import("../types/route.ts").MatchItRouteToken[]; | ||
| * existing list of middleware | ||
| * @param middleware - Array of middleware classes to apply globally | ||
| * @returns Current Router instance for method chaining | ||
| */ | ||
@@ -87,2 +97,4 @@ use(middleware: LazyImport<MiddlewareAsClass>[]): this; | ||
| * of functions you can apply on the routes, or router groups. | ||
| * @param collection - Object mapping middleware names to middleware classes | ||
| * @returns Named middleware functions | ||
| */ | ||
@@ -97,2 +109,6 @@ named<NamedMiddleware extends Record<string, LazyImport<MiddlewareAsClass>>>(collection: NamedMiddleware): { [K in keyof NamedMiddleware]: <Args extends import("../types/middleware.ts").GetMiddlewareArgs<import("@poppinss/utils/types").UnWrapLazyImport<NamedMiddleware[K]>>>(...args: Args) => { | ||
| * Add route for a given pattern and methods | ||
| * @param pattern - The route pattern | ||
| * @param methods - Array of HTTP methods | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -102,2 +118,5 @@ route<T extends Constructor<any>>(pattern: string, methods: string[], handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define a route that handles all common HTTP methods | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -107,2 +126,5 @@ any<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define `GET` route | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -112,2 +134,5 @@ get<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define `POST` route | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -117,2 +142,5 @@ post<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define `PUT` route | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -122,2 +150,5 @@ put<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define `PATCH` route | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -127,2 +158,5 @@ patch<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * Define `DELETE` route | ||
| * @param pattern - The route pattern | ||
| * @param handler - Route handler (function, string, or controller tuple) | ||
| * @returns The created route instance | ||
| */ | ||
@@ -133,2 +167,4 @@ delete<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>; | ||
| * to routes in bulk | ||
| * @param callback - Function that defines routes within the group | ||
| * @returns The created route group instance | ||
| */ | ||
@@ -138,2 +174,5 @@ group(callback: () => void): RouteGroup; | ||
| * Registers a route resource with conventional set of routes | ||
| * @param resource - The resource name | ||
| * @param controller - Controller to handle the resource | ||
| * @returns The created route resource instance | ||
| */ | ||
@@ -143,2 +182,5 @@ resource(resource: string, controller: string | LazyImport<Constructor<any>> | Constructor<any>): RouteResource<import("../types/route.ts").ResourceActionNames>; | ||
| * Register a route resource with shallow nested routes. | ||
| * @param resource - The resource name | ||
| * @param controller - Controller to handle the resource | ||
| * @returns The created route resource instance | ||
| */ | ||
@@ -148,2 +190,4 @@ shallowResource(resource: string, controller: string | LazyImport<Constructor<any>> | Constructor<any>): RouteResource<import("../types/route.ts").ResourceActionNames>; | ||
| * Returns a brisk route instance for a given URL pattern | ||
| * @param pattern - The route pattern | ||
| * @returns The created brisk route instance | ||
| */ | ||
@@ -154,2 +198,5 @@ on(pattern: string): BriskRoute; | ||
| * on all the routes (unless overridden at the route level). | ||
| * @param param - The parameter name to match | ||
| * @param matcher - The matcher pattern (RegExp, string, or RouteMatcher) | ||
| * @returns Current Router instance for method chaining | ||
| */ | ||
@@ -169,2 +216,7 @@ where(param: string, matcher: RouteMatcher | string | RegExp): this; | ||
| * only using the route name | ||
| * @param routeIdentifier - Route name, pattern, or controller reference | ||
| * @param domain - Optional domain to search within | ||
| * @param method - Optional HTTP method to filter by | ||
| * @param disableLegacyLookup - Whether to disable legacy lookup strategies | ||
| * @returns Found route or null if not found | ||
| */ | ||
@@ -181,2 +233,8 @@ find(routeIdentifier: string, domain?: string, method?: string, disableLegacyLookup?: boolean): RouteJSON | null; | ||
| * only using the route name | ||
| * @param routeIdentifier - Route name, pattern, or controller reference | ||
| * @param domain - Optional domain to search within | ||
| * @param method - Optional HTTP method to filter by | ||
| * @param disableLegacyLookup - Whether to disable legacy lookup strategies | ||
| * @returns Found route | ||
| * @throws Error when route is not found | ||
| */ | ||
@@ -192,2 +250,7 @@ findOrFail(routeIdentifier: string, domain?: string, method?: string, disableLegacyLookup?: boolean): RouteJSON; | ||
| * method. The default lookupStrategy is "name" and "pattern". | ||
| * @param routeIdentifier - Route name, pattern, or controller reference | ||
| * @param domain - Optional domain to search within | ||
| * @param method - Optional HTTP method to filter by | ||
| * @param followLookupStrategy - Whether to follow the configured lookup strategy | ||
| * @returns True if route exists, false otherwise | ||
| */ | ||
@@ -197,2 +260,3 @@ has(routeIdentifier: string, domain?: string, method?: string, followLookupStrategy?: boolean): boolean; | ||
| * Returns a list of routes grouped by their domain names | ||
| * @returns Object mapping domain names to route arrays | ||
| */ | ||
@@ -206,2 +270,4 @@ toJSON(): { | ||
| * pick them up. | ||
| * @param indentation - Indentation level for generated types | ||
| * @returns Generated TypeScript types as string | ||
| */ | ||
@@ -211,2 +277,7 @@ generateTypes(indentation?: number): string; | ||
| * Find route for a given URL, method and optionally domain | ||
| * @param uri - The URI to match | ||
| * @param method - HTTP method | ||
| * @param shouldDecodeParam - Whether to decode parameters | ||
| * @param hostname - Optional hostname for domain matching | ||
| * @returns Matched route or null if no match found | ||
| */ | ||
@@ -213,0 +284,0 @@ match(uri: string, method: string, shouldDecodeParam: boolean, hostname?: string | null): null | MatchedRoute; |
@@ -9,2 +9,3 @@ import Macroable from '@poppinss/macroable'; | ||
| * type | ||
| * @returns Route matcher configuration for numeric values | ||
| */ | ||
@@ -17,2 +18,3 @@ number(): { | ||
| * Enforce value to be formatted as uuid | ||
| * @returns Route matcher configuration for UUID values | ||
| */ | ||
@@ -25,2 +27,3 @@ uuid(): { | ||
| * Enforce value to be formatted as slug | ||
| * @returns Route matcher configuration for slug values | ||
| */ | ||
@@ -27,0 +30,0 @@ slug(): { |
@@ -16,2 +16,8 @@ import Macroable from '@poppinss/macroable'; | ||
| routes: Route[]; | ||
| /** | ||
| * Creates a new RouteResource instance | ||
| * @param app - The AdonisJS application instance | ||
| * @param routerMiddleware - Array of global middleware registered on the router | ||
| * @param options - Configuration options for the route resource | ||
| */ | ||
| constructor(app: Application<any>, routerMiddleware: ParsedGlobalMiddleware[], options: { | ||
@@ -25,2 +31,4 @@ resource: string; | ||
| * Register only given routes and remove others | ||
| * @param names - Array of action names to keep | ||
| * @returns Current RouteResource instance with filtered actions | ||
| */ | ||
@@ -30,2 +38,4 @@ only<Name extends ActionNames>(names: Name[]): RouteResource<Name>; | ||
| * Register all routes, except the one's defined | ||
| * @param names - Array of action names to exclude | ||
| * @returns Current RouteResource instance with filtered actions | ||
| */ | ||
@@ -36,2 +46,3 @@ except<Name extends ActionNames>(names: Name[]): RouteResource<Exclude<ActionNames, Name>>; | ||
| * are meant to show forms will not be registered | ||
| * @returns Current RouteResource instance without create and edit actions | ||
| */ | ||
@@ -41,2 +52,5 @@ apiOnly(): RouteResource<Exclude<ActionNames, 'create' | 'edit'>>; | ||
| * Define matcher for params inside the resource | ||
| * @param key - The parameter name to match | ||
| * @param matcher - The matcher pattern (RegExp, string, or RouteMatcher) | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
@@ -46,7 +60,17 @@ where(key: string, matcher: RouteMatcher | string | RegExp): this; | ||
| * Tap into multiple routes to configure them by their name | ||
| * @param callback - Function to configure routes | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
| tap(callback: (route: Route) => void): this; | ||
| /** | ||
| * Tap into multiple routes to configure them by their name | ||
| * @param actions - Action name(s) to configure | ||
| * @param callback - Function to configure matching routes | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
| tap(actions: ActionNames | ActionNames[], callback: (route: Route) => void): this; | ||
| /** | ||
| * Set the param name for a given resource | ||
| * @param resources - Object mapping resource names to parameter names | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
@@ -62,2 +86,5 @@ params(resources: { | ||
| * to existing list. | ||
| * @param actions - Action name(s) or '*' for all actions | ||
| * @param middleware - Middleware function(s) to apply | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
@@ -67,2 +94,5 @@ use(actions: ActionNames | ActionNames[] | '*', middleware: OneOrMore<MiddlewareFn | ParsedNamedMiddleware>): this; | ||
| * @alias use | ||
| * @param actions - Action name(s) or '*' for all actions | ||
| * @param middleware - Middleware function(s) to apply | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
@@ -72,4 +102,7 @@ middleware(actions: ActionNames | ActionNames[] | '*', middleware: OneOrMore<MiddlewareFn | ParsedNamedMiddleware>): this; | ||
| * Prepend name to all the routes | ||
| * @param name - The name to prepend to all route names | ||
| * @param normalizeName - Whether to normalize the name to snake_case | ||
| * @returns Current RouteResource instance for method chaining | ||
| */ | ||
| as(name: string, normalizeName?: boolean): this; | ||
| } |
@@ -12,2 +12,8 @@ import Macroable from '@poppinss/macroable'; | ||
| #private; | ||
| /** | ||
| * Creates a new Route instance | ||
| * @param app - The AdonisJS application instance | ||
| * @param routerMiddleware - Array of global middleware registered on the router | ||
| * @param options - Configuration options for the route | ||
| */ | ||
| constructor(app: Application<any>, routerMiddleware: ParsedGlobalMiddleware[], options: { | ||
@@ -37,2 +43,4 @@ pattern: string; | ||
| * applies multiple prefixes in the reverse order. | ||
| * @param prefix - The prefix to add to the route | ||
| * @returns Current Route instance for method chaining | ||
| */ | ||
@@ -39,0 +47,0 @@ prefix(prefix: string): this; |
| import type { Encryption } from '@adonisjs/encryption'; | ||
| import { type Router } from './main.ts'; | ||
| import { type MatchItRouteToken } from '../types/route.ts'; | ||
| import { type UrlFor, type LookupList, type SignedURLOptions } from '../types/url_builder.ts'; | ||
| /** | ||
| * Makes signed URL for a given route pattern. The route pattern could be an | ||
| * identifier or an array of tokens. | ||
| */ | ||
| export declare function createSignedURL(identifier: string, tokens: MatchItRouteToken[], searchParamsStringifier: (qs: Record<string, any>) => string, encryption: Encryption, params?: any[] | { | ||
| [param: string]: any; | ||
| }, options?: SignedURLOptions): string; | ||
| /** | ||
| * Creates the URLBuilder helper for making signed URLs | ||
| * @param router - The router instance | ||
| * @param encryption - Encryption service for signing URLs | ||
| * @param searchParamsStringifier - Function to stringify query string parameters | ||
| * @returns URL builder function for creating signed URLs | ||
| */ | ||
| export declare function createSignedUrlBuilder<Routes extends LookupList>(router: Router, encryption: Encryption, searchParamsStringifier: (qs: Record<string, any>) => string): UrlFor<Routes, SignedURLOptions>; |
@@ -47,2 +47,4 @@ import type { RouteJSON, MatchedRoute, StoreRoutesTree, MatchItRouteToken } from '../types/route.ts'; | ||
| * ``` | ||
| * @param route - The route to add to the store | ||
| * @returns Current RoutesStore instance for method chaining | ||
| */ | ||
@@ -58,2 +60,7 @@ add(route: RouteJSON): this; | ||
| * the pattern for qualified domain | ||
| * @param url - The URL to match | ||
| * @param method - HTTP method | ||
| * @param shouldDecodeParam - Whether to decode parameters | ||
| * @param domain - Optional domain tokens and hostname | ||
| * @returns Matched route or null if no match found | ||
| */ | ||
@@ -66,4 +73,6 @@ match(url: string, method: string, shouldDecodeParam: boolean, domain?: { | ||
| * Match hostname against registered domains. | ||
| * @param hostname - The hostname to match | ||
| * @returns Array of matched domain tokens | ||
| */ | ||
| matchDomain(hostname?: string | null): MatchItRouteToken[]; | ||
| } |
| import { type Router } from './main.ts'; | ||
| import { type MatchItRouteToken } from '../types/route.ts'; | ||
| import { type UrlFor, type LookupList, type URLOptions } from '../types/url_builder.ts'; | ||
| import { type UrlFor, type LookupList } from '../types/url_builder.ts'; | ||
| /** | ||
| * Makes URL for a given route pattern. The route pattern could be an | ||
| * identifier or an array of tokens. | ||
| */ | ||
| export declare function createURL(identifier: string, tokens: Pick<MatchItRouteToken, 'val' | 'type' | 'end'>[], searchParamsStringifier: (qs: Record<string, any>) => string, params?: any[] | { | ||
| [param: string]: any; | ||
| }, options?: URLOptions): string; | ||
| /** | ||
| * Creates the URLBuilder helper | ||
| * @param router - The router instance | ||
| * @param searchParamsStringifier - Function to stringify query string parameters | ||
| * @returns URL builder function for creating URLs | ||
| */ | ||
| export declare function createUrlBuilder<Routes extends LookupList>(router: Router, searchParamsStringifier: (qs: Record<string, any>) => string): UrlFor<Routes>; |
@@ -6,4 +6,13 @@ import type { ContainerResolver } from '@adonisjs/fold'; | ||
| /** | ||
| * The middleware handler invokes the middleware functions. | ||
| * Creates a middleware execution handler that invokes middleware functions with tracing support | ||
| * | ||
| * This factory function returns a middleware execution handler that: | ||
| * - Executes middleware with debug logging | ||
| * - Provides distributed tracing through tracing channels | ||
| * - Passes the container resolver, HTTP context, and next function to middleware | ||
| * | ||
| * @param resolver - Container resolver for dependency injection | ||
| * @param ctx - HTTP context containing request/response data | ||
| * @returns Middleware execution function | ||
| */ | ||
| export declare function middlewareHandler(resolver: ContainerResolver<any>, ctx: HttpContext): (fn: ParsedGlobalMiddleware, next: NextFn) => Promise<any>; |
@@ -6,6 +6,16 @@ import type { ContainerResolver } from '@adonisjs/fold'; | ||
| /** | ||
| * The route finder is executed after the server middleware stack. | ||
| * It looks for a matching route and executes the route middleware | ||
| * stack. | ||
| * Creates a route finder function that matches HTTP requests to registered routes | ||
| * | ||
| * This factory function returns a route handler that: | ||
| * - Matches incoming requests against registered routes | ||
| * - Extracts route parameters and subdomains | ||
| * - Executes the matched route's handler and middleware | ||
| * - Throws E_ROUTE_NOT_FOUND error for unmatched requests | ||
| * | ||
| * @param router - Router instance containing registered routes | ||
| * @param resolver - Container resolver for dependency injection | ||
| * @param ctx - HTTP context containing request/response data | ||
| * @param errorResponder - Error handler for route execution errors | ||
| * @returns Route execution function | ||
| */ | ||
| export declare function routeFinder(router: Router, resolver: ContainerResolver<any>, ctx: HttpContext, errorResponder: ServerErrorHandler['handle']): () => any; |
| import type { HttpContext } from '../../http_context/main.ts'; | ||
| /** | ||
| * Writes the response to the socket. The "finish" method can | ||
| * raise error when unable to serialize the response. | ||
| * Creates a response writer function that finalizes HTTP responses with error handling | ||
| * | ||
| * This factory function returns a response finalizer that: | ||
| * - Calls the response.finish() method to send the response | ||
| * - Catches serialization errors and sends a 500 error response | ||
| * - Logs fatal errors for debugging and monitoring | ||
| * | ||
| * @param ctx - HTTP context containing the response to finalize | ||
| * @returns Response finalization function | ||
| */ | ||
| export declare function writeResponse(ctx: HttpContext): () => void; |
@@ -16,4 +16,18 @@ import type { Logger } from '@adonisjs/logger'; | ||
| /** | ||
| * The HTTP server implementation to handle incoming requests and respond using the | ||
| * registered routes. | ||
| * The Server class provides the core HTTP server implementation for AdonisJS. | ||
| * | ||
| * It handles incoming HTTP requests by processing them through middleware pipelines, | ||
| * routing them to appropriate handlers, and managing response generation. The server | ||
| * supports custom error handling, middleware registration, and various Node.js HTTP | ||
| * server configurations. | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * const server = new Server(app, encryption, emitter, logger, config) | ||
| * server.use([AuthMiddleware, CorsMiddleware]) | ||
| * server.errorHandler(() => import('./error_handler.ts')) | ||
| * await server.boot() | ||
| * | ||
| * http.createServer(server.handle.bind(server)) | ||
| * ``` | ||
| */ | ||
@@ -23,66 +37,106 @@ export declare class Server { | ||
| /** | ||
| * Check if the server has already been booted | ||
| * Indicates whether the server has completed its boot process | ||
| */ | ||
| get booted(): boolean; | ||
| /** | ||
| * Know if async local storage is enabled or not. | ||
| * Indicates whether async local storage is enabled for request context | ||
| */ | ||
| get usingAsyncLocalStorage(): boolean; | ||
| /** | ||
| * Creates a new Server instance | ||
| * | ||
| * @param app - AdonisJS application instance | ||
| * @param encryption - Encryption service for secure operations | ||
| * @param emitter - Event emitter for server lifecycle events | ||
| * @param logger - Logger instance for server operations | ||
| * @param config - Server configuration settings | ||
| */ | ||
| constructor(app: Application<any>, encryption: Encryption, emitter: EmitterLike<HttpServerEvents>, logger: Logger, config: ServerConfig); | ||
| /** | ||
| * Creates a pipeline of middleware. | ||
| * Creates a testing middleware pipeline for unit/integration testing | ||
| * | ||
| * @param middleware - Array of middleware classes to include in pipeline | ||
| * @returns TestingMiddlewarePipeline instance for test execution | ||
| */ | ||
| pipeline(middleware: MiddlewareAsClass[]): TestingMiddlewarePipeline; | ||
| /** | ||
| * Define an array of middleware to use on all the incoming HTTP request. | ||
| * Calling this method multiple times pushes to the existing list | ||
| * of middleware | ||
| * Registers global middleware to run on all incoming HTTP requests | ||
| * | ||
| * @param middleware - Array of lazy-imported middleware classes | ||
| * @returns The Server instance for method chaining | ||
| */ | ||
| use(middleware: LazyImport<MiddlewareAsClass>[]): this; | ||
| /** | ||
| * Register a custom error handler for HTTP requests. | ||
| * All errors will be reported to this method | ||
| * Registers a custom error handler for HTTP request processing | ||
| * | ||
| * @param handler - Lazy import of the error handler class | ||
| * @returns The Server instance for method chaining | ||
| */ | ||
| errorHandler(handler: LazyImport<ErrorHandlerAsAClass>): this; | ||
| /** | ||
| * Boot the server. Calling this method performs the following actions. | ||
| * Initializes the server by compiling middleware, committing routes, and resolving handlers | ||
| * | ||
| * - Register routes with the store. | ||
| * - Resolve and construct the error handler. | ||
| * Performs the following operations: | ||
| * - Compiles the middleware stack | ||
| * - Commits registered routes to the router | ||
| * - Resolves and instantiates the custom error handler | ||
| */ | ||
| boot(): Promise<void>; | ||
| /** | ||
| * Set the HTTP server instance used to listen for requests. | ||
| * Configures the underlying Node.js HTTP/HTTPS server with timeout settings | ||
| * | ||
| * @param server - Node.js HTTP or HTTPS server instance | ||
| */ | ||
| setNodeServer(server: HttpServer | HttpsServer): void; | ||
| /** | ||
| * Returns reference to the underlying HTTP server | ||
| * in use | ||
| * Gets the underlying Node.js HTTP/HTTPS server instance | ||
| * | ||
| * @returns The configured server instance or undefined if not set | ||
| */ | ||
| getNodeServer(): HttpServer<typeof IncomingMessage, typeof ServerResponse> | HttpsServer<typeof IncomingMessage, typeof ServerResponse> | undefined; | ||
| /** | ||
| * Returns reference to the router instance used | ||
| * by the server. | ||
| * Gets the router instance used for route registration and matching | ||
| * | ||
| * @returns The Router instance | ||
| */ | ||
| getRouter(): Router; | ||
| /** | ||
| * Creates an instance of the [[Request]] class | ||
| * Creates a Request instance from Node.js request/response objects | ||
| * | ||
| * @param req - Node.js IncomingMessage | ||
| * @param res - Node.js ServerResponse | ||
| * @returns New Request instance | ||
| */ | ||
| createRequest(req: IncomingMessage, res: ServerResponse): Request; | ||
| /** | ||
| * Creates an instance of the [[Response]] class | ||
| * Creates a Response instance from Node.js request/response objects | ||
| * | ||
| * @param req - Node.js IncomingMessage | ||
| * @param res - Node.js ServerResponse | ||
| * @returns New Response instance | ||
| */ | ||
| createResponse(req: IncomingMessage, res: ServerResponse): Response; | ||
| /** | ||
| * Creates an instance of the [[HttpContext]] class | ||
| * Creates an HttpContext instance with request-specific logger | ||
| * | ||
| * @param request - Request instance | ||
| * @param response - Response instance | ||
| * @param resolver - Container resolver for dependency injection | ||
| * @returns New HttpContext instance | ||
| */ | ||
| createHttpContext(request: Request, response: Response, resolver: ContainerResolver<any>): HttpContext; | ||
| /** | ||
| * Returns a list of server middleware stack | ||
| * Gets the list of registered global middleware | ||
| * | ||
| * @returns Array of parsed global middleware | ||
| */ | ||
| getMiddlewareList(): ParsedGlobalMiddleware[]; | ||
| /** | ||
| * Handle request | ||
| * Handles an incoming HTTP request by creating context and processing through pipeline | ||
| * | ||
| * @param req - Node.js IncomingMessage | ||
| * @param res - Node.js ServerResponse | ||
| * @returns Promise that resolves when request processing is complete | ||
| */ | ||
| handle(req: IncomingMessage, res: ServerResponse): Promise<any>; | ||
| } |
| import diagnostics_channel from 'node:diagnostics_channel'; | ||
| import type { MiddlewareTracingData } from './types/tracing_channels.ts'; | ||
| import type { MiddlewareTracingData, HTTPRequestTracingData, RouteHandlerTracingData } from './types/tracing_channels.ts'; | ||
| /** | ||
| * Traces every HTTP request handled by the {@link Server} class. | ||
| */ | ||
| export declare const httpRequest: diagnostics_channel.TracingChannel<"adonisjs:http.request", import("./http_context/main.ts").HttpContext>; | ||
| export declare const httpRequest: diagnostics_channel.TracingChannel<"adonisjs.http.request", HTTPRequestTracingData>; | ||
| /** | ||
| * Traces middleware executed during the HTTP request | ||
| */ | ||
| export declare const httpMiddleware: diagnostics_channel.TracingChannel<"adonisjs:http.middleware", MiddlewareTracingData>; | ||
| export declare const httpMiddleware: diagnostics_channel.TracingChannel<"adonisjs.http.middleware", MiddlewareTracingData>; | ||
| /** | ||
@@ -18,3 +18,3 @@ * Traces the exception handler that converts errors into HTTP responses | ||
| */ | ||
| export declare const httpRouteHandler: diagnostics_channel.TracingChannel<"adonisjs:http.route.handler", import("./types/route.ts").RouteJSON>; | ||
| export declare const httpRouteHandler: diagnostics_channel.TracingChannel<"adonisjs.http.route.handler", RouteHandlerTracingData>; | ||
| /** | ||
@@ -21,0 +21,0 @@ * Traces non-stream and non-file download responses written by the AdonisJS |
@@ -6,3 +6,3 @@ import type { ContainerResolver } from '@adonisjs/fold'; | ||
| /** | ||
| * Middleware represented as a class | ||
| * Middleware represented as a class constructor that implements a handle method | ||
| */ | ||
@@ -13,60 +13,85 @@ export type MiddlewareAsClass = Constructor<{ | ||
| /** | ||
| * Check if a union has undefined or null | ||
| * Utility type to check if a union type includes undefined or null values | ||
| */ | ||
| type HasUndefined<T> = T extends NonNullable<T> ? true : false; | ||
| /** | ||
| * Returns the arguments accepted by the middleware's handle method | ||
| * Extracts and returns the argument types accepted by a middleware's handle method | ||
| * Returns an empty array if no args, otherwise returns the args type as a tuple | ||
| */ | ||
| export type GetMiddlewareArgs<Middleware extends MiddlewareAsClass> = Parameters<InstanceType<Middleware>['handle']>[2] extends undefined ? [] : HasUndefined<Parameters<InstanceType<Middleware>['handle']>[2]> extends true ? [Parameters<InstanceType<Middleware>['handle']>[2]] : [Parameters<InstanceType<Middleware>['handle']>[2]?]; | ||
| /** | ||
| * The middleware defined as a function on the router or the server | ||
| * Middleware defined as a function that accepts HTTP context and next function | ||
| */ | ||
| export type MiddlewareFn = (ctx: HttpContext, next: NextFn) => any; | ||
| /** | ||
| * Parsed global middleware | ||
| * Representation of a parsed global middleware with its metadata and execution handler | ||
| */ | ||
| export type ParsedGlobalMiddleware = { | ||
| /** Optional name for the middleware */ | ||
| name?: string; | ||
| /** Reference to the middleware class or lazy import */ | ||
| reference: LazyImport<MiddlewareAsClass> | MiddlewareAsClass; | ||
| /** Handler function that executes the middleware */ | ||
| handle: (resolver: ContainerResolver<any>, ...args: [ctx: HttpContext, next: NextFn, params?: any]) => any; | ||
| }; | ||
| /** | ||
| * Parsed named middleware | ||
| * Representation of a parsed named middleware with its metadata, arguments and execution handler | ||
| */ | ||
| export type ParsedNamedMiddleware = { | ||
| /** Name identifier for the middleware */ | ||
| name: string; | ||
| /** Reference to the middleware class or lazy import */ | ||
| reference: LazyImport<MiddlewareAsClass> | MiddlewareAsClass; | ||
| /** Handler function that executes the middleware */ | ||
| handle: ParsedGlobalMiddleware['handle']; | ||
| /** Arguments to pass to the middleware */ | ||
| args: any; | ||
| }; | ||
| /** | ||
| * Info node representing a middleware handler | ||
| * Information node describing different types of middleware handlers and their metadata | ||
| */ | ||
| export type MiddlewareHandlerInfo = { | ||
| /** Type identifier for closure middleware */ | ||
| type: 'closure'; | ||
| /** Name of the closure middleware */ | ||
| name: string; | ||
| } | { | ||
| /** Type identifier for named middleware */ | ||
| type: 'named'; | ||
| /** Name of the named middleware */ | ||
| name: string; | ||
| /** Arguments to pass to the middleware */ | ||
| args: any | undefined; | ||
| /** Method name on the middleware class */ | ||
| method: string; | ||
| /** Module name or file path for the middleware */ | ||
| moduleNameOrPath: string; | ||
| } | { | ||
| /** Type identifier for global middleware */ | ||
| type: 'global'; | ||
| /** Optional name for the global middleware */ | ||
| name?: string | undefined; | ||
| /** Method name on the middleware class */ | ||
| method: string; | ||
| /** Module name or file path for the middleware */ | ||
| moduleNameOrPath: string; | ||
| }; | ||
| /** | ||
| * Info node representing route handler | ||
| * Information node describing different types of route handlers and their metadata | ||
| */ | ||
| export type RouteHandlerInfo = { | ||
| /** Type identifier for closure route handler */ | ||
| type: 'closure'; | ||
| /** Name of the closure handler */ | ||
| name: string; | ||
| /** Optional arguments for the closure */ | ||
| args?: string; | ||
| } | { | ||
| /** Type identifier for controller route handler */ | ||
| type: 'controller'; | ||
| /** Method name on the controller class */ | ||
| method: string; | ||
| /** Module name or file path for the controller */ | ||
| moduleNameOrPath: string; | ||
| }; | ||
| export {}; |
@@ -0,2 +1,6 @@ | ||
| /** | ||
| * Configuration options for query string parsing and stringification | ||
| */ | ||
| export type QSParserConfig = { | ||
| /** Configuration options for parsing query strings */ | ||
| parse: { | ||
@@ -36,2 +40,3 @@ /** | ||
| }; | ||
| /** Configuration options for stringifying query objects */ | ||
| stringify: { | ||
@@ -38,0 +43,0 @@ /** |
| /** | ||
| * Shape of the request config | ||
| * Configuration options for HTTP request handling and processing | ||
| */ | ||
@@ -4,0 +4,0 @@ export type RequestConfig = { |
| import { type Readable } from 'node:stream'; | ||
| /** | ||
| * Cookie options can that can be set on the response | ||
| * Configuration options for HTTP cookies that can be set on the response | ||
| */ | ||
| export type CookieOptions = { | ||
| /** Domain name for the cookie */ | ||
| domain: string; | ||
| /** Expiration date for the cookie or function that returns the date */ | ||
| expires: Date | (() => Date); | ||
| /** Whether the cookie should be accessible only through HTTP(S) */ | ||
| httpOnly: boolean; | ||
| /** Maximum age of the cookie in seconds or as a string */ | ||
| maxAge: number | string; | ||
| /** URL path for which the cookie is valid */ | ||
| path: string; | ||
| /** SameSite attribute to control cross-site request behavior */ | ||
| sameSite: boolean | 'lax' | 'none' | 'strict'; | ||
| /** Whether the cookie should only be sent over HTTPS */ | ||
| secure: boolean; | ||
| /** Whether the cookie should be partitioned (optional) */ | ||
| partitioned?: boolean; | ||
| /** Priority level for the cookie (optional) */ | ||
| priority?: 'low' | 'medium' | 'high'; | ||
| }; | ||
| /** | ||
| * Types from which response header can be casted to a | ||
| * string | ||
| * Types that can be cast to a string for HTTP response headers | ||
| */ | ||
| export type CastableHeader = string | number | boolean | string[] | number[] | boolean[]; | ||
| /** | ||
| * Config accepted by response the class | ||
| * Configuration options for HTTP response handling and processing | ||
| */ | ||
@@ -39,3 +47,3 @@ export type ResponseConfig = { | ||
| /** | ||
| * Options to set cookies | ||
| * Default options to apply when setting cookies | ||
| */ | ||
@@ -45,4 +53,4 @@ cookie: Partial<CookieOptions>; | ||
| /** | ||
| * Stream that can be piped to the "response.stream" method | ||
| * A readable stream that can be piped to the response stream method | ||
| */ | ||
| export type ResponseStream = Readable; |
@@ -8,20 +8,25 @@ import type Middleware from '@poppinss/middleware'; | ||
| /** | ||
| * Shape of a route param matcher | ||
| * Configuration for matching and casting route parameters | ||
| */ | ||
| export type RouteMatcher = { | ||
| /** Regular expression to match parameter values */ | ||
| match?: RegExp; | ||
| /** Function to cast string parameter values to specific types */ | ||
| cast?: (value: string) => any; | ||
| }; | ||
| /** | ||
| * Route token stored by matchit library | ||
| * Route token structure used internally by the matchit routing library | ||
| */ | ||
| export type MatchItRouteToken = RouteMatcher & { | ||
| /** Original token string */ | ||
| old: string; | ||
| /** Token type identifier (0=static, 1=param, 2=wildcard, 3=optional) */ | ||
| type: 0 | 1 | 2 | 3; | ||
| /** Token value */ | ||
| val: string; | ||
| /** Token end delimiter */ | ||
| end: string; | ||
| }; | ||
| /** | ||
| * Returns a union of methods from a controller that accepts | ||
| * the context as the first argument. | ||
| * Extracts method names from a controller class that accept HttpContext as first parameter | ||
| */ | ||
@@ -32,17 +37,22 @@ export type GetControllerHandlers<Controller extends Constructor<any>> = { | ||
| /** | ||
| * Route handler defined as a function | ||
| * Route handler implemented as a function that accepts HTTP context | ||
| */ | ||
| export type RouteFn = (ctx: HttpContext) => any; | ||
| /** | ||
| * Route handler persisted with the route store | ||
| * Route handler representation stored in the route registry | ||
| */ | ||
| export type StoreRouteHandler = RouteFn | { | ||
| /** Optional name for the handler */ | ||
| name?: string; | ||
| /** Method name on the controller */ | ||
| method: string; | ||
| /** Dynamic import expression for lazy loading */ | ||
| importExpression: string | null; | ||
| /** Reference to controller class or method */ | ||
| reference: string | [LazyImport<Constructor<any>> | Constructor<any>, any?]; | ||
| /** Handler execution function */ | ||
| handle: (resolver: ContainerResolver<any>, ...args: [ctx: HttpContext, ...injections: any[]]) => any; | ||
| }; | ||
| /** | ||
| * The middleware persisted with the route store | ||
| * Middleware representation stored with route information | ||
| */ | ||
@@ -54,9 +64,12 @@ export type StoreRouteMiddleware = MiddlewareFn | ({ | ||
| /** | ||
| * An object of routes for a given HTTP method | ||
| * Route storage structure for a specific HTTP method containing tokens and route mappings | ||
| */ | ||
| export type StoreMethodNode = { | ||
| /** Array of route tokens for pattern matching */ | ||
| tokens: MatchItRouteToken[][]; | ||
| /** Mapping from route patterns to unique route keys */ | ||
| routeKeys: { | ||
| [pattern: string]: string; | ||
| }; | ||
| /** Mapping from route patterns to route definitions */ | ||
| routes: { | ||
@@ -67,13 +80,15 @@ [pattern: string]: RouteJSON; | ||
| /** | ||
| * Each domain node container an object of methods. Each method | ||
| * object has nested routes. | ||
| * Domain-specific route storage containing method-based route organization | ||
| */ | ||
| export type StoreDomainNode = { | ||
| /** HTTP method to method node mapping */ | ||
| [method: string]: StoreMethodNode; | ||
| }; | ||
| /** | ||
| * Routes tree stored within the routes store | ||
| * Complete route tree structure organizing routes by domains and methods | ||
| */ | ||
| export type StoreRoutesTree = { | ||
| /** Global route tokens for pattern matching */ | ||
| tokens: MatchItRouteToken[][]; | ||
| /** Domain-based route organization */ | ||
| domains: { | ||
@@ -84,5 +99,6 @@ [domain: string]: StoreDomainNode; | ||
| /** | ||
| * Shape of the matched route for a pattern, method and domain. | ||
| * Result of successful route matching containing route details and extracted parameters | ||
| */ | ||
| export type MatchedRoute = { | ||
| /** The matched route definition */ | ||
| route: RouteJSON; | ||
@@ -103,9 +119,10 @@ /** | ||
| /** | ||
| * A collection of route matchers | ||
| * Collection of parameter matchers indexed by parameter name | ||
| */ | ||
| export type RouteMatchers = { | ||
| /** Parameter name to matcher mapping */ | ||
| [param: string]: RouteMatcher; | ||
| }; | ||
| /** | ||
| * Representation of a route as JSON | ||
| * Complete route definition with all metadata, handlers, and execution context | ||
| */ | ||
@@ -156,22 +173,28 @@ export type RouteJSON = { | ||
| /** | ||
| * Resource action names | ||
| * Standard RESTful resource action names for CRUD operations | ||
| */ | ||
| export type ResourceActionNames = 'create' | 'index' | 'store' | 'show' | 'edit' | 'update' | 'destroy'; | ||
| /** | ||
| * Options accepted by makeUrl method | ||
| * Options for URL generation (deprecated - use URLBuilder instead) | ||
| * @deprecated | ||
| */ | ||
| export type MakeUrlOptions = { | ||
| /** Query string parameters to append */ | ||
| qs?: Record<string, any>; | ||
| /** Domain name to use for the URL */ | ||
| domain?: string; | ||
| /** Prefix to prepend to the generated URL */ | ||
| prefixUrl?: string; | ||
| /** Whether to disable route lookup optimization */ | ||
| disableRouteLookup?: boolean; | ||
| }; | ||
| /** | ||
| * Options accepted by makeSignedUrl method | ||
| * Options for signed URL generation (deprecated - use URLBuilder instead) | ||
| * @deprecated | ||
| */ | ||
| export type MakeSignedUrlOptions = MakeUrlOptions & { | ||
| /** Expiration time for the signed URL */ | ||
| expiresIn?: string | number; | ||
| /** Purpose identifier for the signed URL */ | ||
| purpose?: string; | ||
| }; |
@@ -8,59 +8,74 @@ import type { Constructor } from '@poppinss/utils/types'; | ||
| /** | ||
| * Normalized HTTP error used by the exception | ||
| * handler. | ||
| * Normalized HTTP error structure used by exception handlers | ||
| */ | ||
| export type HttpError = { | ||
| /** Error message describing the issue */ | ||
| message: string; | ||
| /** HTTP status code */ | ||
| status: number; | ||
| /** Optional error code identifier */ | ||
| code?: string; | ||
| /** Optional stack trace */ | ||
| stack?: string; | ||
| /** Optional underlying cause of the error */ | ||
| cause?: any; | ||
| /** Optional additional error messages */ | ||
| messages?: any; | ||
| /** Optional validation or field errors */ | ||
| errors?: any; | ||
| /** Optional custom error handler method */ | ||
| handle?: (...args: any[]) => any; | ||
| /** Optional error reporting method */ | ||
| report?: (...args: any[]) => any; | ||
| }; | ||
| /** | ||
| * The pipeline for executing middleware during tests | ||
| * Pipeline interface for executing middleware chains during testing | ||
| */ | ||
| export interface TestingMiddlewarePipeline { | ||
| /** Set the final handler for the pipeline */ | ||
| finalHandler(handler: FinalHandler): this; | ||
| /** Set the error handler for the pipeline */ | ||
| errorHandler(handler: ErrorHandler): this; | ||
| /** Execute the middleware pipeline with the given context */ | ||
| run(ctx: HttpContext): Promise<any>; | ||
| } | ||
| /** | ||
| * The expression to define a status page range | ||
| * Expression format for defining HTTP status code ranges for error pages | ||
| */ | ||
| export type StatusPageRange = `${number}..${number}` | `${number}` | number; | ||
| /** | ||
| * The callback function to render status page for a given | ||
| * error. | ||
| * Callback function to render custom status pages for HTTP errors | ||
| */ | ||
| export type StatusPageRenderer = (error: HttpError, ctx: HttpContext) => any | Promise<any>; | ||
| /** | ||
| * Data type for the "http:request_completed" event | ||
| * Payload structure for the http:request_completed event | ||
| */ | ||
| export type HttpRequestFinishedPayload = { | ||
| /** HTTP context for the completed request */ | ||
| ctx: HttpContext; | ||
| /** Request duration as a high-resolution time tuple */ | ||
| duration: [number, number]; | ||
| }; | ||
| /** | ||
| * Events emitted by the HttpServer | ||
| * Event types and payloads emitted by the HTTP server | ||
| */ | ||
| export type HttpServerEvents = { | ||
| /** Event fired when an HTTP request is completed */ | ||
| 'http:request_completed': HttpRequestFinishedPayload; | ||
| }; | ||
| /** | ||
| * Error handler to handle HTTP errors | ||
| * Interface for handling and reporting HTTP errors in the server | ||
| */ | ||
| export type ServerErrorHandler = { | ||
| /** Method to report errors for logging or monitoring */ | ||
| report: (error: any, ctx: HttpContext) => any; | ||
| /** Method to handle errors and send appropriate responses */ | ||
| handle: (error: any, ctx: HttpContext) => any; | ||
| }; | ||
| /** | ||
| * Error handler represented as a class | ||
| * Constructor type for error handler classes that implement ServerErrorHandler | ||
| */ | ||
| export type ErrorHandlerAsAClass = Constructor<ServerErrorHandler>; | ||
| /** | ||
| * Config accepted by the HTTP server | ||
| * Complete configuration options for the HTTP server extending request and response configs | ||
| */ | ||
@@ -67,0 +82,0 @@ export type ServerConfig = RequestConfig & ResponseConfig & { |
| import type { RouteJSON } from './route.ts'; | ||
| import type { HttpContext } from '../http_context/main.ts'; | ||
| import type { MiddlewareFn, ParsedGlobalMiddleware, ParsedNamedMiddleware } from './middleware.ts'; | ||
| export type HTTPRequestTracingData = HttpContext; | ||
| export type MiddlewareTracingData = ParsedGlobalMiddleware | ParsedNamedMiddleware | MiddlewareFn; | ||
| export type RouteHandlerTracingData = RouteJSON; | ||
| /** | ||
| * Tracing data structure for HTTP request events | ||
| */ | ||
| export type HTTPRequestTracingData = { | ||
| /** HTTP context for the traced request */ | ||
| ctx: HttpContext; | ||
| }; | ||
| /** | ||
| * Tracing data structure for middleware execution events | ||
| */ | ||
| export type MiddlewareTracingData = { | ||
| /** The middleware being traced */ | ||
| middleware: ParsedGlobalMiddleware | ParsedNamedMiddleware | MiddlewareFn; | ||
| }; | ||
| /** | ||
| * Tracing data structure for route handler execution events | ||
| */ | ||
| export type RouteHandlerTracingData = { | ||
| /** The route being traced */ | ||
| route: RouteJSON; | ||
| }; |
@@ -6,17 +6,21 @@ /** | ||
| /** | ||
| * Options accepted by "urlFor" helper | ||
| * Configuration options for URL generation helpers | ||
| */ | ||
| export type URLOptions = { | ||
| /** Query string parameters to append to the URL */ | ||
| qs?: Record<string, any>; | ||
| /** URL prefix to prepend to the generated URL */ | ||
| prefixUrl?: string; | ||
| }; | ||
| /** | ||
| * Options accepted by "signedUrlFor" helper | ||
| * Configuration options for signed URL generation helpers | ||
| */ | ||
| export type SignedURLOptions = URLOptions & { | ||
| /** Expiration time for the signed URL */ | ||
| expiresIn?: string | number; | ||
| /** Purpose identifier for the signed URL */ | ||
| purpose?: string; | ||
| }; | ||
| /** | ||
| * Returns params for a route identifier | ||
| * Utility type that constructs function arguments for route URL builders based on route parameters | ||
| */ | ||
@@ -32,4 +36,16 @@ export type RouteBuilderArguments<Identifier, Route, Options extends any = URLOptions> = Route extends LookupListRoute ? Prettify<Route['params'] extends undefined ? [identifier: Identifier, params?: undefined, options?: Options] : [undefined] extends [Route['params']] ? [ | ||
| ]> : never; | ||
| /** | ||
| * LookupList type is used by the URLBuilder to provide | ||
| * type-safety when creating URLs. | ||
| * | ||
| * There is no runtime property that matches this type. Its | ||
| * purely for type-inference. | ||
| */ | ||
| /** | ||
| * Route definition structure for type-safe URL building | ||
| */ | ||
| export type LookupListRoute = { | ||
| /** Parameters as a tuple for positional arguments */ | ||
| paramsTuple?: [...any[]]; | ||
| /** Parameters as a named object */ | ||
| params?: { | ||
@@ -40,10 +56,8 @@ [name: string]: any; | ||
| /** | ||
| * LookupList type is used by the URLBuilder to provide | ||
| * type-safety when creating URLs. | ||
| * | ||
| * There is no runtime property that matches this type. Its | ||
| * purely for type-inference. | ||
| * Complete route lookup structure organized by HTTP methods and route identifiers | ||
| */ | ||
| export type LookupList = { | ||
| /** HTTP method to route mapping */ | ||
| [method: string]: { | ||
| /** Route identifier to route definition mapping */ | ||
| [identifier: string]: LookupListRoute; | ||
@@ -140,3 +154,3 @@ }; | ||
| /** | ||
| * Helper to get routes for a given method from Routes | ||
| * Utility type to extract routes for a specific HTTP method from the routes collection | ||
| */ | ||
@@ -147,6 +161,5 @@ export type GetRoutesForMethod<Routes, Method> = { | ||
| /** | ||
| * To be generated by the router and used by the URL builder | ||
| * and the LookupStore | ||
| * Interface to be augmented by the router containing all registered routes for type-safe URL generation | ||
| */ | ||
| export interface RoutesList { | ||
| } |
+15
-13
| { | ||
| "name": "@adonisjs/http-server", | ||
| "version": "8.0.0-next.5", | ||
| "version": "8.0.0-next.6", | ||
| "description": "AdonisJS HTTP server with support packed with Routing and Cookies", | ||
@@ -35,3 +35,4 @@ "main": "build/index.js", | ||
| "lint": "eslint", | ||
| "quick:test": "node --import=@poppinss/ts-exec --enable-source-maps bin/test.ts" | ||
| "quick:test": "node --import=@poppinss/ts-exec --enable-source-maps bin/test.ts", | ||
| "docs": "typedoc" | ||
| }, | ||
@@ -45,8 +46,8 @@ "keywords": [ | ||
| "devDependencies": { | ||
| "@adonisjs/application": "^9.0.0-next.2", | ||
| "@adonisjs/encryption": "^7.0.0-next.0", | ||
| "@adonisjs/eslint-config": "^3.0.0-next.0", | ||
| "@adonisjs/events": "^10.1.0-next.1", | ||
| "@adonisjs/fold": "^11.0.0-next.0", | ||
| "@adonisjs/logger": "^7.0.0-next.1", | ||
| "@adonisjs/application": "^9.0.0-next.4", | ||
| "@adonisjs/encryption": "^7.0.0-next.1", | ||
| "@adonisjs/eslint-config": "^3.0.0-next.1", | ||
| "@adonisjs/events": "^10.1.0-next.2", | ||
| "@adonisjs/fold": "^11.0.0-next.2", | ||
| "@adonisjs/logger": "^7.1.0-next.0", | ||
| "@adonisjs/prettier-config": "^1.4.5", | ||
@@ -93,2 +94,3 @@ "@adonisjs/tsconfig": "^2.0.0-next.0", | ||
| "tsup": "^8.5.0", | ||
| "typedoc": "^0.28.11", | ||
| "typescript": "^5.9.2", | ||
@@ -119,7 +121,7 @@ "youch": "^4.1.0-beta.11" | ||
| "peerDependencies": { | ||
| "@adonisjs/application": "^9.0.0-next.2", | ||
| "@adonisjs/encryption": "^7.0.0-next.0", | ||
| "@adonisjs/events": "^10.1.0-next.1", | ||
| "@adonisjs/fold": "^11.0.0-next.0", | ||
| "@adonisjs/logger": "^7.0.0-next.1", | ||
| "@adonisjs/application": "^9.0.0-next.4", | ||
| "@adonisjs/encryption": "^7.0.0-next.1", | ||
| "@adonisjs/events": "^10.1.0-next.2", | ||
| "@adonisjs/fold": "^11.0.0-next.2", | ||
| "@adonisjs/logger": "^7.1.0-next.0", | ||
| "youch": "^4.1.0-beta.11" | ||
@@ -126,0 +128,0 @@ }, |
| var __defProp = Object.defineProperty; | ||
| var __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| // src/helpers.ts | ||
| import cookie from "cookie"; | ||
| import matchit from "@poppinss/matchit"; | ||
| import string from "@poppinss/utils/string"; | ||
| import { parseBindingReference } from "@adonisjs/fold"; | ||
| import { default as default2 } from "encodeurl"; | ||
| import { default as default3 } from "mime-types"; | ||
| function parseRoute(pattern, matchers) { | ||
| const tokens = matchit.parse(pattern, matchers); | ||
| return tokens; | ||
| } | ||
| function matchRoute(url, patterns) { | ||
| const tokensBucket = patterns.map((pattern) => parseRoute(pattern)); | ||
| const match = matchit.match(url, tokensBucket); | ||
| if (!match.length) { | ||
| return null; | ||
| } | ||
| return matchit.exec(url, match); | ||
| } | ||
| function serializeCookie(key, value, options) { | ||
| let expires; | ||
| let maxAge; | ||
| if (options) { | ||
| expires = typeof options.expires === "function" ? options.expires() : options.expires; | ||
| maxAge = options.maxAge ? string.seconds.parse(options.maxAge) : void 0; | ||
| } | ||
| return cookie.serialize(key, value, { ...options, maxAge, expires }); | ||
| } | ||
| async function middlewareInfo(middleware) { | ||
| if (typeof middleware === "function") { | ||
| return { | ||
| type: "closure", | ||
| name: middleware.name || "closure" | ||
| }; | ||
| } | ||
| if ("args" in middleware) { | ||
| return { | ||
| type: "named", | ||
| name: middleware.name, | ||
| args: middleware.args, | ||
| ...await parseBindingReference([middleware.reference]) | ||
| }; | ||
| } | ||
| return { | ||
| type: "global", | ||
| name: middleware.name, | ||
| ...await parseBindingReference([middleware.reference]) | ||
| }; | ||
| } | ||
| async function routeInfo(route) { | ||
| return "reference" in route.handler ? { | ||
| type: "controller", | ||
| ...await parseBindingReference(route.handler.reference) | ||
| } : { | ||
| type: "closure", | ||
| name: route.handler.name || "closure", | ||
| args: "listArgs" in route.handler ? String(route.handler.listArgs) : void 0 | ||
| }; | ||
| } | ||
| export { | ||
| __export, | ||
| parseRoute, | ||
| matchRoute, | ||
| serializeCookie, | ||
| middlewareInfo, | ||
| routeInfo, | ||
| default2 as default, | ||
| default3 as default2 | ||
| }; |
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
360418
26.18%10798
17.38%50
2.04%6
20%