utilitas 1989.9.30 → 1989.9.34

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.
Files changed (3) hide show
  1. package/index.mjs +0 -2
  2. package/lib/tape.mjs +56 -98
  3. package/package.json +2 -4
package/index.mjs CHANGED
@@ -18,8 +18,6 @@ export * as telegraf from 'telegraf';
18
18
  export * as telesign from 'telesignsdk';
19
19
  export * as twilio from 'twilio';
20
20
  export * as uuid from 'uuid';
21
- export * as winston from 'winston';
22
- export * as winstonPapertrail from 'winston-papertrail-mproved';
23
21
 
24
22
  // features
25
23
  export * as bot from './lib/bot.mjs';
package/lib/tape.mjs CHANGED
@@ -2,75 +2,43 @@ import * as bot from './bot.mjs';
2
2
  import * as event from './event.mjs';
3
3
  import * as utilitas from './utilitas.mjs';
4
4
 
5
- // https://github.com/winstonjs/winston#logging-levels
6
- // const levels = ['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly'];
7
- // Handle, report, or silently ignore connection errors and failures
8
- const handleError = (err) => { process.stdout.write(`${err.message}\n`); };
9
- const consoleMap = { log: 'verbose', info: 0, debug: 0, warn: 0, error: 0 };
10
- const [TAPE, maxLength, defBufCycle, maxBufCycle] = ['TAPE', 4096, 10, 100];
11
- const modLog = (content) => { return utilitas.modLog(content, TAPE); };
12
- const getLogger = async () => { return (await init()).logger; };
13
- const [BOT, RSYSLOG, PAPERTRAIL] = ['BOT', 'RSYSLOG', 'PAPERTRAIL'];
5
+ const consoleMap = ['log', 'info', 'debug', 'warn', 'error'];
6
+ const [TAPE, BOT, maxLength, defBufCycle, maxBufCycle] = ['TAPE', 'BOT', 4096, 10, 100];
7
+ const stdout = (message) => { return process.stdout.write(`${message}\n`); };
8
+ const modLog = (c, o) => { utilitas.modLog(c, TAPE, { time: true, ...o || {} }); };
14
9
  const getSendTxt = (arr) => { return arr.map(x => x[1]).join('\n'); };
15
10
  const getSndSize = (arr) => { return getSendTxt(arr).length; };
16
11
  const getBufSize = () => { return maxLength * bufferCycle; };
17
12
  const nextLen = () => { return botBuffer?.[0]?.[1].length || (maxLength + 1); };
18
13
 
19
- let chatIds, tarLevel, botBuffer, bufferCycle, logger, silent, provider;
20
-
21
- // Do something after the connection to the Papertrail server is established
22
- const handleConnect = (data) => {
23
- return silent || modLog(data.replace('Papertrail', provider.toLowerCase()));
24
- };
14
+ let botBuffer, bufferCycle, chatIds, log, tarLevel;
25
15
 
26
16
  const hookConsole = () => {
27
- for (let act in consoleMap) {
28
- const tar = consoleMap[act] || act;
29
- const bakAct = `_${act}`;
30
- console[bakAct] = console[act];
31
- console[act] = function() {
32
- const s = [...arguments].map(
17
+ for (let tar of consoleMap) {
18
+ const bakTar = `_${tar}`;
19
+ console[bakTar] = console[tar];
20
+ console[tar] = function() {
21
+ console[bakTar].apply(console, arguments);
22
+ const str = [...arguments].map(
33
23
  utilitas.ensureString
34
- ).join(' ').replace(/\u001b\[\d+m/g, '');
35
- s.length && (s.length < maxLength) && logger && logger.log(tar, s);
36
- console[bakAct].apply(console, arguments);
24
+ ).join(' ').replace(/\u001b\[\d+m/g, '').split('');
25
+ while (str.length) {
26
+ const message = str.splice(0, maxLength).join('').trim();
27
+ message.length && log?.(tar, message);
28
+ }
37
29
  };
38
30
  }
39
31
  };
40
32
 
41
33
  const releaseConsole = () => {
42
- for (let act in consoleMap) {
43
- const bakAct = `_${act}`;
44
- if (!console[bakAct]) { continue; }
45
- console[act] = console[bakAct];
46
- delete console[bakAct];
34
+ for (let tar of consoleMap) {
35
+ const bakTar = `_${tar}`;
36
+ if (!console[bakTar]) { continue; }
37
+ console[tar] = console[bakTar];
38
+ delete console[bakTar];
47
39
  }
48
40
  };
49
41
 
50
- const getDefaultOptions = async (provider, options) => {
51
- const result = { program: (await utilitas.which()).name };
52
- switch (provider) { case RSYSLOG: result.disableTls = true; }
53
- // result.logFormat = (level, message) => { return message; }
54
- return Object.assign(result, options || {});
55
- };
56
-
57
- const sysLogInit = async (options) => {
58
- options = await getDefaultOptions(provider, options);
59
- const winston = await import('winston');
60
- const papertrail = await import('winston-papertrail-mproved');
61
- const papertrailConnection = new papertrail.PapertrailConnection(options);
62
- papertrailConnection.on('error', handleError);
63
- papertrailConnection.on('connect', handleConnect);
64
- const papertrailTransport = new papertrail.PapertrailTransport(
65
- papertrailConnection, options
66
- );
67
- logger = new winston.createLogger({ transports: [papertrailTransport] });
68
- return {
69
- logger,
70
- dependencies: { winston, papertrail, papertrailConnection, papertrailTransport },
71
- };
72
- };
73
-
74
42
  const addChatId = (id) => {
75
43
  return chatIds && id && !chatIds.includes(id) ? chatIds.push(id) : null;
76
44
  };
@@ -79,77 +47,67 @@ const removeChatId = (id) => {
79
47
  return chatIds && id && chatIds.includes(id) ? delete chatIds[id] : false;
80
48
  };
81
49
 
82
- const botLoggerInit = async (options) => {
83
- chatIds = utilitas.ensureArray(options?.chatId);
84
- utilitas.assert(chatIds.length, 'ChatId is required.', 501);
85
- handleConnect(`Sending logs via bot, chatId: ${chatIds.join(', ')}.`);
86
- bufferCycle = utilitas.ensureInt(
87
- options?.bufferCycle || defBufCycle, { min: 1, max: maxBufCycle }
88
- );
89
- logger = botLogger;
90
- await event.loop(
91
- botLoggerSync, ~~options?.interval || 5, ~~options?.tout || 10,
92
- ~~options?.delay, TAPE, { silent: true }
93
- );
94
- return { logger, dependencies: { bot, event } };
95
- };
96
-
97
- const botLoggerSync = async () => {
50
+ const sync = async () => {
98
51
  let f = [];
99
52
  while (getSndSize(f) + nextLen() <= maxLength) { f.push(botBuffer.shift()) }
100
53
  if (!(f = getSendTxt(f)).length) { return; };
101
54
  for (let id of chatIds) {
102
- try { await bot.send(id, f); } catch (err) { handleError(err); }
55
+ try { await bot.send(id, f); } catch (err) { stdout(err.message); }
103
56
  }
104
57
  };
105
58
 
106
- const botLogger = {
107
- log: (level, message) => {
108
- if (tarLevel !== 'verbose' && level === 'verbose') { return; }
109
- (botBuffer = botBuffer || []).push([level, message]);
110
- while (getSndSize(botBuffer) > getBufSize()) { botBuffer.shift(); }
111
- },
112
- end: () => {
113
- chatIds = undefined; botBuffer = undefined; event.end(TAPE);
114
- },
59
+ const rawLog = (level, message) => {
60
+ if (tarLevel !== 'verbose' && level === 'log') { return; }
61
+ (botBuffer = botBuffer || []).push([level, message]);
62
+ while (getSndSize(botBuffer) > getBufSize()) { botBuffer.shift(); }
115
63
  };
116
64
 
117
65
  // use options.level = 'verbose' to send console.log logs
118
66
  const init = async (options) => {
119
- let result;
120
67
  if (options) {
121
- silent = !!options?.silent;
68
+ utilitas.assert(
69
+ utilitas.insensitiveCompare(options?.provider, BOT),
70
+ `Invalid tape provider: '${options?.provider}'.`, 501
71
+ );
72
+ utilitas.assert(
73
+ (chatIds = utilitas.ensureArray(options?.chatId)).length,
74
+ 'ChatId is required.', 501
75
+ );
122
76
  tarLevel = options?.level;
123
- provider = utilitas.ensureString(options?.provider, { case: 'UP' });
124
- switch (provider) {
125
- case BOT:
126
- result = await botLoggerInit(options);
127
- break;
128
- case RSYSLOG: // prefer this one
129
- case PAPERTRAIL:
130
- result = await sysLogInit(options);
131
- break;
132
- default:
133
- utilitas.throwError(
134
- `Invalid tape provider: '${options?.provider}'.`, 501
135
- );
77
+ bufferCycle = utilitas.ensureInt(
78
+ options?.bufferCycle || defBufCycle, { min: 1, max: maxBufCycle }
79
+ );
80
+ if (!options?.silent) {
81
+ modLog(`Sending logs via bot, chatId: ${chatIds.join(', ')}.`);
136
82
  }
83
+ log = rawLog;
84
+ await event.loop(
85
+ sync, ~~options?.interval || 5, ~~options?.tout || 10,
86
+ ~~options?.delay, TAPE, { silent: true }
87
+ );
137
88
  options.noHook || hookConsole();
138
89
  }
139
- utilitas.assert(logger, 'Logger client has not been initialized.', 501);
140
- return result;
90
+ utilitas.assert(log, 'Tape has not been initialized.', 501);
91
+ return log;
141
92
  };
142
93
 
143
94
  const end = async () => {
144
95
  releaseConsole();
145
- setTimeout(() => { logger?.end?.(); modLog('Terminated.'); }, 1000);
96
+ setTimeout(async () => {
97
+ await event.end(TAPE);
98
+ botBuffer = undefined;
99
+ bufferCycle = undefined;
100
+ chatIds = undefined;
101
+ log = undefined;
102
+ tarLevel = undefined;
103
+ modLog('Terminated.');
104
+ }, 1000);
146
105
  };
147
106
 
148
107
  export default init;
149
108
  export {
150
109
  addChatId,
151
110
  end,
152
- getLogger,
153
111
  init,
154
112
  removeChatId,
155
113
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "utilitas",
3
3
  "description": "Just another common utility for Node.js.",
4
- "version": "1989.9.30",
4
+ "version": "1989.9.34",
5
5
  "private": false,
6
6
  "homepage": "https://github.com/Leask/utilitas",
7
7
  "main": "index.mjs",
@@ -43,8 +43,6 @@
43
43
  "telegraf": "^4.7.0",
44
44
  "telesignsdk": "^2.2.1",
45
45
  "twilio": "^3.74.0",
46
- "uuid": "^8.3.2",
47
- "winston": "^3.5.1",
48
- "winston-papertrail-mproved": "^1.0.7"
46
+ "uuid": "^8.3.2"
49
47
  }
50
48
  }