Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@spinajs/configuration

Package Overview
Dependencies
Maintainers
1
Versions
281
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@spinajs/configuration - npm Package Compare versions

Comparing version 1.1.9 to 1.2.7

lib/exception.d.ts

6

lib/config/configuration.js

@@ -5,7 +5,7 @@ "use strict";

configuration: {
isDevelopment: process.env.NODE_ENV === "development",
isProduction: process.env.NODE_ENV === "production",
}
isDevelopment: process.env.NODE_ENV === 'development',
isProduction: process.env.NODE_ENV === 'production',
},
};
exports.default = config;
//# sourceMappingURL=configuration.js.map

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

import { IContainer } from '@spinajs/di';
import { Container } from '@spinajs/di';
import { ConfigurationSource } from './sources';

@@ -16,10 +16,11 @@ import { Configuration, ConfigurationOptions } from './types';

*/
protected Config: any;
protected Config: Record<string, unknown>;
protected CustomConfigPaths: string[];
protected Sources: ConfigurationSource[];
protected Container: Container;
/**
*
* @param app application name, pass it when you run in application mode
* @param baseDir configuration base dir, where to look for application configs
* @param cfgCustomPaths custom cfg paths eg. to load config from non standard folders ( usefull in tests )
* @param app - application name, pass it when you run in application mode
* @param baseDir - configuration base dir, where to look for application configs
* @param cfgCustomPaths - custom cfg paths eg. to load config from non standard folders ( usefull in tests )
*/

@@ -32,3 +33,2 @@ constructor(options?: ConfigurationOptions);

* @param defaultValue - optional, if value at specified path not exists returns default value
* @returns { T | undefined }
*/

@@ -40,7 +40,7 @@ get<T>(path: string[] | string, defaultValue?: T): T;

*
* @param path config path
* @param value value to set
* @param path - config path
* @param value - value to set
*/
set(path: string[] | string, value: any): void;
resolveAsync(container: IContainer): Promise<void>;
set(path: string[] | string, value: unknown): void;
resolveAsync(): Promise<void>;
protected dir(toJoin: string): string;

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

protected applyAppDirs(): void;
protected validateConfig(): void;
/**

@@ -53,0 +54,0 @@ * runs configuration func on files

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

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrameworkConfiguration = void 0;
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-unsafe-call */
const di_1 = require("@spinajs/di");

@@ -40,8 +45,11 @@ const exceptions_1 = require("@spinajs/exceptions");

const _ = __importStar(require("lodash"));
const ajv_1 = __importDefault(require("ajv"));
const exception_1 = require("./exception");
const internal_logger_1 = require("@spinajs/internal-logger");
let FrameworkConfiguration = class FrameworkConfiguration extends types_1.Configuration {
/**
*
* @param app application name, pass it when you run in application mode
* @param baseDir configuration base dir, where to look for application configs
* @param cfgCustomPaths custom cfg paths eg. to load config from non standard folders ( usefull in tests )
* @param app - application name, pass it when you run in application mode
* @param baseDir - configuration base dir, where to look for application configs
* @param cfgCustomPaths - custom cfg paths eg. to load config from non standard folders ( usefull in tests )
*/

@@ -58,3 +66,3 @@ constructor(options) {

*/
this.RunApp = "";
this.RunApp = '';
/**

@@ -73,3 +81,2 @@ * Loaded & merged configuration

* @param defaultValue - optional, if value at specified path not exists returns default value
* @returns { T | undefined }
*/

@@ -83,4 +90,4 @@ get(path, defaultValue) {

*
* @param path config path
* @param value value to set
* @param path - config path
* @param value - value to set
*/

@@ -90,13 +97,19 @@ set(path, value) {

}
async resolveAsync(container) {
if (!container.hasRegistered(sources_1.ConfigurationSource)) {
throw new exceptions_1.InvalidOperation("No configuration sources configured. Please ensure that config module have any source to read from !");
async resolveAsync() {
if (!this.Container.hasRegistered(sources_1.ConfigurationSource)) {
throw new exceptions_1.InvalidOperation('No configuration sources configured. Please ensure that config module have any source to read from !');
}
this.Sources = await container.resolve(Array.ofType(sources_1.ConfigurationSource), [this.RunApp, this.CustomConfigPaths, this.AppBaseDir]);
await Promise.all(this.Sources.map(s => s.Load())).then(result => {
result.map(c => _.merge(this.Config, c));
this.Sources = this.Container.resolve(Array.ofType(sources_1.ConfigurationSource), [
this.RunApp,
this.CustomConfigPaths,
this.AppBaseDir,
]);
await Promise.all(this.Sources.map((s) => s.Load())).then((result) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
result.map((c) => _.merge(this.Config, c));
return;
});
this.validateConfig();
this.applyAppDirs();
this.configure();
await super.resolveAsync(container);
}

@@ -117,2 +130,42 @@ dir(toJoin) {

}
validateConfig() {
const validator = new ajv_1.default({
logger: {
log: (msg) => internal_logger_1.InternalLogger.info(msg, 'Configuration'),
warn: (msg) => internal_logger_1.InternalLogger.warn(msg, 'Configuration'),
error: (msg) => internal_logger_1.InternalLogger.error(msg, 'Configuration'),
},
// enable all errors on validation, not only first one that occurred
allErrors: true,
// remove properties that are not defined in schema
removeAdditional: true,
// set default values if possible
useDefaults: true,
// The option coerceTypes allows you to have your data types coerced to the types specified in your schema type keywords
coerceTypes: true,
});
// add $merge & $patch for json schema
require('ajv-merge-patch')(validator);
// add common formats validation eg: date time
require('ajv-formats')(validator);
// add keywords
require('ajv-keywords')(validator);
// in strict mode ajv will throw when
// unknown keyword in schema is met
// we use $configurationModule keyword to identify
// to match config module with config schema
validator.addKeyword('$configurationModule');
const schemas = this.Container.get('__configurationSchema__', true);
if (schemas) {
Object.keys(this.Config).forEach((k) => {
const schema = schemas.find((x) => x.$configurationModule === k);
if (schema) {
const result = validator.validate(schema, this.Config[`${k}`]);
if (!result) {
throw new exception_1.InvalidConfiguration('invalid configuration ! Check config files and restart app.', validator.errors);
}
}
});
}
}
/**

@@ -124,4 +177,4 @@ * runs configuration func on files

for (const prop of Object.keys(this.Config)) {
const subconfig = this.Config[prop];
if (_.isFunction(subconfig.configure)) {
const subconfig = this.Config[`${prop}`];
if (subconfig.configure && typeof subconfig.configure === 'function') {
subconfig.configure.apply(this);

@@ -132,2 +185,6 @@ }

};
__decorate([
(0, di_1.Autoinject)(),
__metadata("design:type", di_1.Container)
], FrameworkConfiguration.prototype, "Container", void 0);
FrameworkConfiguration = __decorate([

@@ -134,0 +191,0 @@ (0, di_1.Injectable)(types_1.Configuration),

/**
* Injects configuration value to given class property
*
* @param path path to configuration value eg. "app.dirs.stats"
* @param dafaultValue default value if path not exists
* @param path - path to configuration value eg. "app.dirs.stats"
* @param dafaultValue - default value if path not exists
* @returns
*/
export declare function Config(path: string, dafaultValue?: any): (target?: any, key?: string) => any;
export declare function Config(path: string, dafaultValue?: unknown): (target?: any, key?: string) => any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = void 0;
/* eslint-disable @typescript-eslint/no-explicit-any */
const di_1 = require("@spinajs/di");

@@ -9,4 +10,4 @@ const types_1 = require("./types");

*
* @param path path to configuration value eg. "app.dirs.stats"
* @param dafaultValue default value if path not exists
* @param path - path to configuration value eg. "app.dirs.stats"
* @param dafaultValue - default value if path not exists
* @returns

@@ -26,3 +27,3 @@ */

enumerable: false,
configurable: false
configurable: false,
});

@@ -29,0 +30,0 @@ };

@@ -9,6 +9,6 @@ /**

*/
export * from "./config/configuration";
export * from "./types";
export * from "./sources";
export * from "./decorators";
export * from "./configuration";
export * as configuration from './config/configuration';
export * from './types';
export * from './sources';
export * from './decorators';
export * from './configuration';

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

}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {

@@ -14,2 +26,3 @@ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);

Object.defineProperty(exports, "__esModule", { value: true });
exports.configuration = void 0;
/**

@@ -23,3 +36,3 @@ * We export default configuration for webpack modules

*/
__exportStar(require("./config/configuration"), exports);
exports.configuration = __importStar(require("./config/configuration"));
__exportStar(require("./types"), exports);

@@ -26,0 +39,0 @@ __exportStar(require("./sources"), exports);

export declare abstract class ConfigurationSource {
abstract Load(): Promise<any>;
abstract Load(): Promise<unknown>;
}

@@ -4,0 +4,0 @@ export declare abstract class BaseFileSource extends ConfigurationSource {

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

exports.JsonFileSource = exports.JsFileSource = exports.BaseFileSource = exports.ConfigurationSource = void 0;
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-explicit-any */
const di_1 = require("@spinajs/di");
const glob_1 = require("glob");
const _ = require("lodash");
const _ = __importStar(require("lodash"));
const path_1 = require("path");

@@ -37,3 +43,3 @@ const util_1 = require("./util");

const path = __importStar(require("path"));
const log_1 = require("@spinajs/log/lib/log");
const internal_logger_1 = require("@spinajs/internal-logger");
function mergeArrays(target, source) {

@@ -70,3 +76,3 @@ if (_.isArray(target)) {

];
this.BasePath = "";
this.BasePath = '';
this.BasePath = (0, util_1.findBasePath)(process.cwd());

@@ -82,5 +88,5 @@ }

}
this.CommonDirs.map(f => path.isAbsolute(f) ? f : (0, path_1.join)(this.BasePath, f))
this.CommonDirs.map((f) => (path.isAbsolute(f) ? f : (0, path_1.join)(this.BasePath, f)))
// get all config files
.map(d => glob_1.glob.sync(path.join(d, `/**/${extension}`)))
.map((d) => glob_1.glob.sync(path.join(d, `/**/${extension}`)))
// flatten files

@@ -104,7 +110,7 @@ .reduce((prev, current) => {

if (process.env.NODE_ENV) {
if (process.env.NODE_ENV === "development") {
return _.mergeWith(common, this.load("*.dev.js", _load), mergeArrays);
if (process.env.NODE_ENV === 'development') {
return _.mergeWith(common, this.load('*.dev.js', _load), mergeArrays);
}
else if (process.env.NODE_ENV === "production") {
return _.mergeWith(common, this.load("*.prod.js", _load), mergeArrays);
else if (process.env.NODE_ENV === 'production') {
return _.mergeWith(common, this.load('*.prod.js', _load), mergeArrays);
}

@@ -114,4 +120,6 @@ }

function _load(file) {
log_1.Log.trace(`Trying to load file ${file}`, "Configuration");
//Log.trace(`Trying to load file ${file}`, 'Configuration');
(0, util_1.uncache)(file);
internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
// eslint-disable-next-line security/detect-non-literal-require
return require(file);

@@ -129,7 +137,7 @@ }

if (process.env.NODE_ENV) {
if (process.env.NODE_ENV === "development") {
return _.mergeWith(common, this.load("*.dev.json", _load), mergeArrays);
if (process.env.NODE_ENV === 'development') {
return _.mergeWith(common, this.load('*.dev.json', _load), mergeArrays);
}
else if (process.env.NODE_ENV === "production") {
return _.mergeWith(common, this.load("*.prod.json", _load), mergeArrays);
else if (process.env.NODE_ENV === 'production') {
return _.mergeWith(common, this.load('*.prod.json', _load), mergeArrays);
}

@@ -140,4 +148,4 @@ }

try {
log_1.Log.trace(`Trying to load file ${file}`, "Configuration");
return JSON.parse(fs.readFileSync(file, "utf-8"));
internal_logger_1.InternalLogger.trace(`Trying to load file ${file}`, 'Configuration');
return JSON.parse(fs.readFileSync(file, 'utf-8'));
}

@@ -144,0 +152,0 @@ catch (err) {

@@ -9,2 +9,8 @@ import { AsyncModule } from '@spinajs/di';

}
export interface IConfigurationSchema {
$configurationModule: string;
}
export interface IConfigurable {
configure(this: Configuration): void;
}
export interface ConfigurationOptions {

@@ -47,6 +53,6 @@ /**

*
* @param path config path
* @param value value to set
* @param path - config path
* @param value - value to set
*/
abstract set(path: string[] | string, value: any): void;
abstract set(path: string[] | string, value: unknown): void;
}
export declare function parseArgv(param: string): string;
export declare function findBasePath(path: string): string;
export declare function merge(to: any, from: any): void;
export declare function merge(to: unknown, from: unknown): unknown;
export declare function uncache(file: string): string;
export declare function filterDirs(dir: string): boolean;

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

exports.filterDirs = exports.uncache = exports.merge = exports.findBasePath = exports.parseArgv = void 0;
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/unbound-method */
const fs = __importStar(require("fs"));

@@ -58,3 +60,3 @@ const _ = require("lodash");

function uncache(file) {
delete require.cache[file];
delete require.cache[`${file}`];
return file;

@@ -61,0 +63,0 @@ }

{
"name": "@spinajs/configuration",
"version": "1.1.9",
"version": "1.2.7",
"description": "framework configuration module",

@@ -14,4 +14,4 @@ "main": "lib/index.js",

"prepare": "npm run build",
"format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
"lint": "tslint -p tsconfig.json",
"format": "prettier --write \"src/**/*.ts\"",
"lint": "eslint -c .eslintrc.js --ext .ts src",
"prepublishOnly": "npm test && npm run lint",

@@ -43,32 +43,13 @@ "preversion": "npm run lint",

"dependencies": {
"@spinajs/di": "^1.1.7",
"@spinajs/exceptions": "^1.0.5",
"@spinajs/log": "^1.1.9",
"@spinajs/di": "^1.2.7",
"@spinajs/exceptions": "^1.2.7",
"@spinajs/internal-logger": "^1.2.7",
"ajv": "^8.8.2",
"ajv-formats": "^2.1.1",
"ajv-keywords": "^5.1.0",
"ajv-merge-patch": "^5.0.1",
"glob": "^7.1.4",
"lodash": "^4.17.14"
},
"devDependencies": {
"@types/bunyan": "^1.8.6",
"@types/chai": "^4.1.7",
"@types/chai-as-promised": "^7.1.0",
"@types/glob": "^7.2.0",
"@types/lodash": "^4.14.136",
"@types/mocha": "^9.1.0",
"@types/sinon": "^10.0.8",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"mocha": "^9.2.0",
"nyc": "^15.1.0",
"prettier": "^2.5.1",
"sinon": "^12.0.1",
"ts-mocha": "^9.0.2",
"ts-node": "^10.4.0",
"tslint": "^6.1.3",
"tslint-circular-dependencies": "^0.1.0",
"tslint-config-prettier": "^1.18.0",
"tslint-config-standard": "^9.0.0",
"tslint-no-unused-expression-chai": "^0.1.4",
"typedoc": "^0.22.11",
"typescript": "^4.2.3"
}
"gitHead": "389cf142b4ca63b7850b93fc858184ddcbb43ce1"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc