utilitas 1990.1.29 → 1990.1.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.
@@ -0,0 +1,39 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
3
+
4
+ name: Node.js Package
5
+
6
+ on:
7
+ push:
8
+ branches: [ master ]
9
+ pull_request:
10
+ branches: [ master ]
11
+
12
+ jobs:
13
+ build:
14
+ runs-on: ubuntu-latest
15
+ if: "!startsWith(github.event.head_commit.message, '[RELEASE]')"
16
+ steps:
17
+ - uses: actions/checkout@v3
18
+ with:
19
+ token: ${{ secrets.GITHUB_TOKEN }}
20
+ - uses: actions/setup-node@v3
21
+ with:
22
+ node-version: 18
23
+ registry-url: https://registry.npmjs.org/
24
+ - run: git config --global user.name 'Leask Wong'
25
+ - run: git config --global user.email 'i@leaskh.com'
26
+ - run: npm version patch -m "[RELEASE] %s"
27
+ - run: git push
28
+ - run: npm install
29
+ - run: node build.mjs
30
+ - run: npm test
31
+ - run: npm publish
32
+ env:
33
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
34
+
35
+ # publish-npm:
36
+ # needs: build
37
+ # runs-on: ubuntu-latest
38
+ # steps:
39
+ # - uses: actions/checkout@v3
package/lib/bot.mjs CHANGED
@@ -4,9 +4,10 @@ import { ensureArray, insensitiveCompare, log as _log } from './utilitas.mjs';
4
4
  import { join } from 'path';
5
5
  import { readdirSync } from 'fs';
6
6
  import { Telegraf } from 'telegraf';
7
+ import cluster from 'cluster';
7
8
 
8
9
  const signals = ['SIGINT', 'SIGTERM'];
9
- const provider = 'TELEGRAM';
10
+ const [BOT_SEND, provider, MESSAGE] = ['BOT_SEND', 'TELEGRAM', 'message'];
10
11
  const iCmp = (strA, strB) => ~~insensitiveCompare(strA, strB, { w: true });
11
12
  const log = (cnt, opt) => _log(cnt, import.meta.url, { time: 1, ...opt || {} });
12
13
  const end = async (options) => bot && bot.stop(options?.signal);
@@ -56,34 +57,49 @@ const init = async (options) => {
56
57
  insensitiveCompare(options?.provider, provider),
57
58
  'Invalid bot provider.', 501
58
59
  );
59
- bot = new Telegraf(options?.botToken);
60
- const [mods, pmsTrain] = [[{
61
- ...subconscious, run: !options?.silent
62
- }, ...ensureArray(options?.skill)], []];
63
- for (let skillPath of ensureArray(options?.skillPath)) {
64
- log(`SKILLS: ${skillPath}`);
65
- const files = (readdirSync(skillPath) || []).filter(
66
- file => /\.mjs$/i.test(file) && !file.startsWith('.')
67
- );
68
- for (let f of files) {
69
- const m = await import(join(skillPath, f));
70
- mods.push({ ...m, name: m.name || f.replace(/^(.*)\.mjs$/i, '$1') });
60
+ if (cluster.isPrimary) {
61
+ bot = new Telegraf(options?.botToken);
62
+ const [mods, pmsTrain] = [[{
63
+ ...subconscious, run: !options?.silent
64
+ }, ...ensureArray(options?.skill)], []];
65
+ for (let skillPath of ensureArray(options?.skillPath)) {
66
+ log(`SKILLS: ${skillPath}`);
67
+ const files = (readdirSync(skillPath) || []).filter(
68
+ file => /\.mjs$/i.test(file) && !file.startsWith('.')
69
+ );
70
+ for (let f of files) {
71
+ const m = await import(join(skillPath, f));
72
+ mods.push({ ...m, name: m.name || f.replace(/^(.*)\.mjs$/i, '$1') });
73
+ }
71
74
  }
75
+ mods.map(mod => { mod.run && pmsTrain.push(load(bot, mod, options)) });
76
+ assert(pmsTrain.length, 'Invalid skill set.', 501);
77
+ await Promise.all(pmsTrain);
78
+ bot.launch();
79
+ cluster.on(MESSAGE, (worker, msg) => eventHandler(msg));
80
+ // Graceful stop
81
+ signals.map(signal => process.once(signal, () => bot.stop(signal)));
82
+ } else {
83
+ bot = {
84
+ telegram: {
85
+ sendMessage: (...args) =>
86
+ process.send({ action: BOT_SEND, data: args })
87
+ }
88
+ };
72
89
  }
73
- mods.map(mod => { mod.run && pmsTrain.push(load(bot, mod, options)) });
74
- assert(pmsTrain.length, 'Invalid skill set.', 501);
75
- await Promise.all(pmsTrain);
76
- bot.launch();
77
- // Graceful stop
78
- signals.map(signal => process.once(signal, () => bot.stop(signal)));
79
90
  }
80
91
  assert(bot, 'Bot have not been initialized.', 501);
81
92
  return bot;
82
93
  };
83
94
 
84
- const send = async (chatId, content, options) => (
85
- await init()
86
- ).telegram.sendMessage(chatId, content);
95
+ const send = async (chatId, content, options) =>
96
+ (await init()).telegram.sendMessage(chatId, content);
97
+
98
+ const eventHandler = async (msg) => {
99
+ switch (msg?.action) {
100
+ case BOT_SEND: return await send(...msg?.data || []);
101
+ }
102
+ };
87
103
 
88
104
  export default init;
89
105
  export {
package/lib/manifest.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  const manifest = {
2
2
  "name": "utilitas",
3
3
  "description": "Just another common utility for JavaScript.",
4
- "version": "1990.1.29",
4
+ "version": "1990.1.34",
5
5
  "private": false,
6
6
  "homepage": "https://github.com/Leask/utilitas",
7
7
  "main": "index.mjs",
package/lib/network.mjs CHANGED
@@ -4,7 +4,8 @@ import { ensureArray, log as _log, throwError } from './utilitas.mjs';
4
4
  import { getCurrentIp } from './shot.mjs';
5
5
  import { lookup } from 'fast-geoip';
6
6
 
7
- const log = (content) => _log(content, import.meta.url);
7
+ const isLocalhost = host => ['127.0.0.1', '::1', 'localhost'].includes(host);
8
+ const log = content => _log(content, import.meta.url);
8
9
 
9
10
  const ping = async (host, options = { timeout: 3, min_reply: 3 }) => {
10
11
  await assertExist('ping');
@@ -94,6 +95,7 @@ const getCurrentPosition = async () => {
94
95
  export {
95
96
  getCurrentPosition,
96
97
  httping,
98
+ isLocalhost,
97
99
  pickFastestHost,
98
100
  pickFastestHttpServer,
99
101
  ping,
package/lib/shot.mjs CHANGED
@@ -63,7 +63,7 @@ const get = async (url, options) => {
63
63
  ) : [];
64
64
  const meta = options?.refresh || !base ? null : await readJson(cacheMeta);
65
65
  const cache = options?.refresh || !base ? null : await ignoreErrFunc(
66
- async () => { return await fs.readFile(cacheCont); }
66
+ () => fs.readFile(cacheCont)
67
67
  );
68
68
  const headers = meta?.responseHeaders && cache ? {
69
69
  'cache-control': 'max-age=0',
@@ -75,7 +75,7 @@ const get = async (url, options) => {
75
75
  if (options.timeout) {
76
76
  const controller = new AbortController();
77
77
  fetchOptions.signal = controller.signal;
78
- timer = setTimeout(() => { controller.abort(); }, options.timeout);
78
+ timer = setTimeout(() => controller.abort(), options.timeout);
79
79
  }
80
80
  try { r = await fetch(url, fetchOptions); } catch (e) {
81
81
  throwError(e.message.includes('aborted') ? 'Timed out.' : e.message, 500);
package/lib/tape.mjs CHANGED
@@ -10,10 +10,10 @@ const consoleMap = ['log', 'info', 'debug', 'warn', 'error'];
10
10
  const trace = { trace: true };
11
11
  const [TAPE, BOT] = ['TAPE', 'BOT'];
12
12
  const [maxLength, defBufCycle, maxBufCycle] = [4096, 10, 100];
13
- const stdout = (message) => process.stdout.write(`${message}\n`);
13
+ const stdout = message => process.stdout.write(`${message}\n`);
14
14
  const log = (cnt, opt) => _log(cnt, import.meta.url, { time: 1, ...opt || {} });
15
- const getSendTxt = (arr) => arr.map(x => x[1]).join('\n');
16
- const getSndSize = (arr) => getSendTxt(arr).length;
15
+ const getSendTxt = arr => arr.map(x => x[1]).join('\n');
16
+ const getSndSize = arr => getSendTxt(arr).length;
17
17
  const getBufSize = () => maxLength * bufferCycle;
18
18
  const nextLen = () => botBuffer?.[0]?.[1].length || (maxLength + 1);
19
19
  const stringify = any => ensureString(any, trace);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "utilitas",
3
3
  "description": "Just another common utility for JavaScript.",
4
- "version": "1990.1.29",
4
+ "version": "1990.1.34",
5
5
  "private": false,
6
6
  "homepage": "https://github.com/Leask/utilitas",
7
7
  "main": "index.mjs",
@@ -16,8 +16,8 @@
16
16
  "updep": "npx ncu -u && npm install && wget https://raw.githubusercontent.com/Marak/colors.js/master/lib/styles.js -O ./lib/style.cjs",
17
17
  "gitsync": "( git commit -am \"Released @ `date`\" || true ) && git pull && git push",
18
18
  "pack": "./node_modules/.bin/webpack-cli --config webpack.config.mjs",
19
- "build": "npm run updep && ( git commit -am 'update dependencies' || true ) && npm version patch && node build.mjs && npm run pack",
20
- "prepublishOnly": "npm run build && npm run gitsync",
19
+ "build": "npm run updep && ( git commit -am 'update dependencies' || true ) && node build.mjs && npm run pack",
20
+ "pub": "npm run build && npm run gitsync",
21
21
  "beta": "npm publish --tag beta"
22
22
  },
23
23
  "author": "Leask Wong <i@leaskh.com>",