web_plsql 0.15.1 → 0.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.
@@ -0,0 +1,53 @@
1
+ /*
2
+ * Html utilities
3
+ */
4
+
5
+ /**
6
+ * Escape html string.
7
+ *
8
+ * @param {string} value - The value.
9
+ * @returns {string} - The escaped value.
10
+ */
11
+ export const escapeHtml = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
12
+
13
+ /**
14
+ * Convert LF and/or CR to <br>
15
+ * @param {string} text - The text to convert.
16
+ * @returns {string} - The converted text.
17
+ */
18
+ export const convertAsciiToHtml = (text) => {
19
+ let html = escapeHtml(text);
20
+
21
+ html = html.replace(/(?:\r\n|\r|\n)/g, '<br />');
22
+ html = html.replace(/\t/g, '&nbsp;&nbsp;&nbsp;');
23
+
24
+ return html;
25
+ };
26
+
27
+ /**
28
+ * get a minimal html page.
29
+ * @param {string} body - The body.
30
+ * @returns {string} - The html page.
31
+ */
32
+ export const getHtmlPage = (body) => `<!DOCTYPE html>
33
+ <html lang="en">
34
+ <head>
35
+ <meta charset="utf-8">
36
+ <title>web_plsql error page</title>
37
+ <style type="text/css">
38
+ html {
39
+ font-family: monospace, sans-serif;
40
+ font-size: 12px;
41
+ }
42
+ h1 {
43
+ font-size: 16px;
44
+ padding: 2px;
45
+ background-color: #cc0000;
46
+ }
47
+ </style>
48
+ </head>
49
+ <body>
50
+ ${body}
51
+ </body>
52
+ </html>
53
+ `;
package/src/util/trace.js CHANGED
@@ -5,6 +5,20 @@
5
5
  import * as rotatingFileStream from 'rotating-file-stream';
6
6
  import express from 'express';
7
7
  import util from 'node:util';
8
+ import oracledb from 'oracledb';
9
+ import {escapeHtml, convertAsciiToHtml} from './html.js';
10
+ import {errorToString} from './errorToString.js';
11
+
12
+ /**
13
+ * @typedef {import('express').Request} Request
14
+ * @typedef {import('../types.js').BindParameterConfig} BindParameterConfig
15
+ * @typedef {import('../types.js').environmentType} environmentType
16
+ * @typedef {{html: string; text: string}} outputType
17
+ * @typedef {{type: 'error' | 'warning' | 'trace'; message: string; timestamp?: Date | null; req?: Request | null; environment?: environmentType | null, sql?: string | null; bind?: BindParameterConfig | null}} messageType
18
+ */
19
+
20
+ const SEPARATOR_H1 = '='.repeat(100);
21
+ const SEPARATOR_H2 = '-'.repeat(30);
8
22
 
9
23
  /**
10
24
  * Return a string representation of the value.
@@ -13,7 +27,58 @@ import util from 'node:util';
13
27
  * @param {number | null} depth - Specifies the number of times to recurse while formatting object.
14
28
  * @returns {string} - The string representation.
15
29
  */
16
- export const inspect = (value, depth = null) => util.inspect(value, {showHidden: false, depth, colors: false});
30
+ export const inspect = (value, depth = null) => {
31
+ try {
32
+ return util.inspect(value, {showHidden: false, depth, colors: false});
33
+ } catch (err) {
34
+ /* empty */
35
+ }
36
+
37
+ try {
38
+ return JSON.stringify(value);
39
+ } catch (err) {
40
+ /* empty */
41
+ }
42
+
43
+ return 'Unable to convert value to string';
44
+ };
45
+
46
+ /**
47
+ * Return a tabular representation of the values.
48
+ *
49
+ * @param {string[]} head - The header values.
50
+ * @param {string[][]} body - The row values.
51
+ * @returns {outputType} - The output.
52
+ */
53
+ export const toTable = (head, body) => {
54
+ if (head.length === 0) {
55
+ throw new Error('head cannot be empty');
56
+ }
57
+
58
+ // Calculate column widths
59
+ const widths = head.map((h, i) => {
60
+ const bodyMax = Math.max(0, ...body.map((row) => (row[i] || '').length));
61
+ return Math.max(h.length, bodyMax);
62
+ });
63
+
64
+ // Build text representation
65
+ /**
66
+ * @param {string} cell - The string
67
+ * @param {number} width - The width
68
+ * @returns {string} - The result
69
+ */
70
+ const padCell = (cell, width) => cell.padEnd(width, ' ');
71
+ const textHeader = head.map((h, i) => padCell(h, widths[i])).join(' | ');
72
+ const textSeparator = widths.map((w) => '-'.repeat(w)).join('-+-');
73
+ const textRows = body.map((row) => head.map((_, i) => padCell(row[i] || '', widths[i])).join(' | '));
74
+ const text = [textHeader, textSeparator, ...textRows].join('\n');
75
+
76
+ const htmlHead = head.map((h) => `<th>${escapeHtml(h)}</th>`).join('');
77
+ const htmlBody = body.map((row) => `<tr>${head.map((_, i) => `<td>${escapeHtml(row[i] || '')}</td>`).join('')}</tr>`).join('');
78
+ const html = `<table><thead><tr>${htmlHead}</tr></thead><tbody>${htmlBody}</tbody></table>`;
79
+
80
+ return {text, html};
81
+ };
17
82
 
18
83
  /**
19
84
  * Log text to the console and to a file.
@@ -40,7 +105,7 @@ export const logToFile = (text) => {
40
105
  * @param {boolean} simple - Set to false to see all public properties of the request.
41
106
  * @returns {string} - The string representation.
42
107
  */
43
- export const inspectRequest = (req, simple = true) => {
108
+ const inspectRequest = (req, simple = true) => {
44
109
  /** @type {Record<string, unknown>} */
45
110
  const requestData = {};
46
111
 
@@ -55,20 +120,206 @@ export const inspectRequest = (req, simple = true) => {
55
120
  return inspect(requestData);
56
121
  };
57
122
 
123
+ /**
124
+ * Return a string representation of the bind parameter.
125
+ * @param {number | undefined} dir - The direction.
126
+ * @returns {string} The string.
127
+ */
128
+ const dirToString = (dir) => {
129
+ switch (dir) {
130
+ case oracledb.BIND_IN:
131
+ return 'IN';
132
+ case oracledb.BIND_OUT:
133
+ return 'OUT';
134
+ case oracledb.BIND_INOUT:
135
+ return 'INOUT';
136
+ default:
137
+ return '';
138
+ }
139
+ };
140
+
141
+ /**
142
+ * Return a string representation of the bind type.
143
+ * @param {oracledb.DbType | string | number | undefined} type - The type.
144
+ * @returns {string} The string.
145
+ */
146
+ const bindTypeToString = (type) => {
147
+ if (typeof type === 'object' && 'name' in type) {
148
+ return type.name;
149
+ }
150
+
151
+ if (typeof type === 'string') {
152
+ return type;
153
+ }
154
+
155
+ if (typeof type === 'number') {
156
+ return type.toString();
157
+ }
158
+
159
+ return '';
160
+ };
161
+
162
+ /**
163
+ * Return a string representation of the bind parameter.
164
+ * @param {outputType} output - The output.
165
+ * @param {BindParameterConfig} bind - The bind parameters.
166
+ * @returns {undefined}
167
+ */
168
+ const inspectBindParameter = (output, bind) => {
169
+ const rows = Object.entries(bind);
170
+
171
+ if (rows.length === 0) {
172
+ return;
173
+ }
174
+
175
+ const body = rows.map(([id, row]) => {
176
+ const dir = dirToString(row.dir);
177
+ const maxArraySize = row.maxArraySize ? row.maxArraySize.toString() : '';
178
+ const maxSize = row.maxSize ? row.maxSize.toString() : '';
179
+ const bindType = bindTypeToString(row.type);
180
+ const value = inspect(row.val);
181
+ const valueType = typeof row.val;
182
+
183
+ return [id, dir, maxArraySize, maxSize, bindType, value, valueType];
184
+ });
185
+
186
+ const {html, text} = toTable(['id', 'dir', 'maxArraySize', 'maxSize', 'bind type', 'value', 'value type'], body);
187
+
188
+ output.html += html;
189
+ output.text += text;
190
+ };
191
+
192
+ /**
193
+ * Add environment
194
+ * @param {outputType} output - The output.
195
+ * @param {environmentType} environment - The environment.
196
+ */
197
+ const inspectEnvironment = (output, environment) => {
198
+ const rows = Object.entries(environment);
199
+
200
+ if (rows.length === 0) {
201
+ return;
202
+ }
203
+
204
+ const {html, text} = toTable(['key', 'value'], rows);
205
+
206
+ output.html += html;
207
+ output.text += text;
208
+ };
209
+
58
210
  /**
59
211
  * Get a block.
60
212
  * @param {string} title - The name.
61
213
  * @param {string} body - The name.
62
214
  * @returns {string} - The text.
63
215
  */
64
- export const getBlock = (title, body) => {
65
- const SEPARATOR = '-'.repeat(30);
216
+ export const getBlock = (title, body) => `\n${SEPARATOR_H2}${title.toUpperCase()}${SEPARATOR_H2}\n${body}`;
217
+
218
+ /**
219
+ * Get line html
220
+ * @param {string} text - The text.
221
+ * @returns {string} - The line.
222
+ */
223
+ const getLineHtml = (text) => `<p>${convertAsciiToHtml(text)}</p>`;
224
+
225
+ /**
226
+ * Get line text
227
+ * @param {string} text - The text.
228
+ * @returns {string} - The line.
229
+ */
230
+ const getLineText = (text) => `${text}\n`;
231
+
232
+ /**
233
+ * Add line
234
+ * @param {outputType} output - The output.
235
+ * @param {string} text - The text to convert.
236
+ */
237
+ const addLine = (output, text) => {
238
+ output.html += getLineHtml(text);
239
+ output.text += getLineText(text);
240
+ };
241
+
242
+ /**
243
+ * Add header
244
+ * @param {outputType} output - The output.
245
+ * @param {string} text - The text to convert.
246
+ */
247
+ const addHeader = (output, text) => {
248
+ output.html += `<h2>${text}</h2>`;
249
+ output.text += `\n${text}\n${'-'.repeat(text.length)}\n`;
250
+ };
251
+
252
+ /**
253
+ * Add procedure
254
+ * @param {outputType} output - The output.
255
+ * @param {string} sql - The SQL to execute.
256
+ * @param {BindParameterConfig} bind - The bind parameters.
257
+ */
258
+ const addProcedure = (output, sql, bind) => {
259
+ output.html += `${sql}<br><br>`;
260
+ output.text += `${sql}\n\n`;
66
261
 
67
- return `\n${SEPARATOR}${title.toUpperCase()}${SEPARATOR}\n${body}`;
262
+ try {
263
+ inspectBindParameter(output, bind);
264
+ } catch (err) {
265
+ addLine(output, `Unable to inspect bind parameter: ${errorToString(err)}`);
266
+ }
267
+
268
+ output.html += `<br>`;
269
+ output.text += `\n`;
68
270
  };
69
271
 
70
272
  /**
71
- * Get a timestamp
72
- * @returns {string} - The timestamp.
273
+ * Get a formatted message.
274
+ * @param {messageType} para - The req object represents the HTTP request.
275
+ * @returns {outputType} - The output.
73
276
  */
74
- export const getTimestamp = () => new Date().toISOString();
277
+ export const getFormattedMessage = (para) => {
278
+ const timestamp = para.timestamp ?? new Date();
279
+
280
+ // header
281
+ const url = typeof para.req?.originalUrl === 'string' && para.req.originalUrl.length > 0 ? ` on ${para.req.originalUrl}` : '';
282
+ const header = `${para.type.toUpperCase()} at ${timestamp.toUTCString()}${url}`;
283
+ const output = {
284
+ html: `<h1>${header}</h1>`,
285
+ text: `\n\n${SEPARATOR_H1}\n== ${header}\n${SEPARATOR_H1}\n`,
286
+ };
287
+
288
+ // error
289
+ addHeader(output, 'ERROR');
290
+ addLine(output, para.message);
291
+
292
+ // request
293
+ if (para.req) {
294
+ addHeader(output, 'REQUEST');
295
+ addLine(output, inspectRequest(para.req));
296
+ }
297
+
298
+ // parameters
299
+ if (para.sql && para.bind) {
300
+ addHeader(output, 'PROCEDURE');
301
+ addProcedure(output, para.sql, para.bind);
302
+ }
303
+
304
+ // environment
305
+ if (para.environment) {
306
+ addHeader(output, 'ENVIRONMENT');
307
+ inspectEnvironment(output, para.environment);
308
+ }
309
+
310
+ return output;
311
+ };
312
+
313
+ /**
314
+ * Log a warning message.
315
+ * @param {messageType} para - The req object represents the HTTP request.
316
+ */
317
+ export const warningMessage = (para) => {
318
+ const {text} = getFormattedMessage(para);
319
+
320
+ // trace to file
321
+ logToFile(text);
322
+
323
+ // console
324
+ console.warn(text);
325
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Get duration as human readable string.
3
+ * @param {number} duration - Milliseconds.
4
+ * @returns {string} String.
5
+ */
6
+ export const humanDuration = (duration) => {
7
+ if (!Number.isFinite(duration)) return 'invalid';
8
+
9
+ const ms = Math.floor(duration % 1000);
10
+ const s = Math.floor((duration / 1000) % 60);
11
+ const m = Math.floor((duration / (1000 * 60)) % 60);
12
+ const h = Math.floor((duration / (1000 * 60 * 60)) % 24);
13
+ const d = Math.floor(duration / (1000 * 60 * 60 * 24));
14
+
15
+ const parts = [];
16
+ if (d) parts.push(`${d}d`);
17
+ if (h) parts.push(`${h}h`);
18
+ if (m) parts.push(`${m}m`);
19
+ if (s) parts.push(`${s}s`);
20
+ if (ms || !parts.length) parts.push(`${ms}ms`);
21
+
22
+ return parts.join(' ');
23
+ };
24
+
25
+ /**
26
+ * Convert a string to a number
27
+ *
28
+ * @param {unknown} value - The string to convert
29
+ * @returns {number | null} The number or null if the string could not be converted
30
+ */
31
+ export const stringToNumber = (value) => {
32
+ // is the value already of type number?
33
+ if (typeof value === 'number') {
34
+ return !Number.isNaN(value) && Number.isFinite(value) ? value : null;
35
+ }
36
+
37
+ // Test for invalid characters
38
+ if (typeof value !== 'string' || !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:E[+-]?\d+)?$/i.test(value)) {
39
+ return null;
40
+ }
41
+
42
+ // Convert value to a number
43
+ const num = Number(value);
44
+ return Number.isNaN(num) ? null : num;
45
+ };
46
+
47
+ /**
48
+ * Convert a string to a integer
49
+ *
50
+ * @param {unknown} value - The value to convert
51
+ * @returns {number | null} The integer or null if the string could not be converted
52
+ */
53
+ export const stringToInteger = (value) => {
54
+ // is the value already a "real" integer, we just return the value
55
+ if (typeof value === 'number' && Number.isInteger(value)) {
56
+ return value;
57
+ }
58
+
59
+ // try to convert value to a number
60
+ const num = stringToNumber(value);
61
+ if (num === null || !Number.isInteger(num)) {
62
+ return null;
63
+ }
64
+
65
+ return num;
66
+ };
@@ -1,14 +1,17 @@
1
- export function getProcedureNamed(procName: string, argObj: argObjType, databaseConnection: Connection, options: configPlSqlHandlerType): Promise<{
1
+ export function getBinding(argName: string, argValue: unknown, argType: string): BindParameter;
2
+ export function getProcedureNamed(req: Request, procName: string, argObj: argObjType, databaseConnection: Connection): Promise<{
2
3
  sql: string;
3
4
  bind: BindParameterConfig;
4
5
  }>;
5
- export type argsType = Record<string, string>;
6
- export type cacheEntryType = {
7
- hitCount: number;
8
- args: argsType;
9
- };
6
+ export type Request = import("express").Request;
10
7
  export type Connection = import("oracledb").Connection;
11
8
  export type Result = import("oracledb").Result<unknown>;
12
9
  export type configPlSqlHandlerType = import("../../types.js").configPlSqlHandlerType;
13
10
  export type argObjType = import("../../types.js").argObjType;
14
11
  export type BindParameterConfig = import("../../types.js").BindParameterConfig;
12
+ export type BindParameter = import("../../types.js").BindParameter;
13
+ export type argsType = Record<string, string>;
14
+ export type cacheEntryType = {
15
+ hitCount: number;
16
+ args: argsType;
17
+ };
@@ -1,7 +1,8 @@
1
- export function getProcedureVariable(procName: string, argObj: argObjType, databaseConnection: Connection, options: configPlSqlHandlerType): Promise<{
1
+ export function getProcedureVariable(req: Request, procName: string, argObj: argObjType): {
2
2
  sql: string;
3
3
  bind: BindParameterConfig;
4
- }>;
4
+ };
5
+ export type Request = import("express").Request;
5
6
  export type Connection = import("oracledb").Connection;
6
7
  export type Result = import("oracledb").Result<unknown>;
7
8
  export type configPlSqlHandlerType = import("../../types.js").configPlSqlHandlerType;
@@ -0,0 +1,3 @@
1
+ export function escapeHtml(value: string): string;
2
+ export function convertAsciiToHtml(text: string): string;
3
+ export function getHtmlPage(body: string): string;
@@ -1,6 +1,22 @@
1
1
  export function inspect(value: unknown, depth?: number | null): string;
2
+ export function toTable(head: string[], body: string[][]): outputType;
2
3
  export function logToFile(text: string): void;
3
- export function inspectRequest(req: express.Request, simple?: boolean): string;
4
4
  export function getBlock(title: string, body: string): string;
5
- export function getTimestamp(): string;
6
- import express from 'express';
5
+ export function getFormattedMessage(para: messageType): outputType;
6
+ export function warningMessage(para: messageType): void;
7
+ export type Request = import("express").Request;
8
+ export type BindParameterConfig = import("../types.js").BindParameterConfig;
9
+ export type environmentType = import("../types.js").environmentType;
10
+ export type outputType = {
11
+ html: string;
12
+ text: string;
13
+ };
14
+ export type messageType = {
15
+ type: "error" | "warning" | "trace";
16
+ message: string;
17
+ timestamp?: Date | null;
18
+ req?: Request | null;
19
+ environment?: environmentType | null;
20
+ sql?: string | null;
21
+ bind?: BindParameterConfig | null;
22
+ };
@@ -0,0 +1,3 @@
1
+ export function humanDuration(duration: number): string;
2
+ export function stringToNumber(value: unknown): number | null;
3
+ export function stringToInteger(value: unknown): number | null;
package/src/util/date.js DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * Get duration as human readable string.
3
- * @param {number} duration - Milliseconds.
4
- * @returns {string} String.
5
- */
6
- export const humanDuration = (duration) => {
7
- if (!Number.isFinite(duration)) return 'invalid';
8
-
9
- const ms = Math.floor(duration % 1000);
10
- const s = Math.floor((duration / 1000) % 60);
11
- const m = Math.floor((duration / (1000 * 60)) % 60);
12
- const h = Math.floor((duration / (1000 * 60 * 60)) % 24);
13
- const d = Math.floor(duration / (1000 * 60 * 60 * 24));
14
-
15
- const parts = [];
16
- if (d) parts.push(`${d}d`);
17
- if (h) parts.push(`${h}h`);
18
- if (m) parts.push(`${m}m`);
19
- if (s) parts.push(`${s}s`);
20
- if (ms || !parts.length) parts.push(`${ms}ms`);
21
-
22
- return parts.join(' ');
23
- };