jsir 1.2.9 → 1.3.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/evalCode.js ADDED
@@ -0,0 +1,14 @@
1
+ const {info: $info, msg: $msg, warn: $warn, error: $error,
2
+ infoStr: $infoStr, msgStr: $msgStr, warnStr: $warnStr, errorStr: $errorStr,
3
+ tableStr: $tableStr, nableStr: $nableStr,
4
+ errorMsg: $errorMsg, errorStack: $errorStack,
5
+ importG: $import} = require("./util");
6
+ require = require("./util").requireG;
7
+ module.exports = async ($text = '', $cmdName = '', $args = [],
8
+ $cmdDir, $cmdMap, $require, $data,
9
+ $nextLine, $nextText, $setTips, $delTips,
10
+ $enter, $filterCmd) => {
11
+ const $defArgs = () => $args;
12
+ return await eval(`(async ()=>{${$text};
13
+ })()`)
14
+ }
package/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
 
2
2
  module.exports = {
3
3
  ...require('util'),
4
- ...require('ethWeb'),
5
4
  ...require('sol')
6
5
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "jsir",
3
- "version": "1.2.9",
4
- "description": "",
3
+ "version": "1.3.1",
4
+ "description": "js script manager tool",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -14,7 +14,6 @@
14
14
  "jsir-scd": "cmd/solCd.js",
15
15
  "jsir-stt": "cmd/solTt.js",
16
16
  "jsir-cleanLog": "cmd/cleanLog.js",
17
- "jsir-ethPrivateHit": "cmd/ethPrivateHit.js",
18
17
  "jsir-staticServer": "cmd/staticServer.js",
19
18
  "jsir-dirServer": "cmd/dirServer.js",
20
19
  "jsir-stop": "cmd/stop.js",
@@ -40,9 +39,7 @@
40
39
  "ethers": "^5.1.0",
41
40
  "global-dirs": "^3.0.0",
42
41
  "keccak": "^3.0.2",
43
- "md5": "^2.3.0",
44
42
  "pad": "^3.2.0",
45
- "randomhex": "^0.1.5",
46
43
  "server": "^1.0.30",
47
44
  "urlencode": "^1.1.0",
48
45
  "web3": "^1.6.1",
package/util.js CHANGED
@@ -17,6 +17,7 @@ const globalDirectories = require('global-dirs');
17
17
  const emptyFn = ()=>{}
18
18
  const dayJs = require('dayjs')
19
19
  const table = require('console.table')
20
+ const _fs = require("fs");
20
21
 
21
22
  let _globalLog = createLimitLogger2(`${setting.name}.log`, null, false)
22
23
  global.$log = str => {
@@ -28,7 +29,10 @@ global.$log = str => {
28
29
  const $log = global.$log
29
30
  let _globalDraft= createLimitLogger2(`draft.log`, null, false)
30
31
  global.$draft = str => {
31
- if (trim(str)) {
32
+ if (getType(str) === 'RegExp') {
33
+ let results = draftQuery(trim(str.source))
34
+ return results.map(i => i.split(/\n/).slice(1).join('\n'))
35
+ } else if (trim(str)) {
32
36
  _globalDraft(`---------${timeStr()}\n${str.split("\n").filter(i => trim(i)).join("\n")}`)
33
37
  }
34
38
  }
@@ -87,13 +91,88 @@ async function _buildConfig() {
87
91
  $config._buildId = setTimeout(_buildConfig, 3000);
88
92
  }
89
93
 
94
+ function isArgsMatch(text, args, callback, useMd5) {
95
+ let match = false
96
+ for (let arg of args) {
97
+ let r = true
98
+ for (let str of arg.split(',').filter(item => trim(item) !== '')) {
99
+ let reg = new RegExp(str, 'i')
100
+ if (!reg.test(text) && !(useMd5 && ('0x' + md5(text).substr(0, 8)) === str)) {
101
+ r = false
102
+ break
103
+ }
104
+ }
105
+ if (r) {
106
+ match = true
107
+ break
108
+ }
109
+ }
110
+ if (match && callback) {
111
+ callback()
112
+ }
113
+ return match
114
+ }
115
+
116
+ function draftQuery(fLine) {
117
+ let lines = []
118
+ let text = String(_fs.readFileSync(getLibDataDir() + "/log/draft.log"))
119
+ let temp = []
120
+ for (let line of text.split("\n")) {
121
+ if (!trim(line)) {
122
+ continue
123
+ }
124
+ if (line.startsWith("---------")) {
125
+ if (temp.length > 0) {
126
+ lines.push(temp.join('\n'))
127
+ }
128
+ temp = []
129
+ temp.push(warnStr(line))
130
+ } else {
131
+ temp.push(line)
132
+ }
133
+ }
134
+ if (temp.length > 0) {
135
+ lines.push(temp.join('\n'))
136
+ }
137
+
138
+ let results = []
139
+ if (!/^\d+$/.test(fLine)) {
140
+ let items = fLine.split(/\s+/).filter(i => i)
141
+ for (let line of lines) {
142
+ if (isArgsMatch(line, items.filter(item => !/^\d+$/.test(item)))) {
143
+ results.push(line)
144
+ }
145
+ }
146
+
147
+ lines = results
148
+ results = []
149
+
150
+ let nums = items.filter(item => /^\d+$/.test(item))
151
+ if (nums.length > 0) {
152
+ fLine = nums[nums.length - 1]
153
+ } else {
154
+ fLine = lines.length
155
+ }
156
+ }
157
+ if (fLine && /^\d+$/.test(fLine)) {
158
+ let index = Math.abs(parseInt(fLine));
159
+ results.push(...lines.slice(- index))
160
+ }
161
+ return results
162
+ }
163
+
90
164
  function tableStr(...args) {
91
165
  return trim(table.getTable(...args))
92
166
  }
93
-
94
167
  function nableStr(rows) {
95
168
  return tableStr(wrapRows(rows))
96
169
  }
170
+ console.table = (...args) => {
171
+ console.log(tableStr(...args))
172
+ }
173
+ console.nable = (rows) => {
174
+ console.log(nableStr(rows))
175
+ }
97
176
 
98
177
  function timeStr(fmt, date) {
99
178
  return dayJs(date || new Date()).format(fmt || 'YYYY/MM/DD HH:mm:ss')
@@ -117,8 +196,8 @@ function getVl(...obj) {
117
196
  }
118
197
  }
119
198
 
120
- let cacheFnResp;
121
- async function cacheFn(key, fn, validMs, awaitRefresh) {
199
+ const cacheFnRespMap = {};
200
+ async function cacheFn(key, fn, validMs, awaitRefresh = true) {
122
201
  getOr($fnCache, key, {
123
202
  validMsTime: 0
124
203
  });
@@ -126,20 +205,12 @@ async function cacheFn(key, fn, validMs, awaitRefresh) {
126
205
  // do nothing
127
206
  } else {
128
207
  $fnCache[key].validMsTime = Date.now() * 3;
129
- let sync = true
130
- cacheFnResp = (async () => {
208
+ cacheFnRespMap[key] = (async () => {
131
209
  let val;
132
210
  try {
133
211
  val = await fn()
134
212
  } finally {
135
- if (!$fnCache[key].validMsTime > Date.now() * 2) {
136
- sync = false
137
- } else {
138
- $fnCache[key].validMsTime = 0
139
- }
140
- }
141
- if (!sync) {
142
- return;
213
+ $fnCache[key].validMsTime = 0
143
214
  }
144
215
  $fnCache[key] = {
145
216
  val,
@@ -149,7 +220,7 @@ async function cacheFn(key, fn, validMs, awaitRefresh) {
149
220
  })();
150
221
  }
151
222
  if (awaitRefresh || !$fnCache[key].valInit) {
152
- await cacheFnResp;
223
+ await cacheFnRespMap[key];
153
224
  }
154
225
  return $fnCache[key].val
155
226
  }
@@ -238,49 +309,52 @@ function createLimitLogger2(fileName, maxChars, logInfo = true) {
238
309
  }
239
310
  }
240
311
 
241
- function textDataFile(fileName, fn) {
242
- let dataDir = getLibDataDir() + "/data"
243
- let path = dataDir + "/" + fileName
244
- if (!fs.existsSync(path)) {
245
- mkdir(dataDir)
246
- fs.writeFileSync(path, "")
247
- }
248
-
249
- let text = String(fs.readFileSync(path))
250
- if (!fn) {
251
- return text
252
- }
253
- let val = fn(text)
254
- if (vl(val) && getType(val) === 'Promise') {
255
- return val.then(result => {
256
- if (vl(result) || String(result) === '') {
257
- fileLock(fileName, () => fs.writeFileSync(path, result))
258
- }
259
- return result
260
- })
261
- } else {
262
- if (vl(val) || String(val) === '') {
263
- fileLock(fileName, () => fs.writeFileSync(path, val))
264
- }
265
- return val
266
- }
267
- }
268
-
269
312
  function objDataFile(fileName, fn, fmt) {
313
+ fileName = trim(fileName)
270
314
  return dataFile(fileName, fn, fmt, {})
271
315
  }
272
316
  function arrayDataFile(fileName, fn, fmt) {
317
+ fileName = trim(fileName)
273
318
  return dataFile(fileName, fn, fmt, [])
274
319
  }
275
- function dataFile(fileName, fn, fmt, defaultObj = {}) {
320
+ function iobjDataFile(fileName, fn, fmt) {
321
+ return dataFile(getInitName(fileName), fn, fmt, {}, true)
322
+ }
323
+ function iarrayDataFile(fileName, fn, fmt) {
324
+ return dataFile(getInitName(fileName), fn, fmt, [], true)
325
+ }
326
+ function getInitName(fileName) {
327
+ fileName = trim(fileName)
328
+ let ooaDir = getLibDataDir() + "/ooa"
329
+ if (!fileName.startsWith("/")) {
330
+ fileName = 'i ' + fileName.replace(/i\s+/, '')
331
+ if (!/\..+/.test(fileName)) {
332
+ fileName = fileName + '.js'
333
+ }
334
+ fileName = ooaDir + '/' + fileName
335
+ }
336
+ return fileName;
337
+ }
338
+ function dataFile(fileName, fn, fmt, defaultObj = {}, returnStr = false) {
276
339
  let dataDir = getLibDataDir() + "/data"
277
- let path = dataDir + "/" + fileName
340
+ fileName = trim(fileName)
341
+ let path
342
+ if (fileName.startsWith("/")) {
343
+ path = fileName
344
+ } else {
345
+ path = dataDir + "/" + fileName
346
+ }
347
+ let prefixStr = returnStr ? 'return ' : '';
278
348
  if (!fs.existsSync(path)) {
279
349
  mkdir(dataDir)
280
- fs.writeFileSync(path, JSON.stringify(defaultObj, null, fmt ? 2:null))
350
+ fs.writeFileSync(path, prefixStr + JSON.stringify(defaultObj, null, fmt ? 2:null))
281
351
  }
282
352
 
283
- let obj = JSON.parse(String(fs.readFileSync(path)))
353
+ let text = String(fs.readFileSync(path));
354
+ if (returnStr) {
355
+ text = text.replace(/return\s+/, '')
356
+ }
357
+ let obj = JSON.parse(text)
284
358
  if (!fn) {
285
359
  return obj
286
360
  }
@@ -291,14 +365,14 @@ function dataFile(fileName, fn, fmt, defaultObj = {}) {
291
365
  if (result && typeof result === 'object') {
292
366
  obj = result
293
367
  }
294
- fileLock(fileName, () => fs.writeFileSync(path, JSON.stringify(obj, null, fmt ? 2:null)))
368
+ fileLock(fileName, () => fs.writeFileSync(path, prefixStr + JSON.stringify(obj, null, fmt ? 2:null)))
295
369
  resolve(obj)
296
370
  })
297
371
  } else {
298
372
  if (val && typeof val === 'object') {
299
373
  obj = val
300
374
  }
301
- fileLock(fileName, () => fs.writeFileSync(path, JSON.stringify(obj, null, fmt ? 2:null)))
375
+ fileLock(fileName, () => fs.writeFileSync(path, prefixStr + JSON.stringify(obj, null, fmt ? 2:null)))
302
376
  return obj
303
377
  }
304
378
  }
@@ -317,6 +391,20 @@ function requireG(module){
317
391
  return require(path);
318
392
  }
319
393
 
394
+ async function importG(module) {
395
+ try {
396
+ let result = await import(module);
397
+ if (result) {
398
+ return result
399
+ }
400
+ } catch (e) {}
401
+ let path = globalDirectories.npm.packages + '/' + module + '/index.js';
402
+ if (!fs.existsSync(path)) {
403
+ throw `ERROR: ${module} not found, use [npm install -g ${module}] to install it`;
404
+ }
405
+ return await import(path);
406
+ }
407
+
320
408
  function validStr(str, name) {
321
409
  if (!vl(str) || typeof str !== 'string') {
322
410
  throw "invalid cipher " + name;
@@ -855,6 +943,9 @@ function wrapRows(rows) {
855
943
  let temp = []
856
944
  for(let key of Object.keys(row)) {
857
945
  let val = row[key]
946
+ if (getType(val) !== "String") {
947
+ val = JSON.stringify(val, null, 2)
948
+ }
858
949
  let items = String(val).split('\n')
859
950
  for(let i = 0; i<items.length; i++) {
860
951
  let r = getOr(temp, i, {})
@@ -867,18 +958,30 @@ function wrapRows(rows) {
867
958
  }
868
959
 
869
960
  function info(msg) {
961
+ if (typeof msg === 'string' && msg && msg.indexOf('\n') === -1) {
962
+ msg = infoStr(msg)
963
+ }
870
964
  console.log(infoStr('[info]'), msg)
871
965
  }
872
966
 
873
967
  function msg(msg) {
968
+ if (typeof msg === 'string' && msg && msg.indexOf('\n') === -1) {
969
+ msg = msgStr(msg)
970
+ }
874
971
  console.log(msgStr('[msg]'), msg)
875
972
  }
876
973
 
877
974
  function warn(msg) {
975
+ if (typeof msg === 'string' && msg && msg.indexOf('\n') === -1) {
976
+ msg = warnStr(msg)
977
+ }
878
978
  console.warn(warnStr('[warn]'), msg)
879
979
  }
880
980
 
881
981
  function error(msg, tag) {
982
+ if (typeof msg === 'string' && msg && msg.indexOf('\n') === -1) {
983
+ msg = errorStr(msg)
984
+ }
882
985
  console.error(errorStr(`[${tag || 'error'}]`), msg)
883
986
  }
884
987
 
@@ -941,7 +1044,7 @@ function errorMsg(e) {
941
1044
 
942
1045
  function getType(obj) {
943
1046
  if (obj === '') {
944
- return typeof obj;
1047
+ return 'String';
945
1048
  }
946
1049
  if (!vl(obj)) {
947
1050
  return String(obj)
@@ -1059,6 +1162,18 @@ function objProfileRows(result) {
1059
1162
  return temp
1060
1163
  }
1061
1164
 
1165
+ function errorTag(e, tag) {
1166
+ if (!tag) {
1167
+ return e;
1168
+ }
1169
+ if (!isError(e)) {
1170
+ e = new Error(e)
1171
+ e.stack = e.stack.split(/\n/)[0]
1172
+ }
1173
+ e.stack = e.stack + `\n at ${tag}`
1174
+ return e
1175
+ }
1176
+
1062
1177
  module.exports = {
1063
1178
  run,
1064
1179
  reget,
@@ -1122,7 +1237,6 @@ module.exports = {
1122
1237
  emptyFn,
1123
1238
  setConfig,
1124
1239
  axios,
1125
- textDataFile,
1126
1240
  arrayDataFile,
1127
1241
  dataFile,
1128
1242
  strEq,
@@ -1146,5 +1260,11 @@ module.exports = {
1146
1260
  errorMsg,
1147
1261
  tableStr,
1148
1262
  nableStr,
1149
- objProfileRows
1263
+ objProfileRows,
1264
+ errorTag,
1265
+ iobjDataFile,
1266
+ iarrayDataFile,
1267
+ isArgsMatch,
1268
+ draftQuery,
1269
+ importG
1150
1270
  }
@@ -1,64 +0,0 @@
1
- #!/usr/bin/env node
2
- if (!process.argv[2]) {
3
- console.log("web3 http provider required")
4
- return
5
- }
6
-
7
- let {run, web3BatchReq, trim, createLimitLogger2, lisPid, timeStr, sleep, getOrFn} = {...require('../util'), ...require('../ethWeb')}
8
- const Web3 = require("web3");
9
- let randomHex = require('randomhex');
10
-
11
- let accountLog = createLimitLogger2('ethPrivateHit.account')
12
- let recordLog = createLimitLogger2('ethPrivateHit.log')
13
- let batchNum = 365
14
- lisPid(`ethPrivateHit`)
15
- let web3Map = {}
16
- let web3 = new Web3()
17
-
18
- run(async ()=>{
19
- let trys = 1
20
- while (true) {
21
- await sleep(1)
22
- try {
23
- let accounts = []
24
- for(let i = 0; i<batchNum; i++) {
25
- accounts.push(web3.eth.accounts.privateKeyToAccount(randomHex(32)))
26
- }
27
- for(let url of process.argv.slice(2)) {
28
- let web3Obj = getOrFn(web3Map, url, () => {
29
- return {web3: new Web3(trim(url))}
30
- })
31
- if (!web3Obj.chainId) {
32
- web3Obj.chainId = await web3Obj.web3.eth.getChainId()
33
- }
34
- await processChain(accounts, web3Obj.web3, web3Obj.chainId, trys)
35
- }
36
- trys ++
37
- } catch (e) {
38
- recordLog(e)
39
- }
40
- }
41
- })
42
-
43
- async function processChain(accounts, web3, chainId, trys) {
44
- let calls = []
45
- for(let account of accounts) {
46
- calls.push({
47
- method: web3.eth.getBalance,
48
- args: [account.address],
49
- callback: (error, bal) => {
50
- if (error) {
51
- recordLog(error)
52
- return
53
- }
54
- if (bal > 0) {
55
- account.balance = bal
56
- account.chainId = chainId
57
- accountLog(`account: ${JSON.stringify(account, null, 2)}`)
58
- }
59
- }
60
- })
61
- }
62
- await web3BatchReq(calls, 49, 9, web3)
63
- recordLog(`${timeStr()}: ${chainId} ${trys * batchNum}`)
64
- }