@zwa73/dev-utils 1.0.87 → 1.0.89

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 (108) hide show
  1. package/bin/cli +2 -2
  2. package/data/template/base/package.json +6 -6
  3. package/data/template/base/scripts/compile.ps1 +23 -6
  4. package/data/template/base/tsconfig.cjs.json +2 -1
  5. package/data/template/base/tsconfig.json +3 -5
  6. package/data/template/base/tsconfig.mjs.json +2 -2
  7. package/data/template/base/tsconfig.types.json +8 -0
  8. package/data/template/cjs/gitignore +3 -0
  9. package/data/template/cjs/package.json +19 -0
  10. package/data/template/cjs/scripts/compile.ps1 +6 -0
  11. package/data/template/cjs/scripts/expand-macro.ps1 +2 -0
  12. package/data/template/cjs/scripts/release.ps1 +4 -0
  13. package/data/template/cjs/scripts/watch.ps1 +10 -0
  14. package/data/template/cjs/src/index.ts +0 -0
  15. package/data/template/cjs/src/macro.macro.ts +6 -0
  16. package/data/template/cjs/tsconfig.compile.json +12 -0
  17. package/data/template/cjs/tsconfig.json +21 -0
  18. package/data/template/electron/package.json +25 -25
  19. package/dist/{cjs/Command → Command}/GenI18n.js +14 -10
  20. package/dist/{cjs/Command → Command}/GenTemplate.js +7 -4
  21. package/dist/{cjs/Command → Command}/MapPath.js +34 -25
  22. package/dist/{cjs/Command → Command}/Release.js +3 -1
  23. package/dist/Command/ScanDups.js +122 -0
  24. package/dist/DynImport.d.ts +15 -0
  25. package/dist/DynImport.js +15 -0
  26. package/dist/{mjs/UtilAst.d.ts → UtilAst.d.ts} +1 -1
  27. package/dist/{cjs/UtilDevTool.js → UtilDevTool.js} +13 -34
  28. package/dist/UtilInterface.d.ts +8 -0
  29. package/dist/UtilMacro.d.ts +7 -0
  30. package/dist/{cjs/UtilMacro.js → UtilMacro.js} +2 -2
  31. package/package.json +2 -8
  32. package/dist/cjs/Command/ScanDups.js +0 -101
  33. package/dist/cjs/UtilAst.d.ts +0 -13
  34. package/dist/cjs/UtilInterface.d.ts +0 -4
  35. package/dist/cjs/UtilMacro.d.ts +0 -7
  36. package/dist/cjs/test/testFileMacro.d.ts +0 -1
  37. package/dist/cjs/test/testFileMacro.js +0 -1
  38. package/dist/cjs/test/testGlobMacro.d.ts +0 -1
  39. package/dist/cjs/test/testGlobMacro.js +0 -2
  40. package/dist/cjs/test/testRegex.d.ts +0 -1
  41. package/dist/cjs/test/testRegex.js +0 -3
  42. package/dist/cjs/test/testRegexa.d.ts +0 -1
  43. package/dist/cjs/test/testRegexa.js +0 -1
  44. package/dist/mjs/Command/ExpandMacro.d.ts +0 -3
  45. package/dist/mjs/Command/ExpandMacro.js +0 -16
  46. package/dist/mjs/Command/GenI18n.d.ts +0 -3
  47. package/dist/mjs/Command/GenI18n.js +0 -75
  48. package/dist/mjs/Command/GenSchema.d.ts +0 -3
  49. package/dist/mjs/Command/GenSchema.js +0 -22
  50. package/dist/mjs/Command/GenTemplate.d.ts +0 -3
  51. package/dist/mjs/Command/GenTemplate.js +0 -61
  52. package/dist/mjs/Command/MapPath.d.ts +0 -3
  53. package/dist/mjs/Command/MapPath.js +0 -64
  54. package/dist/mjs/Command/Node.d.ts +0 -3
  55. package/dist/mjs/Command/Node.js +0 -14
  56. package/dist/mjs/Command/Release.d.ts +0 -3
  57. package/dist/mjs/Command/Release.js +0 -88
  58. package/dist/mjs/Command/Route.d.ts +0 -1
  59. package/dist/mjs/Command/Route.js +0 -20
  60. package/dist/mjs/Command/RouteInterface.d.ts +0 -24
  61. package/dist/mjs/Command/RouteInterface.js +0 -58
  62. package/dist/mjs/Command/ScanDups.d.ts +0 -3
  63. package/dist/mjs/Command/ScanDups.js +0 -94
  64. package/dist/mjs/Command/index.d.ts +0 -1
  65. package/dist/mjs/Command/index.js +0 -1
  66. package/dist/mjs/QuickFunc.d.ts +0 -2
  67. package/dist/mjs/QuickFunc.js +0 -2
  68. package/dist/mjs/UtilAst.js +0 -15
  69. package/dist/mjs/UtilDevTool.d.ts +0 -99
  70. package/dist/mjs/UtilDevTool.js +0 -297
  71. package/dist/mjs/UtilInterface.d.ts +0 -4
  72. package/dist/mjs/UtilInterface.js +0 -1
  73. package/dist/mjs/UtilMacro.d.ts +0 -7
  74. package/dist/mjs/UtilMacro.js +0 -23
  75. package/dist/mjs/index.d.ts +0 -5
  76. package/dist/mjs/index.js +0 -5
  77. package/dist/mjs/test/testFileMacro.d.ts +0 -1
  78. package/dist/mjs/test/testFileMacro.js +0 -1
  79. package/dist/mjs/test/testGlobMacro.d.ts +0 -1
  80. package/dist/mjs/test/testGlobMacro.js +0 -2
  81. package/dist/mjs/test/testRegex.d.ts +0 -1
  82. package/dist/mjs/test/testRegex.js +0 -2
  83. package/dist/mjs/test/testRegexa.d.ts +0 -1
  84. package/dist/mjs/test/testRegexa.js +0 -1
  85. /package/dist/{cjs/Command → Command}/ExpandMacro.d.ts +0 -0
  86. /package/dist/{cjs/Command → Command}/ExpandMacro.js +0 -0
  87. /package/dist/{cjs/Command → Command}/GenI18n.d.ts +0 -0
  88. /package/dist/{cjs/Command → Command}/GenSchema.d.ts +0 -0
  89. /package/dist/{cjs/Command → Command}/GenSchema.js +0 -0
  90. /package/dist/{cjs/Command → Command}/GenTemplate.d.ts +0 -0
  91. /package/dist/{cjs/Command → Command}/MapPath.d.ts +0 -0
  92. /package/dist/{cjs/Command → Command}/Node.d.ts +0 -0
  93. /package/dist/{cjs/Command → Command}/Node.js +0 -0
  94. /package/dist/{cjs/Command → Command}/Release.d.ts +0 -0
  95. /package/dist/{cjs/Command → Command}/Route.d.ts +0 -0
  96. /package/dist/{cjs/Command → Command}/Route.js +0 -0
  97. /package/dist/{cjs/Command → Command}/RouteInterface.d.ts +0 -0
  98. /package/dist/{cjs/Command → Command}/RouteInterface.js +0 -0
  99. /package/dist/{cjs/Command → Command}/ScanDups.d.ts +0 -0
  100. /package/dist/{cjs/Command → Command}/index.d.ts +0 -0
  101. /package/dist/{cjs/Command → Command}/index.js +0 -0
  102. /package/dist/{cjs/QuickFunc.d.ts → QuickFunc.d.ts} +0 -0
  103. /package/dist/{cjs/QuickFunc.js → QuickFunc.js} +0 -0
  104. /package/dist/{cjs/UtilAst.js → UtilAst.js} +0 -0
  105. /package/dist/{cjs/UtilDevTool.d.ts → UtilDevTool.d.ts} +0 -0
  106. /package/dist/{cjs/UtilInterface.js → UtilInterface.js} +0 -0
  107. /package/dist/{cjs/index.d.ts → index.d.ts} +0 -0
  108. /package/dist/{cjs/index.js → index.js} +0 -0
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.importTsMorph = importTsMorph;
4
+ exports.importTJS = importTJS;
5
+ exports.importCliProgress = importCliProgress;
6
+ const utils_1 = require("@zwa73/utils");
7
+ async function importTsMorph() {
8
+ return await utils_1.UtilFunc.dynamicImport("ts-morph");
9
+ }
10
+ async function importTJS() {
11
+ return await utils_1.UtilFunc.dynamicImport("typescript-json-schema");
12
+ }
13
+ async function importCliProgress() {
14
+ return await utils_1.UtilFunc.dynamicImport("cli-progress");
15
+ }
@@ -1,5 +1,5 @@
1
1
  import { AnyFunc } from "@zwa73/utils";
2
- import { SyntaxKind, KindToNodeMappings, Node } from "ts-morph";
2
+ import type { SyntaxKind, KindToNodeMappings, Node } from "ts-morph";
3
3
  export declare namespace UtilAst {
4
4
  /**匹配Node的类型进行处理 无法匹配时返回undefined
5
5
  * @param node - ast节点
@@ -1,37 +1,13 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
4
  };
28
5
  Object.defineProperty(exports, "__esModule", { value: true });
29
6
  exports.UtilDT = void 0;
30
7
  const pathe_1 = __importDefault(require("pathe"));
31
- const TJS = __importStar(require("typescript-json-schema"));
32
- const fs = __importStar(require("fs"));
8
+ const fs_1 = __importDefault(require("fs"));
33
9
  const utils_1 = require("@zwa73/utils");
34
- const ts_morph_1 = require("ts-morph");
10
+ const DynImport_1 = require("./DynImport");
35
11
  var UtilDT;
36
12
  (function (UtilDT) {
37
13
  /**生成匹配的文件的所有type的schema
@@ -47,6 +23,9 @@ var UtilDT;
47
23
  * @param opt.excludeTypes - 排除的types正则匹配数组
48
24
  */
49
25
  async function generateSchema(dir, opt) {
26
+ //导入
27
+ const TJS = await (0, DynImport_1.importTJS)();
28
+ const TsMorph = await (0, DynImport_1.importTsMorph)();
50
29
  //生成
51
30
  const settings = {
52
31
  required: true,
@@ -65,10 +44,10 @@ var UtilDT;
65
44
  //const schema = TJS.generateSchema(program, opt?.typeName??"*", settings,undefined,gener) as JObject;
66
45
  const it = opt?.includeTypes?.map(t => new RegExp(t)) ?? [/.*/];
67
46
  const et = opt?.excludeTypes?.map(t => new RegExp(t)) ?? [];
68
- const p = new ts_morph_1.Project();
47
+ const p = new TsMorph.Project();
69
48
  const types = files.map(fp => p
70
49
  .addSourceFileAtPath(fp)
71
- .getDescendantsOfKind(ts_morph_1.SyntaxKind.TypeAliasDeclaration)
50
+ .getDescendantsOfKind(TsMorph.SyntaxKind.TypeAliasDeclaration)
72
51
  .map(d => d.getName())).flat();
73
52
  const list = gener.getUserSymbols()
74
53
  .filter(t => types.some(i => i === t))
@@ -89,8 +68,8 @@ var UtilDT;
89
68
  function procSchema(schema, coverDefine) {
90
69
  //覆盖
91
70
  coverObj(schema["definitions"], coverDefine);
92
- //替换SchemaString标识符
93
- schema = JSON.parse(JSON.stringify(schema).replace(/\^\.\*SchemaString\$/g, '^.*$'));
71
+ ////替换SchemaString标识符
72
+ //schema = JSON.parse(JSON.stringify(schema).replace(/\^\.\*SchemaString\$/g,'^.*$'));
94
73
  return schema;
95
74
  }
96
75
  /**展开schema以供使用 */
@@ -174,7 +153,7 @@ var UtilDT;
174
153
  : opt?.filePath.map((filepath) => filepath)
175
154
  : [basePath.replace(/(.+)\.macro\.(js|ts|cjs|mjs)$/, "$1.$2")];
176
155
  };
177
- const readFile = async (basePath) => (await fs.promises.readFile(basePath, 'utf-8')).replaceAll("\r\n", "\n");
156
+ const readFile = async (basePath) => (await fs_1.default.promises.readFile(basePath, 'utf-8')).replaceAll("\r\n", "\n");
178
157
  const parseCodeText = async (codeText, opt) => {
179
158
  const strText = typeof codeText === "function" ? await codeText(opt) : codeText;
180
159
  return strText.split('\n').map((line) => `${opt.inent}${line}`).join('\n');
@@ -229,7 +208,7 @@ var UtilDT;
229
208
  regex.lastIndex += fileText.length - ol;
230
209
  }
231
210
  if (hasMatch)
232
- await fs.promises.writeFile(filePath, fileText, 'utf-8');
211
+ await fs_1.default.promises.writeFile(filePath, fileText, 'utf-8');
233
212
  else if (!opt?.glob)
234
213
  utils_1.SLogger.error(`UtilDT.regionMacro 无法找到区域 ${regionId}`);
235
214
  };
@@ -287,7 +266,7 @@ var UtilDT;
287
266
  regex.lastIndex += fileText.length - ol;
288
267
  }
289
268
  if (hasMatch)
290
- await fs.promises.writeFile(filePath, fileText, 'utf-8');
269
+ await fs_1.default.promises.writeFile(filePath, fileText, 'utf-8');
291
270
  else if (!opt?.glob)
292
271
  utils_1.SLogger.error(`UtilDT.commentMacro 无法找到注释 ${commentId}`);
293
272
  };
@@ -316,7 +295,7 @@ var UtilDT;
316
295
  inent: '',
317
296
  filePath
318
297
  });
319
- await fs.promises.writeFile(filePath, parseCode, 'utf-8');
298
+ await fs_1.default.promises.writeFile(filePath, parseCode, 'utf-8');
320
299
  };
321
300
  plist.push(utils_1.PromiseQueue.enqueue(pathe_1.default.normalize(filePath), queuefunc));
322
301
  }
@@ -0,0 +1,8 @@
1
+ /**用在转换为Schema时解析为string并且不影响智能补全的类型
2
+ * @TJS-type string
3
+ */
4
+ export type SchemaString = (string & String);
5
+ /**用于在转换为schema时解析为整数的类型
6
+ * @TJS-type integer
7
+ */
8
+ export type SchemaInt = (string & String);
@@ -0,0 +1,7 @@
1
+ export declare namespace UtilMacro {
2
+ /**根据注释批量生成导出
3
+ * @param glob - 应用的golb 默认 src\/**\/index.ts
4
+ * @example
5
+ */
6
+ function exportComment(glob?: string): void;
7
+ }
@@ -10,10 +10,10 @@ const pathe_1 = __importDefault(require("pathe"));
10
10
  var UtilMacro;
11
11
  (function (UtilMacro) {
12
12
  /**根据注释批量生成导出
13
- * @param glob - 应用的golb
13
+ * @param glob - 应用的golb 默认 src\/**\/index.ts
14
14
  * @example
15
15
  */
16
- function exportComment(glob) {
16
+ function exportComment(glob = 'src/**/index.ts') {
17
17
  (0, QuickFunc_1.commentMacro)(/export (\S*)/, async ({ filePath, matchId, execArr }) => {
18
18
  const basedir = pathe_1.default.dirname(filePath);
19
19
  const result = (await utils_1.UtilFT.fileSearchGlob(basedir, execArr[1]))
package/package.json CHANGED
@@ -1,14 +1,8 @@
1
1
  {
2
2
  "name": "@zwa73/dev-utils",
3
- "version": "1.0.87",
3
+ "version": "1.0.89",
4
4
  "description": "编译与调试工具",
5
- "exports": {
6
- ".": {
7
- "require": "./dist/cjs/index.js",
8
- "import": "./dist/mjs/index.js"
9
- }
10
- },
11
- "types": "./dist/mjs/index.d.ts",
5
+ "main": "dist/index.js",
12
6
  "scripts": {
13
7
  "test": "jest",
14
8
  "release": "powershell scripts/release",
@@ -1,101 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.CmdScanDups = void 0;
7
- const utils_1 = require("@zwa73/utils");
8
- const fs_1 = __importDefault(require("fs"));
9
- const crypto_1 = __importDefault(require("crypto"));
10
- const pathe_1 = __importDefault(require("pathe"));
11
- const cli_progress_1 = __importDefault(require("cli-progress"));
12
- const { tap } = utils_1.UtilFP;
13
- async function calculateHash(filePath) {
14
- return new Promise((resolve, reject) => {
15
- const hash = crypto_1.default.createHash('md5');
16
- const stream = fs_1.default.createReadStream(filePath);
17
- stream.on('data', (data) => hash.update(data));
18
- stream.on('end', () => resolve(hash.digest('hex')));
19
- stream.on('error', reject);
20
- });
21
- }
22
- async function calculateSampledHash(filePath, chunkSize = 1024, // 每块大小(例如 1KB)
23
- chunkCount = 10) {
24
- const stats = await fs_1.default.promises.stat(filePath);
25
- const totalSize = stats.size;
26
- if (totalSize < chunkSize * chunkCount)
27
- return calculateHash(filePath);
28
- const positions = Array.from({ length: chunkCount }, (_, i) => Math.floor((totalSize / chunkCount) * i));
29
- const hash = crypto_1.default.createHash("md5"); // 或其他哈希算法,如 CRC32/BLAKE3
30
- for (const position of positions) {
31
- const buffer = await new Promise((resolve, reject) => {
32
- // 创建一个文件流,限制读取范围
33
- const stream = fs_1.default.createReadStream(filePath, {
34
- start: position,
35
- end: Math.min(position + chunkSize - 1, totalSize - 1), // 确保不会超出文件末尾
36
- highWaterMark: chunkSize, // 高效流式块
37
- });
38
- const chunks = [];
39
- stream.on("data", (chunk) => chunks.push(chunk));
40
- stream.on("end", () => resolve(Buffer.concat(chunks))); // 合并块数据
41
- stream.on("error", reject);
42
- });
43
- hash.update(buffer); // 更新哈希计算
44
- }
45
- return hash.digest("hex"); // 返回最终哈希值
46
- }
47
- /**重命名文件或路径 scan_duplicates */
48
- const CmdScanDups = (program) => program
49
- .command("Scan-Dups")
50
- .alias("scandups")
51
- .description("扫描当前目录下hash重复的文件")
52
- .option("-re, --regex <regex>", "文件的正则表达式, 使用posix路径", ".*")
53
- .option("-o, --out <dir|console>", "输出的json文件路径, 默认 scandups.json, 为 \"console\" 时无文件输出", "scandups")
54
- .option("-r, --recursive", "是否处理子目录, 默认 true", true)
55
- .action(async (options) => {
56
- const regex = new RegExp(options.regex);
57
- const basePath = process.cwd();
58
- // **添加一个多步进度条**
59
- const progressBar = new cli_progress_1.default.MultiBar({
60
- clearOnComplete: true, hideCursor: true,
61
- format: " {task} [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {status}",
62
- }, cli_progress_1.default.Presets.shades_classic);
63
- // 采样哈希进度条
64
- const sampledProgress = progressBar.create(1, 0, { task: "快速扫描", status: "准备中..." });
65
- // 完整哈希进度条
66
- const fullHashProgress = progressBar.create(1, 0, { task: "完整扫描", status: "准备中..." });
67
- const reduce2Dupmap = (list) => list.reduce((acc, cur) => {
68
- const files = acc[cur.hash] ?? [];
69
- acc[cur.hash] = [...files, cur.filePath]; // 分类采样哈希到对应文件路径
70
- return acc;
71
- }, {});
72
- await (0, utils_1.pipe)(
73
- // 第一步:文件搜索,获取符合正则的文件路径
74
- utils_1.UtilFT.fileSearchRegex(basePath, regex.source, { recursive: options.recursive }), tap(list => void sampledProgress.setTotal(list.length) ??
75
- void sampledProgress.update(0, { status: `总计 ${list.length} 个文件` })),
76
- // 第二步:快速扫描,计算采样哈希
77
- list => utils_1.Stream.from(list, 8)
78
- .map(async (filePath) => ({
79
- filePath,
80
- hash: await calculateSampledHash(filePath).then(tap(() => sampledProgress.increment())),
81
- }))
82
- .toArray(),
83
- // 第三步:筛选重复的采样哈希(去掉唯一的采样哈希)
84
- reduce2Dupmap, map => Object.entries(map).reduce((acc, [hash, files]) => files.length > 1 ? [...acc, ...files] : acc, // 筛选出重复采样哈希的文件路径
85
- []), tap(dupPaths => void fullHashProgress.setTotal(dupPaths.length) ??
86
- void fullHashProgress.update(0, { status: `快速扫描检出 ${dupPaths.length} 个可能的相等项` })),
87
- // 第四步:对筛选出的重复文件路径并发计算完整哈希
88
- dups => utils_1.Stream.from(dups, 8)
89
- .map(async (filePath) => ({
90
- filePath,
91
- hash: await calculateHash(filePath).then(tap(() => fullHashProgress.increment())), // 计算完整哈希
92
- }))
93
- .toArray(),
94
- // 第五步:重新整理完整哈希结果,过滤唯一哈希
95
- reduce2Dupmap, map => Object.entries(map).reduce((acc, [hash, files]) => files.length <= 1 ? acc : { ...acc, [hash]: files }, {}),
96
- // 第六步:输出结果
97
- tap(() => progressBar.stop()), out => (0, utils_1.match)(options.out, {
98
- "console": () => utils_1.SLogger.info(out),
99
- }, () => utils_1.UtilFT.writeJSONFile(pathe_1.default.join(basePath, options.out), out)));
100
- });
101
- exports.CmdScanDups = CmdScanDups;
@@ -1,13 +0,0 @@
1
- import { AnyFunc } from "@zwa73/utils";
2
- import { SyntaxKind, KindToNodeMappings, Node } from "ts-morph";
3
- export declare namespace UtilAst {
4
- /**匹配Node的类型进行处理 无法匹配时返回undefined
5
- * @param node - ast节点
6
- * @param funcMap - 处理函数映射表
7
- */
8
- function withKind<T extends Partial<{
9
- [P in SyntaxKind]: ((n: KindToNodeMappings[P]) => unknown);
10
- }>>(node: Node, funcMap: T): {
11
- [P in keyof T]: T[P] extends AnyFunc ? ReturnType<T[P]> : never;
12
- }[keyof T] | undefined;
13
- }
@@ -1,4 +0,0 @@
1
- /**用于辅助解析只能补全的类型
2
- * 输出后替换为 ^.*$ 的 string 匹配
3
- */
4
- export type SchemaString = `${string}SchemaString`;
@@ -1,7 +0,0 @@
1
- export declare namespace UtilMacro {
2
- /**根据注释批量生成导出
3
- * @param glob - 应用的golb
4
- * @example
5
- */
6
- function exportComment(glob: string): void;
7
- }
@@ -1 +0,0 @@
1
- type FileMacro = 5;
@@ -1 +0,0 @@
1
- "use strict";
@@ -1 +0,0 @@
1
- type Test3 = 4;
@@ -1,2 +0,0 @@
1
- "use strict";
2
- //#endregion 1 ssa
@@ -1 +0,0 @@
1
- export {};
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- 2;
@@ -1 +0,0 @@
1
- type CM1 = 3;
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**构造macro */
3
- export declare const CmdExpandMacro: (program: Command) => Command;
@@ -1,16 +0,0 @@
1
- import { UtilDT } from "../UtilDevTool.js";
2
- /**构造macro */
3
- export const CmdExpandMacro = (program) => program
4
- .command("Expand-Macro")
5
- .alias("expandmacro")
6
- .description("根据macro生成代码")
7
- .option("-i, --include <glob>", "包含的glob 默认 src/**/*.macro.ts", "src/**/*.macro.ts")
8
- .option("-g, --exclude <glob>", "忽略的glob")
9
- .option("-p, --project <path>", "tsconfig路径 默认tsconfig.json", "tsconfig.json")
10
- .action(async (opt) => {
11
- await UtilDT.matchNode(process.cwd(), {
12
- include: opt.include,
13
- exclude: opt.ignore,
14
- project: opt.project,
15
- });
16
- });
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**生成i18n */
3
- export declare const CmdGenI18n: (program: Command) => Command;
@@ -1,75 +0,0 @@
1
- import { SI18n, UtilFT } from "@zwa73/utils";
2
- import { Project, SyntaxKind } from 'ts-morph';
3
- import { UtilAst } from "../UtilAst.js";
4
- import path from 'pathe';
5
- function format(str) {
6
- return str.replace(/\\(.)/g, '$1').replace(/%/g, '\\%');
7
- }
8
- async function procFile(p, filePath, funckey) {
9
- const date = new Date().toISOString();
10
- //const content = await fs.promises.readFile(filePath,'utf-8');
11
- const b = p.addSourceFileAtPath(filePath);
12
- //const b = p.createSourceFile(path.relative(process.cwd(),filePath),content,{overwrite:true});
13
- const ds = b.getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression);
14
- const dats = [];
15
- for (const d of ds) {
16
- if (!funckey.includes(d.getTag().getText()))
17
- continue;
18
- const template = d.getTemplate();
19
- let result = '';
20
- let i = 0;
21
- UtilAst.withKind(template, {
22
- [SyntaxKind.NoSubstitutionTemplateLiteral]: (t) => result += format(t.getLiteralText()),
23
- [SyntaxKind.TemplateExpression]: (t) => {
24
- t.getChildren().forEach((c) => {
25
- UtilAst.withKind(c, {
26
- [SyntaxKind.TemplateHead]: (sc) => result += format(sc.getLiteralText()),
27
- [SyntaxKind.SyntaxList]: (sc) => {
28
- sc.getChildrenOfKind(SyntaxKind.TemplateSpan).forEach((span) => {
29
- span.getChildren().forEach((ssc) => {
30
- result += UtilAst.withKind(ssc, {
31
- [SyntaxKind.TemplateMiddle]: (sssc) => format(sssc.getLiteralText()),
32
- [SyntaxKind.TemplateTail]: (sssc) => format(sssc.getLiteralText()),
33
- }) ?? String(`%${i++}`);
34
- });
35
- });
36
- },
37
- });
38
- });
39
- }
40
- });
41
- const pos = b.getLineAndColumnAtPos(d.getStart());
42
- const dat = {
43
- original: result,
44
- scan_time: date,
45
- position: `${filePath}:${pos.line}:${pos.column}`,
46
- lang_table: {},
47
- source: "Ast"
48
- };
49
- dats.push(dat);
50
- }
51
- return dats;
52
- }
53
- async function scanI18n(i18nDataDir, include, exclude, funckey) {
54
- const fixedKey = typeof funckey == 'string' ? [funckey] : funckey;
55
- const filePaths = (await UtilFT.fileSearchGlob(process.cwd(), include, { ingore: exclude }))
56
- .filter(p => ['.ts', '.tsx'].includes(path.parse(p).ext));
57
- const project = new Project();
58
- await SI18n.init(i18nDataDir, '*');
59
- //console.log(filePaths);
60
- (await Promise.all(filePaths.map(p => procFile(project, p, fixedKey))))
61
- .flat().forEach(dat => SI18n.addOriginalText(dat));
62
- await SI18n.saveTable();
63
- }
64
- /**生成i18n */
65
- export const CmdGenI18n = (program) => program
66
- .command("Gen-I18n")
67
- .alias("geni18n")
68
- .description("根据文件行为树生成i18n数据")
69
- .option("-o, --output <path>", "输出的数据目录位置 默认 i18n", 'i18n')
70
- .option("-i, --include <glob>", "包含的glob 默认 src/**/*.ts", "src/**/*.ts")
71
- .option("-g, --exclude <glob>", "忽略的glob")
72
- .option("-f, --funckey <string|strings>", "扫描的目标函数名, 可传入逗号分隔数组, 默认 t", (i) => i.split(','), ['t'])
73
- .action(async (opt) => {
74
- await scanI18n(opt.output, opt.include, opt.exclude, opt.funckey);
75
- });
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**生成schema */
3
- export declare const CmdGenSchema: (program: Command) => Command;
@@ -1,22 +0,0 @@
1
- import { UtilDT } from "../UtilDevTool.js";
2
- /**生成schema */
3
- export const CmdGenSchema = (program) => program
4
- .command("Gen-Schema")
5
- .alias("genschema")
6
- .description("生成匹配的文件的所有type的schema")
7
- .option("-i, --include <glob>", "包含的glob 默认 src/**/*.schema.ts", "src/**/*.schema.ts")
8
- .option("-g, --exclude <glob>", "忽略的glob")
9
- .option("-p, --project <path>", "tsconfig路径 默认tsconfig.json", "tsconfig.json")
10
- .option("-o, --out <dir>", "schema输出路径目录 默认 ./schema/")
11
- .option("-it, --include-types <regexp[]>", "包含的types正则匹配数组, 传入逗号分隔数组", (i) => i.split(','))
12
- .option("-et, --exclude-types <regexp[]>", "排除的types正则匹配数组, 传入逗号分隔数组", (i) => i.split(','))
13
- .action(async (opt) => {
14
- await UtilDT.generateSchema(process.cwd(), {
15
- include: opt.include,
16
- exclude: opt.exclude,
17
- project: opt.project,
18
- outDir: opt.out,
19
- includeTypes: opt.includeTypes,
20
- excludeTypes: opt.excludeTypes
21
- });
22
- });
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**生成schema */
3
- export declare const CmdGenTemplate: (program: Command) => Command;
@@ -1,61 +0,0 @@
1
- import path from 'pathe';
2
- import { MIRROR_SOURCE, TEMPLATE_PATH } from "./RouteInterface.js";
3
- import { SLogger, UtilFT, UtilFunc } from "@zwa73/utils";
4
- import fs from 'fs';
5
- /**复制基础文件 */
6
- async function copyData(templatePath, projectPath) {
7
- const filelist = await fs.promises.readdir(templatePath);
8
- const plist = filelist.map(async (fileName) => {
9
- SLogger.info(`正在复制 ${fileName}`);
10
- const filePath = path.join(templatePath, fileName);
11
- const targetPath = path.join(projectPath, fileName);
12
- if (!await UtilFT.pathExists(targetPath))
13
- await fs.promises.cp(filePath, targetPath, { recursive: true });
14
- else
15
- SLogger.info(`${fileName} 已存在 跳过`);
16
- return null;
17
- });
18
- await Promise.all(plist);
19
- }
20
- /**安装npm包 */
21
- async function installPackage(projectPath, depList, devDepList) {
22
- const install = async (name) => await UtilFunc.exec(`npm i --registry ${MIRROR_SOURCE} ${name}`, { cwd: projectPath });
23
- const installdev = async (name) => await UtilFunc.exec(`npm i --registry ${MIRROR_SOURCE} --save-dev ${name}`, { cwd: projectPath });
24
- for (const name of depList) {
25
- SLogger.info(`正在安装 ${name}`);
26
- await install(name);
27
- }
28
- for (const name of devDepList) {
29
- SLogger.info(`正在安装 ${name}`);
30
- await installdev(name);
31
- }
32
- }
33
- /**生成schema */
34
- export const CmdGenTemplate = (program) => program
35
- .command("Gen-Template")
36
- .alias("gentemplate")
37
- .description("生成项目模板")
38
- .argument("<template>", "项目模板 可用 base|electron")
39
- .requiredOption("-n, --projectName <name>", "项目名称")
40
- .requiredOption("-d, --projectDescription <description>", "项目描述")
41
- .requiredOption("-a, --authorName <name>", "作者名")
42
- .action(async (templateName, opt) => {
43
- const templatePath = path.join(TEMPLATE_PATH, templateName);
44
- if (!await UtilFT.pathExists(templatePath))
45
- SLogger.error(`模板 ${templateName} 不存在`);
46
- const projectPath = path.join(process.cwd(), opt.projectName);
47
- await UtilFT.ensurePathExists(projectPath, { dir: true });
48
- await copyData(templatePath, projectPath);
49
- await installPackage(projectPath, ['@zwa73/utils'], ['@types/node']);
50
- if (await UtilFT.pathExists(path.join(projectPath, "gitignore")))
51
- await fs.promises.rename(path.join(projectPath, "gitignore"), path.join(projectPath, ".gitignore"));
52
- const packageJson = await UtilFT.loadJSONFile(path.join(projectPath, 'package.json'));
53
- packageJson.name = opt.projectName;
54
- packageJson.description = opt.projectDescription;
55
- packageJson.author = opt.authorName;
56
- await UtilFT.writeJSONFile(path.join(projectPath, 'package.json'), packageJson);
57
- switch (templateName) {
58
- case 'base': break;
59
- case 'electron': break;
60
- }
61
- });
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**重命名文件或路径 */
3
- export declare const CmdMapPath: (program: Command) => Command;
@@ -1,64 +0,0 @@
1
- import { SLogger, UtilFT, match, throwError } from "@zwa73/utils";
2
- import fs from "fs";
3
- import path from "pathe";
4
- const DupMethodList = ["skip", "overwrite", "move"];
5
- const DupMethodWithoutMove = DupMethodList.filter(t => t != 'move');
6
- /**重命名文件或路径 */
7
- export const CmdMapPath = (program) => program
8
- .command("Map-Path")
9
- .alias("mappath")
10
- .description("根据正则表达式对文件名进行映射")
11
- .argument("<regex>", "要匹配的正则表达式, posix风格路径")
12
- .argument("<replacement>", "替换字符串")
13
- .option("-e, --exclude <regex>", "排除文件的正则表达式")
14
- .option(`-d, --duplicate-handling <${DupMethodWithoutMove.join('|')}|[path:string]>`, `处理重名文件的方式:
15
- skip 不进行处理
16
- overwrite 覆盖重名
17
- 其他字符串 将重名部分映射到指定目录下的对应位置, 再次重复将会覆盖`, "skip")
18
- .option("-r, --recursive", "是否处理子目录", false)
19
- .option("-m, --move", "重命名而不是复制文件", false)
20
- .option("-t, --test", "不对文件进行实际操作, 在控制台输出映射结果", false)
21
- .action(async (regexStr, replacement, options) => {
22
- const regex = new RegExp(regexStr);
23
- const excludeRegex = options.exclude ? new RegExp(options.exclude) : null;
24
- if (!DupMethodList.includes(options.duplicateHandling))
25
- throwError(`${options.duplicateHandling} 不是有效的 duplicate-handling`);
26
- const duplicateHandling = options.duplicateHandling;
27
- const basePath = process.cwd();
28
- // 遍历当前目录下的所有文件
29
- const filePaths = (await UtilFT.fileSearchRegex(basePath, regex.source, { relative: options.recursive }))
30
- .map((filePath) => path.relative(basePath, filePath))
31
- .filter((filePath) => excludeRegex ? (!excludeRegex.test(filePath)) : true);
32
- //对单个路径映射
33
- const mapPath = async (source, target) => {
34
- const dir = path.parse(target).dir;
35
- await UtilFT.ensurePathExists(dir, { dir: true });
36
- if (options.test)
37
- return SLogger.info(`${source} -> ${target}`);
38
- if (options.move)
39
- await fs.promises.rename(source, target);
40
- else
41
- await fs.promises.copyFile(source, target);
42
- };
43
- for (const filePath of filePaths) {
44
- // 重命名文件
45
- const newFilePath = filePath.replace(regex, replacement);
46
- // 如果文件名发生了变化
47
- if (newFilePath === filePath)
48
- continue;
49
- //如果文件已存在
50
- if (await UtilFT.pathExists(newFilePath)) {
51
- if (DupMethodWithoutMove.includes(options.duplicateHandling)) {
52
- const fixhd = duplicateHandling;
53
- await match(fixhd, {
54
- 'skip': () => SLogger.info(`重名文件存在,跳过:${newFilePath}`),
55
- 'overwrite': () => mapPath(filePath, newFilePath),
56
- });
57
- }
58
- else
59
- await mapPath(filePath, path.join(duplicateHandling, newFilePath));
60
- }
61
- else
62
- await mapPath(filePath, newFilePath);
63
- }
64
- });
@@ -1,3 +0,0 @@
1
- import { Command } from 'commander';
2
- /**编译并运行某个文件 */
3
- export declare const CmdNode: (program: Command) => Command;
@@ -1,14 +0,0 @@
1
- import { SLogger, UtilFunc } from '@zwa73/utils';
2
- /**编译并运行某个文件 */
3
- export const CmdNode = (program) => program
4
- .command('Node <path|path[]>')
5
- .alias('node')
6
- .option('-p, --project <path>', 'tsconfig的目录')
7
- .description('编译并运行某个文件')
8
- .action(async (arg, opt) => {
9
- SLogger.info(`编译并运行: ${arg}`);
10
- let cmd = `ts-node -r tsconfig-paths/register ${arg}`;
11
- if (opt.project)
12
- cmd += ` -P ${opt.project}`;
13
- await UtilFunc.exec(cmd, { outlvl: 'info', errlvl: 'error' });
14
- });
@@ -1,3 +0,0 @@
1
- import { Command } from 'commander';
2
- /**更新版本号并发布npm包 */
3
- export declare const CmdRelease: (program: Command) => Command;