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 3.12.0 to 4.0.0

4

package.json
{
"name": "@mocks-server/core",
"version": "3.12.0",
"version": "4.0.0",
"description": "Pluggable mock server supporting multiple route variants and mocks",

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

"scripts": {
"test:unit": "jest"
"test:unit": "jest --runInBand"
},
"readme": "<p align=\"center\"><a href=\"https://mocks-server.org\" target=\"_blank\" rel=\"noopener noreferrer\"><img width=\"120\" src=\"https://www.mocks-server.org/img/logo_120.png\" alt=\"Mocks Server logo\"></a></p>\n\n<p align=\"center\">\n <a href=\"https://github.com/mocks-server/main/actions?query=workflow%3Abuild+branch%3Amaster\"><img src=\"https://github.com/mocks-server/main/workflows/build/badge.svg?branch=master\" alt=\"Build Status\"></a>\n <a href=\"https://codecov.io/gh/mocks-server/main\"><img src=\"https://codecov.io/gh/mocks-server/main/branch/master/graph/badge.svg?token=2S8ZR55AJV\" alt=\"Coverage\"></a>\n <a href=\"https://sonarcloud.io/project/overview?id=mocks-server_main_core\"><img src=\"https://sonarcloud.io/api/project_badges/measure?project=mocks-server_main_core&metric=alert_status\" alt=\"Quality Gate\"></a>\n <a href=\"https://www.npmjs.com/package/@mocks-server/core\"><img src=\"https://img.shields.io/npm/dm/@mocks-server/core.svg\" alt=\"Downloads\"></a>\n <a href=\"https://renovatebot.com\"><img src=\"https://img.shields.io/badge/renovate-enabled-brightgreen.svg\" alt=\"Renovate\"></a>\n <a href=\"https://github.com/mocks-server/main/blob/master/packages/core/LICENSE\"><img src=\"https://img.shields.io/npm/l/@mocks-server/core.svg\" alt=\"License\"></a>\n</p>\n\n---\n\n# Mocks Server Core\n\nThis package provides the plugabble core of the [Mocks Server][website-url] project.\n\nUse it if you want to [start Mocks Server programmatically by yourself](https://www.mocks-server.org/docs/api/javascript), or even [create your own Mocks Server distribution](https://www.mocks-server.org/docs/integrations/javascript) with the plugins of your choice. If this is not the case, you would probably prefer using the [main distribution of the Mocks Server project][main-url].\n\n## Documentation\n\nPlease refer to the [project documentation website][website-url]:\n\n* [Overview](https://www.mocks-server.org/docs/overview)\n* [Usage](https://www.mocks-server.org/docs/usage/basics)\n* [Configuration](https://www.mocks-server.org/docs/configuration/how-to-change-settings)\n* [API](https://www.mocks-server.org/docs/api/javascript)\n\n[website-url]: https://www.mocks-server.org\n[logo-url]: https://www.mocks-server.org/img/logo_120.png\n[main-url]: https://www.npmjs.com/package/@mocks-server/main\n"
}

@@ -13,2 +13,5 @@ /*

const ALERTS_ROOT_ID = "alerts";
const ID_SEP = ":";
class Alerts extends NestedCollections {

@@ -36,20 +39,12 @@ constructor(id, options) {

// LEGACY, to be changed by flat in next major version
get customFlat() {
get flat() {
return this._flat.map((item) => {
let context = item.collection;
let sep = ":";
if (context.startsWith("alerts:")) {
context = context.replace("alerts:", "");
} else {
context = "";
sep = "";
let collectionPaths = item.collection.split(ID_SEP);
if (collectionPaths[0] === ALERTS_ROOT_ID) {
collectionPaths.shift();
}
const id = `${context}${sep}${item.id}`;
return {
...item.value,
id,
context: id,
id: [...collectionPaths, item.id].join(ID_SEP),
};

@@ -56,0 +51,0 @@ });

@@ -1,26 +0,3 @@

const { docsUrl } = require("./helpers");
const CORE_METHODS = ["start", "stop"];
const CORE_METHODS = [
"start",
"stop",
// LEGACY, to be removed
"addRoutesHandler",
// LEGACY, to be removed
"onChangeMocks",
// LEGACY, to be removed
"onChangeAlerts",
// LEGACY, to be removed
"onChangeLogs",
// LEGACY, to be removed
"restartServer",
// LEGACY, to be removed
"addRouter",
// LEGACY, to be removed
"removeRouter",
// LEGACY, to be removed
"loadMocks",
// LEGACY, to be removed
"loadRoutes",
];
function cloneMethods(origin, dest) {

@@ -33,13 +10,3 @@ CORE_METHODS.forEach((methodName) => {

class CoreApi {
constructor({
core,
loadMocks,
loadRoutes,
addAlert,
removeAlerts,
renameAlerts,
config,
alerts,
logger,
}) {
constructor({ core, config, alerts, logger }) {
this._core = core;

@@ -50,52 +17,9 @@

// Add custom methods
if (loadMocks) {
this.loadMocks = loadMocks;
}
if (loadRoutes) {
this.loadRoutes = loadRoutes;
}
this._config = config;
this._alerts = alerts;
this._deprecationAlerts = alerts
? alerts.collection("deprecated")
: this._core._deprecationAlerts;
this._logger = logger;
// LEGACY, to be removed
this.addAlert = addAlert;
this.removeAlerts = removeAlerts;
this.renameAlerts = renameAlerts;
}
// LEGACY. To be removed
get core() {
// TODO, add link to releases URL.
this._deprecationAlerts.set(
"core",
`Usage of core property is deprecated. Use properties at first level instead: ${docsUrl(
"releases/migrating-from-v3#plugins"
)}`
);
return this._core;
}
// LEGACY, to be removed
get mocks() {
return this._core.mocks;
}
// LEGACY, to be removed
get tracer() {
return this._core.tracer;
}
// LEGACY, to be removed
get logs() {
return this._core.logs;
}
get config() {
return this._config || this._core.config;
return this._config;
}

@@ -102,0 +26,0 @@

@@ -22,4 +22,3 @@ /*

CHANGE_ALERTS: "change:alerts",
CHANGE_LOGS: "change:logs",
addEventListener,
};

@@ -17,4 +17,2 @@ /*

const tracer = require("./common/legacyTracer");
const AlertsLegacy = require("./alerts/AlertsLegacy");
const VariantHandlers = require("./variant-handlers/VariantHandlers");

@@ -28,5 +26,4 @@ const Mock = require("./mock/Mock");

const UpdateNotifier = require("./update-notifier/UpdateNotifier");
const { scopedAlertsMethods } = require("./alerts/legacyHelpers");
const { addEventListener, CHANGE_MOCK, CHANGE_ALERTS, CHANGE_LOGS } = require("./common/events");
const { arrayMerge, deprecatedMessage } = require("./common/helpers");
const { CHANGE_MOCK, CHANGE_ALERTS } = require("./common/events");
const { arrayMerge } = require("./common/helpers");
const { version } = require("../package.json");

@@ -43,8 +40,2 @@

},
{
description: "Array of VariantHandlers to be added. Legacy",
name: "routesHandlers",
type: "array",
default: [],
},
];

@@ -63,7 +54,2 @@

// LEGACY, to be removed
this._logger.onChangeGlobalStore(() => {
this._eventEmitter.emit(CHANGE_LOGS);
});
// Create config

@@ -76,6 +62,3 @@ this._config = new Config({ moduleName: MODULE_NAME });

// LEGACY, to be removed
this._configMocksLegacy = this._config.addNamespace(Mock.legacyId);
[this._logOption, this._variantHandlersOption] = this._config.addOptions(ROOT_OPTIONS);
[this._logOption] = this._config.addOptions(ROOT_OPTIONS);
this._logOption.onChange((level) => {

@@ -85,8 +68,4 @@ this._logger.setLevel(level);

// LEGACY, to be removed
this._logOption.onChange(tracer.set);
// Create alerts
const alertsLogger = this._logger.namespace("alerts");
const alertsLegacyLogger = alertsLogger.namespace("deprecated");
this._alerts = new Alerts("alerts", { logger: alertsLogger });

@@ -96,7 +75,2 @@ this._alerts.onChange(() => {

});
this._alertsLegacy = new AlertsLegacy({
alerts: this._alerts,
logger: alertsLegacyLogger,
});
this._deprecationAlerts = this._alerts.collection("deprecated");

@@ -121,4 +95,2 @@ // Create update notifier

logger: this._logger.namespace(Mock.id),
// LEGACY, to be removed
legacyConfig: this._configMocksLegacy,
onChange: () => this._eventEmitter.emit(CHANGE_MOCK),

@@ -129,7 +101,2 @@ },

// LEGACY, to be removed
const loaders = this._mock.createLoaders();
this._loadCollections = loaders.loadCollections;
this._loadRoutes = loaders.loadRoutes;
// Create plugins

@@ -141,40 +108,2 @@ this._plugins = new Plugins(

logger: this._logger.namespace(Plugins.id),
// LEGACY, to be removed
createCollectionsLoader: () => {
const { loadCollections } = this._mock.createLoaders();
return (collections) => {
this._deprecationAlerts.set(
"loadMocks",
deprecatedMessage(
"method",
"core.loadMocks",
"core.mock.createLoaders",
"releases/migrating-from-v3#api"
)
);
return loadCollections(collections);
};
},
createRoutesLoader: () => {
const { loadRoutes } = this._mock.createLoaders();
return (routes) => {
this._deprecationAlerts.set(
"loadRoutes",
deprecatedMessage(
"method",
"core.loadRoutes",
"core.mock.createLoaders",
"releases/migrating-from-v3#api"
)
);
return loadRoutes(routes);
};
},
// LEGACY, remove when legacy alerts are removed
...scopedAlertsMethods(
Plugins.id,
this._alertsLegacy.add,
this._alertsLegacy.remove,
this._alertsLegacy.rename
),
},

@@ -199,2 +128,3 @@ this //To be used only by plugins

alerts: this._alerts.collection(FilesLoaders.id),
// TODO, move to another element. Files loader has not to handle specific loaders
loadCollections: fileLoaders.loadCollections,

@@ -263,2 +193,3 @@ loadRoutes: fileLoaders.loadRoutes,

// Update notifier
// TODO, move to about module
this._updateNotifier.init();

@@ -270,22 +201,8 @@

// LEGACY, to be removed
tracer.set(this._logOption.value);
// Register plugins, let them add their custom config
await this._plugins.register();
if (this._variantHandlersOption.hasBeenSet) {
this._deprecationAlerts.set(
"routesHandlers",
deprecatedMessage(
"option",
"routesHandlers",
"variantHandlers.register",
"configuration/migrating-from-v3#options"
)
);
}
await this._variantHandlers.registerConfig();
await this._variantHandlers.registerConfig(this._variantHandlersOption.value);
// TODO, add to data model
await this._scaffold.init({

@@ -317,189 +234,8 @@ filesLoaderPath: this._filesLoader.path,

// LEGACY, to be removed
addRoutesHandler(VariantHandler) {
this._deprecationAlerts.set(
"addRoutesHandler",
deprecatedMessage(
"method",
"core.addRoutesHandler",
"core.variantHandlers.register",
"releases/migrating-from-v3#api"
)
);
this._variantHandlers.register([VariantHandler]);
}
// LEGACY, to be removed
loadMocks(collections) {
this._deprecationAlerts.set(
"loadMocks",
deprecatedMessage(
"method",
"core.loadMocks",
"core.mock.createLoaders",
"releases/migrating-from-v3#api"
)
);
this._loadCollections(collections);
}
// LEGACY, to be removed
loadRoutes(routes) {
this._deprecationAlerts.set(
"loadRoutes",
deprecatedMessage(
"method",
"core.loadRoutes",
"core.mock.createLoaders",
"releases/migrating-from-v3#api"
)
);
this._loadRoutes(routes);
}
// Listeners
// LEGACY, to be removed
onChangeMocks(listener) {
this._deprecationAlerts.set(
"onChangeMocks",
deprecatedMessage(
"method",
"core.onChangeMocks",
"core.mock.onChange",
"releases/migrating-from-v3#api"
)
);
return addEventListener(listener, CHANGE_MOCK, this._eventEmitter);
}
// LEGACY, to be removed
onChangeAlerts(listener) {
this._deprecationAlerts.set(
"onChangeAlerts",
deprecatedMessage(
"method",
"core.onChangeAlerts",
"core.alerts.root.onChange",
"releases/migrating-from-v3#api"
)
);
return addEventListener(listener, CHANGE_ALERTS, this._eventEmitter);
}
// LEGACY, to be removed
onChangeLogs(listener) {
this._deprecationAlerts.set(
"onChangeLogs",
deprecatedMessage(
"method",
"core.onChangeLogs",
"core.logger.onChangeGlobalStore",
"releases/migrating-from-v3#api"
)
);
return addEventListener(listener, CHANGE_LOGS, this._eventEmitter);
}
// Expose Server methods and getters
// LEGACY, to be removed
restartServer() {
this._deprecationAlerts.set(
"restartServer",
deprecatedMessage(
"method",
"core.restartServer",
"core.server.restart",
"releases/migrating-from-v3#api"
)
);
return this._server.restart();
}
// LEGACY, to be removed
addRouter(path, router) {
this._deprecationAlerts.set(
"addRouter",
deprecatedMessage(
"method",
"core.addRouter",
"core.server.addRouter",
"releases/migrating-from-v3#api"
)
);
return this._server.addRouter(path, router);
}
// LEGACY, to be removed
removeRouter(path, router) {
this._deprecationAlerts.set(
"removeRouter",
deprecatedMessage(
"method",
"core.removeRouter",
"core.server.removeRouter",
"releases/migrating-from-v3#api"
)
);
return this._server.removeRouter(path, router);
}
// LEGACY, change by whole alerts object in next major version
get alerts() {
this._deprecationAlerts.set(
"alerts",
deprecatedMessage(
"method",
"core.alerts",
"core.alertsApi",
"releases/migrating-from-v3#api"
)
);
return this._alerts.customFlat;
}
// Provides access to alerts API while alerts legacy is maintained
// LEGACY, to be removed
get alertsApi() {
return this._alerts;
}
// LEGACY, to be removed
get mocks() {
this._deprecationAlerts.set(
"mocks",
deprecatedMessage("getter", "core.mocks", "core.mock", "releases/migrating-from-v3#api")
);
return this._mock;
}
// LEGACY, to be removed
get tracer() {
this._deprecationAlerts.set(
"tracer",
deprecatedMessage(
"object",
"core.tracer",
"core.logger",
"releases/migrating-from-v3#logger"
)
);
return tracer;
}
// LEGACY, to be removed
get logs() {
this._deprecationAlerts.set(
"logs",
deprecatedMessage(
"getter",
"core.logs",
"core.logger.globalStore",
"releases/migrating-from-v3#logger"
)
);
return this._logger.globalStore;
}
get logger() {

@@ -521,2 +257,3 @@ return this._logger;

// TODO, move to mock
get variantHandlers() {

@@ -530,2 +267,3 @@ return this._variantHandlers;

// TODO, move to about module
get version() {

@@ -532,0 +270,0 @@ return version;

@@ -18,3 +18,3 @@ /*

const YAML_EXTENSIONS = [".yaml", ".yml"];
const DEFAULT_EXTENSIONS = [".json", ".js"].concat(YAML_EXTENSIONS);
const DEFAULT_EXTENSIONS = [".json", ".js", ".cjs"].concat(YAML_EXTENSIONS);
const BABEL_DEFAULT_EXTENSIONS = [".es6", ".es", ".esm", ".cjs", ".jsx", ".js", ".mjs", ".ts"];

@@ -21,0 +21,0 @@

@@ -43,3 +43,3 @@ /*

const logAndApplyDelay = (req, _res, next) => {
this._logger.info(`Request ${req.method} => ${req.url} | req: ${req.id}`);
routeVariant.logger.info(`Request ${req.method} => ${req.url} | req: ${req.id}`);
const delay = routeVariant.delay !== null ? routeVariant.delay : this._getDelay();

@@ -46,0 +46,0 @@ if (delay > 0) {

@@ -18,7 +18,7 @@ /*

type: "string",
// LEGACY, remove and set value from scaffold when legacy option is removed
default: "base",
},
];
// TODO, add to data model
class Collections {

@@ -29,16 +29,9 @@ static get id() {

constructor({
logger,
config,
onChangeSelected,
getIds,
getSelectedCollection,
getPlainCollections,
}) {
constructor({ logger, config, onChangeSelected, getIds, getPlainCollections, getSelected }) {
this._logger = logger;
this._config = config;
this._onChangeSelected = onChangeSelected;
this._getSelectedCollection = getSelectedCollection;
this._getPlainCollections = getPlainCollections;
this._getIds = getIds;
this._getSelected = getSelected;

@@ -50,3 +43,3 @@ [this._selectedOption] = this._config.addOptions(OPTIONS);

get selected() {
return this._getSelectedCollection();
return this._getSelected();
}

@@ -62,3 +55,2 @@

// LEGACY, set check to true by default on next major version, or remove the option
select(collection, { check = false } = {}) {

@@ -65,0 +57,0 @@ this._selectedOption.value = collection;

@@ -29,4 +29,2 @@ /*

const DEFAULT_ROUTES_HANDLER = "default";
function findEqualRouteVariant(routeVariants, routeVariantToFind) {

@@ -72,3 +70,3 @@ return routeVariants.find((routeVariant) => {

const collectionRouteVariants = compact(
getCollectionRouteVariantsProperty(collection, alertsCollections).map((variantId) => {
getCollectionRouteVariantsProperty(collection).map((variantId) => {
return findRouteVariantByVariantId(routeVariants, variantId);

@@ -227,3 +225,3 @@ })

function getHandlerId(variant) {
return variant.type || variant.handler || DEFAULT_ROUTES_HANDLER;
return variant.type;
}

@@ -283,4 +281,4 @@

const routeVariantLogger = loggerRoutes.namespace(variantNamespace);
loggerRoutes.debug(`Creating logger namespace for route variant ${variantNamespace}`);
const routeVariantAlerts = alertsRoutes.collection(variantNamespace);
const handlersAlerts = alertsRoutes.collection("handlers");
const routeVariantCoreApi = new CoreApi({

@@ -301,7 +299,6 @@ core,

try {
const variantArgument = getDataFromVariant(variant, Handler, handlersAlerts);
const variantArgument = getDataFromVariant(variant);
routeHandler = new Handler(
{
...variantArgument,
variantId, // LEGACY, remove
url: route.url,

@@ -320,2 +317,3 @@ method: route.method,

routeHandler.method = route.method;
routeHandler.logger = routeVariantLogger;
} catch (error) {

@@ -498,27 +496,2 @@ variantAlerts.set("process", error.message, error);

// LEGACY, to be removed
function plainCollectionsToLegacy(plainCollections) {
return plainCollections.map((collection) => {
return {
id: collection.id,
from: collection.from,
routesVariants: collection.definedRoutes,
appliedRoutesVariants: collection.routes,
};
});
}
// LEGACY, to be removed
function plainRouteVariantsToLegacy(plainRouteVariants) {
return plainRouteVariants.map((routeVariant) => {
return {
id: routeVariant.id,
routeId: routeVariant.route,
handler: routeVariant.type,
response: routeVariant.preview,
delay: routeVariant.delay,
};
});
}
module.exports = {

@@ -537,4 +510,2 @@ getCollectionRouteVariants,

getCollections,
plainCollectionsToLegacy,
plainRouteVariantsToLegacy,
};

@@ -18,3 +18,2 @@ /*

const Routes = require("./Routes");
const { deprecatedMessage } = require("../common/helpers");
const {

@@ -28,32 +27,5 @@ getPlainCollections,

getCollection,
plainCollectionsToLegacy,
plainRouteVariantsToLegacy,
} = require("./helpers");
const { getIds, compileRouteValidator } = require("./validations");
const LEGACY_OPTIONS = [
// LEGACY, to be removed
{
description: "Selected collection. Legacy",
name: "selected",
type: "string",
extraData: {
scaffold: {
omit: true,
},
},
},
{
description: "Global delay to apply to routes. Legacy",
name: "delay",
type: "number",
default: 0,
extraData: {
scaffold: {
omit: true,
},
},
},
];
const SELECTED_COLLECTION_ID = "selected";

@@ -68,16 +40,6 @@ const EMPTY_ALERT_ID = "empty";

static get legacyId() {
return "mocks";
}
constructor({ config, legacyConfig, logger, onChange, alerts }, core) {
constructor({ config, logger, onChange, alerts }, core) {
this._eventEmitter = new EventEmitter();
this._logger = logger;
this._legacyConfig = legacyConfig;
[this._selectedCollectionOptionLegacy, this._currentDelayOptionLegacy] =
this._legacyConfig.addOptions(LEGACY_OPTIONS);
this._selectedCollectionOptionLegacy.onChange(this._setCurrentLegacy.bind(this));
this._currentDelayOptionLegacy.onChange(this._emitChange.bind(this));
this._config = config;

@@ -89,3 +51,2 @@

this._alerts = alerts;
this._alertsDeprecation = alerts.collection("deprecated");

@@ -118,5 +79,7 @@ this._routesConfig = this._config.addNamespace(Routes.id);

onChangeSelected: this._setCurrent.bind(this),
getSelectedCollection: this._getSelectedCollection.bind(this),
getIds: this._getCollectionsIds.bind(this),
getPlainCollections: this._getPlainCollections.bind(this),
getSelected: () => {
return this._selectedId;
},
});

@@ -167,42 +130,9 @@

_getDelay() {
// Temportal workaround to know current delay in this class
// TODO, move to Routes class
if (this._currentDelayOptionLegacy.hasBeenSet) {
this._alertsDeprecation.set(
"mocks.delay",
deprecatedMessage(
"option",
"mocks.delay",
"mock.routes.delay",
"releases/migrating-from-v3#options"
)
);
}
return this._routes._delayOption.hasBeenSet
? this._routes._delayOption.value
: this._currentDelayOptionLegacy.value;
return this._routes.delay;
}
// LEGACY, to be removed
_addCollectionsSelectedOptionAlert() {
this._alertsDeprecation.set(
"mocks.selected",
deprecatedMessage(
"option",
"mocks.selected",
"mock.collections.selected",
"releases/migrating-from-v3#options"
)
);
}
// Temportal workaround to know selected collection in this class while it has a deprecated option setting the same value.
// TODO, move to Collections class
_getCollectionSelected() {
if (this._selectedCollectionOptionLegacy.hasBeenSet) {
this._addCollectionsSelectedOptionAlert();
}
return this._collectionsInstance._selectedOption.hasBeenSet
? this._collectionsInstance._selectedOption.value
: this._selectedCollectionOptionLegacy.value;
return this._collectionsInstance._selectedOption.value;
}

@@ -312,21 +242,2 @@

_setCurrentLegacy(id) {
this._addCollectionsSelectedOptionAlert();
this._setCurrent(id);
}
// Legacy, to be removed
set current(id) {
this._alertsDeprecation.set(
"current",
deprecatedMessage(
"setter",
"mocks.current",
"mock.collections.select()",
"releases/migrating-from-v3#api"
)
);
this._setCurrent(id);
}
_stopUsingVariants() {

@@ -338,2 +249,3 @@ this._customVariants = [];

_createCustomCollection() {
// TODO, set custom collection. Reserve "custom" id in collections for this one
const selectedCollectionId = this._selectedId;

@@ -357,16 +269,2 @@ const alerts = this._alertsLoadCollections.collection("custom");

// Legacy, to be removed
restoreRoutesVariants() {
this._alertsDeprecation.set(
"restorerouteVariants",
deprecatedMessage(
"method",
"mocks.restoreRoutesVariants",
"mock.restoreRouteVariants",
"releases/migrating-from-v3#api"
)
);
this.restoreRouteVariants();
}
restoreRouteVariants() {

@@ -403,34 +301,2 @@ this._stopUsingVariants();

// Legacy, to be removed
get customRoutesVariants() {
this._alertsDeprecation.set(
"customrouteVariants",
deprecatedMessage(
"method",
"mocks.customrouteVariants",
"mock.plainCustomRouteVariants",
"releases/migrating-from-v3#api"
)
);
return this._getPlainCustomRouteVariants();
}
_getSelectedCollection() {
return this._selectedId;
}
// Legacy, to be removed
get current() {
this._alertsDeprecation.set(
"current",
deprecatedMessage(
"getter",
"mocks.current",
"mock.collections.selected",
"releases/migrating-from-v3#api"
)
);
return this._getSelectedCollection();
}
_getCollectionsIds() {

@@ -440,16 +306,2 @@ return [...this._collectionsIds];

// Legacy, to be removed
get ids() {
this._alertsDeprecation.set(
"ids",
deprecatedMessage(
"getter",
"mocks.ids",
"mock.collections.ids",
"releases/migrating-from-v3#api"
)
);
return this._getCollectionsIds();
}
_getPlainCollections() {

@@ -459,16 +311,2 @@ return [...this._plainCollections];

// Legacy, to be removed
get plainMocks() {
this._alertsDeprecation.set(
"plainMocks",
deprecatedMessage(
"getter",
"mocks.plainMocks",
"mock.collections.plain",
"releases/migrating-from-v3#api"
)
);
return plainCollectionsToLegacy(this._getPlainCollections());
}
_getPlainRoutes() {

@@ -482,30 +320,2 @@ return [...this._plainRoutes];

// Legacy, to be removed
get plainRoutes() {
this._alertsDeprecation.set(
"plainRoutes",
deprecatedMessage(
"getter",
"mocks.plainRoutes",
"mock.routes.plain",
"releases/migrating-from-v3#api"
)
);
return this._getPlainRoutes();
}
// Legacy, to be removed
get plainRoutesVariants() {
this._alertsDeprecation.set(
"plainRoutesVariants",
deprecatedMessage(
"getter",
"mocks.plainRoutesVariants",
"mock.routes.plainVariants",
"releases/migrating-from-v3#api"
)
);
return plainRouteVariantsToLegacy(this._getPlainVariants());
}
get routes() {

@@ -512,0 +322,0 @@ return this._routes;

@@ -10,2 +10,4 @@ const OPTIONS = [

// TODO, add to data model
class Routes {

@@ -34,4 +36,8 @@ static get id() {

}
get delay() {
return this._delayOption.value;
}
}
module.exports = Routes;

@@ -15,4 +15,3 @@ /*

const { getDataFromVariant, isVersion4 } = require("../variant-handlers/helpers");
const { deprecatedMessage } = require("../common/helpers");
const { getDataFromVariant } = require("../variant-handlers/helpers");

@@ -50,64 +49,20 @@ const ajv = new Ajv({ allErrors: true });

const collectionsSchema = {
oneOf: [
{
type: "object",
properties: {
id: {
type: "string",
},
from: {
type: ["string", "null"],
},
routesVariants: {
type: "array",
uniqueItems: true,
items: {
type: "string",
},
},
},
required: ["id", "routesVariants"],
additionalProperties: false,
type: "object",
properties: {
id: {
type: "string",
},
{
type: "object",
properties: {
id: {
type: "string",
},
from: {
type: ["string", "null"],
},
routeVariants: {
type: "array",
uniqueItems: true,
items: {
type: "string",
},
},
},
required: ["id", "routeVariants"],
additionalProperties: false,
from: {
type: ["string", "null"],
},
{
type: "object",
properties: {
id: {
type: "string",
},
from: {
type: ["string", "null"],
},
routes: {
type: "array",
uniqueItems: true,
items: {
type: "string",
},
},
routes: {
type: "array",
uniqueItems: true,
items: {
type: "string",
},
required: ["id", "routes"],
additionalProperties: false,
},
],
},
required: ["id", "routes"],
additionalProperties: false,
};

@@ -154,32 +109,48 @@

items: {
type: "object",
properties: {
id: {
type: "string",
oneOf: [
{
type: "object",
properties: {
id: {
type: "string",
},
disabled: {
enum: [false],
},
type: {
type: "string",
enum: [], // this enum is defined when validator is compiled
},
delay: {
oneOf: [
{
type: "null",
},
{
type: "integer",
minimum: 0,
},
],
},
options: {
type: "object",
},
},
required: ["id", "type"],
additionalProperties: false,
},
disabled: {
type: "boolean",
},
handler: {
type: "string",
enum: [], // this enum is defined when validator is compiled
},
type: {
type: "string",
enum: [], // this enum is defined when validator is compiled
},
delay: {
oneOf: [
{
type: "null",
{
type: "object",
properties: {
id: {
type: "string",
},
{
type: "integer",
minimum: 0,
disabled: {
enum: [true],
},
],
},
required: ["id"],
additionalProperties: false,
},
},
// TODO, require "options" in all variants to be an object, do not allow additionalProperties. Deprecate "response"
required: ["id"],
],
},

@@ -217,5 +188,3 @@ },

const schema = { ...routesSchema };
// LEGACY, handler property
schema.properties.variants.items.properties.handler.enum = supportedRouteHandlersIds;
schema.properties.variants.items.properties.type.enum = supportedRouteHandlersIds;
schema.properties.variants.items.oneOf[0].properties.type.enum = supportedRouteHandlersIds;
routeSchema = { ...schema };

@@ -306,16 +275,4 @@ routeValidator = ajv.compile(schema);

function getCollectionRouteVariantsProperty(collection, alertsCollections) {
if (alertsCollections && collection && collection.routesVariants) {
alertsCollections.set(
"routesVariants",
deprecatedMessage(
"property",
"collection.routesVariants",
"collection.routes",
"releases/migrating-from-v3#main-concepts"
)
);
}
// LEGACY, remove routesVariants support
return collection.routes || collection.routeVariants || collection.routesVariants;
function getCollectionRouteVariantsProperty(collection) {
return collection.routes || collection.routeVariants;
}

@@ -403,4 +360,4 @@

const variantValidator = ajv.compile(Handler.validationSchema);
const dataToCheck = getDataFromVariant(variant, Handler);
const dataMessage = isVersion4(Handler) ? "Invalid 'options' property:" : "";
const dataToCheck = getDataFromVariant(variant);
const dataMessage = "Invalid 'options' property:";
const isValid = variantValidator(dataToCheck);

@@ -407,0 +364,0 @@ if (!isValid) {

@@ -12,7 +12,5 @@ /*

const isPromise = require("is-promise");
const { isObject, isFunction } = require("lodash");
const { isFunction } = require("lodash");
const { scopedAlertsMethods } = require("../alerts/legacyHelpers");
const CoreApi = require("../common/CoreApi");
const { docsUrl } = require("../common/helpers");

@@ -33,8 +31,2 @@ const OPTIONS = [

function formatDeprecatedMessage(format) {
return `Defining Plugins as ${format} is deprecated and it won't be supported in next major version. Consider migrating it to a Class Plugin: ${docsUrl(
"plugins/development"
)}`;
}
class Plugins {

@@ -45,15 +37,3 @@ static get id() {

constructor(
{
config,
alerts,
logger,
addAlert,
removeAlerts,
renameAlerts,
createCollectionsLoader,
createRoutesLoader,
},
core
) {
constructor({ config, alerts, logger }, core) {
this._config = config;

@@ -72,10 +52,4 @@ this._logger = logger;

this._addAlert = addAlert;
this._removeAlerts = removeAlerts;
this._renameAlerts = renameAlerts;
this._createCollectionsLoader = createCollectionsLoader;
this._createRoutesLoader = createRoutesLoader;
this._core = core;
this._pluginsInstances = [];
this._pluginsMethods = [];
this._pluginsOptions = [];

@@ -138,51 +112,30 @@ this._pluginsRegistered = 0;

_registerPlugin(Plugin, pluginMethods, pluginIndex) {
let pluginInstance,
formatIsObject,
formatIsFunction,
pluginConfig,
pluginAlerts,
pluginLogger,
optionsAdded = false,
coreApi;
const pluginOptions = { core: this._core, ...pluginMethods };
if (isObject(Plugin) && !isFunction(Plugin)) {
pluginInstance = Plugin;
_registerPlugin(Plugin, pluginIndex) {
let pluginInstance, pluginConfig, pluginAlerts, pluginLogger, coreApi;
const pluginCoreOptions = { core: this._core };
try {
// TODO, throw an error if plugin has no id. legacy
if (Plugin.id) {
pluginConfig = this._config.addNamespace(Plugin.id);
pluginAlerts = this._alerts.collection(Plugin.id);
pluginLogger = this._logger.namespace(Plugin.id);
} else {
this._alertsFormat.set(
this._pluginId(pluginIndex),
"Plugins must have a static id property"
);
}
const pluginCoreFinalOptions = {
...pluginCoreOptions,
config: pluginConfig,
alerts: pluginAlerts,
logger: pluginLogger,
};
coreApi = new CoreApi(pluginCoreFinalOptions);
pluginInstance = new Plugin(coreApi);
this._pluginsOptions.push(coreApi);
this._pluginsInstances.push(pluginInstance);
this._pluginsRegistered++;
formatIsObject = true;
} else {
try {
if (Plugin.id) {
pluginConfig = this._config.addNamespace(Plugin.id);
pluginAlerts = this._alerts.collection(Plugin.id);
pluginLogger = this._logger.namespace(Plugin.id);
}
const pluginFinalOptions = {
...pluginOptions,
config: pluginConfig,
alerts: pluginAlerts,
logger: pluginLogger,
};
coreApi = new CoreApi(pluginFinalOptions);
pluginInstance = new Plugin(coreApi);
this._pluginsOptions.push(coreApi);
optionsAdded = true;
this._pluginsInstances.push(pluginInstance);
this._pluginsRegistered++;
} catch (error) {
if (error.message.includes("is not a constructor")) {
try {
const pluginFunc = Plugin;
pluginInstance = pluginFunc(new CoreApi(pluginOptions)) || {};
this._pluginsInstances.push(pluginInstance);
this._pluginsRegistered++;
formatIsFunction = true;
} catch (err) {
return this._catchRegisterError(err, pluginIndex);
}
} else {
return this._catchRegisterError(error, pluginIndex);
}
}
} catch (error) {
return this._catchRegisterError(error, pluginIndex);
}

@@ -195,4 +148,4 @@ if (

) {
let pluginFinalOptions = {
...pluginOptions,
let pluginCoreFinalOptions = {
...pluginCoreOptions,
config: pluginConfig,

@@ -202,2 +155,4 @@ alerts: pluginAlerts,

};
// 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) {

@@ -207,4 +162,4 @@ pluginConfig = this._config.addNamespace(pluginInstance.id);

pluginLogger = this._logger.namespace(pluginInstance.id);
pluginFinalOptions = {
...pluginOptions,
pluginCoreFinalOptions = {
...pluginCoreOptions,
config: pluginConfig,

@@ -214,13 +169,9 @@ alerts: pluginAlerts,

};
coreApi = new CoreApi(pluginFinalOptions);
if (optionsAdded) {
this._pluginsOptions.pop();
}
coreApi = new CoreApi(pluginCoreFinalOptions);
this._pluginsOptions.pop();
this._pluginsOptions.push(coreApi);
} else {
if (!coreApi) {
coreApi = new CoreApi(pluginFinalOptions);
}
this._pluginsOptions.push(coreApi);
}
// TODO, deprecate register method. It is duplicated with the constructor. Legacy
if (isFunction(pluginInstance.register)) {

@@ -230,13 +181,7 @@ try {

} catch (error) {
this._catchRegisterError(error, pluginIndex);
this._pluginsRegistered = this._pluginsRegistered - 1;
return this._catchRegisterError(error, pluginIndex);
}
}
}
if (formatIsObject) {
this._alertsFormat.set(this._pluginId(pluginIndex), formatDeprecatedMessage("objects"));
}
if (formatIsFunction) {
this._alertsFormat.set(this._pluginId(pluginIndex), formatDeprecatedMessage("functions"));
}
return pluginInstance;

@@ -249,18 +194,3 @@ }

}
const loadMocks = this._createCollectionsLoader();
const loadRoutes = this._createRoutesLoader();
const pluginMethods = {
loadMocks,
loadRoutes,
...scopedAlertsMethods(
() => {
return this._pluginId(pluginIndex);
},
this._addAlert,
this._removeAlerts,
this._renameAlerts
),
};
this._pluginsMethods.push(pluginMethods);
this._registerPlugin(this._plugins[pluginIndex], pluginMethods, pluginIndex);
this._registerPlugin(this._plugins[pluginIndex], pluginIndex);
return this._registerPlugins(pluginIndex + 1);

@@ -267,0 +197,0 @@ }

@@ -13,3 +13,3 @@ // Use this file only as a guide for first steps using middleware variants. You can delete it when you have understood the concepts.

id: "enabled", // variant id
handler: "middleware", // variant handler id
type: "middleware", // variant handler id
options: {

@@ -16,0 +16,0 @@ // Express middleware to execute

@@ -153,4 +153,5 @@ /*

this._alerts.set("config", "Configuration file was not found. A scaffold was created");
// LEGACY, Set base collection, which is the one created in the scaffold, when selected collection is not defined in the option. (when legacy option is removed)
// If the collection selected option value is not set, it should be set as "base"
if (!this._collectionSelectedOption.hasBeenSet) {
this._collectionSelectedOption.value = "base";
}
return this._createConfig();

@@ -157,0 +158,0 @@ }

@@ -34,3 +34,3 @@ /*

(req, _res, next) => {
logger.debug(`Sending Not found response | ${req.id}`);
logger.debug(`Sending Not found response | ${req.method} => ${req.url} | ${req.id}`);
next(Boom.notFound());

@@ -37,0 +37,0 @@ };

@@ -172,3 +172,2 @@ /*

this._customRouters = [];
this._error = null;
this._alerts = alerts;

@@ -227,3 +226,2 @@

this._alerts.set(SERVER_ALERT_ID, "Server error", error);
this._error = error;
throw error;

@@ -295,7 +293,5 @@ });

this._alerts.set(START_ALERT_ID, START_ERROR_MESSAGE, error);
this._error = error;
reject(error);
} else {
this._logger.info(`Server started and listening at ${this.url}`);
this._error = null;
this._serverStarting = false;

@@ -394,9 +390,4 @@ this._serverStarted = true;

}
// LEGACY, to be removed
get error() {
return this._error;
}
}
module.exports = Server;

@@ -24,6 +24,2 @@ /*

static get version() {
return "4";
}
static get validationSchema() {

@@ -30,0 +26,0 @@ return {

@@ -18,6 +18,2 @@ /*

static get version() {
return "4";
}
static get validationSchema() {

@@ -24,0 +20,0 @@ return {

@@ -13,3 +13,3 @@ /*

class Json {
class Middleware {
static get id() {

@@ -19,6 +19,2 @@ return "middleware";

static get version() {
return "4";
}
static get validationSchema() {

@@ -53,2 +49,2 @@ return {

module.exports = Json;
module.exports = Middleware;

@@ -20,6 +20,2 @@ /*

static get version() {
return "4";
}
static get validationSchema() {

@@ -26,0 +22,0 @@ return {

@@ -18,6 +18,2 @@ /*

static get version() {
return "4";
}
get defaultHeaders() {

@@ -24,0 +20,0 @@ return {

@@ -1,44 +0,12 @@

const { docsUrl } = require("../common/helpers");
function isVersion4(Handler) {
return Handler.version === "4";
function getDataFromVariant(variant) {
return variant.options;
}
function getDataFromVariant(variant, Handler, alerts) {
if (alerts && Handler.deprecated) {
alerts.set(
Handler.id,
`Handler '${
Handler.id
}' is deprecated and will be removed in next major version. Consider using another handler. ${docsUrl(
"releases/migrating-from-v3#route-variants-handlers"
)}`
);
}
if (isVersion4(Handler)) {
if (alerts && variant.response) {
alerts.set(
"response",
`'response' property in variants is deprecated and will be removed in next major version. Use 'options' instead.`
);
}
// LEGACY, deprecate "response"
return variant.options || variant.response;
}
return variant;
}
function getPreview(variantInstance) {
if (isVersion4(variantInstance.constructor)) {
return variantInstance.preview;
}
return variantInstance.plainResponsePreview;
return variantInstance.preview;
}
module.exports = {
isVersion4,
getDataFromVariant,
getPreview,
};

@@ -11,3 +11,2 @@ /*

const DefaultVariantHandler = require("./handlers/Default");
const Json = require("./handlers/Json");

@@ -37,11 +36,3 @@ const Text = require("./handlers/Text");

this._registeredVariantHandlers = [];
this._coreVariantHandlers = [
DefaultVariantHandler,
Json,
Text,
Status,
Middleware,
Static,
File,
];
this._coreVariantHandlers = [Json, Text, Status, Middleware, Static, File];
this._config = config;

@@ -64,7 +55,5 @@

// LEGACY, remove parameter
registerConfig(variantHandlersFromLegacyConfig) {
registerConfig() {
const variantHandlersToRegister = [
...this._coreVariantHandlers,
...variantHandlersFromLegacyConfig,
...this._registerOption.value,

@@ -71,0 +60,0 @@ ];

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