@zwa73/dev-utils 1.0.88 → 1.0.90

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 (113) hide show
  1. package/bin/cli +1 -1
  2. package/data/template/base/package.json +7 -6
  3. package/data/template/base/scripts/compile.ps1 +25 -8
  4. package/data/template/base/scripts/release.ps1 +5 -2
  5. package/data/template/base/tsconfig.json +3 -5
  6. package/data/template/base/tsup.config.js +35 -0
  7. package/data/template/cjs/gitignore +3 -0
  8. package/data/template/cjs/package.json +19 -0
  9. package/data/template/cjs/scripts/compile.ps1 +13 -0
  10. package/data/template/cjs/scripts/expand-macro.ps1 +2 -0
  11. package/data/template/cjs/scripts/release.ps1 +8 -0
  12. package/data/template/cjs/scripts/watch.ps1 +10 -0
  13. package/data/template/cjs/src/index.ts +0 -0
  14. package/data/template/cjs/src/macro.macro.ts +6 -0
  15. package/data/template/cjs/tsconfig.compile.json +12 -0
  16. package/data/template/cjs/tsconfig.json +21 -0
  17. package/data/template/electron/package.json +25 -25
  18. package/dist/Command/Bump.d.ts +6 -0
  19. package/dist/Command/Bump.js +70 -0
  20. package/dist/Command/CheckToken.d.ts +10 -0
  21. package/dist/Command/CheckToken.js +52 -0
  22. package/dist/{mjs/Command → Command}/ExpandMacro.d.ts +1 -1
  23. package/dist/{cjs/Command → Command}/GenI18n.d.ts +1 -1
  24. package/dist/{cjs/Command → Command}/GenI18n.js +20 -12
  25. package/dist/{cjs/Command → Command}/GenSchema.d.ts +1 -1
  26. package/dist/{cjs/Command → Command}/GenTemplate.d.ts +1 -1
  27. package/dist/{cjs/Command → Command}/GenTemplate.js +9 -6
  28. package/dist/{cjs/Command → Command}/MapPath.d.ts +1 -1
  29. package/dist/Command/MapPath.js +115 -0
  30. package/dist/{cjs/Command → Command}/Node.d.ts +1 -1
  31. package/dist/{cjs/Command → Command}/Node.js +1 -1
  32. package/dist/{cjs/Command → Command}/Release.d.ts +1 -1
  33. package/dist/{cjs/Command → Command}/Release.js +9 -45
  34. package/dist/{cjs/Command → Command}/Route.js +7 -5
  35. package/dist/{cjs/Command → Command}/ScanDups.d.ts +1 -1
  36. package/dist/{cjs/Command → Command}/ScanDups.js +15 -13
  37. package/dist/DynImport.d.ts +15 -0
  38. package/dist/DynImport.js +15 -0
  39. package/dist/{mjs/UtilAst.d.ts → UtilAst.d.ts} +2 -2
  40. package/dist/{mjs/UtilDevTool.d.ts → UtilDevTool.d.ts} +1 -1
  41. package/dist/{cjs/UtilDevTool.js → UtilDevTool.js} +21 -38
  42. package/dist/UtilInterface.d.ts +8 -0
  43. package/dist/UtilMacro.d.ts +7 -0
  44. package/dist/{cjs/UtilMacro.js → UtilMacro.js} +4 -4
  45. package/package.json +2 -10
  46. package/data/template/base/tsconfig.cjs.json +0 -8
  47. package/data/template/base/tsconfig.mjs.json +0 -9
  48. package/dist/cjs/Command/ExpandMacro.d.ts +0 -3
  49. package/dist/cjs/Command/MapPath.js +0 -80
  50. package/dist/cjs/UtilAst.d.ts +0 -13
  51. package/dist/cjs/UtilDevTool.d.ts +0 -99
  52. package/dist/cjs/UtilInterface.d.ts +0 -4
  53. package/dist/cjs/UtilMacro.d.ts +0 -7
  54. package/dist/cjs/test/testFileMacro.d.ts +0 -1
  55. package/dist/cjs/test/testFileMacro.js +0 -1
  56. package/dist/cjs/test/testGlobMacro.d.ts +0 -1
  57. package/dist/cjs/test/testGlobMacro.js +0 -2
  58. package/dist/cjs/test/testRegex.d.ts +0 -1
  59. package/dist/cjs/test/testRegex.js +0 -3
  60. package/dist/cjs/test/testRegexa.d.ts +0 -1
  61. package/dist/cjs/test/testRegexa.js +0 -1
  62. package/dist/mjs/Command/ExpandMacro.js +0 -16
  63. package/dist/mjs/Command/GenI18n.d.ts +0 -3
  64. package/dist/mjs/Command/GenI18n.js +0 -75
  65. package/dist/mjs/Command/GenSchema.d.ts +0 -3
  66. package/dist/mjs/Command/GenSchema.js +0 -22
  67. package/dist/mjs/Command/GenTemplate.d.ts +0 -3
  68. package/dist/mjs/Command/GenTemplate.js +0 -61
  69. package/dist/mjs/Command/MapPath.d.ts +0 -3
  70. package/dist/mjs/Command/MapPath.js +0 -73
  71. package/dist/mjs/Command/Node.d.ts +0 -3
  72. package/dist/mjs/Command/Node.js +0 -14
  73. package/dist/mjs/Command/Release.d.ts +0 -3
  74. package/dist/mjs/Command/Release.js +0 -90
  75. package/dist/mjs/Command/Route.d.ts +0 -1
  76. package/dist/mjs/Command/Route.js +0 -20
  77. package/dist/mjs/Command/RouteInterface.d.ts +0 -24
  78. package/dist/mjs/Command/RouteInterface.js +0 -58
  79. package/dist/mjs/Command/ScanDups.d.ts +0 -3
  80. package/dist/mjs/Command/ScanDups.js +0 -114
  81. package/dist/mjs/Command/index.d.ts +0 -1
  82. package/dist/mjs/Command/index.js +0 -1
  83. package/dist/mjs/QuickFunc.d.ts +0 -2
  84. package/dist/mjs/QuickFunc.js +0 -2
  85. package/dist/mjs/UtilAst.js +0 -15
  86. package/dist/mjs/UtilDevTool.js +0 -297
  87. package/dist/mjs/UtilInterface.d.ts +0 -4
  88. package/dist/mjs/UtilInterface.js +0 -1
  89. package/dist/mjs/UtilMacro.d.ts +0 -7
  90. package/dist/mjs/UtilMacro.js +0 -23
  91. package/dist/mjs/index.d.ts +0 -5
  92. package/dist/mjs/index.js +0 -5
  93. package/dist/mjs/test/testFileMacro.d.ts +0 -1
  94. package/dist/mjs/test/testFileMacro.js +0 -1
  95. package/dist/mjs/test/testGlobMacro.d.ts +0 -1
  96. package/dist/mjs/test/testGlobMacro.js +0 -2
  97. package/dist/mjs/test/testRegex.d.ts +0 -1
  98. package/dist/mjs/test/testRegex.js +0 -2
  99. package/dist/mjs/test/testRegexa.d.ts +0 -1
  100. package/dist/mjs/test/testRegexa.js +0 -1
  101. package/dist/{cjs/Command → Command}/ExpandMacro.js +0 -0
  102. package/dist/{cjs/Command → Command}/GenSchema.js +0 -0
  103. package/dist/{cjs/Command → Command}/Route.d.ts +0 -0
  104. package/dist/{cjs/Command → Command}/RouteInterface.d.ts +0 -0
  105. package/dist/{cjs/Command → Command}/RouteInterface.js +1 -1
  106. /package/dist/{cjs/Command → Command}/index.d.ts +0 -0
  107. /package/dist/{cjs/Command → Command}/index.js +0 -0
  108. /package/dist/{cjs/QuickFunc.d.ts → QuickFunc.d.ts} +0 -0
  109. /package/dist/{cjs/QuickFunc.js → QuickFunc.js} +0 -0
  110. /package/dist/{cjs/UtilAst.js → UtilAst.js} +0 -0
  111. /package/dist/{cjs/UtilInterface.js → UtilInterface.js} +0 -0
  112. /package/dist/{cjs/index.d.ts → index.d.ts} +0 -0
  113. /package/dist/{cjs/index.js → index.js} +0 -0
@@ -1,24 +0,0 @@
1
- /**npm镜像源 */
2
- export declare const MIRROR_SOURCE = "https://registry.npmmirror.com/";
3
- /**npm官方源 */
4
- export declare const OFFICIAL_SOURCE = "https://registry.npmjs.org/";
5
- /**根目录 */
6
- export declare const ROOT_PATH: string;
7
- /**data文件夹路径 */
8
- export declare const DATA_PATH: string;
9
- /**template文件夹路径 */
10
- export declare const TEMPLATE_PATH: string;
11
- /**当前路径 */
12
- export declare const PROCESS_PATH: string;
13
- /** 检测非浮点的整数类型 */
14
- export declare function parseInteger(value: string): number;
15
- /** 检测任意数字类型 */
16
- export declare function parseNumber(value: string): number;
17
- /** 检测布尔类型 */
18
- export declare function parseBoolean(value: string): boolean;
19
- /**在镜像源内镜像操作 */
20
- export declare function withMirrorSource(func: (() => any)): Promise<void>;
21
- /**在官方源内镜像操作 */
22
- export declare function withOfficialSource(func: (() => any)): Promise<void>;
23
- /**检查目录是否为项目 */
24
- export declare function checkProject(): Promise<void>;
@@ -1,58 +0,0 @@
1
- import path from 'pathe';
2
- import { SLogger, throwError, UtilFT, UtilFunc } from '@zwa73/utils';
3
- /**npm镜像源 */
4
- export const MIRROR_SOURCE = "https://registry.npmmirror.com/";
5
- /**npm官方源 */
6
- export const OFFICIAL_SOURCE = "https://registry.npmjs.org/";
7
- /**根目录 */
8
- export const ROOT_PATH = path.join(`${process.platform === 'win32' ? '' : '/'}${/file:\/{2,3}(.+)\/[^/]/.exec(import.meta.url)[1]}`, '..', '..', '..');
9
- /**data文件夹路径 */
10
- export const DATA_PATH = path.join(ROOT_PATH, 'data');
11
- /**template文件夹路径 */
12
- export const TEMPLATE_PATH = path.join(DATA_PATH, 'template');
13
- /**当前路径 */
14
- export const PROCESS_PATH = process.cwd();
15
- /** 检测非浮点的整数类型 */
16
- export function parseInteger(value) {
17
- const num = Number(value);
18
- if (!(typeof num === 'number' && isFinite(num) && Math.floor(num) === num))
19
- throwError(`${value} 不是有效的整数数字`);
20
- return num;
21
- }
22
- /** 检测任意数字类型 */
23
- export function parseNumber(value) {
24
- const num = Number(value);
25
- if (!(typeof value === 'number' && isFinite(value)))
26
- throwError(`${value} 不是有效的数字`);
27
- return num;
28
- }
29
- /** 检测布尔类型 */
30
- export function parseBoolean(value) {
31
- return value ? true : false;
32
- }
33
- /**在镜像源内镜像操作 */
34
- export async function withMirrorSource(func) {
35
- const out = await UtilFunc.exec('npm config get registry');
36
- const OriginSource = out.stdout.trim(); //?
37
- SLogger.info(`正在修改npm源为 镜像源: ${MIRROR_SOURCE}`);
38
- await UtilFunc.exec(`npm config set registry ${MIRROR_SOURCE}`);
39
- await func();
40
- SLogger.info(`正在修改npm源为 原始源: ${OriginSource}`);
41
- await UtilFunc.exec(`npm config set registry ${OriginSource}`);
42
- }
43
- /**在官方源内镜像操作 */
44
- export async function withOfficialSource(func) {
45
- const out = await UtilFunc.exec('npm config get registry');
46
- const OriginSource = out.stdout.trim(); //?
47
- SLogger.info(`正在修改npm源为 官方源: ${OFFICIAL_SOURCE}`);
48
- await UtilFunc.exec(`npm config set registry ${OFFICIAL_SOURCE}`);
49
- await func();
50
- SLogger.info(`正在修改npm源为 原始源: ${OriginSource}`);
51
- await UtilFunc.exec(`npm config set registry ${OriginSource}`);
52
- }
53
- /**检查目录是否为项目 */
54
- export async function checkProject() {
55
- const filePath = path.join(PROCESS_PATH, "package.json");
56
- if (!(await UtilFT.pathExists(filePath)))
57
- throwError(`当前目录: ${PROCESS_PATH} 不是npm项目目录, 请先使用 npm init`);
58
- }
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- /**重命名文件或路径 scan_duplicates */
3
- export declare const CmdScanDups: (program: Command) => Command;
@@ -1,114 +0,0 @@
1
- import { match, memoize, pipe, PromiseQueue, SLogger, Stream, UtilFP, UtilFT, UtilFunc } from "@zwa73/utils";
2
- import path from "pathe";
3
- import cliProgress from "cli-progress";
4
- import fs from 'fs';
5
- const { tap } = UtilFP;
6
- /**hashlist转为dupmap */
7
- const reduce2Dupmap = (list) => list.reduce((acc, cur) => {
8
- const files = acc[cur.hash] ?? [];
9
- acc[cur.hash] = [...files, cur.filePath]; // 分类采样哈希到对应文件路径
10
- return acc;
11
- }, {});
12
- /**从dupmap提取重复的filepath */
13
- const reduce2DupFpList = (map) => Object.entries(map).reduce((acc, [hash, files]) => files.length > 1 ? [...acc, ...files] : acc, // 筛选出重复采样哈希的文件路径
14
- []);
15
- /**扫描文件结构 */
16
- const scanDirStruct = memoize(async (root) => {
17
- const list = await fs.promises.readdir(root, { withFileTypes: true });
18
- const stack = await Promise.all(list.map(async (fp) => fp.isDirectory()
19
- ? [fp.name, await scanDirStruct(path.join(root, fp.name))]
20
- : [fp.name, path.join(root, fp.name)]));
21
- return stack.reduce((acc, cur) => ({
22
- ...acc, [cur[0]]: cur[1],
23
- }), {});
24
- });
25
- const hashQueue = new PromiseQueue({ concurrency: 8 });
26
- /**计算文件结构的hash */
27
- async function struct2hash(struct, fn) {
28
- const recursion = (struct) => {
29
- return Object.entries(struct).map(async ([k, v]) => {
30
- if (typeof v === "string")
31
- return [await hashQueue.enqueue(async () => fn(v))];
32
- return (await Promise.all(recursion(v))).flat();
33
- });
34
- };
35
- return UtilFunc.calcHash((await Promise.all(recursion(struct)))
36
- .flat().join('|'), { algorithm: "blake2b512" });
37
- }
38
- /**重命名文件或路径 scan_duplicates */
39
- export const CmdScanDups = (program) => program
40
- .command("Scan-Dups")
41
- .alias("scandups")
42
- .description("扫描当前目录下hash重复的文件")
43
- .option("-i, --include <regex>", "文件的正则表达式, 使用posix路径", ".*")
44
- .option("-o, --out <dir|console>", "输出的json文件路径, 默认 scandups.json, 为 \"console\" 时无文件输出", "scandups")
45
- .option("-r, --recursive", "是否处理子目录, 默认 true", true)
46
- .option("-s, --struct", `结构模式
47
- 只扫描 -i 参数目录下的单层目录, 并计算目录是否出现相同的层次结构
48
- 默认 false`, true)
49
- .option("-d, --dir <dirs...>", `扫描的根目录, 以空格分隔 -d "a/b c" "d e/f", 默认为命令行当前目录`, [])
50
- .action(async (options) => {
51
- const { out: outtype, recursive, include, struct, dir } = options;
52
- const regex = new RegExp(include);
53
- const basePath = process.cwd();
54
- const pathList = dir.length <= 0
55
- ? [process.cwd()]
56
- : dir.map(d => path.isAbsolute(d) ? d : path.join(process.cwd(), d));
57
- // 添加一个多步进度条
58
- const progressBar = new cliProgress.MultiBar({
59
- clearOnComplete: true, hideCursor: true,
60
- format: " {task} [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {status}",
61
- }, cliProgress.Presets.shades_classic);
62
- // 文件结构进度条
63
- const structProgress = struct ? progressBar.create(1, 0, { task: "结构扫描", status: "准备中..." }) : undefined;
64
- // 采样哈希进度条
65
- const sampledProgress = progressBar.create(1, 0, { task: "快速扫描", status: "准备中..." });
66
- // 完整哈希进度条
67
- const fullHashProgress = progressBar.create(1, 0, { task: "完整扫描", status: "准备中..." });
68
- await pipe(
69
- // 第一步:文件搜索,获取符合正则的文件路径
70
- Promise.all(pathList.map(async (p) => {
71
- if (struct)
72
- return (await fs.promises.readdir(p, { withFileTypes: true }))
73
- .filter(fp => fp.isDirectory())
74
- .map(fp => path.join(p, fp.name));
75
- return await UtilFT.fileSearchRegex(p, regex.source, { recursive });
76
- })), stacklist => stacklist.flat(), // 扁平化文件路径列表
77
- // 如果是结构模式则先筛选相同结构
78
- // 扁平化文件路径列表
79
- list => struct ? pipe(list, tap(dupFpList => (structProgress.setTotal(dupFpList.length),
80
- structProgress.update(0, { status: `结构扫描检出 ${dupFpList.length} 个可能的相等项` }))), list => Stream.from(list, 8)
81
- .map(async (filePath) => ({
82
- filePath,
83
- hash: await struct2hash(await scanDirStruct(filePath), cpath => path.relative(filePath, cpath)).then(tap(() => structProgress.increment()))
84
- }))
85
- .toArray(), reduce2Dupmap, reduce2DupFpList) : list,
86
- // 第二步:快速扫描,计算采样哈希
87
- tap(list => (sampledProgress.setTotal(list.length),
88
- sampledProgress.update(0, { status: `总计 ${list.length} 个文件` }))), list => Stream.from(list, 8)
89
- .map(async (filePath) => ({
90
- filePath,
91
- hash: struct
92
- ? await struct2hash(await scanDirStruct(filePath), (str) => UtilFT.calculateHash(str, { sampled: true })).then(tap(() => sampledProgress.increment()))
93
- : await UtilFT.calculateHash(filePath, { sampled: true }).then(tap(() => sampledProgress.increment())),
94
- }))
95
- .toArray(),
96
- // 第三步:筛选重复的采样哈希 (去掉唯一的采样哈希)
97
- reduce2Dupmap, reduce2DupFpList,
98
- // 第四步:对筛选出的重复文件路径并发计算完整哈希
99
- tap(dupFpList => (fullHashProgress.setTotal(dupFpList.length),
100
- fullHashProgress.update(0, { status: `快速扫描检出 ${dupFpList.length} 个可能的相等项` }))), dupFpList => Stream.from(dupFpList, 8)
101
- .map(async (filePath) => ({
102
- filePath,
103
- hash: struct
104
- ? await struct2hash(await scanDirStruct(filePath), (str) => UtilFT.calculateHash(str)).then(tap(() => sampledProgress.increment()))
105
- : await UtilFT.calculateHash(filePath).then(tap(() => fullHashProgress.increment())), // 计算完整哈希
106
- }))
107
- .toArray(),
108
- // 第五步:重新整理完整哈希结果, 过滤唯一哈希
109
- reduce2Dupmap, map => Object.entries(map).reduce((acc, [hash, files]) => files.length <= 1 ? acc : { ...acc, [hash]: files }, {}),
110
- // 第六步:输出结果
111
- tap(() => progressBar.stop()), out => match(outtype, {
112
- "console": () => SLogger.info(out),
113
- }, () => UtilFT.writeJSONFile(path.join(basePath, outtype), out)));
114
- });
@@ -1 +0,0 @@
1
- export * from './Route.js';
@@ -1 +0,0 @@
1
- export * from './Route.js';
@@ -1,2 +0,0 @@
1
- import { UtilDT } from "./UtilDevTool.js";
2
- export declare const regionMacro: typeof UtilDT.regionMacro, fileMacro: typeof UtilDT.fileMacro, commentMacro: typeof UtilDT.commentMacro;
@@ -1,2 +0,0 @@
1
- import { UtilDT } from "./UtilDevTool.js";
2
- export const { regionMacro, fileMacro, commentMacro, } = UtilDT;
@@ -1,15 +0,0 @@
1
- export var UtilAst;
2
- (function (UtilAst) {
3
- /**匹配Node的类型进行处理 无法匹配时返回undefined
4
- * @param node - ast节点
5
- * @param funcMap - 处理函数映射表
6
- */
7
- function withKind(node, funcMap) {
8
- const kind = node.getKind();
9
- const func = funcMap[kind];
10
- if (func)
11
- return func(node);
12
- return undefined;
13
- }
14
- UtilAst.withKind = withKind;
15
- })(UtilAst || (UtilAst = {}));
@@ -1,297 +0,0 @@
1
- import path from 'pathe';
2
- import * as TJS from 'typescript-json-schema';
3
- import * as fs from 'fs';
4
- import { PromiseQueue, SLogger, UtilFT, UtilFunc, dedent, throwError } from '@zwa73/utils';
5
- import { Project, SyntaxKind } from 'ts-morph';
6
- export var UtilDT;
7
- (function (UtilDT) {
8
- /**生成匹配的文件的所有type的schema
9
- * @async
10
- * @param dir - 基础目录
11
- * @param opt - 可选参数
12
- * @param opt.include - 包含的glob 默认 **\/\*.schema.ts
13
- * @param opt.exclude - 忽略的glob
14
- * @param opt.coverDefine - 将会覆盖 definitions 对应内容的表
15
- * @param opt.project - tsconfig路径
16
- * @param opt.outDir - schema输出路径目录 默认 ./schema/
17
- * @param opt.includeTypes - 包含的types正则匹配数组 默认 [/.*\/]
18
- * @param opt.excludeTypes - 排除的types正则匹配数组
19
- */
20
- async function generateSchema(dir, opt) {
21
- //生成
22
- const settings = {
23
- required: true,
24
- aliasRef: true,
25
- tsNodeRegister: true,
26
- ignoreErrors: true,
27
- };
28
- const compilerOptions = {
29
- strictNullChecks: true,
30
- };
31
- if (opt?.project)
32
- Object.assign(compilerOptions, (await UtilFT.loadJSONFile(opt.project)).compilerOptions);
33
- const files = await UtilFT.fileSearchGlob(dir, opt?.include ?? "**/*.schema.ts", { ingore: opt?.exclude });
34
- const program = TJS.getProgramFromFiles(files, compilerOptions);
35
- const gener = TJS.buildGenerator(program, settings);
36
- //const schema = TJS.generateSchema(program, opt?.typeName??"*", settings,undefined,gener) as JObject;
37
- const it = opt?.includeTypes?.map(t => new RegExp(t)) ?? [/.*/];
38
- const et = opt?.excludeTypes?.map(t => new RegExp(t)) ?? [];
39
- const p = new Project();
40
- const types = files.map(fp => p
41
- .addSourceFileAtPath(fp)
42
- .getDescendantsOfKind(SyntaxKind.TypeAliasDeclaration)
43
- .map(d => d.getName())).flat();
44
- const list = gener.getUserSymbols()
45
- .filter(t => types.some(i => i === t))
46
- .filter(t => it.some(i => i.test(t)))
47
- .filter(t => !et.some(i => i.test(t)));
48
- const schema = gener.getSchemaForSymbols(list);
49
- const outDir = opt?.outDir ?? path.join(process.cwd(), 'schema');
50
- const schemasPath = path.join(outDir, 'schemas.json');
51
- //预处理
52
- const proced = procSchema(schema, opt?.coverDefine ?? {});
53
- await Promise.all([
54
- UtilFT.writeJSONFile(schemasPath, proced),
55
- //展开
56
- expandSchema(proced, schemasPath),
57
- ]);
58
- }
59
- UtilDT.generateSchema = generateSchema;
60
- function procSchema(schema, coverDefine) {
61
- //覆盖
62
- coverObj(schema["definitions"], coverDefine);
63
- //替换SchemaString标识符
64
- schema = JSON.parse(JSON.stringify(schema).replace(/\^\.\*SchemaString\$/g, '^.*$'));
65
- return schema;
66
- }
67
- /**展开schema以供使用 */
68
- async function expandSchema(schema, schemasPath) {
69
- const plist = [];
70
- const definitions = schema["definitions"];
71
- //展开定义
72
- for (const typeName in definitions) {
73
- const schema = definitions[typeName];
74
- //展开所有object与忽略检测的类型
75
- if (!(schema.type == "object" || schema.type == "array" || schema.type == undefined))
76
- continue;
77
- if ((/^.+_[0-9]/).test(typeName) || (/^{./).test(typeName))
78
- continue;
79
- const basename = path.basename(schemasPath);
80
- const tpath = path.join(path.dirname(schemasPath), `${typeName}.schema.json`);
81
- if (!UtilFT.isValidFilePath(tpath))
82
- continue;
83
- plist.push(UtilFT.writeJSONFile(tpath, {
84
- "$schema": "http://json-schema.org/draft-07/schema#",
85
- "$ref": `${basename}#/definitions/${typeName}`
86
- }));
87
- }
88
- await Promise.all(plist);
89
- }
90
- /**覆盖object */
91
- function coverObj(base, cover) {
92
- for (const k in cover) {
93
- const v = cover[k];
94
- if (typeof v === "object" && !Array.isArray(v) &&
95
- typeof base[k] === "object" && !Array.isArray(base[k]))
96
- coverObj(base[k], v);
97
- else
98
- base[k] = v;
99
- }
100
- }
101
- /**运行所有匹配的的js/ts文件
102
- * @async
103
- * @param dir - 基础目录
104
- * @param opt - 可选参数
105
- * @param opt.include - 包含的glob 默认 index.ts
106
- * @param opt.exclude - 忽略的glob
107
- * @param opt.project - tsconfig路径
108
- */
109
- async function matchNode(dir, opt) {
110
- const files = await UtilFT.fileSearchGlob(dir, opt?.include ?? "index.ts", { ingore: opt?.exclude });
111
- await batchNode(files, opt);
112
- }
113
- UtilDT.matchNode = matchNode;
114
- /**运行所有js/ts文件
115
- * @async
116
- * @param filepath - 需要运行的文件
117
- * @param opt - 可选参数
118
- * @param opt.project - tsconfig路径
119
- */
120
- async function batchNode(filepath, opt) {
121
- // 确保 filepath 总是一个数组
122
- if (!Array.isArray(filepath))
123
- filepath = [filepath];
124
- // 将所有的相对路径转换为绝对路径
125
- const absolutePaths = filepath.map(fp => path.resolve(process.cwd(), fp));
126
- // 创建一个字符串,其中包含所有文件的 require 语句
127
- const requires = absolutePaths.map(fp => `require('${fp}')`).join(';');
128
- // 创建并执行 ts-node 命令
129
- const cmd = `ts-node -r tsconfig-paths/register -e "${requires}" ${opt?.project ? `-P "${opt.project}"` : ""}`;
130
- await UtilFunc.exec(cmd, { outlvl: 'info', errlvl: 'warn' });
131
- }
132
- UtilDT.batchNode = batchNode;
133
- //#region macro工具
134
- const parseMacroPaths = (opt) => {
135
- // JsFunc -> ComposeFunc -> xxxmacro -> parseMacroPaths -> sourceTS
136
- const loc = UtilFunc.getFuncLoc(4);
137
- if (!loc && !opt?.filePath)
138
- throwError(`parseMacroPaths 未能找到函数位置`);
139
- const basePath = loc?.filePath;
140
- return opt?.filePath
141
- ? opt.glob
142
- ? UtilFT.fileSearchGlob(process.cwd(), opt.filePath)
143
- : typeof opt?.filePath === "string"
144
- ? [opt?.filePath]
145
- : opt?.filePath.map((filepath) => filepath)
146
- : [basePath.replace(/(.+)\.macro\.(js|ts|cjs|mjs)$/, "$1.$2")];
147
- };
148
- const readFile = async (basePath) => (await fs.promises.readFile(basePath, 'utf-8')).replaceAll("\r\n", "\n");
149
- const parseCodeText = async (codeText, opt) => {
150
- const strText = typeof codeText === "function" ? await codeText(opt) : codeText;
151
- return strText.split('\n').map((line) => `${opt.inent}${line}`).join('\n');
152
- };
153
- const literalRegex = (str) => new RegExp(`^${str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')}(?!\\S)`);
154
- //#endregion
155
- /**将codeText写入对应region
156
- * @param regionId - 区域id \`//#region ${id}\`
157
- * @param codeText - 文本
158
- * @param opt - 可选参数
159
- * @param opt.filePath - 目标文件 默认为去除".macro"的同名文件
160
- * @param opt.glob - 使用glob匹配而非文件路径
161
- */
162
- async function regionMacro(regionId, codeText, opt) {
163
- const plist = [];
164
- const filePaths = await parseMacroPaths(opt);
165
- for (const filePath of filePaths) {
166
- const queuefunc = async () => {
167
- if (!(await UtilFT.pathExists(filePath))) {
168
- SLogger.error(`UtilDT.regionMacro ${filePath} 不存在`);
169
- return;
170
- }
171
- let fileText = await readFile(filePath);
172
- const regex = new RegExp(/(^|\n)([^\S\n]*)(\/\/#region (.*)\n)/.source +
173
- /([\s\S]*?)/.source +
174
- /([^\S\n]*\/\/#endregion(?!\S).*)/.source, "g");
175
- regex.lastIndex = 0;
176
- let match;
177
- let hasMatch = false;
178
- while (match = regex.exec(fileText)) {
179
- const id = match[4];
180
- const prefix = match[1];
181
- const content = match[5];
182
- const inent = match[2];
183
- const comment = match[3];
184
- const endcomment = match[6];
185
- const idregex = typeof regionId === "string"
186
- ? literalRegex(regionId) : regionId;
187
- let idmatch = idregex.exec(id);
188
- if (idmatch == null)
189
- continue;
190
- hasMatch = true;
191
- const ol = fileText.length;
192
- const parseCode = await parseCodeText(codeText, {
193
- matchId: idmatch[0],
194
- execArr: idmatch,
195
- text: dedent(content),
196
- inent,
197
- filePath
198
- });
199
- fileText = fileText.replace(match[0], `${prefix}${inent}${comment}${parseCode}\n${endcomment}`);
200
- regex.lastIndex += fileText.length - ol;
201
- }
202
- if (hasMatch)
203
- await fs.promises.writeFile(filePath, fileText, 'utf-8');
204
- else if (!opt?.glob)
205
- SLogger.error(`UtilDT.regionMacro 无法找到区域 ${regionId}`);
206
- };
207
- plist.push(PromiseQueue.enqueue(path.normalize(filePath), queuefunc));
208
- }
209
- await Promise.all(plist);
210
- }
211
- UtilDT.regionMacro = regionMacro;
212
- /**将codeText写入对应注释下
213
- * @param commentId - 注释id \`// ${id}\`
214
- * @param codeText - 文本
215
- * @param opt - 可选参数
216
- * @param opt.filePath - 目标文件 默认为去除".macro"的同名文件
217
- * @param opt.glob - 使用glob匹配而非文件路径
218
- */
219
- async function commentMacro(commentId, codeText, opt) {
220
- const plist = [];
221
- const filePaths = await parseMacroPaths(opt);
222
- for (const filePath of filePaths) {
223
- const queuefunc = async () => {
224
- if (!(await UtilFT.pathExists(filePath))) {
225
- SLogger.error(`UtilDT.commentMacro ${filePath} 不存在`);
226
- return;
227
- }
228
- let fileText = await readFile(filePath);
229
- const regex = new RegExp(/(^|\n)([^\S\n]*)(\/\/ (.*))(\n|)/.source +
230
- /([^\n]*)/.source, "g");
231
- let match;
232
- let hasMatch = false;
233
- while (match = regex.exec(fileText)) {
234
- const id = match[4];
235
- const prefix = match[1];
236
- const content = match[6];
237
- const inent = match[2];
238
- const comment = match[3];
239
- const idregex = typeof commentId === "string"
240
- ? literalRegex(commentId) : commentId;
241
- let idmatch = idregex.exec(id);
242
- if (idmatch == null)
243
- continue;
244
- hasMatch = true;
245
- const ol = fileText.length;
246
- const parseCode = await parseCodeText(codeText, {
247
- matchId: idmatch[0],
248
- execArr: idmatch,
249
- text: dedent(content),
250
- inent,
251
- filePath
252
- });
253
- if (parseCode.includes('\n')) {
254
- SLogger.error(`UtilDT.commentMacro 无法使用多行文本, 考虑使用regionMacro ${codeText}`);
255
- return;
256
- }
257
- fileText = fileText.replace(match[0], `${prefix}${inent}${comment}\n${parseCode}`);
258
- regex.lastIndex += fileText.length - ol;
259
- }
260
- if (hasMatch)
261
- await fs.promises.writeFile(filePath, fileText, 'utf-8');
262
- else if (!opt?.glob)
263
- SLogger.error(`UtilDT.commentMacro 无法找到注释 ${commentId}`);
264
- };
265
- plist.push(PromiseQueue.enqueue(path.normalize(filePath), queuefunc));
266
- }
267
- await Promise.all(plist);
268
- }
269
- UtilDT.commentMacro = commentMacro;
270
- /**将codeText写入对应文件 不存在则创建
271
- * @param codeText - 文本
272
- * @param opt - 可选参数
273
- * @param opt.filePath - 目标文件 默认为去除".macro"的同名文件
274
- * @param opt.glob - 使用glob匹配而非文件路径
275
- */
276
- async function fileMacro(codeText, opt) {
277
- const plist = [];
278
- const filePaths = await parseMacroPaths(opt);
279
- for (const filePath of filePaths) {
280
- const queuefunc = async () => {
281
- await UtilFT.ensurePathExists(filePath);
282
- const text = await readFile(filePath);
283
- const parseCode = await parseCodeText(codeText, {
284
- matchId: '',
285
- execArr: /''/.exec(''),
286
- text,
287
- inent: '',
288
- filePath
289
- });
290
- await fs.promises.writeFile(filePath, parseCode, 'utf-8');
291
- };
292
- plist.push(PromiseQueue.enqueue(path.normalize(filePath), queuefunc));
293
- }
294
- await Promise.all(plist);
295
- }
296
- UtilDT.fileMacro = fileMacro;
297
- })(UtilDT || (UtilDT = {}));
@@ -1,4 +0,0 @@
1
- /**用于辅助解析只能补全的类型
2
- * 输出后替换为 ^.*$ 的 string 匹配
3
- */
4
- export type SchemaString = `${string}SchemaString`;
@@ -1 +0,0 @@
1
- export {};
@@ -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,23 +0,0 @@
1
- import { UtilFT } from "@zwa73/utils";
2
- import { commentMacro } from "./QuickFunc.js";
3
- import path from "pathe";
4
- export var UtilMacro;
5
- (function (UtilMacro) {
6
- /**根据注释批量生成导出
7
- * @param glob - 应用的golb
8
- * @example
9
- */
10
- function exportComment(glob) {
11
- commentMacro(/export (\S*)/, async ({ filePath, matchId, execArr }) => {
12
- const basedir = path.dirname(filePath);
13
- const result = (await UtilFT.fileSearchGlob(basedir, execArr[1]))
14
- .map((file) => path.relative(basedir, file))
15
- .map((file) => path.parse(file).name)
16
- .filter((file) => file != path.parse(filePath).name)
17
- .map((file) => `export * from './${file}'`)
18
- .join(';');
19
- return result.length > 0 ? `${result};` : result;
20
- }, { glob: true, filePath: glob });
21
- }
22
- UtilMacro.exportComment = exportComment;
23
- })(UtilMacro || (UtilMacro = {}));
@@ -1,5 +0,0 @@
1
- export * from './UtilDevTool.js';
2
- export * from './Command/index.js';
3
- export * from "./QuickFunc.js";
4
- export * from './UtilMacro.js';
5
- export * from './UtilInterface.js';
package/dist/mjs/index.js DELETED
@@ -1,5 +0,0 @@
1
- export * from './UtilDevTool.js';
2
- export * from './Command/index.js';
3
- export * from "./QuickFunc.js";
4
- export * from './UtilMacro.js';
5
- export * from './UtilInterface.js';
@@ -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,2 +0,0 @@
1
- 2;
2
- export {};
@@ -1 +0,0 @@
1
- type CM1 = 3;
@@ -1 +0,0 @@
1
- "use strict";
File without changes
File without changes
File without changes
@@ -10,8 +10,8 @@ exports.parseBoolean = parseBoolean;
10
10
  exports.withMirrorSource = withMirrorSource;
11
11
  exports.withOfficialSource = withOfficialSource;
12
12
  exports.checkProject = checkProject;
13
- const pathe_1 = __importDefault(require("pathe"));
14
13
  const utils_1 = require("@zwa73/utils");
14
+ const pathe_1 = __importDefault(require("pathe"));
15
15
  /**npm镜像源 */
16
16
  exports.MIRROR_SOURCE = "https://registry.npmmirror.com/";
17
17
  /**npm官方源 */
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes