Compare commits

..

17 Commits

Author SHA1 Message Date
Karl-Philipp Wulfert
22b1b86b40 0.2.1 2019-05-27 16:29:30 +02:00
Karl-Philipp Wulfert
39a1f9ae8f ci: fix automatic publish 2019-05-27 16:29:10 +02:00
Karl-Philipp Wulfert
d5f33d45e2 docs: update changelog 2019-05-27 13:23:33 +02:00
Karl-Philipp Wulfert
305c158a76 0.2.0 2019-05-27 13:23:29 +02:00
Karl-Philipp Wulfert
d9c4ce48dc feat: add automatic publishing
Fixes #6
2019-05-23 13:53:10 +02:00
Karl-Philipp Wulfert
fb9791767d docs: update changelog 2019-05-07 10:37:51 +02:00
Karl-Philipp Wulfert
5b5080dcc7 0.1.0 2019-05-07 10:37:47 +02:00
Karl-Philipp Wulfert
3ba2b0bf3c build: update dependencies and adjust configuration 2019-04-30 14:40:51 +02:00
Karl-Philipp Wulfert
766205049b test: adjust tests
Fixes #1
2019-04-30 14:40:46 +02:00
Karl-Philipp Wulfert
1ae3beb347 refactor: rebuild logger to be static
Fixes #4
2019-04-30 14:40:38 +02:00
Karl-Philipp Wulfert
7ef29ef56d build: adjust scripts 2019-04-30 14:40:38 +02:00
Karl-Philipp Wulfert
f8f94dc026 ci: add audit stage 2019-04-30 14:40:38 +02:00
Karl-Philipp Wulfert
370658fa67 ci: use correct image for ci 2019-04-30 14:40:38 +02:00
Karl-Philipp Wulfert
f63be608b8 build: update dependencies
Fixes #5
2019-04-30 14:40:32 +02:00
Karl-Philipp Wulfert
2b54af6c7e build: replace circular-json with flatted
Fixes #2
2019-02-14 13:20:36 +01:00
Anselm Stordeur
f26153d970 build: add prepublishOnly script 2019-01-16 19:40:00 +01:00
Anselm Stordeur
42713f061a docs: update changelog 2019-01-16 19:28:34 +01:00
15 changed files with 2322 additions and 1906 deletions

View File

@@ -1,4 +1,3 @@
# EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs
# editorconfig.org # editorconfig.org
root = true root = true
@@ -7,7 +6,6 @@ root = true
indent_style = space indent_style = space
indent_size = 2 indent_size = 2
# We recommend you to keep these unchanged
end_of_line = lf end_of_line = lf
charset = utf-8 charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true

29
.gitignore vendored
View File

@@ -20,7 +20,7 @@ coverage
# nyc test coverage # nyc test coverage
.nyc_output .nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt .grunt
# Bower dependency directory (https://bower.io/) # Bower dependency directory (https://bower.io/)
@@ -29,14 +29,14 @@ bower_components
# node-waf configuration # node-waf configuration
.lock-wscript .lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html) # Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release build/Release
# Dependency directories # Dependency directories
node_modules/ node_modules/
jspm_packages/ jspm_packages/
# Typescript v1 declaration files # TypeScript v1 declaration files
typings/ typings/
# Optional npm cache directory # Optional npm cache directory
@@ -57,6 +57,29 @@ typings/
# dotenv environment variables file # dotenv environment variables file
.env .env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
#DynamoDB Local files
.dynamodb/
########## end of https://github.com/github/gitignore/blob/master/Node.gitignore
# ignore ide files # ignore ide files
.idea .idea
.vscode .vscode

View File

@@ -1,9 +1,8 @@
image: node:lts-alpine image: registry.gitlab.com/openstapps/projectmanagement/node
cache: cache:
key: ${CI_COMMIT_REF_SLUG} key: ${CI_COMMIT_REF_SLUG}
paths: paths:
- lib
- node_modules - node_modules
before_script: before_script:
@@ -18,6 +17,9 @@ build:
stage: build stage: build
script: script:
- npm run build - npm run build
artifacts:
paths:
- lib
test: test:
stage: test stage: test
@@ -27,6 +29,36 @@ test:
paths: paths:
- coverage - coverage
audit:
stage: test
script:
- npm audit
except:
- schedules
allow_failure: true
scheduled-audit:
stage: test
script:
- npm audit
only:
- schedules
package:
dependencies:
- build
tags:
- secrecy
stage: deploy
script:
- echo "//registry.npmjs.org/:_authToken=$NPM_AUTH_TOKEN" > ~/.npmrc
- npm publish
only:
- /^v[0-9]+.[0-9]+.[0-9]+$/
artifacts:
paths:
- lib
pages: pages:
stage: deploy stage: deploy
script: script:
@@ -36,4 +68,4 @@ pages:
- /^v[0-9]+\.[0-9]+\.[0-9]+$/ - /^v[0-9]+\.[0-9]+\.[0-9]+$/
artifacts: artifacts:
paths: paths:
- public - public

View File

@@ -1,10 +1,9 @@
# Ignore all files/folders by default # Ignore all files/folders by default
# See https://stackoverflow.com/a/29932318 # See https://stackoverflow.com/a/29932318
/* /*
# Except these files/folders
# Execept this files/folders
!docs
!lib !lib
lib/tsconfig.tsbuildinfo
!LICENSE !LICENSE
!package.json !package.json
!package-lock.json !package-lock.json

View File

@@ -1,3 +1,25 @@
# [0.2.0](https://gitlab.com/openstapps/logger/compare/v0.1.0...v0.2.0) (2019-05-27)
### Features
* add automatic publishing ([d9c4ce4](https://gitlab.com/openstapps/logger/commit/d9c4ce4)), closes [#6](https://gitlab.com/openstapps/logger/issues/6)
# [0.1.0](https://gitlab.com/openstapps/logger/compare/v0.0.5...v0.1.0) (2019-05-07)
## [0.0.5](https://gitlab.com/openstapps/logger/compare/v0.0.4...v0.0.5) (2019-01-16)
### Features
* allow env variables to overwrite smtp config ([3d82c94](https://gitlab.com/openstapps/logger/commit/3d82c94)), closes [#3](https://gitlab.com/openstapps/logger/issues/3)
## [0.0.4](https://gitlab.com/openstapps/logger/compare/v0.0.3...v0.0.4) (2018-11-28) ## [0.0.4](https://gitlab.com/openstapps/logger/compare/v0.0.3...v0.0.4) (2018-11-28)

3119
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@openstapps/logger", "name": "@openstapps/logger",
"version": "0.0.5", "version": "0.2.1",
"description": "A cli logger with colors, loglevels and the possibility to use a transport system for errors", "description": "A cli logger with colors, loglevels and the possibility to use a transport system for errors",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -8,11 +8,12 @@
}, },
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"scripts": { "scripts": {
"build": "npm run tslint && npm run compile && npm run documentation", "build": "npm run tslint && npm run compile",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md && git commit -m 'docs: update changelog'",
"compile": "tsc", "check-configuration": "openstapps-configuration",
"documentation": "typedoc --includeDeclarations --excludeExternals --mode modules --out docs src", "compile": "rimraf lib && tsc && prepend lib/cli.js '#!/usr/bin/env node\n'",
"prepareOnly": "npm run build", "documentation": "typedoc --includeDeclarations --mode modules --out docs --readme README.md --listInvalidSymbolLinks src",
"prepublishOnly": "npm ci && npm run build",
"test": "nyc mocha --require ts-node/register --ui mocha-typescript 'test/*.ts'", "test": "nyc mocha --require ts-node/register --ui mocha-typescript 'test/*.ts'",
"tslint": "tslint 'src/**/*.ts'" "tslint": "tslint 'src/**/*.ts'"
}, },
@@ -24,45 +25,53 @@
"typings": "./lib/Logger.d.ts", "typings": "./lib/Logger.d.ts",
"main": "./lib/Logger.js", "main": "./lib/Logger.js",
"nyc": { "nyc": {
"all": true,
"branches": 95,
"check-coverage": true, "check-coverage": true,
"per-file": true, "exclude": [
"lines": 0, "src/SMTP.ts",
"statements": 0, "src/cli.ts"
"functions": 0,
"branches": 0,
"include": [
"src"
], ],
"extension": [ "extension": [
".ts" ".ts"
], ],
"functions": 95,
"include": [
"src"
],
"lines": 95,
"per-file": true,
"reporter": [ "reporter": [
"html", "html",
"text-summary" "text-summary"
], ],
"all": true "statements": 95
}, },
"devDependencies": { "devDependencies": {
"@openstapps/configuration": "0.5.0", "@openstapps/configuration": "0.16.1",
"@types/chai": "4.1.7", "@types/chai": "4.1.7",
"@types/mocha": "5.2.5", "@types/chai-as-promised": "7.1.0",
"@types/sinon": "7.0.3", "@types/mocha": "5.2.6",
"@types/sinon": "7.0.11",
"chai": "4.2.0", "chai": "4.2.0",
"conventional-changelog-cli": "2.0.11", "chai-as-promised": "7.1.1",
"mocha": "5.2.0", "conventional-changelog-cli": "2.0.17",
"mocha": "6.1.4",
"mocha-typescript": "1.1.17", "mocha-typescript": "1.1.17",
"nyc": "13.1.0", "nyc": "14.1.1",
"sinon": "7.2.2", "prepend-file-cli": "1.0.6",
"ts-node": "7.0.1", "rimraf": "2.6.3",
"tslint": "5.12.0", "sinon": "7.3.2",
"typedoc": "0.14.0", "ts-node": "8.1.0",
"typescript": "3.2.2" "tslint": "5.16.0",
"typedoc": "0.14.2",
"typescript": "3.4.5"
}, },
"dependencies": { "dependencies": {
"@types/circular-json": "0.4.0", "@types/node": "10.14.7",
"@types/node": "10.12.18", "@types/nodemailer": "6.1.0",
"@types/nodemailer": "4.6.5", "chalk": "2.4.2",
"circular-json": "0.5.9", "flatted": "2.0.0",
"nodemailer": "5.1.1" "nodemailer": "6.1.1"
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 StApps * Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -12,8 +12,10 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {stringify} from 'circular-json'; import chalk from 'chalk';
import {Transport, TransportWithVerification} from './Transport'; import {stringify} from 'flatted';
import {isNodeEnvironment, isProductiveNodeEnvironment} from './common';
import {Transport} from './Transport';
/** /**
* Logger with colors, loglevel and transport * Logger with colors, loglevel and transport
@@ -23,189 +25,47 @@ import {Transport, TransportWithVerification} from './Transport';
* *
* Log levels in that order are: * Log levels in that order are:
* ``` * ```
* 1 - INFO * INFO: 1
* 2 - LOG * LOG: 2
* 4 - WARN * WARN: 4
* 8 - ERROR * ERROR: 8
* 16 - OK * OK: 16
* ``` * ```
*/ */
export class Logger { export class Logger {
/*
* Reset = "\x1b[0m"
* Bright = "\x1b[1m"
* Dim = "\x1b[2m"
* Underscore = "\x1b[4m"
* Blink = "\x1b[5m"
* Reverse = "\x1b[7m"
* Hidden = "\x1b[8m"
*
* FgBlack = "\x1b[30m"
* FgRed = "\x1b[31m"
* FgGreen = "\x1b[32m"
* FgYellow = "\x1b[33m"
* FgBlue = "\x1b[34m"
* FgMagenta = "\x1b[35m"
* FgCyan = "\x1b[36m"
* FgWhite = "\x1b[37m"
*
* BgBlack = "\x1b[40m"
* BgRed = "\x1b[41m"
* BgGreen = "\x1b[42m"
* BgYellow = "\x1b[43m"
* BgBlue = "\x1b[44m"
* BgMagenta = "\x1b[45m"
* BgCyan = "\x1b[46m"
* BgWhite = "\x1b[47m"
*/
/**
* Prefix for cyan color
*/
private cyan = '\x1b[36m';
/**
* Prefix for green color
*/
private green = '\x1b[32m';
/**
* Set to true if this code is executed by Node.js
*/
private isNode: boolean;
/**
* Set to true if the environment for a productive environment is given
*
* In Node.js this means that `NODE_ENV` is set to `production`
*/
private isProductiveEnvironment: boolean;
/** /**
* Log levels * Log levels
*/ */
private logLevels: { [logLevel: string]: 1 | 2 | 4 | 8 | 16 } = { private static logLevels = [
'INFO': 1, 'INFO',
'LOG': 2, 'LOG',
'WARN': 4, 'WARN',
// tslint:disable-next-line:object-literal-sort-keys 'ERROR',
'ERROR': 8, 'OK',
'OK': 16, ];
};
/**
* Prefix for red color
*/
private red = '\x1b[31m';
/**
* Suffix to end a color
*/
private reset = '\x1b[0m';
/** /**
* Transport for errors * Transport for errors
*
* For example `@stapps/smtp-transport`
*/ */
private transport?: Transport; private static transport?: Transport;
/**
* Prefix for white color
*/
private white = '\x1b[37m';
/**
* Prefix for yellow color
*/
private yellow = '\x1b[33m';
/**
* Checks if this code is executed in Node.js
*/
public static isNodeEnvironment(): boolean {
// Only Node.js has a process variable that is of [[Class]] process
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}
/**
* Checks if a productive environment is given
*/
public static isProductiveEnvironment(): boolean {
return Logger.isNodeEnvironment &&
(typeof process.env.NODE_ENV === 'string' && process.env.NODE_ENV === 'production');
}
/**
* Instatiate an instance of logger
* @param transport A transport instance that can be used for error transport
*/
constructor(transport?: Transport) {
// node environment -> maybe we run a service which needs monitoring
if (Logger.isNodeEnvironment()) {
this.isNode = true;
// check if we are in productive environment -> then we need to run a transport
if (Logger.isProductiveEnvironment()) {
this.isProductiveEnvironment = true;
if (typeof transport === 'undefined') {
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error('Productive environment doesn\'t set an transport agent for error notifications');
} else {
this.warn('Productive environment doesn\'t set an transport agent for error notifications');
}
} else {
this.transport = transport;
// we expect an transport for error notifications
if (this.isTransportWithVerification(transport) && !transport.isVerified()) {
transport.verify().then((success) => {
if (typeof success === 'string') {
this.ok(success);
} else {
this.ok('Successfully verified transport for error notification');
}
}).catch((err) => {
throw err;
});
}
}
} else {
this.isProductiveEnvironment = false;
}
} else {
this.isProductiveEnvironment = false;
this.isNode = false;
}
}
/** /**
* Check if intended log level is allowed in environment log level * Check if intended log level is allowed in environment log level
* *
* @param logLevel * @param logLevel
* @returns {boolean}
*/ */
private checkLogLevel(logLevel: 1 | 2 | 4 | 8 | 16) { private static checkLogLevel(logLevel: string): boolean {
const logLevelNumber = Math.pow(2, Logger.logLevels.indexOf(logLevel) + 1) - 1;
const requiredLogLevel = this.getLogLevel(); /* tslint:disable-next-line:no-bitwise */
return !!(Logger.getLogLevel() & logLevelNumber);
if (requiredLogLevel > 31 || requiredLogLevel < 0) {
throw new Error('Log level is out of range.');
}
// tslint:disable-next-line:no-bitwise
return requiredLogLevel & logLevel;
} }
/** /**
* Return log level from environment * Return log level from environment
* @returns {number}
*/ */
private getLogLevel(): number { private static getLogLevel(): number {
if (this.isNode && typeof process.env.STAPPS_LOG_LEVEL === 'string') { if (isNodeEnvironment() && typeof process.env.STAPPS_LOG_LEVEL !== 'undefined') {
// Node.js environment exists // Node.js environment exists
return parseInt(process.env.STAPPS_LOG_LEVEL, 10); return parseInt(process.env.STAPPS_LOG_LEVEL, 10);
} else if (typeof window !== 'undefined' && typeof (window as any).STAPPS_LOG_LEVEL === 'number') { } else if (typeof window !== 'undefined' && typeof (window as any).STAPPS_LOG_LEVEL === 'number') {
@@ -217,23 +77,102 @@ export class Logger {
return 31; return 31;
} }
private isTransportWithVerification(transport: Transport): transport is TransportWithVerification { /**
return typeof (transport as any).verify === 'function'; * Log an error
*
* @param args Arguments to log
*/
public static async error(...args: any[]): Promise<string | void> {
if (!Logger.checkLogLevel('ERROR')) {
return;
}
/* tslint:disable-next-line:no-console */
console.error(chalk.bold.red(`[ERROR] ${Logger.stringifyArguments(...args)}`));
if (isProductiveNodeEnvironment()) {
if (typeof Logger.transport !== 'undefined') {
return Logger.transport.send('Error', Logger.stringifyArguments(...args));
} else if (!process.env.ALLOW_NO_TRANSPORT) {
throw new Error(`Error couldn't be transported! Please set a transport or set ALLOW_NO_TRANSPORT='true'.`);
}
}
}
/**
* Log an information
*
* @param args Arguments to log
*/
public static info(...args: any[]): void {
if (!Logger.checkLogLevel('INFO')) {
return;
}
/* tslint:disable-next-line:no-console */
console.info(chalk.cyan(`[INFO] ${Logger.stringifyArguments(args)}`));
}
/**
* Check if the logger is initialized correctly
*/
public static initialized(): void {
if (isProductiveNodeEnvironment() && typeof Logger.transport === 'undefined') {
if (!process.env.ALLOW_NO_TRANSPORT) {
throw new Error(`Productive environment doesn't set a transport for error notifications.`);
} else {
/* tslint:disable-next-line:no-console */
console.warn(chalk.yellow(`Productive environment doesn't set a transport for error notifications.`));
}
}
}
/**
* Log something
*
* @param args Arguments to log
*/
public static log(...args: any[]): void {
if (!this.checkLogLevel('LOG')) {
return;
}
/* tslint:disable-next-line:no-console */
console.log(chalk.white(`[LOG] ${Logger.stringifyArguments(args)}`));
}
/**
* Log something successful
*
* @param args Arguments to log
*/
public static ok(...args: any[]): void {
if (!this.checkLogLevel('OK')) {
return;
}
/* tslint:disable-next-line:no-console */
console.log(chalk.bold.green(`[OK] ${Logger.stringifyArguments(args)}`));
}
/**
* Set a transport
*
* @param transport Transport to set
*/
public static setTransport(transport?: Transport) {
Logger.transport = transport;
} }
/** /**
* Stringify a list of arguments * Stringify a list of arguments
* *
* @param args {any[]} Arguments to stringify * @param args Arguments to stringify
* @returns {string} Stringified arguments
*/ */
private stringifyArguments(..._args: any[]): string { public static stringifyArguments(...args: any[]): string {
const result: string[] = []; const result: string[] = [];
/* tslint:disable:prefer-for-of */ args.forEach((argument) => {
for (let idx = 0; idx < arguments.length; idx++) {
/* tslint:enable */
const argument = arguments[idx];
const type = typeof argument; const type = typeof argument;
if (['string', 'number'].indexOf(type) !== -1) { if (['string', 'number'].indexOf(type) !== -1) {
@@ -246,106 +185,22 @@ export class Logger {
} else { } else {
result.push(stringify(argument, null, 2)); result.push(stringify(argument, null, 2));
} }
} });
return result.join(', '); return result.join(', ');
} }
/** /**
* Log with level ERROR * Log a warning
* *
* @param args {any} Arguments to log * @param args Arguments to log
*/ */
public error(...args: any[]): void { public static warn(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.ERROR)) { if (!this.checkLogLevel('WARN')) {
if (this.isNode) { return;
/* tslint:disable-next-line:no-console */
console.error(this.red + '[ERROR] ' + this.stringifyArguments(...args) + this.reset);
if (this.isProductiveEnvironment) {
if (typeof this.transport === 'undefined') {
if (process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error('Error couldn\'t be tranported. Please set an transport or set ALLOW_NO_TRANSPORT=true');
}
} else {
this.transport.send('Error', this.stringifyArguments(...args)).catch((err) => {
throw err;
});
}
}
} else {
/* tslint:disable-next-line:no-console */
console.log('[ERROR] ' + this.stringifyArguments(...args));
}
} }
}
/** /* tslint:disable-next-line:no-console */
* Log with level INFO console.warn(chalk.yellow(`[WARN] ${Logger.stringifyArguments(args)}`));
*
* @param args {any} Arguments to log
*/
public info(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.INFO)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.info(this.cyan + '[INFO] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.info('[INFO] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level LOG
*
* @param args {any} Arguments to log
*/
public log(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.LOG)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.log(this.white + '[LOG] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.log('[LOG] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level OK
*
* @param args {any} Arguments to log
*/
public ok(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.OK)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.log(this.green + '[OK] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.log('[OK] ' + this.stringifyArguments(...args));
}
}
}
/**
* Log with level WARN
*
* @param args {any} Arguments to log
*/
public warn(...args: any[]): void {
if (this.checkLogLevel(this.logLevels.WARN)) {
if (this.isNode) {
/* tslint:disable-next-line:no-console */
console.warn(this.yellow + '[WARN] ' + this.stringifyArguments(...args) + this.reset);
} else {
/* tslint:disable-next-line:no-console */
console.warn('[WARN] ' + this.stringifyArguments(...args));
}
}
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 StApps * Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -14,9 +14,8 @@
*/ */
import * as nodemailer from 'nodemailer'; import * as nodemailer from 'nodemailer';
import {MailOptions} from 'nodemailer/lib/sendmail-transport'; import {MailOptions} from 'nodemailer/lib/sendmail-transport';
import {deleteUndefinedProperties, RecursivePartial} from './common'; import {deleteUndefinedProperties, isProductiveEnvironment, RecursivePartial} from './common';
import {Logger} from './Logger'; import {VerifiableTransport} from './Transport';
import {TransportWithVerification} from './Transport';
/** /**
* A configuration of the transport used to send mails via SMTP * A configuration of the transport used to send mails via SMTP
@@ -40,14 +39,14 @@ export interface SMTPConfig {
/** /**
* An implementation of mail transport via SMTP * An implementation of mail transport via SMTP
*/ */
export class SMTP extends TransportWithVerification { export class SMTP extends VerifiableTransport {
private static _instance: SMTP; private static _instance: SMTP;
/** /**
* List of all mail addresses to send in cc * List of all mail addresses to send in cc
*/ */
private cc: string[]; private readonly cc: string[];
/** /**
* Who is using this service * Who is using this service
@@ -60,7 +59,7 @@ export class SMTP extends TransportWithVerification {
/** /**
* List of all mail addresses to send to * List of all mail addresses to send to
*/ */
private recipients: string[]; private readonly recipients: string[];
/** /**
* Connection to SMTP server * Connection to SMTP server
@@ -95,7 +94,7 @@ export class SMTP extends TransportWithVerification {
} }
// monitoring is not required -> SMTP init can fail // monitoring is not required -> SMTP init can fail
if (!Logger.isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT === 'true') { if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT === 'true') {
try { try {
this._instance = new this(config); this._instance = new this(config);
} catch (err) { } catch (err) {
@@ -122,14 +121,8 @@ export class SMTP extends TransportWithVerification {
* @return {boolean} * @return {boolean}
*/ */
public static isValidEmailAddress(address: string): boolean { public static isValidEmailAddress(address: string): boolean {
if (typeof address !== 'string') {
return false;
}
// tslint:disable-next-line:max-line-length // tslint:disable-next-line:max-line-length
const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; return /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i.test(address);
return regex.test(address);
} }
/** /**
@@ -153,13 +146,13 @@ export class SMTP extends TransportWithVerification {
password: process.env.SMTP_AUTH_PASSWORD, password: process.env.SMTP_AUTH_PASSWORD,
user: process.env.SMTP_AUTH_USER, user: process.env.SMTP_AUTH_USER,
}, },
cc: ((typeof process.env.SMTP_CC === 'string') ? (process.env.SMTP_CC as string).split(',') : []), cc: ((typeof process.env.SMTP_CC !== 'undefined') ? (process.env.SMTP_CC as string).split(',') : []),
host: process.env.SMTP_HOST, host: process.env.SMTP_HOST,
port: (typeof process.env.SMTP_PORT === 'string') ? parseInt(process.env.SMTP_PORT, 10) : undefined, port: (typeof process.env.SMTP_PORT !== 'undefined') ? parseInt(process.env.SMTP_PORT, 10) : undefined,
recipients: (typeof process.env.SMTP_RECIPIENTS === 'string') ? recipients: (typeof process.env.SMTP_RECIPIENTS !== 'undefined') ?
(process.env.SMTP_RECIPIENTS).split(',') : (process.env.SMTP_RECIPIENTS).split(',') :
[], [],
secure: (typeof process.env.SMTP_SECURE === 'string') ? (process.env.SMTP_SECURE === 'true') : false, secure: (typeof process.env.SMTP_SECURE !== 'undefined') ? (process.env.SMTP_SECURE === 'true') : false,
sender: { sender: {
mail: process.env.SMTP_SENDER_MAIL, mail: process.env.SMTP_SENDER_MAIL,
name: process.env.SMTP_SENDER_NAME, name: process.env.SMTP_SENDER_NAME,
@@ -173,13 +166,13 @@ export class SMTP extends TransportWithVerification {
...deleteUndefinedProperties(envConfig), ...deleteUndefinedProperties(envConfig),
}; };
if (typeof config!.host !== 'string') { if (typeof config!.host === 'undefined') {
throw new Error( throw new Error(
'SMTP configuration needs a host. Add it to the config or use environment variables (SMTP_HOST).', 'SMTP configuration needs a host. Add it to the config or use environment variables (SMTP_HOST).',
); );
} }
if (typeof config!.port !== 'number' || isNaN(config!.port)) { if (typeof config!.port === 'undefined' || isNaN(config!.port)) {
throw new Error( throw new Error(
'SMTP configuration needs a port. Add it to the config or use environment variables (SMTP_PORT).', 'SMTP configuration needs a port. Add it to the config or use environment variables (SMTP_PORT).',
); );
@@ -192,13 +185,13 @@ export class SMTP extends TransportWithVerification {
); );
} }
if (typeof config!.auth.user !== 'string') { if (typeof config!.auth.user === 'undefined') {
throw new Error( throw new Error(
'SMTP auth configuration needs a user. Add it to the config or use environment variables (SMTP_AUTH_USER).', 'SMTP auth configuration needs a user. Add it to the config or use environment variables (SMTP_AUTH_USER).',
); );
} }
if (typeof config!.auth.password !== 'string') { if (typeof config!.auth.password === 'undefined') {
throw new Error( throw new Error(
'SMTP auth configuration needs a password.' + 'SMTP auth configuration needs a password.' +
'Add it to the config or use environment variables (SMTP_AUTH_PASSWORD).', 'Add it to the config or use environment variables (SMTP_AUTH_PASSWORD).',
@@ -211,7 +204,7 @@ export class SMTP extends TransportWithVerification {
); );
} }
if (typeof config!.sender.mail !== 'string') { if (typeof config!.sender.mail === 'undefined') {
throw new Error( throw new Error(
'SMTP configuration needs a sender. Add it to the config or use environment variables (SMTP_SENDER_MAIL).', 'SMTP configuration needs a sender. Add it to the config or use environment variables (SMTP_SENDER_MAIL).',
); );
@@ -247,7 +240,7 @@ export class SMTP extends TransportWithVerification {
}, },
host: config!.host, host: config!.host,
port: config!.port, port: config!.port,
secure: typeof config!.secure === 'boolean' ? config!.secure : false, secure: typeof config!.secure !== 'undefined' ? config!.secure : false,
}); });
} }
@@ -311,7 +304,7 @@ export class SMTP extends TransportWithVerification {
try { try {
verificationSuccessfull = await this.transportAgent.verify(); verificationSuccessfull = await this.transportAgent.verify();
} catch (err) { } catch (err) {
if (!Logger.isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') { if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw err; throw err;
} else { } else {
/* tslint:disable-next-line:no-console */ /* tslint:disable-next-line:no-console */
@@ -323,7 +316,7 @@ export class SMTP extends TransportWithVerification {
} }
if (!verificationSuccessfull) { if (!verificationSuccessfull) {
if (!Logger.isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') { if (!isProductiveEnvironment() || process.env.ALLOW_NO_TRANSPORT !== 'true') {
throw new Error( throw new Error(
'Verification of SMTP transport failed.' + 'Verification of SMTP transport failed.' +
'If you want to ignore this error set' + 'If you want to ignore this error set' +

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 StApps * Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -14,34 +14,33 @@
*/ */
/** /**
* An abstract wrapper for a transport system like for example smtp * An abstract wrapper for a transport system like for example SMTP
*/ */
export abstract class Transport { export abstract class Transport {
/** /**
* Send message with subject. A message can be a mail or something completly different. Depending on what Transport * Send message with subject
* is implemented *
* @param {string} subject * A message can be a mail or something completely different depending on what transport is implemented.
* @param {string} message *
* @param subject Subject of the message
* @param message Message to send
*/ */
abstract send(subject: string, message: string): Promise<string>; abstract send(subject: string, message: string): Promise<string>;
} }
/** /**
* A transport wrapper of transport which can be veriefied * A transport wrapper of transport which can be verified
*/ */
export abstract class TransportWithVerification extends Transport { export abstract class VerifiableTransport extends Transport {
/** /**
* Checks if the transport was verified at least once * Checks if the transport was verified at least once
* @returns {boolean}
*/ */
abstract isVerified(): boolean; abstract isVerified(): boolean;
/** /**
* Verifies transport (check connection, authentication, ...) * Verifies transport
*
* Check connection, authentication, ...
*/ */
abstract verify(): Promise<boolean>; abstract verify(): Promise<boolean>;
} }

View File

@@ -13,15 +13,17 @@
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
/** /**
* A recursive partial object * A recursive partial object
* *
* Copied from https://stackoverflow.com/a/51365037 * Copied from https://stackoverflow.com/a/51365037
*/ */
import {Transport, VerifiableTransport} from './Transport';
export type RecursivePartial<T> = { export type RecursivePartial<T> = {
[P in keyof T]?: T[P] extends Array<infer U> ? [P in keyof T]?: T[P] extends Array<infer U> ?
Array<RecursivePartial<U>> : Array<RecursivePartial<U>> :
T[P] extends object ? RecursivePartial<T[P]> : T[P]; T[P] extends object ? RecursivePartial<T[P]> : T[P];
}; };
/** /**
@@ -47,3 +49,35 @@ export function deleteUndefinedProperties(obj: any) {
return obj; return obj;
} }
/**
* Checks if environment is Node.js
*/
export function isNodeEnvironment(): boolean {
return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}
/**
* Checks if environment is productive
*/
export function isProductiveEnvironment(): boolean {
return typeof process.env === 'object'
&& typeof process.env.NODE_ENV !== 'undefined'
&& process.env.NODE_ENV === 'production';
}
/**
* Checks if environment is Node.js and productive
*/
export function isProductiveNodeEnvironment(): boolean {
return isNodeEnvironment() && isProductiveEnvironment();
}
/**
* Check if a transport is a verifiable transport
*
* @param transport Transport to check
*/
export function isTransportWithVerification(transport: Transport): transport is VerifiableTransport {
return transport instanceof VerifiableTransport;
}

View File

@@ -14,11 +14,15 @@
*/ */
import {expect} from 'chai'; import {expect} from 'chai';
import {slow, suite, test, timeout} from 'mocha-typescript'; import {slow, suite, test, timeout} from 'mocha-typescript';
import {deleteUndefinedProperties} from '../src/common'; import {
deleteUndefinedProperties,
isNodeEnvironment,
isProductiveEnvironment,
isProductiveNodeEnvironment,
} from '../src/common';
@suite(timeout(2000), slow(1000)) @suite(timeout(2000), slow(1000))
export class CommonSpec { export class CommonSpec {
/* tslint:disable:member-ordering */
@test @test
deleteUndefinedProperties1() { deleteUndefinedProperties1() {
expect(deleteUndefinedProperties( expect(deleteUndefinedProperties(
@@ -67,4 +71,48 @@ export class CommonSpec {
}, },
); );
} }
@test
isNodeEnvironment() {
expect(isNodeEnvironment()).to.be.equal(true);
const savedProcess = process;
// @ts-ignore
process = undefined;
expect(isNodeEnvironment()).to.be.equal(false);
process = savedProcess;
}
@test
isProductiveEnvironment() {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = '';
expect(isProductiveEnvironment()).to.be.equal(false);
process.env.NODE_ENV = 'production';
expect(isProductiveEnvironment()).to.be.equal(true);
process.env.NODE_ENV = nodeEnv;
}
@test
isProductiveNodeEnvironment() {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = '';
expect(isProductiveNodeEnvironment()).to.be.equal(false);
process.env.NODE_ENV = 'production';
expect(isProductiveNodeEnvironment()).to.be.equal(true);
process.env.NODE_ENV = nodeEnv;
}
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 StApps * Copyright (C) 2018, 2019 StApps
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free * under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3. * Software Foundation, version 3.
@@ -12,216 +12,282 @@
* You should have received a copy of the GNU General Public License along with * You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>. * this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import * as chai from 'chai';
import {expect} from 'chai'; import {expect} from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import {slow, suite, test, timeout} from 'mocha-typescript'; import {slow, suite, test, timeout} from 'mocha-typescript';
import * as sinon from 'sinon'; import * as sinon from 'sinon';
import {Logger} from '../src/Logger'; import {Logger} from '../src/Logger';
import {DummyTransport} from './Transport.spec';
const logger1 = new Logger(); chai.should();
chai.use(chaiAsPromised);
@suite(timeout(2000), slow(1000)) @suite(timeout(2000), slow(1000))
export class LoggerSpec { export class LoggerSpec {
@test @test
error1(done: () => void) { async error() {
let const stub = sinon.stub(console, 'error');
stub;
stub = sinon.stub(console, 'error');
logger1.error('Foobar'); await Logger.error('Foobar');
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('[ERROR] Foobar'); expect(stub.args[0][0]).contains('[ERROR]');
expect(stub.args[0][0]).contains('Foobar');
done();
} }
@test @test
error2(done: () => void) { async errorInProductiveEnvironment() {
const errorStub = sinon.stub(console, 'error');
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
await Logger.error('Foobar').should.be.rejectedWith(Error);
expect(errorStub.callCount).to.be.equal(1);
process.env.ALLOW_NO_TRANSPORT = 'true';
await Logger.error('Foobar').should.not.be.rejectedWith(Error);
expect(errorStub.callCount).to.be.equal(2);
delete process.env.ALLOW_NO_TRANSPORT;
Logger.setTransport(new DummyTransport());
await Logger.error('Foobar').should.not.be.rejectedWith(Error);
expect(errorStub.callCount).to.be.equal(3);
Logger.setTransport();
process.env.NODE_ENV = nodeEnv;
errorStub.restore();
}
@test
async errorNoOutput() {
const stub = sinon.stub(console, 'error');
process.env.STAPPS_LOG_LEVEL = '0';
await Logger.error('Foobar');
stub.restore();
delete process.env.STAPPS_LOG_LEVEL;
return expect(stub.called).to.be.false;
}
@test
async errorWithError() {
const e = new Error(); const e = new Error();
const stub = sinon.stub(console, 'error'); const stub = sinon.stub(console, 'error');
logger1.error(e); await Logger.error(e);
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('Error').contains('at').contains(process.cwd()); expect(stub.args[0][0]).contains('Error').contains('at').contains(process.cwd());
done();
} }
@test @test
info(done: () => void) { getLogLevel() {
let const savedProcess = process;
stub;
stub = sinon.stub(console, 'info');
logger1.info('Foobar'); // @ts-ignore
process = undefined;
(global as any).window = {
STAPPS_LOG_LEVEL: 0,
};
const stub = sinon.stub(console, 'info');
Logger.info('Foobar');
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('[INFO] Foobar'); process = savedProcess;
done(); delete (global as any).window;
return expect(stub.called).to.be.false;
} }
@test @test
log(done: () => void) { info() {
let const stub = sinon.stub(console, 'info');
stub;
stub = sinon.stub(console, 'log');
logger1.log('Foobar'); Logger.info('Foobar');
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('[LOG] Foobar'); expect(stub.args[0][0]).contains('[INFO]');
expect(stub.args[0][0]).contains('Foobar');
done();
} }
@test @test
logLevel1(done: () => void) { infoNoOutput() {
let logStub; const stub = sinon.stub(console, 'info');
let warnStub;
process.env.STAPPS_LOG_LEVEL = '8'; process.env.STAPPS_LOG_LEVEL = '0';
logStub = sinon.stub(console, 'log'); Logger.info('Foobar');
warnStub = sinon.stub(console, 'warn');
logger1.ok('foo'); stub.restore();
logger1.warn('bar');
logStub.restore();
/* tslint:disable:no-unused-expression */
expect(logStub.called).to.be.false;
expect(warnStub.called).to.be.false;
/* tslint:enable */
delete process.env.STAPPS_LOG_LEVEL; delete process.env.STAPPS_LOG_LEVEL;
logger1.warn('bar'); return expect(stub.called).to.be.false;
/* tslint:disable:no-unused-expression */
expect(warnStub.called).to.be.true;
/* tslint:enable */
warnStub.restore();
done();
} }
@test @test
logLevel2(done: () => void) { initialized() {
let logStub; Logger.setTransport(new DummyTransport());
let warnStub;
process.env.STAPPS_LOG_LEVEL = '12'; expect(() => {
Logger.initialized();
}).not.to.throw();
logStub = sinon.stub(console, 'log'); Logger.setTransport();
warnStub = sinon.stub(console, 'warn'); }
logger1.ok('foo'); @test
logger1.warn('bar'); initializedInProductiveEnvironment() {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
logStub.restore(); Logger.setTransport(new DummyTransport());
/* tslint:disable:no-unused-expression */ expect(() => {
expect(logStub.called).to.be.false; Logger.initialized();
expect(warnStub.called).to.be.true; }).not.to.throw();
/* tslint:enable */
Logger.setTransport();
expect(() => {
Logger.initialized();
}).to.throw();
const stub = sinon.stub(console, 'warn');
process.env.ALLOW_NO_TRANSPORT = 'true';
expect(() => {
Logger.initialized();
}).not.to.throw();
delete process.env.ALLOW_NO_TRANSPORT;
expect(stub.called).to.be.equal(true);
stub.restore();
process.env.NODE_ENV = nodeEnv;
}
@test
log() {
const stub = sinon.stub(console, 'log');
Logger.log('Foobar');
stub.restore();
expect(stub.args[0][0]).contains('[LOG]');
expect(stub.args[0][0]).contains('Foobar');
}
@test
logNoOutput() {
const stub = sinon.stub(console, 'log');
process.env.STAPPS_LOG_LEVEL = '0';
Logger.log('Foobar');
stub.restore();
delete process.env.STAPPS_LOG_LEVEL; delete process.env.STAPPS_LOG_LEVEL;
logger1.warn('bar'); return expect(stub.called).to.be.false;
/* tslint:disable:no-unused-expression */
expect(warnStub.called).to.be.true;
/* tslint:enable */
warnStub.restore();
done();
} }
@test @test
logLevel3(done: () => void) { ok() {
let logStub; const stub = sinon.stub(console, 'log');
let warnStub;
process.env.STAPPS_LOG_LEVEL = '20'; Logger.ok('Foobar');
logStub = sinon.stub(console, 'log'); stub.restore();
warnStub = sinon.stub(console, 'warn');
logger1.ok('foo'); expect(stub.args[0][0]).contains('[OK]');
logger1.warn('bar'); expect(stub.args[0][0]).contains('Foobar');
}
logStub.restore(); @test
okNoOutput() {
const stub = sinon.stub(console, 'log');
/* tslint:disable:no-unused-expression */ process.env.STAPPS_LOG_LEVEL = '0';
expect(logStub.called).to.be.true;
expect(warnStub.called).to.be.true; Logger.ok('Foobar');
/* tslint:enable */
stub.restore();
delete process.env.STAPPS_LOG_LEVEL; delete process.env.STAPPS_LOG_LEVEL;
logger1.warn('bar'); return expect(stub.called).to.be.false;
/* tslint:disable:no-unused-expression */
expect(warnStub.called).to.be.true;
/* tslint:enable */
warnStub.restore();
done();
} }
@test @test
ok(done: () => void) { setTransport() {
let expect(() => {
stub; Logger.setTransport(new DummyTransport());
stub = sinon.stub(console, 'log'); Logger.setTransport();
}).not.to.throw();
logger1.ok('Foobar');
stub.restore();
expect(stub.args[0][0]).contains('[OK] Foobar');
done();
} }
@test @test
stringifyArguments(done: () => void) { stringifyArguments() {
let const stub = sinon.stub(console, 'log');
stub;
stub = sinon.stub(console, 'log');
logger1.log('foo', 'bar'); Logger.log('foo', 'bar');
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('[LOG]').and.contains('foo').and.contains('bar'); expect(stub.args[0][0]).contains('[LOG]');
expect(stub.args[0][0]).contains('foo');
done(); expect(stub.args[0][0]).contains('bar');
} }
@test @test
warn(done: () => void) { warn() {
let const stub = sinon.stub(console, 'warn');
stub;
stub = sinon.stub(console, 'warn');
logger1.warn('Foobar'); Logger.warn('Foobar');
stub.restore(); stub.restore();
expect(stub.args[0][0]).contains('[WARN] Foobar'); expect(stub.args[0][0]).contains('[WARN]');
expect(stub.args[0][0]).contains('Foobar');
}
done(); @test
warnNoOutput() {
const stub = sinon.stub(console, 'warn');
process.env.STAPPS_LOG_LEVEL = '0';
Logger.warn('Foobar');
stub.restore();
delete process.env.STAPPS_LOG_LEVEL;
return expect(stub.called).to.be.false;
} }
} }

65
test/Transport.spec.ts Normal file
View File

@@ -0,0 +1,65 @@
/*
* Copyright (C) 2019 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {expect} from 'chai';
import {slow, suite, test, timeout} from 'mocha-typescript';
import {isTransportWithVerification} from '../src/common';
import {Transport, VerifiableTransport} from '../src/Transport';
export class DummyTransport extends Transport {
send(subject: string, message: string): Promise<string> {
return new Promise((resolve, reject) => {
if (0 === 0) {
resolve(subject);
}
reject(message);
});
}
}
export class VerifiableDummyTransport extends VerifiableTransport {
isVerified(): boolean {
return false;
}
send(subject: string, message: string): Promise<string> {
return new Promise((resolve, reject) => {
if (0 === 0) {
resolve(subject);
}
reject(message);
});
}
verify(): Promise<boolean> {
return new Promise((resolve) => {
resolve(true);
});
}
}
@suite(timeout(2000), slow(1000))
export class TransportSpec {
@test
isNotTransportWithVerification() {
return expect(isTransportWithVerification(new DummyTransport())).to.be.false;
}
@test
isTransportWithVerification() {
return expect(isTransportWithVerification(new VerifiableDummyTransport())).to.be.true;
}
}