Socket
Socket
Sign inDemoInstall

@mocks-server/core

Package Overview
Dependencies
283
Maintainers
1
Versions
52
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.0.0-beta.2 to 5.0.0-beta.3

24

dist/alerts/Alerts.js

@@ -30,4 +30,15 @@ "use strict";

}
get flat() {
return this._flat.map((item) => {
const collection = item.collection;
const collectionPaths = collection.split(ID_SEP);
if (collectionPaths[0] === ALERTS_ROOT_ID) {
collectionPaths.shift();
}
const value = item.value;
return Object.assign(Object.assign({}, value), { id: [...collectionPaths, item.id].join(ID_SEP) });
});
}
set(id, message, error) {
this._logger.silly(`Setting alert with id '${id}'`);
this._logger.silly(`Setting alert with id '${id}': '${message}'`);
if (error) {

@@ -48,14 +59,3 @@ this._logger.error(`${message}: ${error.message}`);

}
get flat() {
return this._flat.map((item) => {
const collection = item.collection;
const collectionPaths = collection.split(ID_SEP);
if (collectionPaths[0] === ALERTS_ROOT_ID) {
collectionPaths.shift();
}
const value = item.value;
return Object.assign(Object.assign({}, value), { id: [...collectionPaths, item.id].join(ID_SEP) });
});
}
};
exports.Alerts = Alerts;
import type { ResolveWhenConditionPassOptions } from "./Helpers.types";
export declare function arrayMerge(_destinationArray: unknown[], sourceArray: unknown[]): unknown[];
export declare function docsUrl(url: string): string;

@@ -4,0 +3,0 @@ export declare function deprecatedMessage(type: string, oldName: string, newName: string, url: string): string;

@@ -15,9 +15,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayLowerAndUpper = exports.objectKeys = exports.arrayToLowerCase = exports.toLowerCase = exports.readFileSync = exports.resolveWhenConditionPass = exports.deprecatedMessage = exports.docsUrl = exports.arrayMerge = void 0;
exports.arrayLowerAndUpper = exports.objectKeys = exports.arrayToLowerCase = exports.toLowerCase = exports.readFileSync = exports.resolveWhenConditionPass = exports.deprecatedMessage = exports.docsUrl = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function arrayMerge(_destinationArray, sourceArray) {
return sourceArray;
}
exports.arrayMerge = arrayMerge;
function docsUrl(url) {

@@ -24,0 +20,0 @@ return `https://www.mocks-server.org/docs/${url}`;

@@ -9,8 +9,8 @@ import type { ConfigNamespaceInterface } from "@mocks-server/config";

core: CoreInterface;
/** Namespace of the root core config object. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance */
config?: ConfigNamespaceInterface;
/** Namespace, or scoped child collection of the root core alerts. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance */
alerts?: AlertsInterface;
/** Namespace of the root core logger. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance */
logger?: LoggerInterface;
/** Namespace of the root core config object.*/
config: ConfigNamespaceInterface;
/** Namespace, or scoped child collection of the root core alerts.*/
alerts: AlertsInterface;
/** Namespace of the root core logger.*/
logger: LoggerInterface;
}

@@ -30,8 +30,8 @@ /** Mocks-server scoped core constructor */

export interface ScopedCoreInterface extends BaseCoreInterface {
/** Namespace of the root core config object. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance*/
config?: ConfigNamespaceInterface;
/** Namespace, or scoped child collection of the root core alerts. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance*/
alerts?: AlertsInterface;
/** Namespace of the root core logger. It may be undefined when scoped core is created for a plugin, and its constructor has no static id nor id getter in instance*/
logger?: LoggerInterface;
/** Namespace of the root core config object.*/
config: ConfigNamespaceInterface;
/** Namespace, or scoped child collection of the root core alerts.*/
alerts: AlertsInterface;
/** Namespace of the root core logger.*/
logger: LoggerInterface;
}

@@ -29,3 +29,2 @@ "use strict";

const logger_1 = require("@mocks-server/logger");
const deepmerge_1 = __importDefault(require("deepmerge"));
const fs_extra_1 = require("fs-extra");

@@ -261,34 +260,29 @@ const alerts_1 = require("./alerts");

}
_startPlugins() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._startPluginsPromise) {
this._startPluginsPromise = this._plugins.start();
}
return this._startPluginsPromise.then(() => {
this._startPluginsPromise = null;
});
});
get alerts() {
return this._alerts;
}
_stopPlugins() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._stopPluginsPromise) {
this._stopPluginsPromise = this._plugins.stop();
}
return this._stopPluginsPromise.then(() => {
this._stopPluginsPromise = null;
});
});
get config() {
return this._config;
}
_loadConfig() {
return __awaiter(this, void 0, void 0, function* () {
yield this._config.load();
this._configLogger.debug(`Programmatic config: ${JSON.stringify(this._config.programmaticLoadedValues)}`);
this._configLogger.debug(`Config from file: ${JSON.stringify(this._config.fileLoadedValues)}`);
this._configLogger.debug(`Config from env: ${JSON.stringify(this._config.envLoadedValues)}`);
this._configLogger.debug(`Config from args: ${JSON.stringify(this._config.argsLoadedValues)}`);
this._configLogger.verbose(`Config: ${JSON.stringify(this._config.value)}`);
this._configLogger.info(`Configuration loaded`);
});
get logger() {
return this._logger;
}
init(programmaticConfig = {}) {
get server() {
return this._server;
}
get mock() {
return this._mock;
}
// TODO, move to mock
get variantHandlers() {
return this._variantHandlers;
}
get files() {
return this._files;
}
// TODO, move to about module
get version() {
return this._version;
}
init() {
return __awaiter(this, void 0, void 0, function* () {

@@ -300,7 +294,2 @@ if (this._initialized) {

this._initialized = true;
if (programmaticConfig) {
this._programmaticConfig = (0, deepmerge_1.default)(this._programmaticConfig, programmaticConfig, {
arrayMerge: common_1.arrayMerge,
});
}
// Update notifier

@@ -343,30 +332,34 @@ // TODO, move to about module

}
// Expose Server methods and getters
get alerts() {
return this._alerts;
_startPlugins() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._startPluginsPromise) {
this._startPluginsPromise = this._plugins.start();
}
return this._startPluginsPromise.then(() => {
this._startPluginsPromise = null;
});
});
}
get config() {
return this._config;
_stopPlugins() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._stopPluginsPromise) {
this._stopPluginsPromise = this._plugins.stop();
}
return this._stopPluginsPromise.then(() => {
this._stopPluginsPromise = null;
});
});
}
get logger() {
return this._logger;
_loadConfig() {
return __awaiter(this, void 0, void 0, function* () {
yield this._config.load();
this._configLogger.debug(`Programmatic config: ${JSON.stringify(this._config.programmaticLoadedValues)}`);
this._configLogger.debug(`Config from file: ${JSON.stringify(this._config.fileLoadedValues)}`);
this._configLogger.debug(`Config from env: ${JSON.stringify(this._config.envLoadedValues)}`);
this._configLogger.debug(`Config from args: ${JSON.stringify(this._config.argsLoadedValues)}`);
this._configLogger.verbose(`Config: ${JSON.stringify(this._config.value)}`);
this._configLogger.info(`Configuration loaded`);
});
}
get server() {
return this._server;
}
get mock() {
return this._mock;
}
// TODO, move to mock
get variantHandlers() {
return this._variantHandlers;
}
get files() {
return this._files;
}
// TODO, move to about module
get version() {
return this._version;
}
};
exports.Core = Core;

@@ -1,2 +0,2 @@

import type { ConfigInterface, ConfigurationObject, GetOptionValueTypeFromDefinition, OptionDefinition } from "@mocks-server/config";
import type { ConfigInterface, GetOptionValueTypeFromDefinition, OptionDefinition, BuiltInConfig } from "@mocks-server/config";
import type { LoggerInterface, LogLevel } from "@mocks-server/logger";

@@ -11,3 +11,3 @@ import type { Package } from "update-notifier";

namespace MocksServer {
interface Config {
interface Config extends BuiltInConfig {
}

@@ -26,2 +26,3 @@ }

}
export declare type Configuration = MocksServer.Config;
/** Mocks-server base core interface */

@@ -52,3 +53,3 @@ export interface BaseCoreInterface {

* Creates a Mocks Server core interface
* @param config - Programmatic configuration {@link ConfigurationObject}
* @param config - Programmatic configuration {@link Configuration}
* @param advancedOptions - Advanced options {@link AdvancedOptions}

@@ -58,3 +59,3 @@ * @returns Mocks Server core interface {@link CoreInterface}.

*/
new (programmaticConfig?: ConfigurationObject, advancedOptions?: CoreAdvancedOptions): CoreInterface;
new (programmaticConfig?: Configuration, advancedOptions?: CoreAdvancedOptions): CoreInterface;
}

@@ -79,8 +80,6 @@ /** Mocks-server base core interface */

get version(): string;
/** Allows to initialize the core passing custom programmatic options.
* @deprecated The method should not be used. It will be removed in next major version.
* @param config - Programmatic configuration {@link ConfigurationObject}
* @example await core.init({ log: "error" });
/** Allows to initialize manually the core. It is automatically called when calling start method
* @example await core.init();
*/
init(programmaticConfig?: ConfigurationObject): Promise<void>;
init(): Promise<void>;
/** Start the files handler and the mock server */

@@ -87,0 +86,0 @@ start(): Promise<void>;

@@ -222,2 +222,8 @@ "use strict";

}
get path() {
return this._getPath();
}
get loaders() {
return Object.assign({}, this._loaders);
}
init() {

@@ -263,2 +269,13 @@ return __awaiter(this, void 0, void 0, function* () {

}
createLoader({ id, src, onLoad }) {
this._logger.debug(`Creating files loader '${id}'`);
this._loaders[id] = new FilesLoader_1.FilesLoader({
id,
alerts: this._alertsLoaders.collection(id),
logger: this._loggerLoaders.namespace(id),
src,
onLoad,
});
return this._loaders[id];
}
_readFile(filePath) {

@@ -332,5 +349,2 @@ return __awaiter(this, void 0, void 0, function* () {

}
get path() {
return this._getPath();
}
_ensurePath() {

@@ -425,17 +439,3 @@ if (!(0, fs_extra_1.existsSync)(this._path)) {

}
createLoader({ id, src, onLoad }) {
this._logger.debug(`Creating files loader '${id}'`);
this._loaders[id] = new FilesLoader_1.FilesLoader({
id,
alerts: this._alertsLoaders.collection(id),
logger: this._loggerLoaders.namespace(id),
src,
onLoad,
});
return this._loaders[id];
}
get loaders() {
return Object.assign({}, this._loaders);
}
};
exports.Files = Files;

@@ -71,4 +71,2 @@ /// <reference types="babel__register" />

export interface FilesConstructor {
/** Unique identifier of Files class. Used for logging and alerts namespaces */
get id(): string;
/** Returns a Files interface

@@ -80,2 +78,4 @@ * @param options - Options to create the files interface {@link FilesOptions}.

new (options: FilesOptions, extraOptions?: FilesExtraOptions): FilesInterface;
/** Unique identifier of Files class. Used for logging and alerts namespaces */
get id(): string;
}

@@ -82,0 +82,0 @@ /** Allows to attach loaders that will receive loaded file contents */

@@ -51,2 +51,8 @@ "use strict";

}
get id() {
return this._id;
}
get src() {
return this._src;
}
load(filesContents, fileErrors) {

@@ -58,9 +64,3 @@ return this._onLoad(filesContents, fileErrors, {

}
get id() {
return this._id;
}
get src() {
return this._src;
}
};
exports.FilesLoader = FilesLoader;

@@ -11,8 +11,5 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Collection = void 0;
const express_1 = __importDefault(require("express"));
const express_1 = require("express");
const variant_handlers_1 = require("../../variant-handlers");

@@ -119,39 +116,2 @@ const routes_1 = require("../routes");

}
_initRouter() {
this._router = express_1.default.Router();
this._routes.forEach((route) => {
const logAndApplyDelay = (req, _res, next) => {
route.logger.info(`Request ${req.method} => ${req.url} | req: ${req.id}`);
const delay = route.delay !== null ? route.delay : this._routesManager.delay;
if (delay > 0) {
this._routesManager.logger.verbose(`Applying delay of ${delay}ms to route variant '${this._id}'`);
setTimeout(() => {
next();
}, delay);
}
else {
next();
}
};
if ((0, routes_1.routeIsEnabled)(route)) {
if ((0, variant_handlers_1.handlerIsRouter)(route.handler)) {
this._router.use(route.path, logAndApplyDelay);
this._router.use(route.path, route.handler.router.bind(route.handler));
}
else {
const middleware = route.handler.middleware.bind(route.handler);
if (route.allMethods) {
this._router.all(route.path, logAndApplyDelay);
this._router.all(route.path, middleware);
}
else {
route.methods.forEach((method) => {
this._router[method](route.path, logAndApplyDelay);
this._router[method](route.path, middleware);
});
}
}
}
});
}
get id() {

@@ -169,5 +129,2 @@ return this._id;

}
get _customRouteIds() {
return this._customRoutes.map((route) => route.id);
}
get customRouteIds() {

@@ -179,2 +136,5 @@ return this._customRouteIds;

}
get _customRouteIds() {
return this._customRoutes.map((route) => route.id);
}
useRoute(routeId) {

@@ -212,3 +172,40 @@ this._logger.info(`Adding route '${routeId}'`);

}
_initRouter() {
this._router = (0, express_1.Router)();
this._routes.forEach((route) => {
const logAndApplyDelay = (req, _res, next) => {
route.logger.info(`Request ${req.method} => ${req.url} | req: ${req.id}`);
const delay = route.delay !== null ? route.delay : this._routesManager.delay;
if (delay > 0) {
this._routesManager.logger.verbose(`Applying delay of ${delay}ms to route variant '${this._id}'`);
setTimeout(() => {
next();
}, delay);
}
else {
next();
}
};
if ((0, routes_1.routeIsEnabled)(route)) {
if ((0, variant_handlers_1.handlerIsRouter)(route.handler)) {
this._router.use(route.path, logAndApplyDelay);
this._router.use(route.path, route.handler.router.bind(route.handler));
}
else {
const middleware = route.handler.middleware.bind(route.handler);
if (route.allMethods) {
this._router.all(route.path, logAndApplyDelay);
this._router.all(route.path, middleware);
}
else {
route.methods.forEach((method) => {
this._router[method](route.path, logAndApplyDelay);
this._router[method](route.path, middleware);
});
}
}
}
});
}
};
exports.Collection = Collection;

@@ -119,2 +119,13 @@ "use strict";

}
get plain() {
return this._collections.map((collection) => {
const plainCollection = collection.toPlainObject();
return {
id: plainCollection.id,
from: plainCollection.from,
definedRoutes: plainCollection.specificRoutes,
routes: plainCollection.routes,
};
});
}
select(collection, { check = false } = {}) {

@@ -128,2 +139,45 @@ this._selectedOption.value = collection;

}
load(collectionDefinitions) {
this._loggerLoad.verbose("Creating collections from collection definitions");
this._loggerLoad.debug(JSON.stringify(collectionDefinitions));
this._collectionDefinitions = collectionDefinitions;
this._alertsLoad.clean();
let errorsProcessing = 0;
const ids = [];
this._collections = (0, lodash_1.compact)(collectionDefinitions.map((collectionDefinition, index) => {
const collectionDefinitionId = collectionDefinition && collectionDefinition.id;
const alertsCollectionId = !collectionDefinitionId || ids.includes(collectionDefinitionId)
? `${index}`
: collectionDefinitionId;
const collectionAlerts = this._alertsLoad.collection(alertsCollectionId);
const collection = this._createCollection({
collectionDefinition,
collectionAlerts,
});
if (!collection) {
errorsProcessing++;
return null;
}
if (ids.includes(collection.id)) {
collectionAlerts.set("duplicated", `Collection with duplicated id '${collection.id}' detected. It has been ignored`);
return null;
}
ids.push(collection.id);
return collection;
}));
if (errorsProcessing > 0) {
this._alertsLoad.set("critical-error", `Critical errors found while loading collections: ${errorsProcessing}`);
}
this._loggerLoad.info(`Created ${this._collections.length} collections`);
this._setCurrent();
}
get() {
return [...this._collections];
}
findById(id) {
return this._collections.find((collection) => collection.id === id);
}
toPlainObject() {
return this._collections.map((collection) => collection.toPlainObject());
}
_setCurrent() {

@@ -219,57 +273,3 @@ const id = this._selectedOption.value;

}
load(collectionDefinitions) {
this._loggerLoad.verbose("Creating collections from collection definitions");
this._loggerLoad.debug(JSON.stringify(collectionDefinitions));
this._collectionDefinitions = collectionDefinitions;
this._alertsLoad.clean();
let errorsProcessing = 0;
const ids = [];
this._collections = (0, lodash_1.compact)(collectionDefinitions.map((collectionDefinition, index) => {
const collectionDefinitionId = collectionDefinition && collectionDefinition.id;
const alertsCollectionId = !collectionDefinitionId || ids.includes(collectionDefinitionId)
? `${index}`
: collectionDefinitionId;
const collectionAlerts = this._alertsLoad.collection(alertsCollectionId);
const collection = this._createCollection({
collectionDefinition,
collectionAlerts,
});
if (!collection) {
errorsProcessing++;
return null;
}
if (ids.includes(collection.id)) {
collectionAlerts.set("duplicated", `Collection with duplicated id '${collection.id}' detected. It has been ignored`);
return null;
}
ids.push(collection.id);
return collection;
}));
if (errorsProcessing > 0) {
this._alertsLoad.set("critical-error", `Critical errors found while loading collections: ${errorsProcessing}`);
}
this._loggerLoad.info(`Created ${this._collections.length} collections`);
this._setCurrent();
}
get() {
return [...this._collections];
}
findById(id) {
return this._collections.find((collection) => collection.id === id);
}
toPlainObject() {
return this._collections.map((collection) => collection.toPlainObject());
}
get plain() {
return this._collections.map((collection) => {
const plainCollection = collection.toPlainObject();
return {
id: plainCollection.id,
from: plainCollection.from,
definedRoutes: plainCollection.specificRoutes,
routes: plainCollection.routes,
};
});
}
};
exports.Collections = Collections;

@@ -33,4 +33,2 @@ import type { ConfigNamespaceInterface, OptionDefinition, GetOptionValueTypeFromDefinition } from "@mocks-server/config";

export interface CollectionsConstructor {
/** Unique identifier of Collections class. Used for logging and alerts namespaces */
get id(): string;
/** Returns a Collections interface

@@ -42,2 +40,4 @@ * @param options - Options to create the collections interface {@link CollectionsOptions}.

new (options: CollectionsOptions): CollectionsInterface;
/** Unique identifier of Collections class. Used for logging and alerts namespaces */
get id(): string;
}

@@ -55,4 +55,6 @@ export interface SelectCollectionOptionsNoPromise {

}
/** Interface for managing Mocks Server collections. Currently it does not have almost responsibility, but this has to be refactored. TODO: Migrate routes responsibility to this interface */
/** Interface for managing Mocks Server collections.*/
export interface CollectionsInterface {
/** Set current collection */
select: SelectCollection;
/** Return id of currently selected collection */

@@ -64,4 +66,2 @@ get selected(): CollectionId | null;

get current(): CollectionInterface | null;
/** Set current collection */
select: SelectCollection;
/**

@@ -68,0 +68,0 @@ * Create collections from collection definitions

@@ -23,2 +23,11 @@ "use strict";

}
getNormalized() {
return this._collectionDefinitions.map(this._normalizeCollection);
}
findByIdAndNormalize(id) {
const collection = this.findById(id);
if (collection) {
return this._normalizeCollection(collection);
}
}
get() {

@@ -36,12 +45,3 @@ return this._collectionDefinitions;

}
getNormalized() {
return this._collectionDefinitions.map(this._normalizeCollection);
}
findByIdAndNormalize(id) {
const collection = this.findById(id);
if (collection) {
return this._normalizeCollection(collection);
}
}
};
exports.CollectionDefinitions = CollectionDefinitions;

@@ -6,4 +6,4 @@ import type { DefinitionsLoaderInterface, DefinitionLoadersManagerInterface, DefinitionLoadersManagerOptions } from "./DefinitionLoadersManager.types";

constructor({ onLoad }: DefinitionLoadersManagerOptions);
get definitions(): Type[];
createLoader(): DefinitionsLoaderInterface<Type>["load"];
get definitions(): Type[];
}

@@ -31,2 +31,5 @@ "use strict";

}
get definitions() {
return this._definitions;
}
load(definitions) {

@@ -36,5 +39,2 @@ this._definitions = definitions;

}
get definitions() {
return this._definitions;
}
}

@@ -58,7 +58,2 @@ class DefinitionLoadersManager {

}
createLoader() {
const loader = new DefinitionsLoader({ onLoad: this._onLoad });
this._loaders.push(loader);
return loader.load;
}
get definitions() {

@@ -71,3 +66,8 @@ let allResources = [];

}
createLoader() {
const loader = new DefinitionsLoader({ onLoad: this._onLoad });
this._loaders.push(loader);
return loader.load;
}
}
exports.DefinitionLoadersManager = DefinitionLoadersManager;

@@ -84,5 +84,2 @@ "use strict";

}
_onLoad() {
this._onLoadCallback();
}
get collections() {

@@ -100,3 +97,6 @@ return this._collectionDefinitions;

}
_onLoad() {
this._onLoadCallback();
}
};
exports.Definitions = Definitions;

@@ -33,2 +33,11 @@ "use strict";

}
getNormalized() {
return this._routeDefinitions.map(this._normalizeRoute);
}
findByIdAndNormalize(id) {
const routeDefinition = this.findById(id);
if (routeDefinition) {
return this._normalizeRoute(routeDefinition);
}
}
_normalizeVariantOptions(variantOptions) {

@@ -59,12 +68,3 @@ const options = variantOptions;

}
getNormalized() {
return this._routeDefinitions.map(this._normalizeRoute);
}
findByIdAndNormalize(id) {
const routeDefinition = this.findById(id);
if (routeDefinition) {
return this._normalizeRoute(routeDefinition);
}
}
};
exports.RouteDefinitions = RouteDefinitions;

@@ -7,8 +7,2 @@ import type { UnknownObject } from "../../common/types";

}
interface VariantHandlerBaseOptions {
/** Route method */
method: RouteDefinitionHTTPMethod;
/** Route path */
url: string;
}
type VariantDefinitionId = string;

@@ -29,3 +23,3 @@ /** Common properties to all types of route variants */

options: VariantHandlerOptionsByType[K];
};
} & VariantDefinitionCommon;
};

@@ -36,3 +30,9 @@ type VariantHandlerTypes = keyof VariantHandlerOptionsByType;

type VariantHandlerTypeOptions = VariantHandlerOptionsByType[keyof VariantHandlerOptionsByType];
type VariantHandlerOptions = VariantHandlerBaseOptions & VariantHandlerOptionsByType[keyof VariantHandlerOptionsByType];
interface VariantHandlerBaseOptions {
/** Route method */
method: RouteDefinitionHTTPMethod;
/** Route path */
url: string;
}
type VariantHandlerOptions = VariantHandlerOptionsByType[keyof VariantHandlerOptionsByType] & VariantHandlerBaseOptions;
}

@@ -39,0 +39,0 @@ }

"use strict";
/*
Copyright 2021-2023 Javier Brea
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -16,13 +25,4 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

exports.Mock = void 0;
/*
Copyright 2021-2022 Javier Brea
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
const events_1 = __importDefault(require("events"));
const express_1 = __importDefault(require("express"));
const express_1 = require("express");
const common_1 = require("../common");

@@ -68,3 +68,3 @@ const collections_1 = require("./collections");

writable: true,
value: express_1.default.Router()
value: (0, express_1.Router)()
});

@@ -122,19 +122,15 @@ Object.defineProperty(this, "_definitions", {

}
_emitChange() {
this._eventEmitter.emit(common_1.CHANGE_MOCK);
this._onChange();
get customRouteVariants() {
var _a;
return ((_a = this._collections.current) === null || _a === void 0 ? void 0 : _a.customRouteIds) || [];
}
_reloadRouter() {
if (this._collections.current) {
this._router = this._collections.current.router;
}
else {
this._router = express_1.default.Router();
}
this._emitChange();
get routes() {
return this._routes;
}
_loadDefinitions() {
this._routes.load(this._definitions.routes.get(), this._variantHandlers);
this._collections.load(this._definitions.collections.get());
get collections() {
return this._collections;
}
get definitions() {
return this._definitions;
}
init(variantHandlers) {

@@ -162,16 +158,20 @@ return __awaiter(this, void 0, void 0, function* () {

}
get customRouteVariants() {
var _a;
return ((_a = this._collections.current) === null || _a === void 0 ? void 0 : _a.customRouteIds) || [];
_emitChange() {
this._eventEmitter.emit(common_1.CHANGE_MOCK);
this._onChange();
}
get routes() {
return this._routes;
_reloadRouter() {
if (this._collections.current) {
this._router = this._collections.current.router;
}
else {
this._router = (0, express_1.Router)();
}
this._emitChange();
}
get collections() {
return this._collections;
_loadDefinitions() {
this._routes.load(this._definitions.routes.get(), this._variantHandlers);
this._collections.load(this._definitions.collections.get());
}
get definitions() {
return this._definitions;
}
};
exports.Mock = Mock;

@@ -5,5 +5,5 @@ import type { ConfigNamespaceInterface } from "@mocks-server/config";

import type { EventListener, EventListenerRemover } from "../common/types";
import type { CoreInterface } from "../Core.types";
import type { NextFunction, Request, Response } from "../server/types";
import type { VariantHandlerConstructor } from "../variant-handlers/types";
import type { CoreInterface } from "../Core.types";
import type { CollectionsInterface } from "./collections/types";

@@ -48,4 +48,2 @@ import type { CollectionDefinition, DefinitionLoadersManagerInterface, DefinitionsLoaderInterface, DefinitionsInterface, DefinitionsLoaders, RouteDefinition } from "./definitions/types";

export interface MockConstructor {
/** Unique identifier of Routes class. Used for logging and alerts namespaces */
get id(): string;
/** Returns a Routes interface

@@ -57,2 +55,4 @@ * @param options - Options to create the mock interface {@link MockOptions}.

new (options: MockOptions, core: CoreInterface): MockInterface;
/** Unique identifier of Routes class. Used for logging and alerts namespaces */
get id(): string;
}

@@ -59,0 +59,0 @@ export interface MockInterface {

@@ -45,3 +45,2 @@ "use strict";

}
// TODO, add to data model, migrate routes logic here
const Routes = class Routes {

@@ -134,2 +133,84 @@ constructor({ alerts, logger, config, onChange }, core) {

}
get plain() {
return (0, lodash_1.compact)(this._routeDefinitions.map((routeDefinition) => {
const route = this._routes.find((routeCandidate) => routeCandidate.routeId === routeDefinition.id);
if (route) {
const plainRoute = route.toPlainObject();
return {
id: routeDefinition.id,
url: plainRoute.path,
method: plainRoute.methods,
delay: (0, lodash_1.isUndefined)(routeDefinition.delay) ? null : routeDefinition.delay,
variants: routeDefinition.variants.map((variant) => {
return `${routeDefinition.id}:${variant.id}`;
}),
};
}
}));
}
get plainVariants() {
return this._routes.map((route) => {
const plainRoute = route.toPlainObject();
return {
id: plainRoute.id,
disabled: plainRoute.disabled,
route: plainRoute.definition.route,
type: plainRoute.type,
preview: plainRoute.preview,
delay: plainRoute.delay,
};
});
}
load(routeDefinitions, variantHandlers) {
this._variantHandlers = variantHandlers;
this._init();
this._loggerLoad.verbose("Creating routes from route definitions");
this._loggerLoad.debug(JSON.stringify(routeDefinitions));
this._routeDefinitions = routeDefinitions; // TODO, stored only for creating the legacy plain routes. Remove when legacy plain getter is removed
const routeDefinitionIds = [];
this._alertsLoad.clean();
this._routes = (0, lodash_1.compact)((0, lodash_1.flatten)(routeDefinitions.map((routeDefinition, index) => {
const routeIds = [];
const loadRouteAlerts = this._alertsLoad.collection(`${(routeDefinition && routeDefinition.id) || index}`);
const routeErrors = (0, RoutesValidator_1.routeValidationErrors)(routeDefinition);
if (routeErrors) {
loadRouteAlerts.set("validation", routeErrors.message);
this._loggerLoad.silly(`Route validation errors: ${JSON.stringify(routeErrors.errors)}`);
return null;
}
if (routeDefinitionIds.includes(routeDefinition.id)) {
loadRouteAlerts.set("duplicated", `Route with duplicated id '${routeDefinition.id}' detected. It has been ignored`);
return null;
}
routeDefinitionIds.push(routeDefinition.id);
const loadRouteVariantsAlerts = loadRouteAlerts.collection("variants");
return routeDefinition.variants.map((variantDefinition) => {
const route = this._createRoute({
routeDefinition,
variantDefinition,
loadRouteVariantsAlerts,
});
if (route) {
if (routeIds.includes(route.id)) {
loadRouteVariantsAlerts
.collection(route.variantId)
.set("duplicated", `Route variant with duplicated id '${route.variantId}' detected in route '${routeDefinition.id}'. It has been ignored`);
return null;
}
routeIds.push(route.id);
}
return route;
});
})));
this._loggerLoad.info(`Created ${this._routes.length} routes`);
}
get() {
return [...this._routes];
}
findById(id) {
return this._routes.find((route) => route.id === id);
}
toPlainObject() {
return this._routes.map((route) => route.toPlainObject());
}
_createRoute({ routeDefinition, variantDefinition, loadRouteVariantsAlerts, }) {

@@ -147,2 +228,3 @@ let route = null;

alerts: routeVariantAlerts,
config: this._config,
});

@@ -202,85 +284,3 @@ if (variantDefinition.disabled) {

}
load(routeDefinitions, variantHandlers) {
this._variantHandlers = variantHandlers;
this._init();
this._loggerLoad.verbose("Creating routes from route definitions");
this._loggerLoad.debug(JSON.stringify(routeDefinitions));
this._routeDefinitions = routeDefinitions; // TODO, stored only for creating the legacy plain routes. Remove when legacy plain getter is removed
const routeDefinitionIds = [];
this._alertsLoad.clean();
this._routes = (0, lodash_1.compact)((0, lodash_1.flatten)(routeDefinitions.map((routeDefinition, index) => {
const routeIds = [];
const loadRouteAlerts = this._alertsLoad.collection(`${(routeDefinition && routeDefinition.id) || index}`);
const routeErrors = (0, RoutesValidator_1.routeValidationErrors)(routeDefinition);
if (routeErrors) {
loadRouteAlerts.set("validation", routeErrors.message);
this._loggerLoad.silly(`Route validation errors: ${JSON.stringify(routeErrors.errors)}`);
return null;
}
if (routeDefinitionIds.includes(routeDefinition.id)) {
loadRouteAlerts.set("duplicated", `Route with duplicated id '${routeDefinition.id}' detected. It has been ignored`);
return null;
}
routeDefinitionIds.push(routeDefinition.id);
const loadRouteVariantsAlerts = loadRouteAlerts.collection("variants");
return routeDefinition.variants.map((variantDefinition) => {
const route = this._createRoute({
routeDefinition,
variantDefinition,
loadRouteVariantsAlerts,
});
if (route) {
if (routeIds.includes(route.id)) {
loadRouteVariantsAlerts
.collection(route.variantId)
.set("duplicated", `Route variant with duplicated id '${route.variantId}' detected in route '${routeDefinition.id}'. It has been ignored`);
return null;
}
routeIds.push(route.id);
}
return route;
});
})));
this._loggerLoad.info(`Created ${this._routes.length} routes`);
}
get() {
return [...this._routes];
}
findById(id) {
return this._routes.find((route) => route.id === id);
}
toPlainObject() {
return this._routes.map((route) => route.toPlainObject());
}
get plain() {
return (0, lodash_1.compact)(this._routeDefinitions.map((routeDefinition) => {
const route = this._routes.find((routeCandidate) => routeCandidate.routeId === routeDefinition.id);
if (route) {
const plainRoute = route.toPlainObject();
return {
id: routeDefinition.id,
url: plainRoute.path,
method: plainRoute.methods,
delay: (0, lodash_1.isUndefined)(routeDefinition.delay) ? null : routeDefinition.delay,
variants: routeDefinition.variants.map((variant) => {
return `${routeDefinition.id}:${variant.id}`;
}),
};
}
}));
}
get plainVariants() {
return this._routes.map((route) => {
const plainRoute = route.toPlainObject();
return {
id: plainRoute.id,
disabled: plainRoute.disabled,
route: plainRoute.definition.route,
type: plainRoute.type,
preview: plainRoute.preview,
delay: plainRoute.delay,
};
});
}
};
exports.Routes = Routes;

@@ -34,4 +34,2 @@ import type { ConfigNamespaceInterface, OptionDefinition, GetOptionValueTypeFromDefinition } from "@mocks-server/config";

export interface RoutesConstructor {
/** Unique identifier of Routes class. Used for logging and alerts namespaces */
get id(): string;
/** Returns a Routes interface

@@ -43,4 +41,6 @@ * @param options - Options to create the routes interface {@link RoutesOptions}.

new (options: RoutesOptions, core: CoreInterface): RoutesInterface;
/** Unique identifier of Routes class. Used for logging and alerts namespaces */
get id(): string;
}
/** Interface for managing Mocks Server routes. Currently it does not have almost responsibility, but this has to be refactored. TODO: Migrate routes responsibility to this interface */
/** Interface for managing Mocks Server routes.*/
export interface RoutesInterface {

@@ -47,0 +47,0 @@ /** Get value of delay configuration */

@@ -201,10 +201,7 @@ "use strict";

const plugin = this._pluginsInstances[index];
if (!plugin) {
return `${index}`;
}
const pluginConstructor = plugin.constructor;
if (pluginConstructor.id) {
const pluginConstructor = plugin === null || plugin === void 0 ? void 0 : plugin.constructor;
if (pluginConstructor === null || pluginConstructor === void 0 ? void 0 : pluginConstructor.id) {
return pluginConstructor.id;
}
return plugin.id || `${index}`;
return `${index}`;
}

@@ -221,3 +218,2 @@ _catchRegisterError(error, index) {

try {
// TODO, throw an error if plugin has no id. legacy. Require config, logger and alerts in ScopedCore
if (Plugin.id) {

@@ -229,3 +225,3 @@ pluginConfig = this._config.addNamespace(Plugin.id);

else {
this._alertsFormat.set(this._pluginId(pluginIndex), "Plugins must have a static id property");
throw new Error("Plugins must have a static id property");
}

@@ -235,3 +231,2 @@ const pluginCoreFinalOptions = Object.assign(Object.assign({}, pluginCoreOptions), { config: pluginConfig, alerts: pluginAlerts, logger: pluginLogger });

pluginInstance = new Plugin(coreApi);
this._pluginsScopedCores.push(coreApi);
this._pluginsInstances.push(pluginInstance);

@@ -243,30 +238,10 @@ this._pluginsRegistered++;

}
if ((0, lodash_1.isFunction)(pluginInstance.register) ||
(0, lodash_1.isFunction)(pluginInstance.init) ||
(0, lodash_1.isFunction)(pluginInstance.start) ||
(0, lodash_1.isFunction)(pluginInstance.stop)) {
let pluginCoreFinalOptions = Object.assign(Object.assign({}, pluginCoreOptions), { config: pluginConfig, alerts: pluginAlerts, logger: pluginLogger });
// If plugin has not static id, custom core API is passed only to methods
// Legacy, remove when plugin static id is mandatory
if (!pluginConfig && pluginInstance.id) {
pluginConfig = this._config.addNamespace(pluginInstance.id);
pluginAlerts = this._alerts.collection(pluginInstance.id);
pluginLogger = this._logger.namespace(pluginInstance.id);
pluginCoreFinalOptions = Object.assign(Object.assign({}, pluginCoreOptions), { config: pluginConfig, alerts: pluginAlerts, logger: pluginLogger });
coreApi = new common_1.ScopedCore(pluginCoreFinalOptions);
this._pluginsScopedCores.pop();
this._pluginsScopedCores.push(coreApi);
if ((0, lodash_1.isFunction)(pluginInstance.register)) {
try {
yield pluginInstance.register();
}
else {
this._pluginsScopedCores.push(coreApi);
catch (error) {
this._pluginsRegistered = this._pluginsRegistered - 1;
return this._catchRegisterError(error, pluginIndex);
}
if ((0, lodash_1.isFunction)(pluginInstance.register)) {
try {
yield pluginInstance.register(coreApi);
}
catch (error) {
this._pluginsRegistered = this._pluginsRegistered - 1;
return this._catchRegisterError(error, pluginIndex);
}
}
}

@@ -310,3 +285,3 @@ return pluginInstance;

const pluginInitMethod = this._pluginsInstances[pluginIndex].init;
pluginInit = pluginInitMethod.bind(this._pluginsInstances[pluginIndex])(this._pluginsScopedCores[pluginIndex]);
pluginInit = pluginInitMethod.bind(this._pluginsInstances[pluginIndex])();
}

@@ -350,3 +325,3 @@ catch (error) {

const pluginStartMethod = this._pluginsInstances[pluginIndex].start;
pluginStart = pluginStartMethod.bind(this._pluginsInstances[pluginIndex])(this._pluginsScopedCores[pluginIndex]);
pluginStart = pluginStartMethod.bind(this._pluginsInstances[pluginIndex])();
}

@@ -390,3 +365,3 @@ catch (error) {

const pluginStopMethod = this._pluginsInstances[pluginIndex].stop;
pluginStop = pluginStopMethod.bind(this._pluginsInstances[pluginIndex])(this._pluginsScopedCores[pluginIndex]);
pluginStop = pluginStopMethod.bind(this._pluginsInstances[pluginIndex])();
}

@@ -393,0 +368,0 @@ catch (error) {

@@ -31,6 +31,2 @@ import type { ConfigNamespaceInterface, OptionDefinition, GetOptionValueTypeFromDefinition } from "@mocks-server/config";

/**
* Plugins class static id
*/
get id(): string;
/**
* Creates a plugins interface

@@ -43,2 +39,6 @@ * @param options - Plugins options {@link PluginsOptions}

new (options: PluginsOptions, core: CoreInterface): PluginsInterface;
/**
* Plugins class static id
*/
get id(): string;
}

@@ -72,6 +72,2 @@ /** Plugins interface */

/**
* Plugin static id. Used for logging purposes, and to create scoped alerts, config and logger for the plugin
*/
get id(): PluginId;
/**
* Register plugin configuration, etc. https://www.mocks-server.org/docs/plugins/development/#constructorcore

@@ -83,6 +79,10 @@ * @param core - Mocks Server core with scoped config, alerts and logger {@link ScopedCoreInterface}

new (core: ScopedCoreInterface): PluginInterface;
/**
* Plugin static id. Used for logging purposes, and to create scoped alerts, config and logger for the plugin
*/
get id(): PluginId;
}
/** Plugin method used by Mocks Server to manage its lifecycle */
export interface PluginLifeCycleMethod {
(core: ScopedCoreInterface): Promise<void>;
(): Promise<void>;
}

@@ -92,9 +92,4 @@ /** Common Interface to be implemented by plugins */

/**
* Plugin static id. Used for logging purposes, and to create scoped alerts, config and logger for the plugin. It can be also defined as a static property in the constructor function
*/
id?: PluginId;
/**
* Register plugin configuration, etc. Use it if you need to make async stuff for registering your settings. Otherwise, use the constructor. https://www.mocks-server.org/docs/plugins/development/#constructorcore
* @param core - Mocks Server core with scoped config, alerts and logger {@link ScopedCoreInterface}
* @example await plugin.register(core);
* @example await plugin.register();
*/

@@ -104,4 +99,3 @@ register?: PluginLifeCycleMethod;

* Init the plugin. Here you should read options, add listeners to core events, etc. https://www.mocks-server.org/docs/plugins/development/#initcore
* @param core - Mocks Server core with scoped config, alerts and logger {@link ScopedCoreInterface}
* @example await plugin.init(core);
* @example await plugin.init();
*/

@@ -111,4 +105,3 @@ init?: PluginLifeCycleMethod;

* Start the plugin. Here you should start the plugin processes in case there are. https://www.mocks-server.org/docs/plugins/development/#startcore
* @param core - Mocks Server core with scoped config, alerts and logger {@link ScopedCoreInterface}
* @example await plugin.start(core);
* @example await plugin.start();
*/

@@ -118,4 +111,3 @@ start?: PluginLifeCycleMethod;

* Stop the plugin. Here you should stop all the plugin processes that you started in the start method. https://www.mocks-server.org/docs/plugins/development/#stopcore
* @param core - Mocks Server core with scoped config, alerts and logger {@link ScopedCoreInterface}
* @example await plugin.stop(core);
* @example await plugin.stop();
*/

@@ -122,0 +114,0 @@ stop?: PluginLifeCycleMethod;

@@ -162,2 +162,10 @@ "use strict";

}
init({ folderPath }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
this._checkAndCreateFolderScaffold(folderPath),
this._checkAndCreateConfigScaffold(),
]);
});
}
_parseConfigForTemplates() {

@@ -203,11 +211,3 @@ return {

}
init({ folderPath }) {
return __awaiter(this, void 0, void 0, function* () {
yield Promise.all([
this._checkAndCreateFolderScaffold(folderPath),
this._checkAndCreateConfigScaffold(),
]);
});
}
};
exports.Scaffold = Scaffold;
"use strict";
/*
Copyright 2019-2023 Javier Brea
Copyright 2019 XbyOrange
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -39,12 +49,2 @@ if (k2 === undefined) k2 = k;

exports.Server = void 0;
/*
Copyright 2019-2023 Javier Brea
Copyright 2019 XbyOrange
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
const http_1 = __importDefault(require("http"));

@@ -236,2 +236,10 @@ const cors_1 = __importDefault(require("cors"));

}
get protocol() {
return this._httpsEnabledOption.value ? "https" : "http";
}
get url() {
const host = this._hostOption.value;
const hostName = host === ServerOptions_1.ALL_HOSTS ? LOCALHOST : host;
return `${this.protocol}://${hostName}:${this._portOption.value}`;
}
init() {

@@ -246,2 +254,55 @@ process.on("SIGINT", () => {

}
stop() {
if (this._serverStoppingPromise) {
return this._serverStoppingPromise;
}
if (this._server) {
const server = this._server;
this._serverStoppingPromise = new Promise((resolve) => {
this._logger.verbose("Stopping server");
server.close(() => {
this._logger.info("Server stopped");
this._serverStarted = false;
this._serverStoppingPromise = undefined;
resolve();
});
});
return this._serverStoppingPromise;
}
return Promise.resolve();
}
start() {
return __awaiter(this, void 0, void 0, function* () {
yield this._initServer();
if (this._serverStartingPromise) {
this._logger.debug("Server is already starting, returning same promise");
return this._serverStartingPromise;
}
this._serverStartingPromise = new Promise(this._startServer);
return this._serverStartingPromise;
});
}
restart() {
return __awaiter(this, void 0, void 0, function* () {
yield this.stop();
return this.start();
});
}
addRouter(path, router) {
this._logger.info(`Adding custom router with path ${path}`);
this._customRouters.push({
path,
router,
});
return this._reinitializeServer();
}
removeRouter(path, router) {
this._logger.info(`Removing custom router with path ${path}`);
const indexToRemove = this._getCustomRouterIndex(path, router);
if (indexToRemove !== null) {
this._customRouters.splice(indexToRemove, 1);
return this._reinitializeServer();
}
return Promise.resolve();
}
_initServer() {

@@ -359,38 +420,2 @@ return __awaiter(this, void 0, void 0, function* () {

}
stop() {
if (this._serverStoppingPromise) {
return this._serverStoppingPromise;
}
if (this._server) {
const server = this._server;
this._serverStoppingPromise = new Promise((resolve) => {
this._logger.verbose("Stopping server");
server.close(() => {
this._logger.info("Server stopped");
this._serverStarted = false;
this._serverStoppingPromise = undefined;
resolve();
});
});
return this._serverStoppingPromise;
}
return Promise.resolve();
}
start() {
return __awaiter(this, void 0, void 0, function* () {
yield this._initServer();
if (this._serverStartingPromise) {
this._logger.debug("Server is already starting, returning same promise");
return this._serverStartingPromise;
}
this._serverStartingPromise = new Promise(this._startServer);
return this._serverStartingPromise;
});
}
restart() {
return __awaiter(this, void 0, void 0, function* () {
yield this.stop();
return this.start();
});
}
_getCustomRouterIndex(path, router) {

@@ -405,28 +430,3 @@ let routerIndex = null;

}
addRouter(path, router) {
this._logger.info(`Adding custom router with path ${path}`);
this._customRouters.push({
path,
router,
});
return this._reinitializeServer();
}
removeRouter(path, router) {
this._logger.info(`Removing custom router with path ${path}`);
const indexToRemove = this._getCustomRouterIndex(path, router);
if (indexToRemove !== null) {
this._customRouters.splice(indexToRemove, 1);
return this._reinitializeServer();
}
return Promise.resolve();
}
get protocol() {
return this._httpsEnabledOption.value ? "https" : "http";
}
get url() {
const host = this._hostOption.value;
const hostName = host === ServerOptions_1.ALL_HOSTS ? LOCALHOST : host;
return `${this.protocol}://${hostName}:${this._portOption.value}`;
}
};
exports.Server = Server;

@@ -48,4 +48,2 @@ import type { ConfigNamespaceInterface } from "@mocks-server/config";

export interface ServerConstructor {
/** Unique id for Server class */
get id(): string;
/**

@@ -58,2 +56,4 @@ * Creates a server interface interface

new (options: ServerOptions): ServerInterface;
/** Unique id for Server class */
get id(): string;
}

@@ -63,2 +63,13 @@ /** Server interface */

/**
* Returns the protocol currently used by the server
* @returns "https" or "http"
*/
get protocol(): ProtocolHttp | ProtocolHttps;
/**
* Returns the server url, including the protocol and the port
* @returns Server url
* @example http://localhost:3000
*/
get url(): string;
/**
* Initialize the server. Listen to process exit signal to stop server before exiting

@@ -93,13 +104,2 @@ * @example await server.init();

removeRouter(path: string, router: Router): Promise<void>;
/**
* Returns the protocol currently used by the server
* @returns "https" or "http"
*/
get protocol(): ProtocolHttp | ProtocolHttps;
/**
* Returns the server url, including the protocol and the port
* @returns Server url
* @example http://localhost:3000
*/
get url(): string;
}

@@ -75,2 +75,7 @@ "use strict";

}
get preview() {
return {
status: this._options.status,
};
}
middleware(req, res, next) {

@@ -90,8 +95,3 @@ if (this._options.headers) {

}
get preview() {
return {
status: this._options.status,
};
}
};
exports.VariantHandlerFile = VariantHandlerFile;

@@ -32,3 +32,3 @@ import type { UnknownObject, ScopedCoreInterface } from "../../common/types";

}
export interface VariantHandlerFileOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerFileOptions {
/** Path to the file to be served */

@@ -35,0 +35,0 @@ path: string;

@@ -28,3 +28,3 @@ "use strict";

this._options = options;
this._logger = core.logger; // TODO, remove cast when plugin id is required
this._logger = core.logger;
}

@@ -73,2 +73,8 @@ static get id() {

}
get preview() {
return {
body: this._options.body,
status: this._options.status,
};
}
middleware(req, res) {

@@ -81,9 +87,3 @@ this._logger.debug(`Setting headers | req: ${req.id}`);

}
get preview() {
return {
body: this._options.body,
status: this._options.status,
};
}
};
exports.VariantHandlerJson = VariantHandlerJson;

@@ -10,3 +10,3 @@ import type { UnknownObject, JSONValue, ScopedCoreInterface } from "../../common/types";

}
export interface VariantHandlerJsonOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerJsonOptions {
/** Status to send in the response */

@@ -35,3 +35,3 @@ status: number;

*/
new (options: VariantHandlerJsonOptions, core: ScopedCoreInterface): VariantHandlerJsonInterface;
new (options: VariantHandlerJsonOptions & MocksServer.VariantHandlerBaseOptions, core: ScopedCoreInterface): VariantHandlerJsonInterface;
}

@@ -38,0 +38,0 @@ /** Json variant handler interface */

@@ -52,2 +52,5 @@ "use strict";

}
get preview() {
return null;
}
middleware(req, res, next) {

@@ -57,6 +60,3 @@ this._logger.verbose(`Executing middleware | req: ${req.id}`);

}
get preview() {
return null;
}
};
exports.VariantHandlerMiddleware = VariantHandlerMiddleware;

@@ -6,3 +6,3 @@ import type { ScopedCoreInterface } from "../../common/types";

export declare type VariantHandlerMiddlewarePreview = null;
export interface VariantHandlerMiddlewareOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerMiddlewareOptions {
/** Middleware to be executed as request handler */

@@ -27,3 +27,3 @@ middleware: (req: Request, res: Response, next: NextFunction, core: ScopedCoreInterface) => void;

*/
new (options: VariantHandlerMiddlewareOptions, core: ScopedCoreInterface): VariantHandlerMiddlewareInterface;
new (options: VariantHandlerMiddlewareOptions & MocksServer.VariantHandlerBaseOptions, core: ScopedCoreInterface): VariantHandlerMiddlewareInterface;
}

@@ -30,0 +30,0 @@ /** Middleware variant handler interface */

@@ -59,2 +59,5 @@ "use strict";

}
get preview() {
return null;
}
get router() {

@@ -70,6 +73,3 @@ this._logger.verbose(`Creating router to serve static folder ${this._options.path}`);

}
get preview() {
return null;
}
};
exports.VariantHandlerStatic = VariantHandlerStatic;

@@ -6,3 +6,3 @@ import type { ServeStaticOptions } from "serve-static";

export declare type VariantHandlerStaticPreview = null;
export interface VariantHandlerStaticOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerStaticOptions {
/** Path of the folder to be served. It can be a relative path from process.cwd, or an absolute path. */

@@ -31,3 +31,3 @@ path: string;

*/
new (options: VariantHandlerStaticOptions, core: ScopedCoreInterface): VariantHandlerStaticInterface;
new (options: VariantHandlerStaticOptions & MocksServer.VariantHandlerBaseOptions, core: ScopedCoreInterface): VariantHandlerStaticInterface;
}

@@ -34,0 +34,0 @@ /** Status variant handler interface */

@@ -48,9 +48,2 @@ "use strict";

}
middleware(req, res) {
this._logger.debug(`Setting headers | req: ${req.id}`);
res.set(Object.assign(Object.assign({}, this.defaultHeaders), this._options.headers));
res.status(this._options.status);
this._logger.verbose(`Sending response with empty body | req: ${req.id}`);
res.send();
}
get defaultHeaders() {

@@ -66,3 +59,10 @@ return {

}
middleware(req, res) {
this._logger.debug(`Setting headers | req: ${req.id}`);
res.set(Object.assign(Object.assign({}, this.defaultHeaders), this._options.headers));
res.status(this._options.status);
this._logger.verbose(`Sending response with empty body | req: ${req.id}`);
res.send();
}
};
exports.VariantHandlerStatus = VariantHandlerStatus;

@@ -8,3 +8,3 @@ import type { UnknownObject, ScopedCoreInterface } from "../../common/types";

}
export interface VariantHandlerStatusOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerStatusOptions {
/** Status to send in the response */

@@ -31,3 +31,3 @@ status: number;

*/
new (options: VariantHandlerStatusOptions, core: ScopedCoreInterface): VariantHandlerStatusInterface;
new (options: VariantHandlerStatusOptions & MocksServer.VariantHandlerBaseOptions, core: ScopedCoreInterface): VariantHandlerStatusInterface;
}

@@ -34,0 +34,0 @@ /** Status variant handler interface */

@@ -51,2 +51,8 @@ "use strict";

}
get preview() {
return {
body: this._options.body,
status: this._options.status,
};
}
get defaultHeaders() {

@@ -64,9 +70,3 @@ return {

}
get preview() {
return {
body: this._options.body,
status: this._options.status,
};
}
};
exports.VariantHandlerText = VariantHandlerText;

@@ -10,3 +10,3 @@ import type { UnknownObject, ScopedCoreInterface } from "../../common/types";

}
export interface VariantHandlerTextOptions extends MocksServer.VariantHandlerBaseOptions {
export interface VariantHandlerTextOptions {
/** Status to send in the response */

@@ -35,3 +35,3 @@ status: number;

*/
new (options: VariantHandlerTextOptions, core: ScopedCoreInterface): VariantHandlerTextInterface;
new (options: VariantHandlerTextOptions & MocksServer.VariantHandlerBaseOptions, core: ScopedCoreInterface): VariantHandlerTextInterface;
}

@@ -38,0 +38,0 @@ /** Json variant handler interface */

@@ -71,6 +71,4 @@ "use strict";

}
_registerOne(VariantHandler) {
// TODO, check id, etc..
this._logger.debug(`Registering '${VariantHandler.id}' variant handler`);
this._registeredVariantHandlers.push(VariantHandler);
get handlers() {
return this._registeredVariantHandlers;
}

@@ -94,6 +92,8 @@ register(variantHandlers) {

}
get handlers() {
return this._registeredVariantHandlers;
_registerOne(VariantHandler) {
// TODO, check id, etc..
this._logger.debug(`Registering '${VariantHandler.id}' variant handler`);
this._registeredVariantHandlers.push(VariantHandler);
}
};
exports.VariantHandlers = VariantHandlers;

@@ -72,6 +72,2 @@ import type { ConfigNamespaceInterface, GetOptionValueTypeFromDefinition, OptionDefinition } from "@mocks-server/config";

/**
* VariantHandlers class static id
*/
get id(): string;
/**
* Creates a variantsHandler interface

@@ -83,2 +79,6 @@ * @param options - VariantHandlers options {@link VariantHandlersOptions}

new (options: VariantHandlersOptions): VariantHandlersInterface;
/**
* VariantHandlers class static id
*/
get id(): string;
}

@@ -85,0 +85,0 @@ /** VariantHandlers interface */

{
"name": "@mocks-server/core",
"version": "5.0.0-beta.2",
"version": "5.0.0-beta.3",
"description": "Pluggable mock server supporting multiple route variants and mocks",

@@ -43,5 +43,5 @@ "keywords": [

"@hapi/boom": "9.1.4",
"@mocks-server/config": "2.0.0-beta.2",
"@mocks-server/logger": "2.0.0-beta.1",
"@mocks-server/nested-collections": "3.0.0-beta.1",
"@mocks-server/config": "2.0.0-beta.3",
"@mocks-server/logger": "2.0.0-beta.2",
"@mocks-server/nested-collections": "3.0.0-beta.2",
"ajv": "8.11.0",

@@ -51,3 +51,2 @@ "better-ajv-errors": "1.2.0",

"cors": "2.8.5",
"deepmerge": "4.2.2",
"express": "4.18.1",

@@ -75,3 +74,4 @@ "express-request-id": "1.4.1",

"@types/serve-static": "1.15.1",
"@types/update-notifier": "6.0.2"
"@types/update-notifier": "6.0.2",
"deepmerge": "4.2.2"
},

@@ -78,0 +78,0 @@ "scripts": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc