This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+9
View File
@@ -0,0 +1,9 @@
# The MIT License
Copyright 2022 Harminder Virk, contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+58
View File
@@ -0,0 +1,58 @@
<div align="center">
<img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1558612869/adonis-readme_zscycu.jpg" width="600px">
</div>
<br />
<hr>
![](https://cdn.jsdelivr.net/gh/thetutlage/static/sponsorkit/sponsors.png)
<hr>
<br />
<div align="center">
<h3>Fullstack MVC framework for Node.js</h3>
<p>AdonisJs is a fullstack Web framework with focus on <strong> ergonomics and speed </strong>. It takes care of much of the Web development hassles, offering you a clean and stable API to build Web apps and micro services.</p>
</div>
<br />
<div align="center">
[![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![snyk-image]][snyk-url]
</div>
<div align="center">
<h3>
<a href="https://adonisjs.com">
Website
</a>
<span> | </span>
<a href="https://docs.adonisjs.com">
Guides
</a>
<span> | </span>
<a href=".github/CONTRIBUTING.md">
Contributing
</a>
</h3>
</div>
<div align="center">
<sub>Built with ❤︎ by <a href="https://github.com/thetutlage">Harminder Virk</a>
</div>
[gh-workflow-image]: https://img.shields.io/github/workflow/status/adonisjs/core/test?style=for-the-badge
[gh-workflow-url]: https://github.com/adonisjs/core/actions/workflows/test.yml "Github action"
[npm-image]: https://img.shields.io/npm/v/@adonisjs/core/latest.svg?style=for-the-badge&logo=npm
[npm-url]: https://www.npmjs.com/package/@adonisjs/core/v/latest "npm"
[typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
[license-url]: LICENSE.md
[license-image]: https://img.shields.io/github/license/adonisjs/adonis-framework?style=for-the-badge
[snyk-image]: https://img.shields.io/snyk/vulnerabilities/github/adonisjs/core?label=Snyk%20Vulnerabilities&style=for-the-badge
[snyk-url]: https://snyk.io/test/github/adonisjs/core?targetFile=package.json "snyk"
+5
View File
@@ -0,0 +1,5 @@
declare module '@ioc:Adonis/Core/Ace' {
import { Kernel } from '@adonisjs/ace';
const Ace: Kernel;
export default Ace;
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+92
View File
@@ -0,0 +1,92 @@
declare module '@ioc:Adonis/Core/AssetsManager' {
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
/**
* Shape of the extend callback
*/
export type ExtendCallback = (manager: AssetsManagerContract, config: AssetsManagerConfig) => AssetsDriverContract;
/**
* Configuration for the asset manager
*/
export type AssetsManagerConfig = {
driver?: string;
publicPath?: string;
script?: {
attributes: Record<string, any>;
};
style?: {
attributes: Record<string, any>;
};
};
/**
* Shape of the driver for the assets manager. Driver driver must implement
* it
*/
export interface AssetsDriverContract {
name: string;
/**
* A boolean to know if entry points are supported or not
*/
hasEntrypoints: boolean;
/**
* Attributes to apply to the script tag
*/
scriptAttributes: Record<string, any>;
/**
* The current version of assets.
*/
version?: string;
/**
* Path to the public output directory. The property must be
* mutable
*/
publicPath: string;
/**
* Returns the manifest contents as an object
*/
manifest(): any;
/**
* Returns path to a given asset entry
*/
assetPath(filename: string): string;
/**
* Returns the entrypoints contents as an object
*/
entryPoints?(): any;
/**
* Returns list for all the javascript files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointJsFiles?(name: string): string[];
/**
* Returns list for all the css files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointCssFiles?(name: string): string[];
}
/**
* Assets manager exposes the API to make link and HTML fragments
* for static assets.
*
* The compilation is not done by the assets manager. It must be done
* separately
*/
export interface AssetsManagerContract extends AssetsDriverContract {
application: ApplicationContract;
/**
* Returns an HTML fragment for script tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointScriptTags(name: string): string;
/**
* Returns an HTML fragment for stylesheet link tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointStyleTags(name: string): string;
/**
* Register a custom asset manager driver
*/
extend(name: string, callback: ExtendCallback): this;
}
const AssetsManager: AssetsManagerContract;
export default AssetsManager;
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+14
View File
@@ -0,0 +1,14 @@
declare module '@ioc:Adonis/Core/Application' {
import Ace from '@ioc:Adonis/Core/Ace';
import { TestUtilsContract } from '@ioc:Adonis/Core/TestUtils';
import { HealthCheckContract } from '@ioc:Adonis/Core/HealthCheck';
import { AssetsManagerContract } from '@ioc:Adonis/Core/AssetsManager';
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler';
interface ContainerBindings {
'Adonis/Core/HealthCheck': HealthCheckContract;
'Adonis/Core/AssetsManager': AssetsManagerContract;
'Adonis/Core/HttpExceptionHandler': typeof HttpExceptionHandler;
'Adonis/Core/Ace': typeof Ace;
'Adonis/Core/TestUtils': TestUtilsContract;
}
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+15
View File
@@ -0,0 +1,15 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
declare module '@ioc:Adonis/Core/Cors' {
import { RequestContract } from '@ioc:Adonis/Core/Request';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
type AllowedValuesTypes = boolean | string | string[];
type CorsConfig = {
enabled: boolean | ((request: RequestContract, ctx: HttpContextContract) => boolean);
origin: AllowedValuesTypes | ((origin: string, ctx: HttpContextContract) => AllowedValuesTypes);
methods: string[];
headers: AllowedValuesTypes | ((headers: string[], ctx: HttpContextContract) => AllowedValuesTypes);
exposeHeaders: string[];
credentials: boolean;
maxAge: number;
};
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@@ -0,0 +1,31 @@
/// <reference types="@adonisjs/logger/build/adonis-typings/logger" />
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
/**
* The binding for the given module is defined inside `providers/AppProvider.ts`
* file.
*/
declare module '@ioc:Adonis/Core/HttpExceptionHandler' {
import { LoggerContract } from '@ioc:Adonis/Core/Logger';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
export default abstract class HttpExceptionHandler {
constructor(logger: LoggerContract);
protected logger: LoggerContract;
protected ignoreCodes: string[];
protected ignoreStatuses: number[];
protected internalIgnoreCodes: string[];
protected statusPages: {
[key: string]: string;
};
expandedStatusPages: {
[key: string]: string;
};
protected disableStatusPagesInDevelopment: boolean;
protected context(ctx: HttpContextContract): any;
protected shouldReport(error: any): boolean;
protected makeJSONResponse(error: any, ctx: HttpContextContract): Promise<void>;
protected makeJSONAPIResponse(error: any, ctx: HttpContextContract): Promise<void>;
protected makeHtmlResponse(error: any, ctx: HttpContextContract): Promise<void>;
report(error: any, ctx: HttpContextContract): void;
handle(error: any, ctx: HttpContextContract): Promise<any>;
}
}
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+40
View File
@@ -0,0 +1,40 @@
/**
* The binding for the given module is defined inside `providers/AppProvider.ts`
* file.
*/
declare module '@ioc:Adonis/Core/HealthCheck' {
export type Checker = string | (() => Promise<HealthReportEntry>);
/**
* Shape of health report entry. Each checker must
* return an object with similar shape.
*/
export type HealthReportEntry = {
displayName: string;
health: {
healthy: boolean;
message?: string;
};
meta?: any;
};
/**
* The shape of entire report
*/
export type HealthReport = {
[service: string]: HealthReportEntry;
};
/**
* Shape of health check contract
*/
export interface HealthCheckContract {
servicesList: string[];
addChecker(service: string, checker: Checker): void;
isLive(): Promise<boolean>;
isReady(): boolean;
getReport(): Promise<{
healthy: boolean;
report: HealthReport;
}>;
}
const HealthCheck: HealthCheckContract;
export default HealthCheck;
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="ace.d.ts" />
/// <reference path="cors.d.ts" />
/// <reference path="health-check.d.ts" />
/// <reference path="exception-handler.d.ts" />
/// <reference path="static.d.ts" />
/// <reference path="assets-manager.d.ts" />
/// <reference path="container.d.ts" />
/// <reference path="test-utils.d.ts" />
/// <reference path="tests.d.ts" />
/// <reference types="@adonisjs/application/build/adonis-typings" />
/// <reference types="@adonisjs/events/build/adonis-typings" />
/// <reference types="@adonisjs/hash/build/adonis-typings" />
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
/// <reference types="@adonisjs/encryption/build/adonis-typings" />
/// <reference types="@adonisjs/bodyparser/build/adonis-typings" />
/// <reference types="@adonisjs/validator" />
/// <reference types="@adonisjs/drive/build/adonis-typings" />
+25
View File
@@ -0,0 +1,25 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/// <reference path="../node_modules/@adonisjs/application/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/events/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/hash/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/http-server/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/encryption/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/bodyparser/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/validator/build/adonis-typings/index.d.ts" />
/// <reference path="../node_modules/@adonisjs/drive/build/adonis-typings/index.d.ts" />
/// <reference path="./ace.ts" />
/// <reference path="./cors.ts" />
/// <reference path="./health-check.ts" />
/// <reference path="./exception-handler.ts" />
/// <reference path="./static.ts" />
/// <reference path="./assets-manager.ts" />
/// <reference path="./container.ts" />
/// <reference path="./test-utils.ts" />
/// <reference path="./tests.ts" />
+15
View File
@@ -0,0 +1,15 @@
/// <reference types="node" />
declare module '@ioc:Adonis/Core/Static' {
import { Stats } from 'fs';
type AssetsConfig = {
enabled: boolean;
acceptRanges?: boolean;
cacheControl?: boolean;
dotFiles?: 'ignore' | 'allow' | 'deny';
etag?: boolean;
lastModified?: boolean;
maxAge?: number | string;
immutable?: boolean;
headers?: (path: string, stats: Stats) => Record<string, any>;
};
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+24
View File
@@ -0,0 +1,24 @@
/// <reference types="node" />
/// <reference types="node" />
declare module '@ioc:Adonis/Core/TestUtils' {
import type { Server as HttpsServer } from 'https';
import type { MacroableConstructorContract } from 'macroable';
import type { IncomingMessage, ServerResponse, Server } from 'http';
export type ServerHandler = (req: IncomingMessage, res: ServerResponse) => any;
export type CustomServerCallback = (handler: ServerHandler) => Server | HttpsServer;
export interface TestUtilsContract {
constructor: MacroableConstructorContract<TestUtilsContract>;
ace(): {
loadCommands(): Promise<void>;
};
httpServer(): {
start(serverCallback?: CustomServerCallback): Promise<() => Promise<void>>;
};
}
/**
* Test utils module is meant to be extended to add custom
* utilities required for testing AdonisJS applications.
*/
const TestUtils: TestUtilsContract;
export default TestUtils;
}
+8
View File
@@ -0,0 +1,8 @@
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+13
View File
@@ -0,0 +1,13 @@
import '@japa/api-client';
declare module '@japa/api-client' {
interface ApiRequest {
/**
* Define encrypted cookie
*/
encryptedCookie(key: string, value: any): this;
/**
* Define plain cookie
*/
plainCookie(key: string, value: any): this;
}
}
+11
View File
@@ -0,0 +1,11 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
require("@japa/api-client");
+13
View File
@@ -0,0 +1,13 @@
import { BaseCommand } from '@adonisjs/ace';
/**
* A command to display a list of routes
*/
export default class DumpRcFile extends BaseCommand {
static commandName: string;
static description: string;
/**
* Log message
*/
private log;
run(): Promise<void>;
}
+33
View File
@@ -0,0 +1,33 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const ace_1 = require("@adonisjs/ace");
/**
* A command to display a list of routes
*/
class DumpRcFile extends ace_1.BaseCommand {
/**
* Log message
*/
log(message) {
if (this.application.environment === 'test') {
this.logger.log(message);
}
else {
console.log(message);
}
}
async run() {
this.log(JSON.stringify(this.application.rcFile, null, 2));
}
}
exports.default = DumpRcFile;
DumpRcFile.commandName = 'dump:rcfile';
DumpRcFile.description = 'Dump contents of .adonisrc.json file along with defaults';
+9
View File
@@ -0,0 +1,9 @@
import { BaseCommand } from '@adonisjs/ace';
/**
* A command to generate a secure app key
*/
export default class GenerateKey extends BaseCommand {
static commandName: string;
static description: string;
run(): Promise<void>;
}
+25
View File
@@ -0,0 +1,25 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const ace_1 = require("@adonisjs/ace");
const helpers_1 = require("@poppinss/utils/build/helpers");
/**
* A command to generate a secure app key
*/
class GenerateKey extends ace_1.BaseCommand {
async run() {
const secret = helpers_1.string.generateRandom(32);
console.log(this.colors.green(secret));
console.log(this.colors.gray(' > During development, you may want to set the above secret as "APP_KEY" inside the .env file'));
}
}
exports.default = GenerateKey;
GenerateKey.commandName = 'generate:key';
GenerateKey.description = 'Generate a new APP_KEY secret';
@@ -0,0 +1,31 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
import ListRoutes from '..';
export declare class BaseRender {
protected command: ListRoutes;
constructor(command: ListRoutes);
/**
* The colors associated with each HTTP method
*/
private methodColors;
/**
* Returns the color name for a HTTP method
*/
getHttpMethodColor(method: string): keyof BaseCommand['colors'];
/**
* Find if the route contains all the methods registered by
* the "Route.any" method
*/
hasAllMethods(methods: string[]): boolean;
/**
* Colorize the route methods
*/
colorizeRouteMethods(methods: string[]): string;
/**
* Colorize the route pattern
*/
colorizeRoutePattern(pattern: string): string;
/**
* Returns the rendering width.
*/
getRenderingWidth(): number;
}
@@ -0,0 +1,70 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseRender = void 0;
/**
* Methods registered by "Route.any" method
*/
const ALL_METHODS = ['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
class BaseRender {
constructor(command) {
this.command = command;
/**
* The colors associated with each HTTP method
*/
this.methodColors = {
GET: 'cyan',
POST: 'green',
PUT: 'yellow',
PATCH: 'yellow',
DELETE: 'red',
HEAD: 'gray',
};
}
/**
* Returns the color name for a HTTP method
*/
getHttpMethodColor(method) {
const methodColor = this.methodColors[method];
return methodColor ? methodColor : 'gray';
}
/**
* Find if the route contains all the methods registered by
* the "Route.any" method
*/
hasAllMethods(methods) {
return ALL_METHODS.every((method) => methods.includes(method));
}
/**
* Colorize the route methods
*/
colorizeRouteMethods(methods) {
return this.hasAllMethods(methods)
? this.command.colors.cyan('ANY')
: methods
.map((method) => this.command.colors[this.getHttpMethodColor(method)](method))
.join(this.command.colors.gray('|'));
}
/**
* Colorize the route pattern
*/
colorizeRoutePattern(pattern) {
return pattern
.replace(/:([^/]+)/gm, `${this.command.colors.yellow('$&')}`)
.replace(/\*/gm, `${this.command.colors.red('$&')}`);
}
/**
* Returns the rendering width.
*/
getRenderingWidth() {
return this.command.maxWidth || process.stdout.columns || 80;
}
}
exports.BaseRender = BaseRender;
@@ -0,0 +1,51 @@
import { BaseRender } from './Base';
import ListRoutes from '../index';
/**
* Renders the routes as a pretty list
*/
export declare class RoutesPrettyRenderer extends BaseRender {
private routes;
private renderingWidth;
private longestMethodName;
constructor(command: ListRoutes);
/**
* Returns a list of serialized routes
*/
private serializeRotues;
/**
* Returns the name of the longest method name
* across all the routes
*/
private findLongestMethodName;
/**
* Render a single route by concatenating and colorizing each part of it
*/
private outputRoute;
/**
* Log message
*/
private log;
/**
* Crop the handler name
*/
private cropHandlerName;
/**
* Returns the whitespace to be rendered between the
* route methods and the route pattern
*/
private getWhiteSpace;
/**
* Returns the rendering width with and without the
* route handler
*/
private getRenderingWidths;
/**
* Returns the dashes to be rendered between pattern and the
* route handler name.
*/
private getDashes;
/**
* Renders routes to the console
*/
render(): void;
}
@@ -0,0 +1,135 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutesPrettyRenderer = void 0;
const Base_1 = require("./Base");
/**
* Renders the routes as a pretty list
*/
class RoutesPrettyRenderer extends Base_1.BaseRender {
constructor(command) {
super(command);
this.routes = this.serializeRotues();
this.renderingWidth = this.getRenderingWidth();
this.longestMethodName = this.findLongestMethodName();
}
/**
* Returns a list of serialized routes
*/
serializeRotues() {
const serializedRoutes = this.command.serializeRoutes();
return Object.keys(serializedRoutes)
.map((domain) => serializedRoutes[domain])
.flat();
}
/**
* Returns the name of the longest method name
* across all the routes
*/
findLongestMethodName() {
return (Math.max(...this.routes.map((route) => {
return this.hasAllMethods(route.methods) ? 'ANY'.length : route.methods.join('|').length;
})) - 1);
}
/**
* Render a single route by concatenating and colorizing each part of it
*/
outputRoute(route, renderingOptions) {
const methodsOutput = this.colorizeRouteMethods(route.methods);
const patternOutput = this.colorizeRoutePattern(route.pattern);
const nameAndHandlerOutput = this.command.colors.gray(route.handler);
const dashesOutput = this.command.colors.gray(renderingOptions.dashes);
this.log(methodsOutput + renderingOptions.spaces + patternOutput + dashesOutput + nameAndHandlerOutput);
/**
* Display middleware in verbose mode
*/
if (route.middleware.length && this.command.verbose) {
const middleware = route.middleware
.map((one) => {
const glyph = '├──';
const spaces = ' '.repeat(Math.max(this.longestMethodName + 5, 0));
return this.command.colors.gray(`${spaces} ${glyph} ${one}`);
})
.join('\n');
this.log(middleware);
}
}
/**
* Log message
*/
log(message) {
if (this.command.application.environment === 'test') {
this.command.logger.log(message);
}
else {
console.log(message);
}
}
/**
* Crop the handler name
*/
cropHandlerName(handlerName, totalLength) {
return handlerName.substring(0, this.renderingWidth - totalLength - 1) + '…';
}
/**
* Returns the whitespace to be rendered between the
* route methods and the route pattern
*/
getWhiteSpace(methods) {
return ' '.repeat(Math.max(this.longestMethodName + 5 - methods.length, 0));
}
/**
* Returns the rendering width with and without the
* route handler
*/
getRenderingWidths(methods, spaces, pattern, nameAndHandler) {
const widthWithoutHandler = (methods + spaces + pattern).length + 1;
const totalWidth = widthWithoutHandler + nameAndHandler.length;
return { widthWithoutHandler, totalWidth };
}
/**
* Returns the dashes to be rendered between pattern and the
* route handler name.
*/
getDashes(totalWidth) {
return ` ${'─'.repeat(Math.max(this.renderingWidth - totalWidth, 0))}`;
}
/**
* Renders routes to the console
*/
render() {
this.routes.forEach((route) => {
const methods = this.hasAllMethods(route.methods) ? 'ANY' : route.methods.join('|');
const pattern = route.domain !== 'root' ? `${route.domain}${route.pattern}` : route.pattern;
let handler = route.name ? ` ${route.name} ${route.handler}` : ` ${route.handler}`;
const spaces = this.getWhiteSpace(methods);
const widths = this.getRenderingWidths(methods, spaces, pattern, handler);
const dashes = this.getDashes(widths.totalWidth);
/**
* If name and handler output is too long we crop it
*/
if (widths.totalWidth > this.renderingWidth) {
handler = this.cropHandlerName(handler, widths.widthWithoutHandler);
}
this.outputRoute({
pattern,
handler,
middleware: route.middleware,
methods: route.methods,
domain: route.domain,
name: route.name,
}, {
spaces,
dashes,
});
});
}
}
exports.RoutesPrettyRenderer = RoutesPrettyRenderer;
@@ -0,0 +1,36 @@
import ListRoutes from '../index';
import { BaseRender } from './Base';
/**
* Renders the routes in a table
*/
export declare class RoutesTableRenderer extends BaseRender {
private routes;
private domains;
private columns;
private longestPatternName;
constructor(command: ListRoutes);
/**
* Returns the length of the longest pattern name among
* all the routes
*/
private getLongestPatterName;
/**
* Returns the width for methods column. We limit them at 15 max and
* return the left over from the column size
*/
private getMethodsColumnWidth;
/**
* Returns the width for all the columns.
*/
private getColumnsSize;
/**
* Distributing the left over from the methods column between
* the pattern column and the handler column.
*/
private distributeLeftOverBetweenColumns;
private getTable;
/**
* Render the serialized routes to the console
*/
render(): void;
}
@@ -0,0 +1,137 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutesTableRenderer = void 0;
const Base_1 = require("./Base");
/**
* Renders the routes in a table
*/
class RoutesTableRenderer extends Base_1.BaseRender {
constructor(command) {
super(command);
this.routes = this.command.serializeRoutes();
this.domains = Object.keys(this.routes);
this.columns = this.getColumnsSize();
this.longestPatternName = this.getLongestPatterName();
}
/**
* Returns the length of the longest pattern name among
* all the routes
*/
getLongestPatterName() {
return (Math.max(...this.domains.map((domain) => {
return Math.max(...this.routes[domain].map((route) => route.pattern.length));
})) + 2);
}
/**
* Returns the width for methods column. We limit them at 15 max and
* return the left over from the column size
*/
getMethodsColumnWidth(columnSize) {
return columnSize < 15
? { size: columnSize, leftOver: 0 }
: { size: 15, leftOver: columnSize - 15 };
}
/**
* Returns the width for all the columns.
*/
getColumnsSize() {
/**
* Dividing equal column width between all the columns
*/
const columnSize = Math.round(this.getRenderingWidth() / 3) - 2;
/**
* Limiting the methods column width to 15 cells at max. 90% of the
* time methods fits within this width, for rest of the cases, they
* will truncate.
*/
const { size: methodsColumnSize, leftOver } = this.getMethodsColumnWidth(columnSize);
/**
* Starting wdith for the patterns column and the handlers column.
*/
const patternColumnSize = columnSize;
const handlerColumnSize = columnSize;
return {
methodsColumnSize,
patternColumnSize,
handlerColumnSize,
leftOver,
};
}
/**
* Distributing the left over from the methods column between
* the pattern column and the handler column.
*/
distributeLeftOverBetweenColumns() {
/**
* If the pattern width is smaller than the column width itself, then
* we just give all the left over to the handler column.
*/
if (this.longestPatternName < this.columns.patternColumnSize) {
this.columns.handlerColumnSize += this.columns.leftOver;
return;
}
const cellsNeeded = this.longestPatternName - this.columns.patternColumnSize;
/**
* If the pattern column width execeeds the left over width, then
* we just give the left over to the pattern column. This will
* also make the pattern column truncate.
*/
if (cellsNeeded > this.columns.leftOver) {
this.columns.patternColumnSize += this.columns.leftOver;
return;
}
/**
* Finally, we give the cells needed for the pattern column and
* give the rest to the handler column.
*/
this.columns.patternColumnSize += cellsNeeded;
this.columns.handlerColumnSize += this.columns.leftOver - cellsNeeded;
return;
}
getTable() {
if (this.columns.leftOver > 0) {
this.distributeLeftOverBetweenColumns();
}
return this.command.ui
.table()
.head(['Method', 'Route & Name', 'Handler & Middleware'])
.columnWidths([
this.columns.methodsColumnSize,
this.columns.patternColumnSize,
this.columns.handlerColumnSize,
]);
}
/**
* Render the serialized routes to the console
*/
render() {
const hasCustomDomains = this.domains.find((domain) => domain !== 'root');
const table = this.getTable();
this.domains.forEach((domain) => {
if (hasCustomDomains) {
table.row([{ colSpan: 3, content: this.command.colors.cyan(domain) }]);
}
const domainRoutes = this.routes[domain];
domainRoutes.forEach((route) => {
const methodsOutput = this.colorizeRouteMethods(route.methods);
const patternAndNameOutput = route.name
? `${this.colorizeRoutePattern(route.pattern)}\n${this.command.colors.gray(route.name)}`
: this.colorizeRoutePattern(route.pattern);
const handlerOutput = route.middleware.length
? `${route.handler}\n${this.command.colors.gray(route.middleware.join('\n'))}`
: route.handler;
table.row([methodsOutput, patternAndNameOutput, handlerOutput]);
});
});
table.render();
}
}
exports.RoutesTableRenderer = RoutesTableRenderer;
+75
View File
@@ -0,0 +1,75 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
import { BaseCommand } from '@adonisjs/ace';
import type { RouteNode } from '@ioc:Adonis/Core/Route';
/**
* Shape of a route serialized by the ListRoute JSON serializer
*/
export type SerializedRoute = {
domain: string;
name: string;
pattern: string;
handler: string;
methods: string[];
middleware: string[];
};
/**
* A command to display a list of routes
*/
export default class ListRoutes extends BaseCommand {
static commandName: string;
static description: string;
verbose: boolean;
reverse: boolean;
methodsFilter: string[];
patternsFilter: string[];
namesFilter: string[];
json: boolean;
table: boolean;
maxWidth: number;
/**
* Load application
*/
static settings: {
loadApp: boolean;
stayAlive: boolean;
};
/**
* Returns the display handler name
*/
private getHandlerName;
/**
* Apply the method filter on the route
*/
private hasPassedMethodFilter;
/**
* Apply the pattern filter on the route
*/
private hasPassedPatternFilter;
/**
* Apply the name filter on the route
*/
private hasPassedNameFilter;
/**
* Log message
*/
private log;
/**
* Serialize route to JSON
*/
serializeRoute(route: RouteNode & {
methods: string[];
}, domain: string): {
domain: string;
name: string;
pattern: string;
methods: string[];
handler: string;
middleware: string[];
};
/**
* Returns an array of routes as JSON, filtered according to the
* flags passed to the command
*/
serializeRoutes(): Record<string, SerializedRoute[]>;
run(): Promise<void>;
}
+166
View File
@@ -0,0 +1,166 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const ace_1 = require("@adonisjs/ace");
const TableRenderer_1 = require("./Renderers/TableRenderer");
const PrettyRenderer_1 = require("./Renderers/PrettyRenderer");
/**
* A command to display a list of routes
*/
class ListRoutes extends ace_1.BaseCommand {
/**
* Returns the display handler name
*/
getHandlerName(route) {
const resolvedHandler = route.meta.resolvedHandler;
if (resolvedHandler.type === 'function') {
return 'Closure';
}
const defaultControllersNamespace = this.application.namespacesMap.get('httpControllers');
return `${resolvedHandler.namespace.replace(new RegExp(`^${defaultControllersNamespace}\/`), '')}.${resolvedHandler.method}`;
}
/**
* Apply the method filter on the route
*/
hasPassedMethodFilter(route) {
if (!this.methodsFilter || !this.methodsFilter.length) {
return true;
}
return !!this.methodsFilter.find((filter) => route.methods.includes(filter.toUpperCase()));
}
/**
* Apply the pattern filter on the route
*/
hasPassedPatternFilter(route) {
if (!this.patternsFilter || !this.patternsFilter.length) {
return true;
}
return !!this.patternsFilter.find((filter) => route.pattern.includes(filter));
}
/**
* Apply the name filter on the route
*/
hasPassedNameFilter(route) {
if (!this.namesFilter || !this.namesFilter.length) {
return true;
}
return !!this.namesFilter.find((filter) => route.name.includes(filter));
}
/**
* Log message
*/
log(message) {
if (this.application.environment === 'test') {
this.logger.log(message);
}
else {
console.log(message);
}
}
/**
* Serialize route to JSON
*/
serializeRoute(route, domain) {
return {
domain,
name: route.name || '',
pattern: route.pattern,
methods: route.methods,
handler: this.getHandlerName(route),
middleware: route.middleware.map((one) => (typeof one === 'function' ? 'Closure' : one)),
};
}
/**
* Returns an array of routes as JSON, filtered according to the
* flags passed to the command
*/
serializeRoutes() {
const Router = this.application.container.use('Adonis/Core/Route');
Router.commit();
const routes = Router.toJSON();
return Object.keys(routes).reduce((result, domain) => {
const domainRoutes = routes[domain]
.map((route) => this.serializeRoute(route, domain))
.filter((route) => {
return (this.hasPassedMethodFilter(route) &&
this.hasPassedNameFilter(route) &&
this.hasPassedPatternFilter(route));
});
if (this.reverse) {
domainRoutes.reverse();
}
result[domain] = domainRoutes;
return result;
}, {});
}
async run() {
if (this.json) {
this.log(JSON.stringify(this.serializeRoutes(), null, 2));
}
else if (this.table) {
new TableRenderer_1.RoutesTableRenderer(this).render();
}
else {
new PrettyRenderer_1.RoutesPrettyRenderer(this).render();
}
await this.application.shutdown();
}
}
ListRoutes.commandName = 'list:routes';
ListRoutes.description = 'List application routes';
/**
* Load application
*/
ListRoutes.settings = {
loadApp: true,
stayAlive: true,
};
__decorate([
ace_1.flags.boolean({ name: 'verbose', description: 'Display more information' }),
__metadata("design:type", Boolean)
], ListRoutes.prototype, "verbose", void 0);
__decorate([
ace_1.flags.boolean({ alias: 'r', name: 'reverse', description: 'Reverse routes display' }),
__metadata("design:type", Boolean)
], ListRoutes.prototype, "reverse", void 0);
__decorate([
ace_1.flags.array({ alias: 'm', name: 'methods', description: 'Filter routes by method' }),
__metadata("design:type", Array)
], ListRoutes.prototype, "methodsFilter", void 0);
__decorate([
ace_1.flags.array({ alias: 'p', name: 'patterns', description: 'Filter routes by the route pattern' }),
__metadata("design:type", Array)
], ListRoutes.prototype, "patternsFilter", void 0);
__decorate([
ace_1.flags.array({ alias: 'n', name: 'names', description: 'Filter routes by route name' }),
__metadata("design:type", Array)
], ListRoutes.prototype, "namesFilter", void 0);
__decorate([
ace_1.flags.boolean({ description: 'Output as JSON' }),
__metadata("design:type", Boolean)
], ListRoutes.prototype, "json", void 0);
__decorate([
ace_1.flags.boolean({ description: 'Output as Table' }),
__metadata("design:type", Boolean)
], ListRoutes.prototype, "table", void 0);
__decorate([
ace_1.flags.number({ description: 'Specify maximum rendering width. Ignored for JSON Output' }),
__metadata("design:type", Number)
], ListRoutes.prototype, "maxWidth", void 0);
exports.default = ListRoutes;
+2
View File
@@ -0,0 +1,2 @@
declare const _default: string[];
export default _default;
+15
View File
@@ -0,0 +1,15 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = [
'@adonisjs/core/build/commands/DumpRc.js',
'@adonisjs/core/build/commands/ListRoutes/index',
'@adonisjs/core/build/commands/GenerateKey.js',
];
+2
View File
@@ -0,0 +1,2 @@
export { InferListFromConfig, hashConfig } from '@adonisjs/hash/build/config';
export { InferDisksFromConfig, driveConfig } from '@adonisjs/drive/build/config';
+15
View File
@@ -0,0 +1,15 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.driveConfig = exports.hashConfig = void 0;
var config_1 = require("@adonisjs/hash/build/config");
Object.defineProperty(exports, "hashConfig", { enumerable: true, get: function () { return config_1.hashConfig; } });
var config_2 = require("@adonisjs/drive/build/config");
Object.defineProperty(exports, "driveConfig", { enumerable: true, get: function () { return config_2.driveConfig; } });
+81
View File
@@ -0,0 +1,81 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const helpers_1 = require("@poppinss/utils/build/helpers");
const ENV_VALIDATIONS_TEMPLATE_STUB = (0, path_1.join)(__dirname, './templates', 'env.txt');
const STATIC_TEMPLATE_STUB = (0, path_1.join)(__dirname, './templates', 'config', 'static.txt');
const APP_CONFIG_TEMPLATE_STUB = (0, path_1.join)(__dirname, './templates', 'config', 'app.txt');
/**
* Configure package
*/
async function instructions(projectRoot, _, { logger, files }) {
const isApiBoilerplate = process.env['ADONIS_CREATE_APP_BOILERPLATE'] === 'api';
const assetsManager = process.env['ADONIS_CREATE_APP_ENCORE'] === 'true';
/**
* Create app config file
*/
const appConfig = new files.MustacheFile(projectRoot, 'config/app.ts', APP_CONFIG_TEMPLATE_STUB);
if (appConfig.exists()) {
logger.action('create').skipped('config/app.ts', 'File already exists');
}
else {
appConfig.apply({ forceContentNegotiationToJSON: isApiBoilerplate, assetsManager }).commit();
logger.action('create').succeeded('config/app.ts');
}
/**
* Create static config file when boilerplate is not for the api
*/
if (!isApiBoilerplate) {
const staticConfig = new files.MustacheFile(projectRoot, 'config/static.ts', STATIC_TEMPLATE_STUB);
if (staticConfig.exists()) {
logger.action('create').skipped('config/static.ts', 'File already exists');
}
else {
staticConfig.apply({}).commit();
logger.action('create').succeeded('config/static.ts');
}
}
/**
* Add `public` folder to the meta files when not selected api
* boilerplate
*/
if (!isApiBoilerplate) {
const rcFile = new files.AdonisRcFile(projectRoot);
rcFile.addMetaFile('public/**', false);
rcFile.commit();
logger.action(rcFile.exists() ? 'update' : 'create').succeeded('.adonisrc.json');
}
/**
* Create .env file for holding environment variables during
* development
*/
const env = new files.EnvFile(projectRoot);
env.set('PORT', 3333);
env.set('HOST', '0.0.0.0');
env.set('NODE_ENV', 'development');
env.set('APP_KEY', helpers_1.string.generateRandom(32));
env.set('DRIVE_DISK', 'local');
env.commit();
logger.action(env.exists() ? 'update' : 'create').succeeded('.env,.env.example');
/**
* Create env.ts file for performing environment variable validations
*/
const envTsFile = new files.MustacheFile(projectRoot, 'env.ts', ENV_VALIDATIONS_TEMPLATE_STUB);
envTsFile.apply({ assetsManager });
if (envTsFile.exists()) {
logger.action('create').skipped('env.ts');
}
else {
envTsFile.apply({}).commit();
logger.action('create').succeeded('env.ts');
}
}
exports.default = instructions;
+68
View File
@@ -0,0 +1,68 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
/**
* The application provider that sticks all core components
* to the container.
*/
export default class AppProvider {
protected app: ApplicationContract;
constructor(app: ApplicationContract);
static needsApplication: boolean;
/**
* Find if web or test environment
*/
private isWebOrTestEnvironment;
/**
* Additional providers to load
*/
provides: string[];
/**
* Register `HttpExceptionHandler` to the container.
*/
protected registerHttpExceptionHandler(): void;
/**
* Registering the health check provider
*/
protected registerHealthCheck(): void;
/**
* Registering the assets manager
*/
protected registerAssetsManager(): void;
/**
* Lazy initialize the cors hook, if enabled inside the config
*/
protected registerCorsHook(): void;
/**
* Lazy initialize the static assets hook, if enabled inside the config
*/
protected registerStaticAssetsHook(): void;
/**
* Registers base health checkers
*/
protected registerHealthCheckers(): void;
/**
* Register ace kernel to the container. When the process is started
* by running an ace command, then the "Adonis/Core/Ace" binding
* will already be in place and hence we do not overwrite it.
*/
protected registerAceKernel(): void;
/**
* Register utilities object required during testing
*/
protected registerTestUtils(): void;
/**
* Define repl bindings
*/
protected defineReplBindings(): void;
/**
* Define bindings for japa tests
*/
protected defineTestsBindings(): void;
/**
* Registering all required bindings to the container
*/
register(): void;
/**
* Register hooks and health checkers on boot
*/
boot(): void;
}
+201
View File
@@ -0,0 +1,201 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("../services/base");
/**
* The application provider that sticks all core components
* to the container.
*/
class AppProvider {
constructor(app) {
this.app = app;
/**
* Find if web or test environment
*/
this.isWebOrTestEnvironment = ['web', 'test'].includes(this.app.environment);
/**
* Additional providers to load
*/
this.provides = [
'@adonisjs/encryption',
'@adonisjs/events',
'@adonisjs/drive',
'@adonisjs/hash',
'@adonisjs/http-server',
'@adonisjs/bodyparser',
'@adonisjs/validator',
];
}
/**
* Register `HttpExceptionHandler` to the container.
*/
registerHttpExceptionHandler() {
this.app.container.bind('Adonis/Core/HttpExceptionHandler', () => {
const { HttpExceptionHandler } = require('../src/HttpExceptionHandler');
return HttpExceptionHandler;
});
}
/**
* Registering the health check provider
*/
registerHealthCheck() {
this.app.container.singleton('Adonis/Core/HealthCheck', () => {
const { HealthCheck } = require('../src/HealthCheck');
return new HealthCheck(this.app);
});
}
/**
* Registering the assets manager
*/
registerAssetsManager() {
this.app.container.singleton('Adonis/Core/AssetsManager', () => {
const { AssetsManager } = require('../src/AssetsManager');
const config = this.app.container.resolveBinding('Adonis/Core/Config').get('app.assets', {});
return new AssetsManager(config, this.app);
});
}
/**
* Lazy initialize the cors hook, if enabled inside the config
*/
registerCorsHook() {
/**
* Do not register hooks when not running in web
* environment
*/
if (!this.isWebOrTestEnvironment) {
return;
}
/**
* Register the cors before hook with the server
*/
this.app.container.withBindings(['Adonis/Core/Config', 'Adonis/Core/Server'], (Config, Server) => {
const config = Config.get('cors', {});
if (!config.enabled) {
return;
}
const { Cors } = require('../src/Hooks/Cors');
const cors = new Cors(config);
Server.hooks.before(cors.handle.bind(cors));
});
}
/**
* Lazy initialize the static assets hook, if enabled inside the config
*/
registerStaticAssetsHook() {
/**
* Do not register hooks when not running in web
* environment
*/
if (!this.isWebOrTestEnvironment) {
return;
}
/**
* Register the cors before hook with the server
*/
this.app.container.withBindings(['Adonis/Core/Config', 'Adonis/Core/Server', 'Adonis/Core/Application'], (Config, Server, Application) => {
const config = Config.get('static', {});
if (!config.enabled) {
return;
}
const ServeStatic = require('../src/Hooks/Static').ServeStatic;
const serveStatic = new ServeStatic(Application.publicPath(), config);
Server.hooks.before(serveStatic.handle.bind(serveStatic));
});
}
/**
* Registers base health checkers
*/
registerHealthCheckers() {
/**
* Do not register hooks when not running in web
* environment
*/
if (!this.isWebOrTestEnvironment) {
return;
}
this.app.container.withBindings(['Adonis/Core/HealthCheck'], (healthCheck) => {
require('../src/HealthCheck/Checkers/Env').default(healthCheck);
require('../src/HealthCheck/Checkers/AppKey').default(healthCheck);
});
}
/**
* Register ace kernel to the container. When the process is started
* by running an ace command, then the "Adonis/Core/Ace" binding
* will already be in place and hence we do not overwrite it.
*/
registerAceKernel() {
if (!this.app.container.hasBinding('Adonis/Core/Ace')) {
this.app.container.singleton('Adonis/Core/Ace', () => {
const { Kernel } = require('@adonisjs/ace');
return new Kernel(this.app);
});
}
}
/**
* Register utilities object required during testing
*/
registerTestUtils() {
this.app.container.singleton('Adonis/Core/TestUtils', () => {
const { TestUtils } = require('../src/TestUtils');
return new TestUtils(this.app);
});
}
/**
* Define repl bindings
*/
defineReplBindings() {
/**
* Do not register repl bindings when not running in "repl"
* environment
*/
if (this.app.environment !== 'repl') {
return;
}
/**
* Define REPL bindings
*/
this.app.container.withBindings(['Adonis/Addons/Repl'], (Repl) => {
const { defineReplBindings } = require('../src/Bindings/Repl');
defineReplBindings(this.app, Repl);
});
}
/**
* Define bindings for japa tests
*/
defineTestsBindings() {
this.app.container.withBindings(['Japa/Preset/ApiRequest', 'Japa/Preset/ApiClient', 'Adonis/Core/CookieClient'], (ApiRequest, ApiClient, CookieClient) => {
const { defineTestsBindings } = require('../src/Bindings/Tests');
defineTestsBindings(ApiRequest, ApiClient, CookieClient);
});
}
/**
* Registering all required bindings to the container
*/
register() {
(0, base_1.setApp)(this.app);
this.registerHttpExceptionHandler();
this.registerHealthCheck();
this.registerAssetsManager();
this.registerAceKernel();
this.registerTestUtils();
}
/**
* Register hooks and health checkers on boot
*/
boot() {
this.registerCorsHook();
this.registerStaticAssetsHook();
this.registerHealthCheckers();
this.defineReplBindings();
this.defineTestsBindings();
}
}
exports.default = AppProvider;
AppProvider.needsApplication = true;
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="../adonis-typings/container.d.ts" />
/// <reference types="@adonisjs/application/build/adonis-typings/application" />
/// <reference types="@adonisjs/drive/build/adonis-typings/container" />
/// <reference types="@adonisjs/http-server/build/adonis-typings/container" />
/// <reference types="@adonisjs/events/build/adonis-typings/container" />
/// <reference types="@adonisjs/hash/build/adonis-typings/container" />
/// <reference types="@adonisjs/encryption/build/adonis-typings/container" />
/// <reference types="@adonisjs/validator/build/adonis-typings/container" />
/// <reference types="@adonisjs/repl/build/adonis-typings/container" />
/// <reference types="@japa/preset-adonis/build/adonis-typings/container" />
declare const _default: import("@ioc:Adonis/Core/Application").ApplicationContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)();
+3
View File
@@ -0,0 +1,3 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
export declare function setApp(app: ApplicationContract): void;
export declare function getApp(): ApplicationContract;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApp = exports.setApp = void 0;
let appInstance;
function setApp(app) {
appInstance = app;
}
exports.setApp = setApp;
function getApp() {
if (!appInstance) {
throw new Error('Cannot get AdonisJS application instance. Make sure to boot the application');
}
return appInstance;
}
exports.getApp = getApp;
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/BodyParser');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/config/build/adonis-typings/config" />
declare const _default: import("@ioc:Adonis/Core/Config").ConfigContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Config');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/drive/build/adonis-typings/drive" />
declare const _default: import("@ioc:Adonis/Core/Drive").DriveManagerContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Drive');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/encryption/build/adonis-typings/encryption" />
declare const _default: import("@ioc:Adonis/Core/Encryption").EncryptionContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Encryption');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/events/build/adonis-typings/events" />
declare const _default: import("@ioc:Adonis/Core/Event").EmitterContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Event');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/hash/build/adonis-typings/hash" />
declare const _default: import("@ioc:Adonis/Core/Hash").HashContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Hash');
+3
View File
@@ -0,0 +1,3 @@
/// <reference path="../adonis-typings/health-check.d.ts" />
declare const _default: import("@ioc:Adonis/Core/HealthCheck").HealthCheckContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/HealthCheck');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
declare const _default: import("@ioc:Adonis/Core/HttpContext").HttpContextConstructorContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/HttpContext');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
declare const _default: import("@ioc:Adonis/Core/Route").RouterContract;
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Route');
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="@adonisjs/validator/build/adonis-typings/validator" />
declare const _default: typeof import("@ioc:Adonis/Core/Validator");
export default _default;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const base_1 = require("./base");
exports.default = (0, base_1.getApp)().container.resolveBinding('Adonis/Core/Validator');
+27
View File
@@ -0,0 +1,27 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
export declare abstract class BaseDriver {
protected application: ApplicationContract;
/**
* We cache the manifest contents and the entrypoints contents
* in production
*/
private manifestCache?;
private entrypointsCache?;
/**
* Path to the output public dir. Defaults to `/public/assets`
*/
publicPath: string;
constructor(application: ApplicationContract);
/**
* Reads the file contents as JSON
*/
protected readFileAsJSON(filePath: string): any;
/**
* Returns the manifest contents as object
*/
manifest(): any;
/**
* Returns the entrypoints contents as object
*/
entryPoints(): any;
}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseDriver = void 0;
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
class BaseDriver {
constructor(application) {
this.application = application;
/**
* Path to the output public dir. Defaults to `/public/assets`
*/
this.publicPath = this.application.publicPath('assets');
}
/**
* Reads the file contents as JSON
*/
readFileAsJSON(filePath) {
if (!(0, fs_extra_1.pathExistsSync)(filePath)) {
throw new Error(`Cannot find "${filePath}" file. Make sure you are compiling assets`);
}
return JSON.parse((0, fs_extra_1.readFileSync)(filePath, 'utf-8'));
}
/**
* Returns the manifest contents as object
*/
manifest() {
/**
* Use in-memory cache when exists
*/
if (this.manifestCache) {
this.application.logger.trace('reading manifest from cache');
return this.manifestCache;
}
const manifest = this.readFileAsJSON((0, path_1.join)(this.publicPath, 'manifest.json'));
this.application.logger.trace('reading manifest from %s', this.publicPath);
/**
* Cache manifest in production to avoid re-reading the file from disk
*/
if (this.application.inProduction) {
this.manifestCache = manifest;
}
return manifest;
}
/**
* Returns the entrypoints contents as object
*/
entryPoints() {
/**
* Use in-memory cache when exists
*/
if (this.entrypointsCache) {
this.application.logger.trace('reading entrypoints from cache');
return this.entrypointsCache;
}
const entryPoints = this.readFileAsJSON((0, path_1.join)(this.publicPath, 'entrypoints.json'));
this.application.logger.trace('reading entrypoints from %s', this.publicPath);
/**
* Cache entrypoints file in production to avoid re-reading the file from disk
*/
if (this.application.inProduction) {
this.entrypointsCache = entryPoints.entrypoints || {};
}
return entryPoints.entrypoints || {};
}
}
exports.BaseDriver = BaseDriver;
@@ -0,0 +1,58 @@
import { AssetsDriverContract } from '@ioc:Adonis/Core/AssetsManager';
import { BaseDriver } from './Base';
/**
* Resolves entry points and assets path for webpack encore. Relies
* on the "manifest.json" and "entrypoints.json" files.
*
**********************************************************************
* The driver assumes following format for the manifest.json file
**********************************************************************
*
* ```json
* {
* "assetName": "assetUrl"
* }
* ```
**********************************************************************
* The driver assumes following format for the entrypoints.json file
***********************************************************************
*
* ```json
* {
* "entrypoints": {
* "entrypointName": {
* "js": ["path1", "path2"],
* "css": ["path1", "path2"]
* }
* }
* }
* ```
*/
export declare class EncoreDriver extends BaseDriver implements AssetsDriverContract {
name: string;
/**
* Encore driver has support for entrypoints
*/
hasEntrypoints: boolean;
/**
* Attributes to apply to the script tag
*/
scriptAttributes: Record<string, any>;
/**
* Returns the version of the assets by hashing the manifest file
* contents
*/
get version(): string;
/**
* Returns path to a given asset file
*/
assetPath(name: string): string;
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(name: string): string[];
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(name: string): string[];
}
+93
View File
@@ -0,0 +1,93 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncoreDriver = void 0;
const crypto_1 = require("crypto");
const Base_1 = require("./Base");
/**
* Resolves entry points and assets path for webpack encore. Relies
* on the "manifest.json" and "entrypoints.json" files.
*
**********************************************************************
* The driver assumes following format for the manifest.json file
**********************************************************************
*
* ```json
* {
* "assetName": "assetUrl"
* }
* ```
**********************************************************************
* The driver assumes following format for the entrypoints.json file
***********************************************************************
*
* ```json
* {
* "entrypoints": {
* "entrypointName": {
* "js": ["path1", "path2"],
* "css": ["path1", "path2"]
* }
* }
* }
* ```
*/
class EncoreDriver extends Base_1.BaseDriver {
constructor() {
super(...arguments);
this.name = 'encore';
/**
* Encore driver has support for entrypoints
*/
this.hasEntrypoints = true;
/**
* Attributes to apply to the script tag
*/
this.scriptAttributes = {};
}
/**
* Returns the version of the assets by hashing the manifest file
* contents
*/
get version() {
return (0, crypto_1.createHash)('md5').update(JSON.stringify(this.manifest())).digest('hex').slice(0, 10);
}
/**
* Returns path to a given asset file
*/
assetPath(name) {
const manifest = this.manifest();
if (!manifest[name]) {
throw new Error(`Cannot find path for "${name}" asset. Make sure you are compiling assets`);
}
return manifest[name];
}
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(name) {
const entrypoints = this.entryPoints();
if (!entrypoints[name]) {
throw new Error(`Cannot find assets for "${name}" entrypoint. Make sure you are compiling assets`);
}
return entrypoints[name].js || [];
}
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(name) {
const entrypoints = this.entryPoints();
if (!entrypoints[name]) {
throw new Error(`Cannot find assets for "${name}" entrypoint. Make sure you are compiling assets`);
}
return entrypoints[name].css || [];
}
}
exports.EncoreDriver = EncoreDriver;
+38
View File
@@ -0,0 +1,38 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import { AssetsDriverContract } from '@ioc:Adonis/Core/AssetsManager';
/**
* Fake driver stubs out the implementation of the Assets
* manager with empty return data.
*
* The main use case is to make assets manager work during
* testing without compiling the real assets
*/
export declare class FakeDriver implements AssetsDriverContract {
private application;
name: string;
hasEntrypoints: boolean;
publicPath: string;
scriptAttributes: Record<string, any>;
get version(): string;
constructor(application: ApplicationContract);
/**
* Returns the manifest contents as object
*/
manifest(): {};
/**
* Returns path to a given asset file
*/
assetPath(name: string): string;
/**
* Returns the entrypoints contents as object
*/
entryPoints(): {};
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(_: string): string[];
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(_: string): string[];
}
+61
View File
@@ -0,0 +1,61 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeDriver = void 0;
/**
* Fake driver stubs out the implementation of the Assets
* manager with empty return data.
*
* The main use case is to make assets manager work during
* testing without compiling the real assets
*/
class FakeDriver {
get version() {
return '';
}
constructor(application) {
this.application = application;
this.name = 'fake';
this.hasEntrypoints = true;
this.publicPath = this.application.publicPath('assets');
this.scriptAttributes = {};
}
/**
* Returns the manifest contents as object
*/
manifest() {
return {};
}
/**
* Returns path to a given asset file
*/
assetPath(name) {
return `__fake('${name}')`;
}
/**
* Returns the entrypoints contents as object
*/
entryPoints() {
return {};
}
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(_) {
return [];
}
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(_) {
return [];
}
}
exports.FakeDriver = FakeDriver;
+84
View File
@@ -0,0 +1,84 @@
import { AssetsDriverContract } from '@ioc:Adonis/Core/AssetsManager';
import { BaseDriver } from './Base';
/**
* Resolves entry points and assets path for Vite. Relies
* on the "manifest.json" and "entrypoints.json" files.
*
**********************************************************************
* The driver assumes following format for the manifest.json file
**********************************************************************
*
* ```json
* {
* "assetName": {
* "file": "path",
* "src": "path"
* },
* ...
* }
* ```
**********************************************************************
* The driver assumes following format for the entrypoints.json file
***********************************************************************
*
* ```json
* {
* "url": "url"
* "entrypoints": {
* "entryPointName": {
* "js": ["url", "url"],
* "css": ["url", "url"],
* }
* }
* }
* ```
*
* Please read the documentation for understanding the format of the files.
*/
export declare class ViteDriver extends BaseDriver implements AssetsDriverContract {
name: string;
/**
* Vite driver has support for entrypoints
*/
hasEntrypoints: boolean;
/**
* Attributes to apply to the script tag. Vite needs to serve
* source over native ESM
*/
scriptAttributes: Record<string, any>;
/**
* If we should use the manifest. We only use the manifest in production.
*/
private shouldUseManifest;
/**
* Get the assets url from the entrypoints.json file
*/
private getAssetUrl;
/**
* Returns path to a given asset file
*/
assetPath(filename: string): string;
/**
* Returns the manifest contents as object
*
* Note that the manifest file is only available in production.
* Vite doesn't generate any manifest file in development.
*/
manifest(): any;
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(name: string): string[];
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(name: string): string[];
/**
* Returns the script needed for the HMR working with React
*/
getReactHmrScript(): string;
/**
* Returns the script needed for the HMR working with Vite
*/
getViteHmrScript(): string;
}
+139
View File
@@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViteDriver = void 0;
const path_1 = require("path");
const Base_1 = require("./Base");
/**
* Resolves entry points and assets path for Vite. Relies
* on the "manifest.json" and "entrypoints.json" files.
*
**********************************************************************
* The driver assumes following format for the manifest.json file
**********************************************************************
*
* ```json
* {
* "assetName": {
* "file": "path",
* "src": "path"
* },
* ...
* }
* ```
**********************************************************************
* The driver assumes following format for the entrypoints.json file
***********************************************************************
*
* ```json
* {
* "url": "url"
* "entrypoints": {
* "entryPointName": {
* "js": ["url", "url"],
* "css": ["url", "url"],
* }
* }
* }
* ```
*
* Please read the documentation for understanding the format of the files.
*/
class ViteDriver extends Base_1.BaseDriver {
constructor() {
super(...arguments);
this.name = 'vite';
/**
* Vite driver has support for entrypoints
*/
this.hasEntrypoints = true;
/**
* Attributes to apply to the script tag. Vite needs to serve
* source over native ESM
*/
this.scriptAttributes = { type: 'module' };
}
/**
* If we should use the manifest. We only use the manifest in production.
*/
shouldUseManifest() {
return this.application.inProduction;
}
/**
* Get the assets url from the entrypoints.json file
*/
getAssetUrl() {
return this.readFileAsJSON((0, path_1.join)(this.publicPath, 'entrypoints.json')).url;
}
/**
* Returns path to a given asset file
*/
assetPath(filename) {
if (!this.shouldUseManifest()) {
return `${this.getAssetUrl()}/${filename}`;
}
const manifest = this.manifest();
if (!manifest[filename]) {
throw new Error(`Cannot find "${filename}" asset in the manifest file`);
}
return `${this.getAssetUrl()}/${manifest[filename].file}`;
}
/**
* Returns the manifest contents as object
*
* Note that the manifest file is only available in production.
* Vite doesn't generate any manifest file in development.
*/
manifest() {
if (!this.shouldUseManifest()) {
throw new Error('Cannot use manifest when not in production');
}
return super.manifest();
}
/**
* Returns list for all the javascript files for a given entry point
*/
entryPointJsFiles(name) {
const entrypoints = this.entryPoints();
if (!entrypoints[name]) {
throw new Error(`Cannot find assets for "${name}" entrypoint. Make sure to define it inside the "entryPoints" vite config`);
}
return entrypoints[name].js;
}
/**
* Returns list for all the css files for a given entry point
*/
entryPointCssFiles(name) {
const entrypoints = this.entryPoints();
if (!entrypoints[name]) {
throw new Error(`Cannot find assets for "${name}" entrypoint. Make sure to define it inside the "entryPoints" vite config`);
}
return entrypoints[name].css;
}
/**
* Returns the script needed for the HMR working with React
*/
getReactHmrScript() {
if (!this.application.inDev) {
return '';
}
return `
<script type="module">
import RefreshRuntime from '${this.getAssetUrl()}/@react-refresh'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
`;
}
/**
* Returns the script needed for the HMR working with Vite
*/
getViteHmrScript() {
if (!this.application.inDev) {
return '';
}
return `<script type="module" src="${this.getAssetUrl()}/@vite/client"></script>`;
}
}
exports.ViteDriver = ViteDriver;
+87
View File
@@ -0,0 +1,87 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import { ExtendCallback, AssetsManagerConfig, AssetsManagerContract } from '@ioc:Adonis/Core/AssetsManager';
/**
* Assets manager exposes the API to make link and HTML fragments
* for static assets.
*
* The compilation is not done by the assets manager. It must be done
* separately
*/
export declare class AssetsManager implements AssetsManagerContract {
private config;
application: ApplicationContract;
private drivers;
/**
* Attributes to apply to the script tag
*/
get scriptAttributes(): Record<string, any>;
/**
* Configured driver
*/
private driver;
private booted;
/**
* Find if the configured driver supports entrypoints or not
*/
get hasEntrypoints(): boolean;
/**
* Path to the public output directory. The property must be
* mutable
*/
get publicPath(): string;
/**
* Returns the current version of assets
*/
get version(): string | undefined;
/**
* Returns the name of the driver currently in use
*/
get name(): string;
constructor(config: AssetsManagerConfig, application: ApplicationContract);
/**
* Boot the manager. Must be done lazily to allow `extend` method to takes
* in effect.
*/
private boot;
/**
* Ensure entrypoints are enabled, otherwise raise an exception. The
* methods relying on the entrypoints file uses this method
*/
private ensureHasEntryPoints;
/**
* Returns the manifest contents as an object
*/
manifest(): any;
/**
* Returns path to a given asset entry
*/
assetPath(filename: string): string;
/**
* Returns the entrypoints contents as an object
*/
entryPoints(): any;
/**
* Returns list for all the javascript files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointJsFiles(name: string): string[];
/**
* Returns list for all the css files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointCssFiles(name: string): string[];
/**
* Returns an HTML fragment for script tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointScriptTags(name: string): string;
/**
* Returns an HTML fragment for stylesheet link tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointStyleTags(name: string): string;
/**
* Register a custom asset manager driver
*/
extend(name: string, callback: ExtendCallback): this;
}
+184
View File
@@ -0,0 +1,184 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetsManager = void 0;
const utils_1 = require("@poppinss/utils");
const stringify_attributes_1 = __importDefault(require("stringify-attributes"));
const Fake_1 = require("./Drivers/Fake");
const Encore_1 = require("./Drivers/Encore");
const Vite_1 = require("./Drivers/Vite");
/**
* Assets manager exposes the API to make link and HTML fragments
* for static assets.
*
* The compilation is not done by the assets manager. It must be done
* separately
*/
class AssetsManager {
/**
* Attributes to apply to the script tag
*/
get scriptAttributes() {
return this.driver.scriptAttributes;
}
/**
* Find if the configured driver supports entrypoints or not
*/
get hasEntrypoints() {
this.boot();
return this.driver.hasEntrypoints;
}
/**
* Path to the public output directory. The property must be
* mutable
*/
get publicPath() {
this.boot();
return this.driver.publicPath;
}
/**
* Returns the current version of assets
*/
get version() {
this.boot();
return this.driver.version;
}
/**
* Returns the name of the driver currently in use
*/
get name() {
this.boot();
return this.driver.name;
}
constructor(config, application) {
this.config = config;
this.application = application;
this.drivers = {
vite: () => new Vite_1.ViteDriver(this.application),
encore: () => new Encore_1.EncoreDriver(this.application),
fake: () => new Fake_1.FakeDriver(this.application),
};
this.booted = false;
}
/**
* Boot the manager. Must be done lazily to allow `extend` method to takes
* in effect.
*/
boot() {
if (this.booted) {
return false;
}
this.booted = true;
const driver = this.config.driver || 'encore';
/**
* Ensure driver name is recognized
*/
if (!this.drivers[driver]) {
throw new utils_1.Exception(`Invalid asset driver "${driver}". Make sure to register the driver using the "AssetsManager.extend" method`);
}
/**
* Configure the driver
*/
this.driver = this.drivers[driver](this, this.config);
/**
* Configure the public path
*/
if (this.config.publicPath) {
this.driver.publicPath = this.config.publicPath;
}
}
/**
* Ensure entrypoints are enabled, otherwise raise an exception. The
* methods relying on the entrypoints file uses this method
*/
ensureHasEntryPoints() {
if (!this.hasEntrypoints) {
throw new Error(`Cannot reference entrypoints. The "${this.driver.name}" driver does not support entrypoints`);
}
}
/**
* Returns the manifest contents as an object
*/
manifest() {
this.boot();
return this.driver.manifest();
}
/**
* Returns path to a given asset entry
*/
assetPath(filename) {
this.boot();
return this.driver.assetPath(filename);
}
/**
* Returns the entrypoints contents as an object
*/
entryPoints() {
this.boot();
this.ensureHasEntryPoints();
return this.driver.entryPoints();
}
/**
* Returns list for all the javascript files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointJsFiles(name) {
this.boot();
this.ensureHasEntryPoints();
return this.driver.entryPointJsFiles(name);
}
/**
* Returns list for all the css files for a given entry point.
* Raises exceptions when [[hasEntrypoints]] is false
*/
entryPointCssFiles(name) {
this.boot();
this.ensureHasEntryPoints();
return this.driver.entryPointCssFiles(name);
}
/**
* Returns an HTML fragment for script tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointScriptTags(name) {
const scripts = this.entryPointJsFiles(name);
const configDefinedAttributes = this.config.script?.attributes || {};
const driverDefinedAttributes = this.driver.scriptAttributes || {};
const mergedAttributes = {
...configDefinedAttributes,
...driverDefinedAttributes,
};
return scripts
.map((url) => `<script src="${url}"${(0, stringify_attributes_1.default)(mergedAttributes)}></script>`)
.join('\n');
}
/**
* Returns an HTML fragment for stylesheet link tags. Raises exceptions
* when [[hasEntrypoints]] is false
*/
entryPointStyleTags(name) {
const links = this.entryPointCssFiles(name);
const styleAttributes = this.config.style?.attributes || {};
return links
.map((url) => `<link rel="stylesheet" href="${url}"${(0, stringify_attributes_1.default)(styleAttributes)} />`)
.join('\n');
}
/**
* Register a custom asset manager driver
*/
extend(name, callback) {
this.drivers[name] = callback;
return this;
}
}
exports.AssetsManager = AssetsManager;
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="@adonisjs/repl" />
import { ReplContract } from '@ioc:Adonis/Addons/Repl';
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
/**
* Define repl bindings. The method must be invoked when application environment
* is set to repl.
*/
export declare function defineReplBindings(application: ApplicationContract, Repl: ReplContract): void;
+90
View File
@@ -0,0 +1,90 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineReplBindings = void 0;
/**
* Shortcuts to load containers bindings
*/
function setupReplState(repl, key, value) {
repl.server.context[key] = value;
repl.notify(`Loaded ${key} module. You can access it using the "${repl.colors.underline(key)}" variable`);
}
/**
* Define repl bindings. The method must be invoked when application environment
* is set to repl.
*/
function defineReplBindings(application, Repl) {
/**
* Load the encryption module
*/
Repl.addMethod('loadEncryption', (repl) => {
setupReplState(repl, 'Encryption', application.container.resolveBinding('Adonis/Core/Encryption'));
}, {
description: 'Load encryption provider and save reference to the "Encryption" variable',
});
/**
* Load the hash module
*/
Repl.addMethod('loadHash', (repl) => {
setupReplState(repl, 'Hash', application.container.resolveBinding('Adonis/Core/Hash'));
}, {
description: 'Load hash provider and save reference to the "Hash" variable',
});
/**
* Load the Env module
*/
Repl.addMethod('loadEnv', (repl) => {
setupReplState(repl, 'Env', application.container.resolveBinding('Adonis/Core/Env'));
}, {
description: 'Load env provider and save reference to the "Env" variable',
});
/**
* Load the HTTP router
*/
Repl.addMethod('loadRouter', (repl) => {
setupReplState(repl, 'Route', application.container.resolveBinding('Adonis/Core/Route'));
}, {
description: 'Load router and save reference to the "Route" variable',
});
/**
* Load config
*/
Repl.addMethod('loadConfig', (repl) => {
setupReplState(repl, 'Config', application.container.resolveBinding('Adonis/Core/Config'));
}, {
description: 'Load config and save reference to the "Config" variable',
});
/**
* Load validator
*/
Repl.addMethod('loadValidator', (repl) => {
setupReplState(repl, 'Validator', application.container.resolveBinding('Adonis/Core/Validator'));
}, {
description: 'Load validator and save reference to the "Validator" variable',
});
/**
* Create context for a dummy route
*/
Repl.addMethod('getContext', (_, route, params) => {
return application.container.use('Adonis/Core/HttpContext').create(route, params || {});
}, {
description: 'Get HTTP context for a given route',
usage: `${Repl.colors.yellow('getContext')}${Repl.colors.gray('(route, params?)')}`,
});
/**
* Load the Helpers module
*/
Repl.addMethod('loadHelpers', (repl) => {
setupReplState(repl, 'Helpers', application.container.resolveBinding('Adonis/Core/Helpers'));
}, {
description: 'Load helpers provider and save reference to the "Helpers" variable',
});
}
exports.defineReplBindings = defineReplBindings;
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
import { ContainerBindings } from '@ioc:Adonis/Core/Application';
import { CookieClientContract } from '@ioc:Adonis/Core/CookieClient';
/**
* Define test bindings
*/
export declare function defineTestsBindings(ApiRequest: ContainerBindings['Japa/Preset/ApiRequest'], ApiClient: ContainerBindings['Japa/Preset/ApiClient'], CookieClient: CookieClientContract): void;
+66
View File
@@ -0,0 +1,66 @@
"use strict";
/*
* @adonisjs/core
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineTestsBindings = void 0;
/**
* Define test bindings
*/
function defineTestsBindings(ApiRequest, ApiClient, CookieClient) {
/**
* Serializing for parsing response cookies
*/
ApiClient.cookiesSerializer({
/**
* The methods on the Request class encrypts and signs cookies.
* Therefore, the prepare method returns the value as it is
*/
prepare(_, value) {
return value;
},
/**
* Process the server response and convert cookie value to a
* plain string
*/
process(key, value) {
return CookieClient.parse(key, value);
},
});
/**
* Define cookie
*/
ApiRequest.macro('cookie', function (key, value) {
const signedValue = CookieClient.sign(key, value);
if (signedValue) {
this.cookiesJar[key] = { name: key, value: signedValue };
}
return this;
});
/**
* Define encrypted cookie
*/
ApiRequest.macro('encryptedCookie', function (key, value) {
const encryptedValue = CookieClient.encrypt(key, value);
if (encryptedValue) {
this.cookiesJar[key] = { name: key, value: encryptedValue };
}
return this;
});
/**
* Define plain cookie
*/
ApiRequest.macro('plainCookie', function (key, value) {
const encodedValue = CookieClient.encode(key, value);
if (encodedValue) {
this.cookiesJar[key] = { name: key, value: encodedValue };
}
return this;
});
}
exports.defineTestsBindings = defineTestsBindings;
@@ -0,0 +1,6 @@
import { HealthCheckContract } from '@ioc:Adonis/Core/HealthCheck';
/**
* Check for the APP_KEY to ensure it is present and has
* desired length.
*/
export default function addAppKeyChecker(healthCheck: HealthCheckContract): void;
+60
View File
@@ -0,0 +1,60 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Message for missing Api Key
*/
const MISSING_APP_KEY_MESSAGE = [
'Missing APP_KEY environment variable.',
'It is required to keep your application secure',
].join(' ');
/**
* Message for insecure Api Key
*/
const INSECURE_APP_KEY_MESSAGE = [
'Insecure APP_KEY.',
'It must be 32 characters long.',
'Run "node ace generate:key" to generate a secure key',
].join(' ');
const DISPLAY_NAME = 'App Key Check';
/**
* Check for the APP_KEY to ensure it is present and has
* desired length.
*/
function addAppKeyChecker(healthCheck) {
healthCheck.addChecker('appKey', async () => {
const appKey = process.env.APP_KEY;
if (!appKey) {
return {
displayName: DISPLAY_NAME,
health: {
healthy: false,
message: MISSING_APP_KEY_MESSAGE,
},
};
}
if (appKey && appKey.length < 32) {
return {
displayName: DISPLAY_NAME,
health: {
healthy: false,
message: INSECURE_APP_KEY_MESSAGE,
},
};
}
return {
displayName: DISPLAY_NAME,
health: {
healthy: true,
},
};
});
}
exports.default = addAppKeyChecker;
+6
View File
@@ -0,0 +1,6 @@
import { HealthCheckContract } from '@ioc:Adonis/Core/HealthCheck';
/**
* Register the `env` checker to ensure that `NODE_ENV` environment
* variable is defined.
*/
export default function addEnvChecker(healthCheck: HealthCheckContract): void;
+42
View File
@@ -0,0 +1,42 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Message for missing app key
*/
const MISSING_NODE_ENV_MESSAGE = [
'Missing NODE_ENV environment variable.',
'It can make some parts of the application misbehave',
].join(' ');
const DISPLAY_NAME = 'Node Env Check';
/**
* Register the `env` checker to ensure that `NODE_ENV` environment
* variable is defined.
*/
function addEnvChecker(healthCheck) {
healthCheck.addChecker('env', async () => {
const env = process.env.NODE_ENV;
return env
? {
displayName: DISPLAY_NAME,
health: {
healthy: true,
},
}
: {
displayName: DISPLAY_NAME,
health: {
healthy: false,
message: MISSING_NODE_ENV_MESSAGE,
},
};
});
}
exports.default = addEnvChecker;
+48
View File
@@ -0,0 +1,48 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import { Checker, HealthReport, HealthCheckContract } from '@ioc:Adonis/Core/HealthCheck';
/**
* The module exposes the API to find the health, liveliness and readiness of
* the system. You can also add your own checkers.
*/
export declare class HealthCheck implements HealthCheckContract {
private application;
/**
* A copy of registered checkers
*/
private healthCheckers;
/**
* Reference to the IoC container to resolve health checkers
*/
private resolver;
/**
* Returns an array of registered services names
*/
get servicesList(): string[];
constructor(application: ApplicationContract);
/**
* Invokes a given checker to collect the report metrics.
*/
private invokeChecker;
/**
* A boolean to know, if all health checks have passed
* or not.
*/
isLive(): Promise<boolean>;
/**
* Add a custom checker to check a given service connectivity
* with the server
*/
addChecker(service: string, checker: Checker): void;
/**
* Ensure that application is ready. This relies on the application module.
*/
isReady(): boolean;
/**
* Returns the health check reports. The health checks are performed when
* this method is invoked.
*/
getReport(): Promise<{
healthy: boolean;
report: HealthReport;
}>;
}
+99
View File
@@ -0,0 +1,99 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HealthCheck = void 0;
/**
* The module exposes the API to find the health, liveliness and readiness of
* the system. You can also add your own checkers.
*/
class HealthCheck {
/**
* Returns an array of registered services names
*/
get servicesList() {
return Object.keys(this.healthCheckers);
}
constructor(application) {
this.application = application;
/**
* A copy of registered checkers
*/
this.healthCheckers = {};
/**
* Reference to the IoC container to resolve health checkers
*/
this.resolver = this.application.container.getResolver('report');
}
/**
* Invokes a given checker to collect the report metrics.
*/
async invokeChecker(service, reportSheet) {
const checker = this.healthCheckers[service];
let report;
try {
if (typeof checker === 'function') {
report = await checker();
}
else {
report = await this.resolver.call(checker);
}
report.displayName = report.displayName || service;
}
catch (error) {
report = {
displayName: service,
health: { healthy: false, message: error.message },
meta: { fatal: true },
};
}
reportSheet[service] = report;
return report.health.healthy;
}
/**
* A boolean to know, if all health checks have passed
* or not.
*/
async isLive() {
if (!this.isReady()) {
return false;
}
const { healthy } = await this.getReport();
return healthy;
}
/**
* Add a custom checker to check a given service connectivity
* with the server
*/
addChecker(service, checker) {
this.healthCheckers[service] = checker;
}
/**
* Ensure that application is ready. This relies on the application module.
*/
isReady() {
return this.application.isReady;
}
/**
* Returns the health check reports. The health checks are performed when
* this method is invoked.
*/
async getReport() {
const report = {};
await Promise.all(Object.keys(this.healthCheckers).map((service) => {
return this.invokeChecker(service, report);
}));
/**
* Finding unhealthy service to know if system is healthy or not
*/
const unhealthyService = Object.keys(report).find((service) => !report[service].health.healthy);
return { healthy: !unhealthyService, report };
}
}
exports.HealthCheck = HealthCheck;
+70
View File
@@ -0,0 +1,70 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
import { CorsConfig } from '@ioc:Adonis/Core/Cors';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
/**
* The Cors middleware class to handle preflight request as per the CORS
* RFC https://www.w3.org/TR/cors/.
*
* This is a functional middleware and shared among all requests. So make
* sure not to set request specific instance properties.
*/
export declare class Cors {
private options;
private isEnabled;
constructor(options: CorsConfig);
/**
* Normalize config options
*/
private normalizeOptions;
/**
* Computes the origin for the current request based upon the
* user config.
*
* Origin match is always case sensitive
*/
private computeResponseOrigin;
/**
* Returns an array of headers allowed based upon user config
* and request headers.
*
* The array items are casted to lowercase for case insensitive
* match.
*/
private computedAllowedHeaders;
/**
* Sets the `Access-Control-Allow-Origin` header
*/
private setOrigin;
/**
* Setting `Access-Control-Expose-Headers` headers, when custom headers
* are defined. If no custom headers are defined, then simple response
* headers are used instead.
*/
private setExposedHeaders;
/**
* Allows `Access-Control-Allow-Credentials` when enabled inside the user
* config.
*/
private setCredentials;
/**
* Set `Access-Control-Allow-Methods` header.
*/
private setAllowMethods;
/**
* Set `Access-Control-Allow-Headers` header.
*/
private setAllowHeaders;
/**
* Set `Access-Control-Max-Age` header.
*/
private setMaxAge;
/**
* Ends the preflight request with 204 status code
*/
private endPreFlight;
/**
* Handle HTTP request for CORS. This method is binded as a before hook
* to the HTTP server.
*/
handle(ctx: HttpContextContract): Promise<void>;
}
+314
View File
@@ -0,0 +1,314 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cors = void 0;
/**
* List of default exposed headers.
*/
const SIMPLE_EXPOSE_HEADERS = [
'cache-control',
'content-language',
'content-type',
'expires',
'last-modified',
'pragma',
];
/**
* The Cors middleware class to handle preflight request as per the CORS
* RFC https://www.w3.org/TR/cors/.
*
* This is a functional middleware and shared among all requests. So make
* sure not to set request specific instance properties.
*/
class Cors {
constructor(options) {
this.options = options;
this.normalizeOptions();
}
/**
* Normalize config options
*/
normalizeOptions() {
/**
* Convert all headers to lowercase
*/
this.options.exposeHeaders = this.options.exposeHeaders.map((header) => header.toLowerCase());
const hasExtraHeaders = this.options.exposeHeaders.find((header) => {
return SIMPLE_EXPOSE_HEADERS.indexOf(header) === -1;
});
/**
* If expose headers doesn't have extra headers, then empty the list
*/
if (!hasExtraHeaders) {
this.options.exposeHeaders = [];
}
/**
* A pre-computed function to know if CORS is enabled for current request or not
*/
if (typeof this.options.enabled === 'function') {
this.isEnabled = this.options.enabled;
}
else {
this.isEnabled = () => this.options.enabled;
}
}
/**
* Computes the origin for the current request based upon the
* user config.
*
* Origin match is always case sensitive
*/
computeResponseOrigin(origin, ctx) {
let allowedOrigins = this.options.origin;
/**
* If the `origin` value inside user config is a function, we
* call that function and use the return value as the
* new config value.
*/
if (typeof allowedOrigins === 'function') {
allowedOrigins = allowedOrigins(origin, ctx);
}
/**
* If true, then allow the current origin
*/
if (allowedOrigins === true) {
return origin;
}
/**
* False, disallows all origins
*/
if (allowedOrigins === false) {
return null;
}
/**
* Wildcard allows the current origin. However, it also indicates
* the browser that all origins are allowed.
*
* Fundamentaly `*` and `true` are not same, though they both allows
* the same origin.
*/
if (allowedOrigins === '*') {
/**
* Setting `Access-Control-Allow-Origin=*` along with `Access-Control-Allow-Credentials=true`
* isn't allowed. So in that case, we return the value of the current origin and not the
* wildcard identifier.
*/
return this.options.credentials === true ? origin : '*';
}
/**
* Find the matching origin, if value is an array
*/
if (Array.isArray(allowedOrigins)) {
if (allowedOrigins.find((allowedOrigin) => allowedOrigin === origin)) {
return origin;
}
return null;
}
/**
* Find the matching origin, if value is a comma seperated string
*/
if (allowedOrigins.split(',').find((allowedOrigin) => allowedOrigin === origin)) {
return origin;
}
/**
* Nothing is allowed
*/
return null;
}
/**
* Returns an array of headers allowed based upon user config
* and request headers.
*
* The array items are casted to lowercase for case insensitive
* match.
*/
computedAllowedHeaders(headers, ctx) {
let allowedHeaders = this.options.headers;
/**
* Compute allowed headers by calling the config function.
*/
if (typeof allowedHeaders === 'function') {
allowedHeaders = allowedHeaders(headers, ctx);
}
/**
* Allow current set of headers, when `allowedHeaders = true`
*/
if (allowedHeaders === true) {
return headers.map((header) => header.toLowerCase());
}
/**
* Disallow all headers
*/
if (allowedHeaders === false) {
return [];
}
/**
* Allow explicitly define headers as an array of comma seperated
* string literal.
*/
if (Array.isArray(allowedHeaders)) {
return allowedHeaders.map((header) => header.toLowerCase());
}
return allowedHeaders.split(',').map((header) => header.toLowerCase());
}
/**
* Sets the `Access-Control-Allow-Origin` header
*/
setOrigin(response, allowedOrigin) {
response.header('Access-Control-Allow-Origin', allowedOrigin);
}
/**
* Setting `Access-Control-Expose-Headers` headers, when custom headers
* are defined. If no custom headers are defined, then simple response
* headers are used instead.
*/
setExposedHeaders(response) {
if (this.options.exposeHeaders.length) {
response.header('Access-Control-Expose-Headers', this.options.exposeHeaders.join(','));
}
}
/**
* Allows `Access-Control-Allow-Credentials` when enabled inside the user
* config.
*/
setCredentials(response) {
if (this.options.credentials === true) {
response.header('Access-Control-Allow-Credentials', 'true');
}
}
/**
* Set `Access-Control-Allow-Methods` header.
*/
setAllowMethods(response) {
response.header('Access-Control-Allow-Methods', this.options.methods.join(','));
}
/**
* Set `Access-Control-Allow-Headers` header.
*/
setAllowHeaders(response, allowedHeaders) {
response.header('Access-Control-Allow-Headers', allowedHeaders.join(','));
}
/**
* Set `Access-Control-Max-Age` header.
*/
setMaxAge(response) {
if (this.options.maxAge) {
response.header('Access-Control-Max-Age', this.options.maxAge);
}
}
/**
* Ends the preflight request with 204 status code
*/
endPreFlight(response) {
response.status(204).send(null);
}
/**
* Handle HTTP request for CORS. This method is binded as a before hook
* to the HTTP server.
*/
async handle(ctx) {
/**
* Return early when CORS is not enabled for the current request
*/
if (!this.isEnabled(ctx.request, ctx)) {
return;
}
const origin = ctx.request.header('origin');
const isOptions = ctx.request.method() === 'OPTIONS';
/**
* If their is no Origin header present, then let the user-agent handle
* this situation, since the request is outside the scope of CORS.
*/
if (!origin) {
return;
}
const allowedOrigin = this.computeResponseOrigin(origin, ctx);
/**
* If origin is not allowed, then we don't set any of the cors headers
*/
if (!allowedOrigin) {
/**
* Also end the OPTIONS request right away
*/
if (isOptions) {
this.endPreFlight(ctx.response);
}
return;
}
/**
* Set required headers for non options request.
*/
if (!isOptions) {
this.setOrigin(ctx.response, allowedOrigin);
this.setCredentials(ctx.response);
this.setExposedHeaders(ctx.response);
return;
}
/**
* Everything below is for pre-flight (aka OPTIONS) request
*/
const requestMethod = ctx.request.header('Access-Control-Request-Method');
/**
* End the request, when `Access-Control-Request-Method` is missing or isn't
* part of allowed methods.
* https://www.w3.org/TR/cors/#http-access-control-request-method
*/
if (!requestMethod || this.options.methods.indexOf(requestMethod) === -1) {
this.endPreFlight(ctx.response);
return;
}
/**
* When `Access-Control-Request-Headers` header is missing or is empty, then
* we subsitute that with an empty list.
* https://www.w3.org/TR/cors/#http-access-control-request-headers
*/
let requestHeaders = ctx.request.header('Access-Control-Request-Headers');
if (requestHeaders && requestHeaders !== '') {
requestHeaders = requestHeaders.split(',');
}
else {
requestHeaders = [];
}
/**
* Computing allowed headers array from the user config
*/
const allowedHeaders = this.computedAllowedHeaders(requestHeaders, ctx);
/**
* Finding if all request `Access-Control-Request-Headers` falls under the
* list of allowed headers inside user config
*/
const headersMatches = requestHeaders.every((header) => {
if (header === 'origin') {
return true;
}
/**
* Doing case insenstive match
*/
return allowedHeaders.indexOf(header.toLowerCase()) > -1;
});
/**
* If headers test fails, then we need to end the request without setting
* any headers (part of spec).
* https://www.w3.org/TR/cors/#http-access-control-request-headers
*/
if (headersMatches === false) {
this.endPreFlight(ctx.response);
return;
}
this.setOrigin(ctx.response, allowedOrigin);
this.setCredentials(ctx.response);
this.setExposedHeaders(ctx.response);
this.setAllowMethods(ctx.response);
this.setAllowHeaders(ctx.response, allowedHeaders);
this.setMaxAge(ctx.response);
this.endPreFlight(ctx.response);
}
}
exports.Cors = Cors;
+18
View File
@@ -0,0 +1,18 @@
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
import { AssetsConfig } from '@ioc:Adonis/Core/Static';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
/**
* A simple server hook to serve static files from the public directory.
* The public directory must be configured within the `.adonisrc.json`
* file.
*/
export declare class ServeStatic {
private publicPath;
private config;
private serve;
constructor(publicPath: string, config: AssetsConfig);
/**
* Handle the request to serve static files.
*/
handle({ request, response }: HttpContextContract): Promise<void>;
}
+66
View File
@@ -0,0 +1,66 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServeStatic = void 0;
const serve_static_1 = __importDefault(require("serve-static"));
/**
* A simple server hook to serve static files from the public directory.
* The public directory must be configured within the `.adonisrc.json`
* file.
*/
class ServeStatic {
constructor(publicPath, config) {
this.publicPath = publicPath;
this.config = config;
this.serve = (0, serve_static_1.default)(this.publicPath, Object.assign({}, this.config, {
setHeaders: (res, path, stats) => {
const headers = res.parent.getHeaders();
Object.keys(headers).forEach((key) => {
res.setHeader(key, headers[key]);
});
/**
* Set user defined custom headers
*/
if (typeof this.config.headers === 'function') {
const customHeaders = this.config.headers(path, stats);
Object.keys(customHeaders).forEach((key) => {
res.setHeader(key, customHeaders[key]);
});
}
},
}));
}
/**
* Handle the request to serve static files.
*/
async handle({ request, response }) {
return new Promise((resolve) => {
function next() {
response.response.removeListener('finish', next);
resolve();
}
response.response['parent'] = response;
/**
* Whether or not the file has been served by serve static, we
* will cleanup the finish event listener.
*
* 1. If file has been served, then the `finish` callback get invoked.
* 2. If file has not been served, then callback (3rd argument) will
* get invoked.
*/
response.response.addListener('finish', next);
this.serve(request.request, response.response, next);
});
}
}
exports.ServeStatic = ServeStatic;
+82
View File
@@ -0,0 +1,82 @@
/// <reference types="@adonisjs/logger/build/adonis-typings/logger" />
/// <reference types="@adonisjs/http-server/build/adonis-typings" />
import { LoggerContract } from '@ioc:Adonis/Core/Logger';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
/**
* Http exception handler serves as the base exception handler
* to handle all exceptions occured during the HTTP request
* lifecycle and makes appropriate response for them.
*/
export declare abstract class HttpExceptionHandler {
protected logger: LoggerContract;
/**
* An array of error codes that must not be reported
*/
protected ignoreCodes: string[];
/**
* An array of http statuses that must not be reported. The first
* level of filteration is on the basis of statuses and then
* the error codes.
*/
protected ignoreStatuses: number[];
/**
* An array of internal error codes to ignore
* from the reporting list
*/
protected internalIgnoreCodes: string[];
/**
* Map of status pages to render, instead of making the
* regular response
*/
protected statusPages: {
[key: string]: string;
};
/**
* Map of status pages for after expanding the expressions
* defined inside statusPages.
*
* This property is initialized using the getter defined at
* the end of this file
*/
expandedStatusPages: {
[key: string]: string;
};
/**
* A flag to disable status pages during development
*/
protected disableStatusPagesInDevelopment: boolean;
constructor(logger: LoggerContract);
/**
* A custom context to send to the logger when reporting
* errors.
*/
protected context(ctx: HttpContextContract): any;
/**
* Returns a boolean telling if a given error is supposed
* to be logged or not
*/
protected shouldReport(error: any): boolean;
/**
* Makes the JSON response, based upon the environment in
* which the app is runing
*/
protected makeJSONResponse(error: any, ctx: HttpContextContract): Promise<void>;
/**
* Makes the JSON API response, based upon the environment in
* which the app is runing
*/
protected makeJSONAPIResponse(error: any, ctx: HttpContextContract): Promise<void>;
/**
* Makes the HTML response, based upon the environment in
* which the app is runing
*/
protected makeHtmlResponse(error: any, ctx: HttpContextContract): Promise<void>;
/**
* Report a given error
*/
report(error: any, ctx: HttpContextContract): void;
/**
* Handle exception and make response
*/
handle(error: any, ctx: HttpContextContract): Promise<any>;
}
+213
View File
@@ -0,0 +1,213 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpExceptionHandler = void 0;
/**
* Http exception handler serves as the base exception handler
* to handle all exceptions occured during the HTTP request
* lifecycle and makes appropriate response for them.
*/
class HttpExceptionHandler {
constructor(logger) {
this.logger = logger;
/**
* An array of error codes that must not be reported
*/
this.ignoreCodes = [];
/**
* An array of http statuses that must not be reported. The first
* level of filteration is on the basis of statuses and then
* the error codes.
*/
this.ignoreStatuses = [400, 422, 401];
/**
* An array of internal error codes to ignore
* from the reporting list
*/
this.internalIgnoreCodes = ['E_ROUTE_NOT_FOUND'];
/**
* Map of status pages to render, instead of making the
* regular response
*/
this.statusPages = {};
/**
* A flag to disable status pages during development
*/
this.disableStatusPagesInDevelopment = true;
}
/**
* A custom context to send to the logger when reporting
* errors.
*/
context(ctx) {
const requestId = ctx.request.id();
return requestId
? {
'x-request-id': requestId,
}
: {};
}
/**
* Returns a boolean telling if a given error is supposed
* to be logged or not
*/
shouldReport(error) {
/**
* Do not report the error when it's status is mentioned inside
* the `ignoreStatuses` array.
*/
if (error.status && this.ignoreStatuses.indexOf(error.status) > -1) {
return false;
}
/**
* Don't report when error has a code and it's in the ignore list.
*/
if (error.code && this.ignoreCodes.concat(this.internalIgnoreCodes).indexOf(error.code) > -1) {
return false;
}
return true;
}
/**
* Makes the JSON response, based upon the environment in
* which the app is runing
*/
async makeJSONResponse(error, ctx) {
if (process.env.NODE_ENV === 'development') {
ctx.response.status(error.status).send({
message: error.message,
stack: error.stack,
code: error.code,
});
return;
}
ctx.response.status(error.status).send({ message: error.message });
}
/**
* Makes the JSON API response, based upon the environment in
* which the app is runing
*/
async makeJSONAPIResponse(error, ctx) {
ctx.response.status(error.status).send({
errors: [
{
title: error.message,
...(process.env.NODE_ENV === 'development' ? { detail: error.stack } : {}),
code: error.code,
status: error.status,
},
],
});
}
/**
* Makes the HTML response, based upon the environment in
* which the app is runing
*/
async makeHtmlResponse(error, ctx) {
if (process.env.NODE_ENV === 'development' &&
(!this.expandedStatusPages[error.status] || this.disableStatusPagesInDevelopment)) {
const Youch = require('youch');
const html = await new Youch(error, ctx.request.request).toHTML();
ctx.response.status(error.status).send(html);
return;
}
/**
* Render status pages
*/
if (ctx['view'] && this.expandedStatusPages[error.status]) {
const html = await ctx['view'].render(this.expandedStatusPages[error.status], { error });
ctx.response.status(error.status).send(html);
return;
}
ctx.response.status(error.status).send(`<h1> ${error.message} </h1>`);
}
/**
* Report a given error
*/
report(error, ctx) {
error.status = error.status || 500;
if (!this.shouldReport(error)) {
return;
}
if (typeof error.report === 'function') {
error.report(error, ctx);
return;
}
/**
* - Using `error` for `500 and above`
* - `warn` for `400 and above`
* - `info` for rest. This should not happen, but technically it's possible for someone
* to raise with 200
*/
if (!error.status || error.status >= 500) {
if (process.env.NODE_ENV !== 'test') {
ctx.logger.error({ err: error, ...this.context(ctx) }, error.message);
}
}
else if (error.status >= 400) {
ctx.logger.warn(this.context(ctx), error.message);
}
else {
ctx.logger.info(this.context(ctx), error.message);
}
}
/**
* Handle exception and make response
*/
async handle(error, ctx) {
error.status = error.status || 500;
if (typeof error.handle === 'function') {
return error.handle(error, ctx);
}
/**
* Send stack in the response when in test environment and
* there is a fatal error.
*/
if (error.status >= 500 && error.stack && process.env.NODE_ENV === 'test') {
return ctx.response.status(error.status).send(error.stack);
}
/**
* Attempt to find the best error reporter for validation
*/
switch (ctx.request.accepts(['html', 'application/vnd.api+json', 'json'])) {
case 'html':
case null:
return this.makeHtmlResponse(error, ctx);
case 'json':
return this.makeJSONResponse(error, ctx);
case 'application/vnd.api+json':
return this.makeJSONAPIResponse(error, ctx);
}
}
}
exports.HttpExceptionHandler = HttpExceptionHandler;
/**
* Single getter to pull status pages after expanding the range expression
*/
Object.defineProperty(HttpExceptionHandler.prototype, 'expandedStatusPages', {
get() {
const value = Object.keys(this.statusPages).reduce((result, codeRange) => {
const parts = codeRange.split('.');
const min = Number(parts[0]);
const max = Number(parts[parts.length - 1]);
if (isNaN(min) || isNaN(max)) {
return result;
}
if (min === max) {
result[codeRange] = this.statusPages[codeRange];
}
Array.apply(null, new Array(max - min + 1)).forEach((_, step) => {
result[min + step] = this.statusPages[codeRange];
});
return result;
}, {});
Object.defineProperty(this, 'expandedStatusPages', { value });
return value;
},
});
+60
View File
@@ -0,0 +1,60 @@
/**
* Exposes the API to execute app commands registered under
* the manifest file.
*/
export declare class App {
private appRoot;
private commandName;
/**
* Returns a boolean if mentioned command is an assembler
* command
*/
private get isAssemblerCommand();
/**
* Reference to the app kernel
*/
private kernel;
/**
* Reference to the ace kernel
*/
private ace;
/**
* Source root always points to the compiled source
* code.
*/
constructor(appRoot: string);
/**
* Print commands help
*/
private printHelp;
/**
* Print framework version
*/
private printVersion;
/**
* Invoked before command source will be read from the
* disk
*/
private onFind;
/**
* Invoked before command is about to run.
*/
private onRun;
/**
* Hooks into ace lifecycle events to conditionally
* load the app.
*/
private registerAceHooks;
/**
* Adding flags
*/
private registerAceFlags;
/**
* Load commands using manifest loader
*/
loadCommands(): Promise<void>;
/**
* Handle application command
*/
handle(argv: string[]): Promise<void>;
}
+236
View File
@@ -0,0 +1,236 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.App = void 0;
const ace_1 = require("@adonisjs/ace");
const cliui_1 = require("@poppinss/cliui");
const helpers_1 = require("@poppinss/utils/build/helpers");
const Kernel_1 = require("../../Kernel");
const utils_1 = require("../../../utils");
const GenerateManifest_1 = require("../GenerateManifest");
/**
* A local list of assembler commands. We need this, so that when assembler
* is not installed (probably in production) and someone is trying to
* build the project by running `serve` or `build`, we should give
* them a better descriptive error.
*
* Also, do note that at times this list will be stale, but we get it back
* in sync over time.
*/
const ASSEMBLER_COMMANDS = [
'build',
'serve',
'invoke',
'make:command',
'make:controller',
'make:exception',
'make:listener',
'make:middleware',
'make:prldfile',
'make:provider',
'make:validator',
'make:view',
];
/**
* Exposes the API to execute app commands registered under
* the manifest file.
*/
class App {
/**
* Returns a boolean if mentioned command is an assembler
* command
*/
get isAssemblerCommand() {
return ASSEMBLER_COMMANDS.includes(this.commandName);
}
/**
* Source root always points to the compiled source
* code.
*/
constructor(appRoot) {
this.appRoot = appRoot;
/**
* Reference to the app kernel
*/
this.kernel = new Kernel_1.AppKernel(this.appRoot, 'console');
/**
* Reference to the ace kernel
*/
this.ace = new ace_1.Kernel(this.kernel.application);
}
/**
* Print commands help
*/
printHelp(value, command) {
if (!value) {
return;
}
this.ace.printHelp(command, [GenerateManifest_1.GenerateManifest.getManifestJSON()]);
process.exit(0);
}
/**
* Print framework version
*/
printVersion(value) {
if (!value) {
return;
}
const appVersion = this.kernel.application.version;
const adonisVersion = this.kernel.application.adonisVersion;
let assemblerVersion = 'Not Installed';
try {
assemblerVersion = require((0, helpers_1.resolveFrom)(this.appRoot, '@adonisjs/assembler/package.json')).version;
}
catch (error) { }
(0, cliui_1.sticker)()
.heading('node ace --version')
.add(`App version: ${cliui_1.logger.colors.cyan(appVersion ? appVersion.version : 'NA')}`)
.add(`Framework version: ${cliui_1.logger.colors.cyan(adonisVersion ? adonisVersion.version : 'NA')}`)
.add(`Assembler version: ${cliui_1.logger.colors.cyan(assemblerVersion)}`)
.render();
process.exit(0);
}
/**
* Invoked before command source will be read from the
* disk
*/
async onFind(command) {
if (!command) {
return;
}
/**
* Register ts hook when
*
* - Haven't registered it already
* - Is a typescript project
* - Is not an assembler command
*/
if (!this.isAssemblerCommand) {
this.kernel.registerTsCompilerHook();
}
/**
* Only main command can load the application or switch
* the environment.
*
* If a sub-command needs application, then the main command
* should set "loadApp" to true as well.
*/
if (command.commandName === this.commandName || command.aliases.includes(this.commandName)) {
/**
* Switch environment before wiring the app
*/
if (command.settings.environment) {
this.kernel.application.switchEnvironment(command.settings.environment);
}
if (command.settings.loadApp) {
/**
* Set ace instance within the container, so that the underlying
* commands or the app can access it from the container
*/
this.kernel.application.container.singleton('Adonis/Core/Ace', () => this.ace);
await this.kernel.boot();
}
}
}
/**
* Invoked before command is about to run.
*/
async onRun() {
if (this.kernel.hasBooted) {
await this.kernel.start();
}
}
/**
* Hooks into ace lifecycle events to conditionally
* load the app.
*/
registerAceHooks() {
this.ace.before('find', async (command) => this.onFind(command));
this.ace.before('run', async () => this.onRun());
}
/**
* Adding flags
*/
registerAceFlags() {
/**
* Showing help including core commands
*/
this.ace.flag('help', async (value, _, command) => this.printHelp(value, command), {
alias: 'h',
});
/**
* Showing app and AdonisJs version
*/
this.ace.flag('version', async (value) => this.printVersion(value), { alias: 'v' });
}
/**
* Load commands using manifest loader
*/
async loadCommands() {
await (0, utils_1.loadAceCommands)(this.kernel.application, this.ace);
}
/**
* Handle application command
*/
async handle(argv) {
try {
/**
* Manifest files to load
*/
await this.loadCommands();
/**
* Define ace hooks to wire the application (if required)
*/
this.registerAceHooks();
/**
* Define global flags
*/
this.registerAceFlags();
/**
* Print help when no arguments have been passed
*/
if (!argv.length) {
this.printHelp(true);
return;
}
/**
* Hold reference to the command name. We will use this to decide whether
* or not to exit the process forcefully after the command has been
* executed
*/
this.commandName = argv[0];
/**
* Listen for the exit signal on ace kernel
*/
this.ace.onExit(async () => {
if (this.kernel.hasBooted) {
await this.kernel.close();
}
if (!this.ace.error) {
process.exit(this.ace.exitCode);
}
return this.kernel
.handleError(this.ace.error)
.finally(() => process.exit(this.ace.exitCode));
});
/**
* Handle command
*/
await this.ace.handle(argv);
}
catch (error) {
if (!error) {
process.exit(1);
}
this.kernel.handleError(error).finally(() => process.exit(1));
}
}
}
exports.App = App;
@@ -0,0 +1,4 @@
import { Exception } from '@poppinss/utils';
export declare class AceRuntimeException extends Exception {
handle(error: AceRuntimeException): void;
}
+19
View File
@@ -0,0 +1,19 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AceRuntimeException = void 0;
const cliui_1 = require("@poppinss/cliui");
const utils_1 = require("@poppinss/utils");
class AceRuntimeException extends utils_1.Exception {
handle(error) {
cliui_1.logger.error(error.message);
}
}
exports.AceRuntimeException = AceRuntimeException;
@@ -0,0 +1,28 @@
/**
* Exposes the API to generate the manifest file
*/
export declare class GenerateManifest {
private appRoot;
private kernel;
/**
* Source root always points to the compiled source
* code.
*/
constructor(appRoot: string);
/**
* Returns manifest object for showing help
*/
static getManifestJSON(): {
commandName: string;
description: string;
args: never[];
flags: never[];
settings: {};
aliases: never[];
commandPath: string;
};
/**
* Generates the manifest file for commands
*/
handle(): Promise<void>;
}
@@ -0,0 +1,75 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenerateManifest = void 0;
const cliui_1 = require("@poppinss/cliui");
const ace_1 = require("@adonisjs/ace");
const Kernel_1 = require("../../Kernel");
const Exceptions_1 = require("../Exceptions");
/**
* Exposes the API to generate the manifest file
*/
class GenerateManifest {
/**
* Source root always points to the compiled source
* code.
*/
constructor(appRoot) {
this.appRoot = appRoot;
this.kernel = new Kernel_1.AppKernel(this.appRoot, 'console');
}
/**
* Returns manifest object for showing help
*/
static getManifestJSON() {
return {
commandName: 'generate:manifest',
description: 'Generate ace commands manifest file. Manifest file speeds up commands lookup',
args: [],
flags: [],
settings: {},
aliases: [],
commandPath: '',
};
}
/**
* Generates the manifest file for commands
*/
async handle() {
try {
this.kernel.registerTsCompilerHook();
const commands = this.kernel.application.rcFile.commands;
/**
* Generating manifest requires us to import the command files to read their
* meta data defined as class static properties. However, at this stage
* the application is not booted and hence top level IoC container
* imports will break
*/
this.kernel.application.container.trap((namespace) => {
if (namespace === 'Adonis/Core/Application') {
return this.kernel.application;
}
return {
__esModule: new Proxy({ namespace }, {
get(target) {
throw new Exceptions_1.AceRuntimeException(`Top level import for module "${target.namespace}" is not allowed in commands. Learn more https://docs.adonisjs.com/guides/ace-commandline#top-level-imports-are-not-allowed`);
},
}),
};
});
await new ace_1.ManifestGenerator(this.appRoot, commands).generate();
cliui_1.logger.action('create').succeeded('ace-manifest.json file');
}
catch (error) {
await this.kernel.handleError(error).finally(() => process.exit(1));
}
}
}
exports.GenerateManifest = GenerateManifest;
+11
View File
@@ -0,0 +1,11 @@
/**
* Exposes the API to execute ace commands.
*/
export declare class Ace {
private appRoot;
constructor(appRoot: string);
/**
* Handles the ace command
*/
handle(argv: string[]): Promise<void>;
}
+36
View File
@@ -0,0 +1,36 @@
"use strict";
/*
* @adonisjs/core
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ace = void 0;
const App_1 = require("./App");
const GenerateManifest_1 = require("./GenerateManifest");
/**
* Exposes the API to execute ace commands.
*/
class Ace {
constructor(appRoot) {
this.appRoot = appRoot;
}
/**
* Handles the ace command
*/
async handle(argv) {
process.env.ADONIS_ACE_CWD = this.appRoot;
if (argv[0] === 'generate:manifest' && !argv.includes('--help')) {
await new GenerateManifest_1.GenerateManifest(this.appRoot).handle();
return;
}
/**
* Proxy over to application commands
*/
await new App_1.App(this.appRoot).handle(argv);
}
}
exports.Ace = Ace;
+56
View File
@@ -0,0 +1,56 @@
import { CustomServerCallback } from '@ioc:Adonis/Core/TestUtils';
import { AppKernel } from '../Kernel';
/**
* Exposes the API to setup the application for starting the HTTP
* server.
*
* - Calling "kill" explicitly exists the process.
* - The "error" event emitted on the server instance explicitly exists the process.
* - SIGINT and in some case SIGTERM explicitly exists the process.
*/
export declare class HttpServer {
private appRoot;
/**
* Reference to the HTTP server.
*/
private server;
/**
* Reference to the app kernel
*/
kernel: AppKernel;
application: import("@adonisjs/application").Application;
constructor(appRoot: string);
/**
* Closes the underlying HTTP server
*/
private closeHttpServer;
/**
* Monitors the HTTP server for close and error events, so that
* we can perform a graceful shutdown.
*/
private monitorHttpServer;
/**
* Creates the HTTP server to handle incoming requests. The server is just
* created but not listening on any port.
*/
createServer(serverCallback?: CustomServerCallback): void;
/**
* Starts the http server a given host and port
*/
listen(): Promise<void>;
/**
* Start the HTTP server by wiring up the application
*/
start(serverCallback?: CustomServerCallback): Promise<void>;
/**
* Prepares the application for shutdown. This method will invoke `shutdown`
* lifecycle method on the providers and closes the `httpServer`.
*/
close(): Promise<void>;
/**
* Kills the http server process by attempting to perform a graceful
* shutdown or killing the app forcefully as waiting for configured
* seconds.
*/
kill(waitTimeout?: number): Promise<void>;
}

Some files were not shown because too many files have changed in this diff Show More