@cley_faye/boilerplate 3.16.0 → 3.17.0

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
@@ -486,6 +486,10 @@ Available config options are:
486
486
  - `staticRootDirectories`: optional, name of directories (in the above root directory) to serve as
487
487
  static files. Defaults to `["js", "css", "img"]`.
488
488
 
489
+ A convenience command is available as "serve_spa" to be called from the command line.
490
+ It is possible to pass it some parameters; run it with `--help` for more informations.
491
+ To use this tool, `minimist` must be installed in addition to express dependencies.
492
+
489
493
  Console logging
490
494
  ---------------
491
495
  For convenience, a winston logger using console as output is provided:
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // eslint-disable-next-line import/no-unresolved
3
+ import("../lib/bin/serve_spa.js");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,113 @@
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
29
+ if (k2 === undefined) k2 = k;
30
+ var desc = Object.getOwnPropertyDescriptor(m, k);
31
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
32
+ desc = { enumerable: true, get: function() { return m[k]; } };
33
+ }
34
+ Object.defineProperty(o, k2, desc);
35
+ }) : (function(o, m, k, k2) {
36
+ if (k2 === undefined) k2 = k;
37
+ o[k2] = m[k];
38
+ }));
39
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
40
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
41
+ }) : function(o, v) {
42
+ o["default"] = v;
43
+ });
44
+ var __importStar = (this && this.__importStar) || function (mod) {
45
+ if (mod && mod.__esModule) return mod;
46
+ var result = {};
47
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
48
+ __setModuleDefault(result, mod);
49
+ return result;
50
+ };
51
+ var __importDefault = (this && this.__importDefault) || function (mod) {
52
+ return (mod && mod.__esModule) ? mod : { "default": mod };
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ const path = __importStar(require("node:path"));
56
+ const express_1 = __importDefault(require("express"));
57
+ const minimist_1 = __importDefault(require("minimist"));
58
+ const singlepageapp_js_1 = require("../express/middlewares/singlepageapp.js");
59
+ const express_js_1 = require("../express.js");
60
+ const winston_js_1 = require("../winston.js");
61
+ const ARGV_START_OFFSET = 2;
62
+ const { port, root, index, help, static: staticDirs } = (0, minimist_1.default)(process.argv.slice(ARGV_START_OFFSET));
63
+ const DEFAULT_PORT = 3000;
64
+ const DEFAULT_PATH = path.join("dist", "webapp");
65
+ const DEFAULT_INDEX = "index.html";
66
+ const DEFAULT_STATIC = ["js", "css", "img"];
67
+ if (help) {
68
+ winston_js_1.consoleLogger.info(`
69
+ Usage:
70
+
71
+ serve_spa \\
72
+ [--port=${DEFAULT_PORT}] \\
73
+ [--root=${DEFAULT_PATH}] \\
74
+ [--index=${DEFAULT_INDEX}] \\
75
+ [--static=js…] \\
76
+ [--help]
77
+
78
+ The --static argument can be repeated to add more directories to it.
79
+ It defaults to ${JSON.stringify(DEFAULT_STATIC)}.
80
+ `.trim());
81
+ // eslint-disable-next-line no-process-exit
82
+ process.exit(0);
83
+ }
84
+ const getPort = () => port ?? DEFAULT_PORT;
85
+ const getStatic = () => {
86
+ if (!staticDirs)
87
+ return;
88
+ return Array.isArray(staticDirs) ? staticDirs : [staticDirs];
89
+ };
90
+ const app = (0, express_1.default)();
91
+ app.use((0, express_js_1.createPipeline)({
92
+ routes: (0, singlepageapp_js_1.singlePageApp)({
93
+ rootDir: root ?? "dist/webapp",
94
+ htmlFile: index,
95
+ staticRootDirectories: getStatic(),
96
+ }),
97
+ options: {
98
+ defaultErrorHandler: true,
99
+ log: {
100
+ route: true,
101
+ error: true,
102
+ logger: winston_js_1.consoleLogger,
103
+ },
104
+ },
105
+ }));
106
+ (0, express_js_1.appStart)({
107
+ app,
108
+ port: getPort(),
109
+ logger: winston_js_1.consoleLogger,
110
+ }).then(({ port: activePort }) => {
111
+ winston_js_1.consoleLogger.info(`SPA served on port ${activePort}`);
112
+ })
113
+ .catch(winston_js_1.consoleLogger.error);
@@ -80,7 +80,10 @@ const singlePageApp = (config) => {
80
80
  for (const candidates of staticDirs)
81
81
  if (req.url.startsWith(candidates))
82
82
  return next();
83
- res.sendFile(htmlFile, { root: rootDir }, (err) => next(err));
83
+ res.sendFile(htmlFile, { root: rootDir }, (err) => {
84
+ if (err)
85
+ return next(err);
86
+ });
84
87
  };
85
88
  const staticRoute = express_1.default.static(rootDir);
86
89
  return [appRoute, staticRoute];
@@ -32,15 +32,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
32
32
  const express_1 = __importDefault(require("express"));
33
33
  const winston_js_1 = require("../winston.js");
34
34
  const logger_js_1 = require("./logger.js");
35
+ const unprocessableentityerror_js_1 = require("./unprocessableentityerror.js");
36
+ const getErrorData = (error) => {
37
+ const unprocessable = (0, unprocessableentityerror_js_1.get422Fields)(error);
38
+ if (unprocessable) {
39
+ return {
40
+ message: unprocessable.message,
41
+ extraFields: { fields: unprocessable.fields, errors: unprocessable.errors },
42
+ };
43
+ }
44
+ return error.expose ? { message: error.message } : {};
45
+ };
35
46
  const defaultErrorHandler = (errorHandlerConfig) => (err, req, res, next) => {
36
47
  const noErrorFilter = typeof errorHandlerConfig === "boolean"
37
48
  ? false
38
49
  : Boolean(errorHandlerConfig.noErrorFilter);
39
50
  if (!res.headersSent) {
40
51
  if (err.statusCode) {
41
- const message = err.expose
42
- ? err.message
43
- : undefined;
52
+ const errorData = getErrorData(err);
44
53
  const accepted = req.accepts([
45
54
  "text",
46
55
  "html",
@@ -49,12 +58,13 @@ const defaultErrorHandler = (errorHandlerConfig) => (err, req, res, next) => {
49
58
  if (accepted === "json") {
50
59
  res.status(err.statusCode).send({
51
60
  statusCode: err.statusCode,
52
- message,
61
+ message: errorData.message,
62
+ ...errorData.extraFields,
53
63
  });
54
64
  return;
55
65
  }
56
- if (message) {
57
- res.status(err.statusCode).send(message);
66
+ if (errorData.message) {
67
+ res.status(err.statusCode).send(errorData.message);
58
68
  }
59
69
  else {
60
70
  res.sendStatus(err.statusCode);
@@ -0,0 +1,8 @@
1
+ import { ExtendedError } from "../winston.js";
2
+ interface Error422Fields {
3
+ message: string;
4
+ fields: Array<string>;
5
+ errors: Array<unknown>;
6
+ }
7
+ export declare const get422Fields: (error: ExtendedError) => Error422Fields | undefined;
8
+ export {};
@@ -0,0 +1,57 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.get422Fields = void 0;
30
+ const UNPROCESSABLE_ENTITY = 422;
31
+ const get422Fields = (error) => {
32
+ const { statusCode, cause, fields } = error;
33
+ if (statusCode !== UNPROCESSABLE_ENTITY
34
+ || !cause
35
+ || !Array.isArray(cause)
36
+ || !fields
37
+ || !Array.isArray(fields)) {
38
+ return;
39
+ }
40
+ let fieldsStr;
41
+ try {
42
+ fieldsStr = JSON.stringify(fields);
43
+ }
44
+ catch {
45
+ fieldsStr = "<error>";
46
+ }
47
+ let errorsStr;
48
+ try {
49
+ errorsStr = JSON.stringify(cause);
50
+ }
51
+ catch {
52
+ errorsStr = "<error>";
53
+ }
54
+ const message = `${error.message}: fields=${fieldsStr}, errors=${errorsStr}`;
55
+ return { message, fields, errors: cause };
56
+ };
57
+ exports.get422Fields = get422Fields;
package/lib/winston.d.ts CHANGED
@@ -23,9 +23,11 @@ interface ExtendedErrorFields {
23
23
  request?: {
24
24
  _currentUrl?: string;
25
25
  };
26
+ fields?: Set<string>;
26
27
  statusCode?: number;
28
+ expose?: boolean;
27
29
  }
28
- type ExtendedError = Error & ExtendedErrorFields;
30
+ export type ExtendedError = Error & ExtendedErrorFields;
29
31
  /** Return a string with the full error and stacktrace, including causes */
30
32
  export declare const filterError: (error: ExtendedError, collapseStacktrace?: boolean, extraFilter?: Array<RegExp> | RegExp) => string;
31
33
  export declare const customFormat: (timestamp?: boolean, collapseStacktrace?: boolean, stacktraceFilter?: Array<RegExp> | RegExp) => Format;
package/lib/winston.js CHANGED
@@ -31,6 +31,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  exports.consoleLogger = exports.transports = exports.setConfig = exports.customFormat = exports.filterError = exports.prefixOutput = exports.filterStacktrace = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
+ const unprocessableentityerror_js_1 = require("./express/unprocessableentityerror.js");
34
35
  const LOG_LEVEL_PADDING_SIZE = 10;
35
36
  const stackFilterRegex = /(?:at process|at runMicrotasks)/u;
36
37
  const isFiltered = (line, extraFilter) => {
@@ -150,9 +151,20 @@ const getCause = (error) => {
150
151
  return new Error("Unknown cause");
151
152
  }
152
153
  };
154
+ /** Handle 422
155
+ *
156
+ * If return a string, do not process the error normally.
157
+ */
158
+ const process422Error = (error) => {
159
+ const errorInfo = (0, unprocessableentityerror_js_1.get422Fields)(error);
160
+ return errorInfo?.message;
161
+ };
153
162
  /** Return a string with the full error and stacktrace, including causes */
154
163
  const filterError = (error, collapseStacktrace = true, extraFilter) => {
155
164
  const resultRows = [];
165
+ const unprocessableCheck = process422Error(error);
166
+ if (unprocessableCheck)
167
+ return unprocessableCheck;
156
168
  let cursor = error;
157
169
  let indentLevel = 0;
158
170
  while (cursor) {
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@cley_faye/boilerplate",
3
- "version": "3.16.0",
3
+ "version": "3.17.0",
4
4
  "description": "Boilerplate code generator for generic projects",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/CleyFaye/boilerplate.git"
8
8
  },
9
+ "bin": {
10
+ "serve_spa": "bin/serve_spa.js"
11
+ },
9
12
  "scripts": {
10
13
  "prepack": "npm run grunt -- clean build",
11
14
  "check": "tsc --noEmit && eslint .",
@@ -22,6 +25,7 @@
22
25
  "@types/express": "^4.17.17",
23
26
  "@types/grunt": "^0.4.27",
24
27
  "@types/http-errors": "^2.0.1",
28
+ "@types/minimist": "^1.2.2",
25
29
  "@types/node": "^18.14.2",
26
30
  "@typescript-eslint/eslint-plugin": "^5.53.0",
27
31
  "@typescript-eslint/parser": "^5.53.0",
@@ -58,6 +62,7 @@
58
62
  "grunt-contrib-watch": "1.x",
59
63
  "grunt-sass": "3.x",
60
64
  "grunt-webpack": "5.x",
65
+ "minimist": "^1.2.8",
61
66
  "sass": "1.x",
62
67
  "ts-loader": "^9.4.1",
63
68
  "winston": "3.x"
@@ -111,6 +116,9 @@
111
116
  "grunt-webpack": {
112
117
  "optional": true
113
118
  },
119
+ "minimist": {
120
+ "optional": true
121
+ },
114
122
  "sass": {
115
123
  "optional": true
116
124
  },