@cley_faye/boilerplate 3.2.2 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,8 @@ required, and for what. It's up to the calling project to have the proper depend
19
19
 
20
20
  For webapp building:
21
21
 
22
+ - resolve-typescript-plugin (due to the way webpack plugins are handled, this is mandatory for dev
23
+ install)
22
24
  - babel-loader
23
25
  - eslint-webpack-plugin
24
26
  - @babel/core
@@ -34,6 +36,7 @@ For webapp building:
34
36
  - sass
35
37
  - grunt-webpack
36
38
  - grunt
39
+ - ts-loader (for supporting TypeScript import in webpack/babel)
37
40
 
38
41
  For express:
39
42
 
@@ -76,7 +79,7 @@ example):
76
79
  const {
77
80
  reactApp,
78
81
  reactAppDynamicTasks,
79
- } = require("@cley_faye/boilerplate/grunt");
82
+ } = require("@cley_faye/boilerplate/grunt.js");
80
83
 
81
84
  module.exports = grunt => {
82
85
  const baseGruntConfig = {};
@@ -178,7 +181,7 @@ The example from before can become:
178
181
  const {
179
182
  reactApp,
180
183
  reactAppOptionsHelper,
181
- } = require("@cley_faye/boilerplate/grunt");
184
+ } = require("@cley_faye/boilerplate/grunt.js");
182
185
 
183
186
  module.exports = grunt => {
184
187
  const baseGruntConfig = {};
@@ -236,7 +239,7 @@ It provide basic type checking and inline help display for arguments passed to G
236
239
  Usage:
237
240
 
238
241
  ```JavaScript
239
- const {getOpts, OptType} = require("@cley_faye/boilerplate/grunt");
242
+ const {getOpts, OptType} = require("@cley_faye/boilerplate/grunt.js");
240
243
  module.exports = grunt => {
241
244
  const opts = getOpts(
242
245
  grunt,
@@ -286,7 +289,7 @@ Quick sample:
286
289
 
287
290
  ```JavaScript
288
291
  import express from "express";
289
- import {createPipeline} from "@cley_faye/boilerplate/lib/express";
292
+ import {createPipeline} from "@cley_faye/boilerplate/lib/express.js";
290
293
 
291
294
  const app = express();
292
295
  app.use(createPipeline({
@@ -368,7 +371,7 @@ root of the service, or an object with the following properties:
368
371
  #### Configuring the template engine
369
372
 
370
373
  ```JavaScript
371
- import {setViewEngine} from "@cley_faye/boilerplate/lib/express";
374
+ import {setViewEngine} from "@cley_faye/boilerplate/lib/express.js";
372
375
 
373
376
  const app = express();
374
377
  setViewEngine(app, "pug", "webres/views", {});
@@ -382,9 +385,9 @@ Once the express application is defined, it need to be started to serve files an
382
385
  A helper is provided to do so, using the `appStart()` function.
383
386
 
384
387
  ```JavaScript
385
- import consoleLogger from "@cley_faye/boilerplate/lib/winston";
386
- import app from "./app";
387
- import {appStart} from "@cley_faye/boilerplate/lib/express";
388
+ import {consoleLogger} from "@cley_faye/boilerplate/lib/winston.js";
389
+ import app from "./app.js";
390
+ import {appStart} from "@cley_faye/boilerplate/lib/express.js";
388
391
 
389
392
  appStart({
390
393
  app,
@@ -407,7 +410,7 @@ The function returns a promise that resolve with the actual port used for listen
407
410
  The server is automatically registered using the `autoclose` part to stop when a SIGINT signal is
408
411
  received.
409
412
  It is also possible to trigger a stop by calling the `closeServer()` function on
410
- `@cley_faye/boilerplate/lib/express/autoclose`.
413
+ `@cley_faye/boilerplate/lib/express/autoclose.js`.
411
414
  This feature only supports one server at a time.
412
415
 
413
416
  Console logging
@@ -415,7 +418,7 @@ Console logging
415
418
  For convenience, a winston logger using console as output is provided:
416
419
 
417
420
  ```JavaScript
418
- import consoleLogger from "@cley_faye/boilerplate/lib/winston";
421
+ import {consoleLogger} from "@cley_faye/boilerplate/lib/winston.js";
419
422
 
420
423
  consoleLogger.info("Log line");
421
424
  ```
@@ -426,8 +429,18 @@ Typical use of TypeScript implies converting `.ts` file to `.js`.
426
429
  For a React app using webpack, there's two approach: either instruct webpack to accept `.ts` files
427
430
  (for example, using `ts-loader`) or have your entry point be a `.js` file that imports the generated
428
431
  output from TypeScript.
429
- Either way, watch mode will be capable of detecting change in the source material, as long as the
430
- TypeScript compiler is also running.
432
+ If you reference the output of the TypeScript compiler, you can keep it updated using `npx tsc -w`.
433
+
434
+ Using `ts-loader` can be done automatically by setting the `typescript` property in the webpack
435
+ configuration to `true`.
431
436
 
432
437
  For Express app, there is no particular things to take care, except that if you use a facility like
433
438
  `nodemon` you have to watch the TypeScript output instead of the actual source files.
439
+
440
+ REPL
441
+ ----
442
+ This library provides a function to start a simple REPL instance (using node's built-in repl module)
443
+ to provide access to JavaScript features.
444
+
445
+ Basic usage includes predefined behavior for providing a database object and a list of services.
446
+ The export is in `lib/repl.js`.
package/grunt.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // This file is kept as an "old" require/modules file to make it easier to use
2
2
  // with Gruntfile
3
- module.exports = require("./lib/grunt");
3
+ module.exports = require("./lib/grunt.js");
@@ -33,38 +33,6 @@ exports.registerErrorLogger = exports.registerRouteLogger = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
34
  const express_winston_1 = __importDefault(require("express-winston"));
35
35
  const winston_js_1 = require("../winston.js");
36
- // High value because of colorize()
37
- const LOG_LEVEL_PADDING_SIZE = 19;
38
- /**
39
- * Collapse all lines containing /node_modules/ into an ellipsis
40
- */
41
- const filterNodeModules = function* (message) {
42
- let inNodeModules = false;
43
- const lines = message.split("\n");
44
- for (const line of lines) {
45
- if (/\/node_modules\//u.exec(line)) {
46
- if (!inNodeModules) {
47
- inNodeModules = true;
48
- yield "[...]";
49
- }
50
- }
51
- else {
52
- inNodeModules = false;
53
- yield line;
54
- }
55
- }
56
- };
57
- /**
58
- * Prefix all lines with the level and the timestamp if needed
59
- */
60
- const prefixOutput = (level, message, timestamp) => {
61
- const timestampPrefix = timestamp
62
- ? `${new Date().toISOString()} `
63
- : "";
64
- const levelPrefix = `${level.toString().padStart(LOG_LEVEL_PADDING_SIZE)}: `;
65
- return message.split("\n").map(line => `${timestampPrefix}${levelPrefix}${line}`)
66
- .join("\n");
67
- };
68
36
  const customRouteFormat = (outputTimestamp) => winston_1.default.format.printf((info) => {
69
37
  const meta = info.meta;
70
38
  // Clean the meta object from stuff displayed in the regular message
@@ -86,7 +54,7 @@ const customRouteFormat = (outputTimestamp) => winston_1.default.format.printf((
86
54
  }
87
55
  const metaString = JSON.stringify(info.meta);
88
56
  const finalMessage = `${info.message} ${metaString === "{}" ? "" : metaString}`;
89
- return prefixOutput(info.level, finalMessage, outputTimestamp);
57
+ return (0, winston_js_1.prefixOutput)(info.level, finalMessage, outputTimestamp);
90
58
  });
91
59
  const registerRouteLogger = (app, logOptions) => {
92
60
  const { route, logger, timestamp } = logOptions ?? {};
@@ -131,9 +99,9 @@ const customErrorFormat = (outputTimestamp, config) => {
131
99
  return winston_1.default.format.printf((info) => {
132
100
  const meta = info.meta;
133
101
  const finalMessage = collapseNodeModules
134
- ? [...filterNodeModules(meta.message)].join("\n")
102
+ ? [...(0, winston_js_1.filterNodeModules)(meta.message)].join("\n")
135
103
  : meta.message;
136
- return prefixOutput(info.level, finalMessage, outputTimestamp);
104
+ return (0, winston_js_1.prefixOutput)(info.level, finalMessage, outputTimestamp);
137
105
  });
138
106
  };
139
107
  const registerErrorLogger = (app, logOptions) => {
@@ -1,7 +1,7 @@
1
1
  import express from "express";
2
2
  import { OptionsJson, OptionsUrlencoded, OptionsText, Options as OptionsRaw } from "body-parser";
3
- import { LoggerOptions, ErrorLoggerOptions } from "./logger.js";
4
3
  import winston from "winston";
4
+ import { LoggerOptions, ErrorLoggerOptions } from "./logger.js";
5
5
  export declare type LogFunction = (...args: Array<string | number | Record<string, unknown>>) => void;
6
6
  export interface MiddlewareOptions {
7
7
  urlencoded?: boolean | OptionsUrlencoded;
@@ -30,6 +30,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  const express_1 = __importDefault(require("express"));
33
+ const winston_js_1 = require("../winston.js");
33
34
  const logger_js_1 = require("./logger.js");
34
35
  const defaultErrorHandler = (err, req, res, next) => {
35
36
  if (!res.headersSent && err.statusCode) {
@@ -88,6 +89,15 @@ class PipelineBuilder {
88
89
  createPipeline({ topLevels, routes, statics, postStatics, errorHandlers, options, }) {
89
90
  const { middleware, log, defaultErrorHandler: useDefaultErrorHandler } = options ?? {};
90
91
  this.internalLog("createPipeline()");
92
+ if (log) {
93
+ const errorConfig = typeof log.error === "boolean"
94
+ ? {}
95
+ : log.error ?? {};
96
+ (0, winston_js_1.setConfig)({
97
+ timestamp: log.timestamp ?? false,
98
+ collapseNodeModules: errorConfig.collapseNodeModules ?? true,
99
+ });
100
+ }
91
101
  const router = express_1.default.Router();
92
102
  this.internalLog("setGenericMiddlewares()");
93
103
  this._setGenericMiddlewares(router, middleware);
package/lib/express.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /// <reference types="express-serve-static-core" />
2
2
  /// <reference types="node" />
3
- import { PipelineSettings, LogFunction } from "./express/pipelinebuilder.js";
3
+ import { Server } from "net";
4
4
  import express from "express";
5
5
  import winston from "winston";
6
- import { Server } from "net";
6
+ import { PipelineSettings, LogFunction } from "./express/pipelinebuilder.js";
7
7
  /** Create the full processing pipeline for an Express server
8
8
  *
9
9
  * This function creates a pipeline this way:
@@ -23,6 +23,9 @@ import { Server } from "net";
23
23
  * If the request accepts json, a json object with the error is returned.
24
24
  * Otherwise text is returned.
25
25
  *
26
+ * For convenience, providing timestamp and collapseNodeModules here will automatically
27
+ * update the basic consoleLogger configuration.
28
+ *
26
29
  * @param settings
27
30
  *
28
31
  * @param [settings.topLevels]
package/lib/express.js CHANGED
@@ -51,6 +51,9 @@ const pipelinebuilder_js_1 = __importDefault(require("./express/pipelinebuilder.
51
51
  * If the request accepts json, a json object with the error is returned.
52
52
  * Otherwise text is returned.
53
53
  *
54
+ * For convenience, providing timestamp and collapseNodeModules here will automatically
55
+ * update the basic consoleLogger configuration.
56
+ *
54
57
  * @param settings
55
58
  *
56
59
  * @param [settings.topLevels]
@@ -1,6 +1,6 @@
1
- import { GruntConfig } from "./util.js";
2
1
  import { BaseOptions } from "../util.js";
3
2
  import { HandlerFunctionResult } from "../reactapp.js";
3
+ import { GruntConfig } from "./util.js";
4
4
  export interface CopyOptions extends BaseOptions {
5
5
  options?: Record<string, unknown>;
6
6
  excludedExtensions?: Array<string>;
@@ -1,6 +1,6 @@
1
- import { GruntConfig } from "./util.js";
2
1
  import { BaseOptions } from "../util.js";
3
2
  import { HandlerFunctionResult } from "../reactapp.js";
3
+ import { GruntConfig } from "./util.js";
4
4
  export interface ImageOptions extends BaseOptions {
5
5
  options?: Record<string, unknown>;
6
6
  sourcePath?: string;
@@ -1,6 +1,6 @@
1
- import { GruntConfig } from "./util.js";
2
1
  import { BaseOptions } from "../util.js";
3
2
  import { HandlerFunctionResult } from "../reactapp.js";
3
+ import { GruntConfig } from "./util.js";
4
4
  export declare type DynamicDataFunc = () => Promise<Record<string, unknown>>;
5
5
  export interface PugOptions extends BaseOptions {
6
6
  options?: Record<string, unknown>;
@@ -1,6 +1,6 @@
1
- import { GruntConfig } from "./util.js";
2
1
  import { BaseOptions } from "../util.js";
3
2
  import { HandlerFunctionResult } from "../reactapp.js";
3
+ import { GruntConfig } from "./util.js";
4
4
  interface SassOptionsOptions {
5
5
  implementation?: Record<string, unknown>;
6
6
  }
@@ -1,6 +1,6 @@
1
- import { GruntConfig } from "./util.js";
2
1
  import { BaseOptions } from "../util.js";
3
2
  import { HandlerFunctionResult } from "../reactapp.js";
3
+ import { GruntConfig } from "./util.js";
4
4
  export interface WebpackLoadersOptions {
5
5
  development?: boolean;
6
6
  defines?: Record<string, string>;
@@ -9,6 +9,7 @@ export interface WebpackLoadersOptions {
9
9
  targets?: string;
10
10
  plugins?: Array<Record<string, unknown>>;
11
11
  };
12
+ typescript?: boolean;
12
13
  }
13
14
  /** Build the default webpack loaders list.
14
15
  *
@@ -30,6 +31,9 @@ export interface WebpackLoadersOptions {
30
31
  *
31
32
  * @param [options.babel.plugins]
32
33
  * Plugins to add to babel
34
+ *
35
+ * @param [options.typescript]
36
+ * Add support for importing .ts and .tsx files
33
37
  */
34
38
  export declare const webpackLoadersDefault: (options: WebpackLoadersOptions) => Array<Record<string, unknown>>;
35
39
  export interface WebpackOptions extends BaseOptions {
@@ -45,7 +49,8 @@ export interface WebpackOptions extends BaseOptions {
45
49
  plugins?: Array<Record<string, unknown>>;
46
50
  babelPlugins?: Array<Record<string, unknown>>;
47
51
  defines?: Record<string, string>;
48
- resolve?: unknown;
52
+ resolve?: Record<string, unknown>;
53
+ typescript?: boolean;
49
54
  }
50
55
  /** Add a webpack task for the reactApp recipe
51
56
  *
@@ -99,6 +104,9 @@ export interface WebpackOptions extends BaseOptions {
99
104
  * Build mode. "development", "production" or "none".
100
105
  * Defaults to "development"
101
106
  *
107
+ * @param [webpackOptions.typescript]
108
+ * Allow loading typescript source for webpack/babel.
109
+ *
102
110
  * @return
103
111
  * List of tasks added.
104
112
  * This function add "webpack:<targetName>".
@@ -31,8 +31,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  exports.handle = exports.webpackLoadersDefault = void 0;
33
33
  const path_1 = require("path");
34
- const util_js_1 = require("./util.js");
35
34
  const eslint_webpack_plugin_1 = __importDefault(require("eslint-webpack-plugin"));
35
+ const resolve_typescript_plugin_1 = __importDefault(require("resolve-typescript-plugin"));
36
+ const util_js_1 = require("./util.js");
36
37
  const defaultCoreJS = 3;
37
38
  const eslintPlugin = () => new eslint_webpack_plugin_1.default({ cache: true });
38
39
  const defaultLoadersDefine = (options) => [
@@ -78,27 +79,43 @@ const defaultLoadersReact = (options) => [
78
79
  *
79
80
  * @param [options.babel.plugins]
80
81
  * Plugins to add to babel
82
+ *
83
+ * @param [options.typescript]
84
+ * Add support for importing .ts and .tsx files
81
85
  */
82
- const webpackLoadersDefault = (options) => [
83
- {
84
- test: /.js$/u,
85
- exclude: /node_modules/u,
86
- use: {
87
- loader: "babel-loader",
88
- options: {
89
- cacheDirectory: true,
90
- presets: [
91
- defaultLoadersPresetEnv(options),
92
- defaultLoadersReact(options),
93
- ],
94
- plugins: [
95
- defaultLoadersDefine(options),
96
- ...(options.babel?.plugins ?? []),
97
- ],
86
+ const webpackLoadersDefault = (options) => {
87
+ const allFilesCheck = options.typescript
88
+ ? /.(?:js|ts|tsx)$/u
89
+ : /.js$/u;
90
+ const res = [
91
+ {
92
+ test: allFilesCheck,
93
+ exclude: /node_modules/u,
94
+ use: {
95
+ loader: "babel-loader",
96
+ options: {
97
+ cacheDirectory: true,
98
+ presets: [
99
+ defaultLoadersPresetEnv(options),
100
+ defaultLoadersReact(options),
101
+ ],
102
+ plugins: [
103
+ defaultLoadersDefine(options),
104
+ ...(options.babel?.plugins ?? []),
105
+ ],
106
+ },
98
107
  },
99
108
  },
100
- },
101
- ];
109
+ ];
110
+ if (options.typescript) {
111
+ res.push({
112
+ test: /.(?:ts|tsx)$/u,
113
+ use: "ts-loader",
114
+ exclude: /node_modules/u,
115
+ });
116
+ }
117
+ return res;
118
+ };
102
119
  exports.webpackLoadersDefault = webpackLoadersDefault;
103
120
  const computeWebpackOutput = (webpackOptions, targetName) => webpackOptions.output ?? {
104
121
  path: (0, path_1.resolve)("dist", targetName, "js"),
@@ -143,6 +160,16 @@ const registerTasks = (gruntConfig, targetName, webpackConfig) => {
143
160
  (0, util_js_1.insertTask)(gruntConfig, "webpack", targetName, webpackConfig),
144
161
  ];
145
162
  };
163
+ const computeWebpackResolve = (webpackOptions) => {
164
+ const res = { ...webpackOptions.resolve };
165
+ if (webpackOptions.typescript) {
166
+ if (res.plugins === undefined) {
167
+ res.plugins = [];
168
+ }
169
+ res.plugins.push(new resolve_typescript_plugin_1.default());
170
+ }
171
+ return res;
172
+ };
146
173
  /** Add a webpack task for the reactApp recipe
147
174
  *
148
175
  * @param gruntConfig
@@ -195,6 +222,9 @@ const registerTasks = (gruntConfig, targetName, webpackConfig) => {
195
222
  * Build mode. "development", "production" or "none".
196
223
  * Defaults to "development"
197
224
  *
225
+ * @param [webpackOptions.typescript]
226
+ * Allow loading typescript source for webpack/babel.
227
+ *
198
228
  * @return
199
229
  * List of tasks added.
200
230
  * This function add "webpack:<targetName>".
@@ -209,7 +239,9 @@ const handle = (gruntConfig, targetName, webpackOptions) => {
209
239
  development: webpackOptions.mode === "development",
210
240
  defines: webpackOptions.defines,
211
241
  babel: { plugins: webpackOptions.babelPlugins },
242
+ typescript: webpackOptions.typescript,
212
243
  });
244
+ const webpackResolve = computeWebpackResolve(webpackOptions);
213
245
  const webpackConfig = {
214
246
  mode: webpackOptions.mode,
215
247
  devtool: webpackOptions.mode === "development" ? "eval-source-map" : false,
@@ -221,7 +253,7 @@ const handle = (gruntConfig, targetName, webpackOptions) => {
221
253
  eslintPlugin(),
222
254
  ...webpackOptions.plugins ?? [],
223
255
  ],
224
- resolve: webpackOptions.resolve,
256
+ resolve: webpackResolve,
225
257
  };
226
258
  // Special case: I'm not sure I can move options in the task-specific part of
227
259
  // the configuration, so I add it at the toplevel of the "webpack" task.
@@ -103,9 +103,6 @@ const createWatchTasks = (gruntConfig, mergedResults, watchMode) => {
103
103
  if (watchMode === false) {
104
104
  return;
105
105
  }
106
- if (mergedResults.watchTasks.length > 0) {
107
- (0, util_js_2.insertTask)(gruntConfig, "watch", "options", getWatcherOptions(watchMode));
108
- }
109
106
  mergedResults.watchTasks.forEach(watchTask => {
110
107
  (0, util_js_2.insertTask)(gruntConfig, "watch", getWatchTaskName(watchTask), {
111
108
  options: getWatcherOptions(watchMode),
package/lib/repl.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** Function called when the REPL is closed */
2
+ export declare type ReplCloseFunc = () => void;
3
+ /** Mimic the required elements from a db object */
4
+ interface DBLikeObject {
5
+ /** db object can have a reference to an initialized sequelize instance */
6
+ sequelize?: {
7
+ /** Sequelize instance should have a close() method */
8
+ close?: () => void;
9
+ };
10
+ }
11
+ interface ReplArgs {
12
+ /** Display a service name in the prompt */
13
+ serviceName: string;
14
+ /**
15
+ * A DB object. If it exposes a db.sequelize.close() function, it will be called when the REPL is
16
+ * closed.
17
+ */
18
+ db?: DBLikeObject;
19
+ srv?: Record<string, unknown>;
20
+ /** Extra properties to attach to the REPL context */
21
+ extraContext?: Record<string, unknown>;
22
+ onClose?: ReplCloseFunc;
23
+ historyFile?: string;
24
+ }
25
+ /** Start the REPL prompt */
26
+ export declare const startRepl: ({ serviceName, db, srv, extraContext, onClose, historyFile, }: ReplArgs) => void;
27
+ export {};
package/lib/repl.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2021 Gabriel Paul "Cley Faye" Risterucci
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ */
27
+ "use strict";
28
+ var __importDefault = (this && this.__importDefault) || function (mod) {
29
+ return (mod && mod.__esModule) ? mod : { "default": mod };
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.startRepl = void 0;
33
+ const repl_1 = __importDefault(require("repl"));
34
+ const setupContext = (r, db, srv, extraContext) => {
35
+ const doContextSetup = () => {
36
+ Object.assign(r.context, {
37
+ ...extraContext,
38
+ db,
39
+ srv,
40
+ });
41
+ };
42
+ doContextSetup();
43
+ r.on("reset", doContextSetup);
44
+ };
45
+ /** Configure action when the REPL is closed */
46
+ const setupClose = (r, db, onClose) => {
47
+ if (!db && !onClose)
48
+ return;
49
+ r.on("exit", () => {
50
+ if (db?.sequelize?.close) {
51
+ db.sequelize.close();
52
+ }
53
+ if (onClose) {
54
+ onClose();
55
+ }
56
+ });
57
+ };
58
+ /** Start the REPL prompt */
59
+ const startRepl = ({ serviceName = "", db, srv, extraContext, onClose, historyFile = ".node_repl_history", }) => {
60
+ const r = repl_1.default.start({
61
+ prompt: `${serviceName}> `,
62
+ breakEvalOnSigint: true,
63
+ });
64
+ setupContext(r, db, srv, extraContext);
65
+ setupClose(r, db, onClose);
66
+ r.setupHistory(historyFile, () => { });
67
+ };
68
+ exports.startRepl = startRepl;
package/lib/winston.d.ts CHANGED
@@ -1,3 +1,17 @@
1
1
  import winston from "winston";
2
+ /**
3
+ * Collapse all lines containing /node_modules/ into an ellipsis
4
+ */
5
+ export declare const filterNodeModules: (message: string) => Generator<string>;
6
+ /**
7
+ * Prefix all lines with the level and the timestamp if needed
8
+ */
9
+ export declare const prefixOutput: (level: string, message: string, timestamp: boolean | undefined) => string;
10
+ export interface LogConfig {
11
+ timestamp: boolean;
12
+ collapseNodeModules: boolean;
13
+ }
14
+ /** Edit the configuration applied to consoleLogger */
15
+ export declare const setConfig: (config: LogConfig) => void;
2
16
  export declare const transports: winston.transports.ConsoleTransportInstance[];
3
17
  export declare const consoleLogger: winston.Logger;
package/lib/winston.js CHANGED
@@ -29,11 +29,61 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
29
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.consoleLogger = exports.transports = void 0;
32
+ exports.consoleLogger = exports.transports = exports.setConfig = exports.prefixOutput = exports.filterNodeModules = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
+ // High value because of colorize()
35
+ const LOG_LEVEL_PADDING_SIZE = 19;
36
+ /**
37
+ * Collapse all lines containing /node_modules/ into an ellipsis
38
+ */
39
+ const filterNodeModules = function* (message) {
40
+ let inNodeModules = false;
41
+ const lines = message.split("\n");
42
+ for (const line of lines) {
43
+ if (/\/node_modules\//u.exec(line)) {
44
+ if (!inNodeModules) {
45
+ inNodeModules = true;
46
+ yield "[...]";
47
+ }
48
+ }
49
+ else {
50
+ inNodeModules = false;
51
+ yield line;
52
+ }
53
+ }
54
+ };
55
+ exports.filterNodeModules = filterNodeModules;
56
+ /**
57
+ * Prefix all lines with the level and the timestamp if needed
58
+ */
59
+ const prefixOutput = (level, message, timestamp) => {
60
+ const timestampPrefix = timestamp
61
+ ? `${new Date().toISOString()} `
62
+ : "";
63
+ const levelPrefix = `${level.toString().padStart(LOG_LEVEL_PADDING_SIZE)}: `;
64
+ return message.split("\n").map(line => `${timestampPrefix}${levelPrefix}${line}`)
65
+ .join("\n");
66
+ };
67
+ exports.prefixOutput = prefixOutput;
68
+ const logConfig = {
69
+ timestamp: true,
70
+ collapseNodeModules: true,
71
+ };
72
+ const customFormat = winston_1.default.format.printf((info) => {
73
+ const message = ("stack" in info) ? info.stack : info.message;
74
+ const filteredMessage = logConfig.collapseNodeModules
75
+ ? [...(0, exports.filterNodeModules)(message)].join("\n")
76
+ : message;
77
+ return (0, exports.prefixOutput)(info.level, filteredMessage, logConfig.timestamp);
78
+ });
79
+ /** Edit the configuration applied to consoleLogger */
80
+ const setConfig = (config) => {
81
+ Object.assign(logConfig, config);
82
+ };
83
+ exports.setConfig = setConfig;
34
84
  exports.transports = [new winston_1.default.transports.Console()];
35
85
  exports.consoleLogger = winston_1.default.createLogger({
36
86
  level: "info",
37
- format: winston_1.default.format.combine(winston_1.default.format.colorize(), winston_1.default.format.simple()),
87
+ format: winston_1.default.format.combine(winston_1.default.format.colorize(), customFormat),
38
88
  transports: exports.transports,
39
89
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cley_faye/boilerplate",
3
- "version": "3.2.2",
3
+ "version": "3.5.1",
4
4
  "description": "Boilerplate code generator for generic projects",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,15 +17,16 @@
17
17
  },
18
18
  "homepage": "https://github.com/CleyFaye/boilerplate#readme",
19
19
  "devDependencies": {
20
- "@keeex/eslint-config": "^1.5.9",
20
+ "@keeex/eslint-config": "^1.7.1",
21
21
  "@types/express": "^4.17.11",
22
22
  "@types/grunt": "^0.4.25",
23
23
  "@types/http-errors": "^1.8.0",
24
24
  "@types/node": "^16.0.0",
25
- "@typescript-eslint/eslint-plugin": "^5.3.1",
26
- "@typescript-eslint/parser": "^5.3.1",
27
- "eslint": "^7.20.0",
28
- "eslint-plugin-promise": "^5.1.1",
25
+ "@typescript-eslint/eslint-plugin": "^5.12.0",
26
+ "@typescript-eslint/parser": "^5.12.0",
27
+ "eslint": "^8.7.0",
28
+ "eslint-plugin-import": "^2.25.4",
29
+ "eslint-plugin-promise": "^6.0.0",
29
30
  "eslint-webpack-plugin": "^3.0.1",
30
31
  "express-winston": "^4.0.5",
31
32
  "grunt": "^1.4.1",
@@ -33,6 +34,7 @@
33
34
  "grunt-contrib-clean": "^2.0.0",
34
35
  "grunt-run": "^0.8.1",
35
36
  "load-grunt-tasks": "^5.1.0",
37
+ "logform": "^2.3.2",
36
38
  "typescript": "^4.1.5",
37
39
  "winston": "^3.3.3"
38
40
  },
@@ -53,7 +55,9 @@
53
55
  "grunt-contrib-watch": "1.x",
54
56
  "grunt-sass": "3.x",
55
57
  "grunt-webpack": "5.x",
58
+ "resolve-typescript-plugin": "^1.1.1",
56
59
  "sass": "1.x",
60
+ "ts-loader": "^9.2.6",
57
61
  "winston": "3.x"
58
62
  },
59
63
  "peerDependenciesMeta": {