jsir 2.2.8 → 2.3.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/cmd/oaa.js CHANGED
@@ -4,14 +4,14 @@ const {
4
4
  getLibDataDir, trim, regEach, getConfig, mkdir, reget,
5
5
  getCbText, e, sleep, objDataFile, vl, md5, BigNumber,
6
6
  arrayDataFile, infoStr, warnStr,
7
- getInfo, ei, pad, msgStr, getType,
7
+ getInfo, pad, msgStr, getType,
8
8
  isMatch, draftQuery, setConfig,
9
9
  getTextComments, importG, requireG,
10
10
  clearConsole, trimText, getFnArgsStr,
11
11
  createConsole, setTips, delTips,
12
12
  getEditor, errorStr, getConfigDir,
13
13
  getFullPath, parseUniqueName, toUniqueName, isJsirFileName, toJsirFileName,
14
- getOr, getAlias
14
+ getOr, getAlias, wrapperJsirText, eia
15
15
  } = $lib;
16
16
  const _args = process.argv.slice(2).map(trim);
17
17
  const evalCode = require('../deps/evalCode')
@@ -26,11 +26,7 @@ const example = require("../deps/example");
26
26
  const _workspaceConfigFile = 'workspace.json';
27
27
  const _libDataDir = getLibDataDir()
28
28
  const _fileWatcherMap = {}
29
- const _types = {
30
- 'e': "exe",
31
- 'i': "init",
32
- 'f': "file"
33
- }
29
+ const _types = setting.fileType
34
30
  const console = createConsole();
35
31
 
36
32
  let lastFilterArg = '';
@@ -41,6 +37,7 @@ let _rlHistory = []
41
37
  let _haveWrapperInput = true
42
38
  let _noAppendNextLine = true
43
39
  let _onLazyTempCode = null
40
+ let _isTipsDoneShowKey = false
44
41
 
45
42
  const _onLazyGetMap = Object.create(null)
46
43
  const _data = Object.create(null)
@@ -291,7 +288,9 @@ async function nextLine(callback, promptStr, hidden) {
291
288
  }
292
289
 
293
290
  function defaultPromptStr(showKey = false) {
294
- return [getTipStr(showKey), $defaultSpace].filter(i => i).join(':') + `> `;
291
+ let tips = [getTipStr(showKey), $defaultSpace].filter(i => i).join(':') + `> `;
292
+ _isTipsDoneShowKey = showKey;
293
+ return tips;
295
294
  }
296
295
 
297
296
  function initRl(callback, promptStr, hidden) {
@@ -367,7 +366,11 @@ function getTipStr(showKey = false) {
367
366
  items.push(item)
368
367
  }
369
368
  }
370
- return items.join(',');
369
+ let tips = items.join(',')
370
+ if (!showKey && !_isTipsDoneShowKey && tips.length > 81) {
371
+ return '...'
372
+ }
373
+ return tips;
371
374
  }
372
375
 
373
376
  function closeRl() {
@@ -450,9 +453,9 @@ async function save(args) {
450
453
  return
451
454
  }
452
455
  let resp;
453
- if (args[0] === 'e') {
456
+ if (args[0].startsWith(setting.exeKey)) {
454
457
  resp = example.exeFile;
455
- } else if (args[0] === 'i') {
458
+ } else if (args[0].startsWith(setting.initKey)) {
456
459
  resp = example.initFile;
457
460
  } else {
458
461
  resp = await getCbText();
@@ -534,7 +537,7 @@ function listCmd(tmpMap) {
534
537
  let item = {
535
538
  key: ' ' + i,
536
539
  name: pair[0] + '/' + name,
537
- type: [_types[name.split(/\s+/)[0]] || 'note', suffix].map(trim).join(".")
540
+ type: [_types[name.substring(0, 1)] || setting.defaultType, suffix].map(trim).join(".")
538
541
  }
539
542
  items.push(item)
540
543
 
@@ -552,9 +555,9 @@ function listCmd(tmpMap) {
552
555
  }
553
556
  if (item.type) {
554
557
  let pair = parseUniqueName(item.name);
555
- if (item.type.startsWith('exe.')) {
558
+ if (item.type.startsWith(_types[setting.exeKey] + '.')) {
556
559
  item.name = infoStr(pair[1])
557
- } else if (item.type.startsWith('init.')) {
560
+ } else if (item.type.startsWith(_types[setting.initKey] + '.')) {
558
561
  item.name = msgStr(pair[1])
559
562
  } else {
560
563
  item.name = pair[1]
@@ -574,6 +577,33 @@ async function wrapperInput(str) {
574
577
  }
575
578
  }
576
579
 
580
+ function wrapperAlias(str) {
581
+ let aliasMap = null;
582
+ try {
583
+ aliasMap = getConfig("alias");
584
+ } catch (e) {
585
+ console.$error(e);
586
+ }
587
+ if (!aliasMap) {
588
+ return str;
589
+ }
590
+ let args = enrichArgs(str);
591
+ for (let i = 0; i < args.length; i++) {
592
+ let arg = args[i];
593
+ if (arg.endsWith(" ")) {
594
+ arg = `\`${arg}\``
595
+ } else if (arg.endsWith(" ")) {
596
+ arg = `"${arg}"`
597
+ } else if (arg.endsWith(" ")) {
598
+ arg = `'${arg}'`
599
+ } else {
600
+ arg = getAlias(aliasMap, arg)
601
+ }
602
+ args[i] = arg;
603
+ }
604
+ return args.join(' ')
605
+ }
606
+
577
607
  async function _wrapperInput(str) {
578
608
  _haveWrapperInput = true;
579
609
  global.$newInput = true;
@@ -582,6 +612,8 @@ async function _wrapperInput(str) {
582
612
  if (!str) {
583
613
  return;
584
614
  }
615
+ str = wrapperAlias(str);
616
+
585
617
  if (/^[`'"]/.test(str)) {
586
618
  let fstr = str.substr(0, 1);
587
619
  if (fstr === '`') {
@@ -616,10 +648,10 @@ async function _wrapperInput(str) {
616
648
  let path = getFullPath(_cmdMap[strs[0]])
617
649
  let uniqueName = trim(_cmdMap[strs[0]]);
618
650
  let fileName = parseUniqueName(uniqueName)[1]
619
- let firstName = fileName.split(/\s+/)[0]
620
- if (firstName === 'f') {
651
+ let firstName = fileName.substring(0, 1)
652
+ if (firstName === setting.fileKey) {
621
653
  await workFile(uniqueName)
622
- } else if (firstName !== 'e') {
654
+ } else if (firstName !== setting.exeKey) {
623
655
  console.log(String(fs.readFileSync(path)));
624
656
  } else {
625
657
  await runCmd(str)
@@ -1073,7 +1105,7 @@ const keywordDef = {
1073
1105
  console.warn("no items")
1074
1106
  } else {
1075
1107
  let path = getFullPath(uniqueName)
1076
- ei(getEditor(), [path])
1108
+ await eia(getEditor(), [path])
1077
1109
  }
1078
1110
  },
1079
1111
  args: {
@@ -1088,9 +1120,9 @@ const keywordDef = {
1088
1120
  if (uniqueName) {
1089
1121
  let configDir = `${getLibDataDir()}/config`;
1090
1122
  mkdir(configDir)
1091
- ei(getEditor(), [`${configDir}/${md5(uniqueName)}.json`])
1123
+ await eia(getEditor(), [`${configDir}/${md5(uniqueName)}.json`])
1092
1124
  } else {
1093
- ei(getEditor(), [`${getLibDataDir()}/config.json`])
1125
+ await eia(getEditor(), [`${getLibDataDir()}/config.json`])
1094
1126
  }
1095
1127
  },
1096
1128
  short: 's'
@@ -1179,18 +1211,17 @@ const keywordDef = {
1179
1211
  let text = removeComment(String(fs.readFileSync(path)))
1180
1212
  let [space] = parseUniqueName(uniqueName)
1181
1213
 
1214
+ text = wrapperJsirText(text)
1215
+
1182
1216
  await preLoad(text, "[\\s=;]require", requireG, packages, space)
1183
1217
  await preLoad(text, "^require", requireG, packages, space)
1184
1218
  await preLoad(text, "\\$import", importG, packages, space)
1185
- await preLoad(text, "[\\s=;]import", importG, packages, space)
1186
- await preLoad(text, "^import", importG, packages, space)
1187
1219
  }
1188
1220
  Object.keys(packages).forEach(key => {
1189
1221
  let info = packages[key];
1190
1222
  info.version = getPackageVersion(info.space, info.name)
1191
- let loadedSpace = global.$packages[info.name]
1192
- if (loadedSpace) {
1193
- info.loaded = loadedSpace
1223
+ if (global.$packages.hasOwnProperty(info.name)) {
1224
+ info.loaded = global.$packages[info.name]
1194
1225
  }
1195
1226
  if (info.loaded && info.loaded !== info.space) {
1196
1227
  let version = getPackageVersion(info.loaded, info.name)
@@ -1284,7 +1315,7 @@ const keywordDef = {
1284
1315
  let keyword = args[0]
1285
1316
  let justList = false;
1286
1317
  if (keyword.endsWith('.')) {
1287
- let _tmp = getAlias(keyword.substring(0, keyword.length - 1));
1318
+ let _tmp = trim(keyword.substring(0, keyword.length - 1));
1288
1319
  if (_tmp) {
1289
1320
  if (keywordDef[_tmp] || Object.values(keywordDef).map(item => item.short).indexOf(_tmp) !== -1) {
1290
1321
  help(i => i === _tmp || keywordDef[i].short === _tmp);
@@ -1296,8 +1327,6 @@ const keywordDef = {
1296
1327
  console.warn('invalid keyword')
1297
1328
  return
1298
1329
  }
1299
- } else {
1300
- keyword = getAlias(keyword)
1301
1330
  }
1302
1331
  let pair = parseUniqueName(keyword)
1303
1332
  let cmds;
@@ -1344,7 +1373,7 @@ const keywordDef = {
1344
1373
  },
1345
1374
  exe: {
1346
1375
  comment: 'System execute',
1347
- exeFn: (args) => {
1376
+ exeFn: async (args) => {
1348
1377
  let cmd = ''
1349
1378
  let _args = []
1350
1379
  if (args.length > 0) {
@@ -1353,18 +1382,20 @@ const keywordDef = {
1353
1382
  if (args.length > 1) {
1354
1383
  _args = args.slice(1)
1355
1384
  }
1356
- ei(`cd "${$workspaceMap[global.$defaultSpace]}";${cmd}`, _args, true)
1385
+ await eia(`cd "${$workspaceMap[global.$defaultSpace]}";${cmd}`, _args, true)
1357
1386
  },
1358
1387
  short: 'E'
1359
1388
  },
1360
1389
  log: {
1361
1390
  comment: 'View log (type[[lt][le]], index)',
1362
- exeFn: (args) => {
1391
+ exeFn: async (args) => {
1363
1392
  let path = `${getLibDataDir()}/log/jsir`
1364
1393
  let type = '';
1365
1394
  for (let arg of args) {
1366
1395
  if (_cmdMap[arg]) {
1367
- path = `${getLibDataDir()}/log/${md5(_cmdMap[trim(arg)])}`
1396
+ let pair = parseUniqueName(_cmdMap[arg])
1397
+ let fileName = pair[0] + '/' + pair[1].split(".")[0]
1398
+ path = `${getLibDataDir()}/log/${fileName}`
1368
1399
  } else {
1369
1400
  type = arg;
1370
1401
  }
@@ -1382,7 +1413,7 @@ const keywordDef = {
1382
1413
  console.warn('log file not found')
1383
1414
  return;
1384
1415
  }
1385
- ei(cmdStr, [path], true)
1416
+ await eia(cmdStr, [`"${path}"`], true)
1386
1417
  },
1387
1418
  short: 'l'
1388
1419
  },
@@ -1407,7 +1438,7 @@ function getQuickRunCmds(input, matchStr) {
1407
1438
  } else if (input.startsWith("/")) {
1408
1439
  matchStr = '/' + matchStr;
1409
1440
  }
1410
- return filterCmd(matchStr).filter(i => parseUniqueName(i)[1].startsWith("e "))
1441
+ return filterCmd(matchStr).filter(i => parseUniqueName(i)[1].startsWith(setting.exeKey))
1411
1442
  }
1412
1443
 
1413
1444
  async function preLoad(text, fnNameMatch, fn, packages = [], space) {
@@ -1508,6 +1539,9 @@ function removeComment(text) {
1508
1539
  function _getScriptRequires(uniqueName, cmds, links) {
1509
1540
  let path = getFullPath(uniqueName);
1510
1541
  let text = removeComment(String(fs.readFileSync(path)))
1542
+
1543
+ text = wrapperJsirText(text);
1544
+
1511
1545
  let temp = []
1512
1546
  regEach(text, /\$require\s*\(([^()]+)\)/g, r=> {
1513
1547
  if (r[1]) {
@@ -1914,7 +1948,7 @@ function parseArgDef(inputString) {
1914
1948
  }
1915
1949
 
1916
1950
  function getArgDef(text, uniqueName) {
1917
- if (uniqueName && !parseUniqueName(uniqueName)[1].startsWith("e ")) {
1951
+ if (uniqueName && !parseUniqueName(uniqueName)[1].startsWith(setting.exeKey)) {
1918
1952
  return {}
1919
1953
  }
1920
1954
  if (text.indexOf("$defArgs") === -1) {
@@ -1966,12 +2000,7 @@ function filterRequire(currSpace, cmdMatchStr) {
1966
2000
 
1967
2001
  let cmds;
1968
2002
  let uName = toUniqueName(cmdMatchStr, currSpace)
1969
- let pr = parseUniqueName(uName)
1970
- let fullPath;
1971
- if (!/^[ef]\s+/.test(pr[1])) {
1972
- uName = pr[0] + "/i " + pr[1].replace(/^f\s+/, '')
1973
- fullPath = getFullPath(uName)
1974
- }
2003
+ let fullPath = getFullPath(uName)
1975
2004
  if (fullPath && fs.existsSync(fullPath)) {
1976
2005
  cmds = [uName]
1977
2006
  } else {
@@ -1980,6 +2009,9 @@ function filterRequire(currSpace, cmdMatchStr) {
1980
2009
  if (cmds.length > 0) {
1981
2010
  cmds = cmds.filter(cmd => parseUniqueName(cmd)[0] === (appointSpace || currSpace))
1982
2011
  }
2012
+ if (cmds.length > 0) {
2013
+ cmds = cmds.filter(cmd => parseUniqueName(cmd)[1].startsWith(setting.initKey))
2014
+ }
1983
2015
  }
1984
2016
  if (cmds.length > 1) {
1985
2017
  throw `multiple match: ${cmdMatchStr}`
@@ -1995,9 +2027,9 @@ async function _requireSource(currSpace, cmdMatchStr) {
1995
2027
  let path = getFullPath(uniqueName)
1996
2028
  let text = String(await fp.readFile(path))
1997
2029
  let pair = parseUniqueName(uniqueName)
1998
- if (pair[1].startsWith('i ')) {
2030
+ if (pair[1].startsWith(setting.initKey)) {
1999
2031
  result = await evalText(text, uniqueName)
2000
- } else if (pair[1].startsWith('e ')) {
2032
+ } else if (pair[1].startsWith(setting.exeKey)) {
2001
2033
  result = async (argsStr) => {
2002
2034
  return await runCmd(trim(argsStr), uniqueName, text)
2003
2035
  }
@@ -2080,15 +2112,15 @@ function sigExit() {
2080
2112
  }
2081
2113
 
2082
2114
  process.on('uncaughtException',function(err){
2083
- console.error('uncaughtException', err)
2115
+ console.$error('uncaughtException', err)
2084
2116
  _noAppendNextLine || nextLine()
2085
2117
  })
2086
2118
  process.on('unhandledRejection',function(err){
2087
- console.error('unhandledRejection', err)
2119
+ console.$error('unhandledRejection', err)
2088
2120
  _noAppendNextLine || nextLine()
2089
2121
  })
2090
2122
  process.on('rejectionHandled',function(err){
2091
- console.error('rejectionHandled', err)
2123
+ console.$error('rejectionHandled', err)
2092
2124
  _noAppendNextLine || nextLine()
2093
2125
  })
2094
2126
  process.on('SIGINT', sigExit);
package/deps/evalCode.js CHANGED
@@ -19,9 +19,7 @@ module.exports = async ($text = '', $cmdName = '', $args = [],
19
19
  };
20
20
 
21
21
  // 兼容
22
- $text = $text.replace(/^module\.exports\s*=\s*/m, 'return ');
23
- $text = $text.replace(/([\s=;])import\s*\(/g, '$1$import(');
24
- $text = $text.replace(/^import\s*\(/mg, '$import(');
22
+ $text = $lib.wrapperJsirText($text)
25
23
 
26
24
  const $setTips = $lib.setTips;
27
25
  const $delTips = $lib.delTips;
package/deps/example.js CHANGED
@@ -7,11 +7,14 @@ let {
7
7
  arg, // required argument
8
8
  _arg // optional argument
9
9
  } = $defArgs()
10
+
10
11
  `,
11
12
  initFile: `/*
12
13
  An init script
13
14
  */
14
15
 
15
- return {}
16
+ module.exports = {
17
+
18
+ }
16
19
  `
17
20
  }
package/deps/setting.js CHANGED
@@ -1,4 +1,21 @@
1
+
2
+ const exeKey = 'e';
3
+ const initKey = 'i';
4
+ const fileKey = 'f';
5
+
6
+ const fileType = {};
7
+ fileType[exeKey] = "exe";
8
+ fileType[initKey] = "init";
9
+ fileType[fileKey] = "file";
10
+
11
+ const defaultType = 'note';
12
+
1
13
  module.exports = {
2
14
  name: 'jsir',
3
- libDataDir: '.jsirData'
4
- }
15
+ libDataDir: '.jsirData',
16
+ fileType,
17
+ exeKey,
18
+ initKey,
19
+ fileKey,
20
+ defaultType
21
+ }
package/deps/util.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const setting = require('./setting')
2
2
  const os = require('os')
3
3
  const home = os.homedir()
4
- const {exec, spawnSync} = require('child_process');
4
+ const {exec, spawnSync, spawn} = require('child_process');
5
5
  const readline = require('readline')
6
6
  const fs = require('fs')
7
7
  const fp = require('fs').promises
@@ -11,17 +11,21 @@ const crypto = require('crypto');
11
11
  const dayJs = require('dayjs')
12
12
  const table = require('console.table')
13
13
  const initModulePaths = Object.assign([], module.paths)
14
+ const path = require('path')
15
+ const _types = setting.fileType
16
+ const _typeKeys = Object.keys(_types)
14
17
 
15
18
  global.$newInput = false
16
19
  global.$workspaceMap = {}
17
20
  global.$defaultSpace = 'local'
18
21
  global.$newError = false
19
22
  global.$tips = {}
20
- global.$packages = Object.create(null)
23
+ global.$packages = {}
21
24
 
22
25
  let libDataDir;
23
26
  let lockDir;
24
27
  let logDir;
28
+ let tempDir;
25
29
  let configDir;
26
30
 
27
31
  class SyncQueue {
@@ -198,10 +202,12 @@ function createConsole(uniqueName) {
198
202
  result.$error = $error;
199
203
  result.$draft = draftLog;
200
204
  if (uniqueName) {
201
- result.$log = createLimitLogger(md5(uniqueName) + '.log', {
205
+ let pair = parseUniqueName(uniqueName)
206
+ let fileName = pair[0] + '/' + pair[1].split(".")[0]
207
+ result.$log = createLimitLogger(fileName + '.log', {
202
208
  logInfo: false
203
209
  });
204
- result.$error = createLimitLogger(md5(uniqueName) + '.error', {
210
+ result.$error = createLimitLogger(fileName + '.error', {
205
211
  logInfo: false,
206
212
  error: true
207
213
  });
@@ -297,6 +303,9 @@ function toJsirFileName(name) {
297
303
  }
298
304
 
299
305
  function isJsirFileName(name) {
306
+ if (name.indexOf(".") === 1) {
307
+ return _typeKeys.indexOf(name.substring(0, 1)) === -1
308
+ }
300
309
  return /^[^./]*[^./\s]\.[^./\s]+$/.test(name)
301
310
  }
302
311
 
@@ -604,6 +613,29 @@ function getLogDir() {
604
613
  return logDir;
605
614
  }
606
615
 
616
+ function getTempDir() {
617
+ if (tempDir) {
618
+ return tempDir;
619
+ }
620
+ tempDir = getLibDataDir() + "/temp"
621
+ mkdir(tempDir)
622
+ return tempDir;
623
+ }
624
+
625
+ /**
626
+ * 根据文件完整路径,检查并创建其父级目录
627
+ * 示例:/a/b/c/d.txt -> 检查并创建 /a/b/c
628
+ * @param {string} filePath 文件的完整路径
629
+ */
630
+ function createDirs(filePath) {
631
+ // 1. 获取父目录,比如 '/a/b/c'
632
+ const dirPath = path.dirname(filePath);
633
+
634
+ // 2. 使用 mkdirSync + { recursive: true } 来递归创建目录
635
+ // 如果目录已存在,则不会报错
636
+ fs.mkdirSync(dirPath, { recursive: true });
637
+ }
638
+
607
639
  function createLimitLogger(fileName, {
608
640
  maxChars = 49 * 1024 * 1024,
609
641
  logInfo = true,
@@ -616,6 +648,7 @@ function createLimitLogger(fileName, {
616
648
  }
617
649
  let logDir = getLogDir()
618
650
  let logPath = logDir + "/" + fileName
651
+ createDirs(logPath)
619
652
  if (logInfo) {
620
653
  console.info(`log: ${logPath}`)
621
654
  }
@@ -661,7 +694,7 @@ function getInitName(fileName) {
661
694
  fileName = trim(fileName)
662
695
  let homeDir = global.$workspaceMap[$defaultSpace]
663
696
  if (!fileName.startsWith("/")) {
664
- fileName = 'i ' + fileName.replace(/i\s+/, '')
697
+ fileName = setting.initKey + ' ' + fileName.replace(new RegExp(`^${setting.initKey}\\s+`), '')
665
698
  if (!/\..+/.test(fileName)) {
666
699
  fileName = fileName + '.js'
667
700
  }
@@ -669,6 +702,7 @@ function getInitName(fileName) {
669
702
  }
670
703
  return fileName;
671
704
  }
705
+
672
706
  function dataFile(fileName, fn, fmt, defaultObj = {}, returnStr = false) {
673
707
  let dataDir = getLibDataDir() + "/data"
674
708
  fileName = trim(fileName)
@@ -728,7 +762,7 @@ async function fileJson(key, fn, fmt = true) {
728
762
  let fileName = trim(key)
729
763
  let path = dataDir + "/" + fileName;
730
764
  let homeDir = global.$workspaceMap[$defaultSpace]
731
- let isInit = fileName.startsWith("i ");
765
+ let isInit = fileName.startsWith(setting.initKey);
732
766
  if (isInit) {
733
767
  path = homeDir + '/' + toJsirFileName(fileName);
734
768
  }
@@ -766,7 +800,7 @@ function setModulePaths(space) {
766
800
  }
767
801
 
768
802
  function enrichPackages(moduleName, space) {
769
- if (!global.$packages[moduleName]) {
803
+ if (!global.$packages.hasOwnProperty(moduleName)) {
770
804
  global.$packages[moduleName] = space
771
805
  }
772
806
  }
@@ -863,12 +897,11 @@ function getConfigDir() {
863
897
  return configDir;
864
898
  }
865
899
 
866
- function getAlias(key) {
900
+ function getAlias(aliasMap, key) {
867
901
  key = trim(key)
868
902
  if (!key) {
869
903
  return key;
870
904
  }
871
- let aliasMap = getConfig('alias', {});
872
905
  if (aliasMap.hasOwnProperty(key) && vl(aliasMap[key])) {
873
906
  return aliasMap[key].trim();
874
907
  }
@@ -1072,6 +1105,9 @@ function setTips(key, value, onRm) {
1072
1105
  `
1073
1106
  可以设置相同的key, value值,会在左侧提示符体现出来
1074
1107
  `
1108
+ if (!vl(key) || key.indexOf(",") !== -1) {
1109
+ throw "invalid tip key";
1110
+ }
1075
1111
  getOr(global.$tips, key, []).push(value);
1076
1112
  if (onRm) {
1077
1113
  getOr(_tipsOnRm, key, []).push(onRm)
@@ -1318,7 +1354,7 @@ function mkdir(dir) {
1318
1354
 
1319
1355
  function e(cmd, mbNum = 3, doTrim = true){
1320
1356
  `
1321
- return Promise(result)
1357
+ return Promise(resolve, reject)
1322
1358
  `
1323
1359
  return new Promise((resolve, reject) => {
1324
1360
  exec(`${cmd}`, {
@@ -1335,7 +1371,7 @@ function e(cmd, mbNum = 3, doTrim = true){
1335
1371
 
1336
1372
  function ee(cmd, mbNum = 3, doTrim = true){
1337
1373
  `
1338
- return Promise([stdout, stderr])
1374
+ return Promise(resolve([stdout, stderr]))
1339
1375
  `
1340
1376
  return new Promise((resolve, reject) => {
1341
1377
  exec(`${cmd}`, {
@@ -1354,6 +1390,23 @@ function ei(cmd, args = [], shell = false) {
1354
1390
  spawnSync(cmd, args, {stdio:"inherit", shell});
1355
1391
  }
1356
1392
 
1393
+ async function eia(cmd, args = [], shell = false) {
1394
+ `
1395
+ 当前进程不会卡住,输入输出由cmd进程持有
1396
+ `
1397
+ let child = spawn(cmd, args, {stdio:"inherit", shell});
1398
+ return new Promise((resolve, reject) => {
1399
+ // 监听子进程的关闭事件
1400
+ child.on('close', (code) => {
1401
+ resolve(code);
1402
+ });
1403
+ // 可选:监听子进程的错误事件
1404
+ child.on('error', (err) => {
1405
+ reject(err)
1406
+ });
1407
+ })
1408
+ }
1409
+
1357
1410
  async function getCbText(mbNum) {
1358
1411
  return await e(`pbpaste`, mbNum, false)
1359
1412
  }
@@ -1778,7 +1831,36 @@ function getTextComments(text) {
1778
1831
  return results.map(i => i.replace(/\s+$/, ''))
1779
1832
  }
1780
1833
 
1834
+ function wrapperJsirText(text) {
1835
+ return text
1836
+ .replace(/^require\s*\(\s*(["'`][ei]\s+)/mg, 'await $require($2')
1837
+ .replace(/([\s=;])require\s*\(\s*(["'`][ei]\s+)/g, '$1await $require($2')
1838
+ .replace(/([\s=;])import\s*\(/g, '$1$import(')
1839
+ .replace(/^import\s*\(/mg, '$import(')
1840
+ .replace(/^module\.exports\s*=\s*/m, 'return ')
1841
+ ;
1842
+ }
1843
+
1844
+ async function terminalRun(cmd) {
1845
+ `
1846
+ 打开新的苹果终端并执行命令
1847
+ `
1848
+ const scriptText = `tell application "Terminal"
1849
+ activate
1850
+ do script "${cmd}"
1851
+ end tell
1852
+ `;
1853
+ let tempScriptPath = getTempDir() + `/terminalRun_${Date.now()}.scpt`
1854
+ fs.writeFileSync(tempScriptPath, scriptText);
1855
+ try {
1856
+ console.log(await e(`osascript ${tempScriptPath}`))
1857
+ } finally {
1858
+ fs.unlinkSync(tempScriptPath)
1859
+ }
1860
+ }
1861
+
1781
1862
  module.exports = {
1863
+ wrapperJsirText,
1782
1864
  run,
1783
1865
  reget,
1784
1866
  trim,
@@ -1873,5 +1955,9 @@ module.exports = {
1873
1955
  toJsirFileName,
1874
1956
  fileJson,
1875
1957
  debugStr,
1876
- getAlias
1958
+ getAlias,
1959
+ createDirs,
1960
+ getTempDir,
1961
+ terminalRun,
1962
+ eia
1877
1963
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsir",
3
- "version": "2.2.8",
3
+ "version": "2.3.0",
4
4
  "description": "JavaScript Script Management Tool",
5
5
  "main": "index.js",
6
6
  "scripts": {