@zwa73/utils 1.0.266 → 1.0.268

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.
@@ -10,8 +10,9 @@ export declare class Hbs<T extends Record<Keyable, any> = Record<Keyable, any>>
10
10
  */
11
11
  private constructor();
12
12
  /**创建一个新的 Hbs 实例
13
- * @param context - 上下文对象,用于在渲染模板时提供数据
14
- */
13
+ * 依赖于 handlebars@4.7.8 但不会自动安装
14
+ * @param context - 上下文对象,用于在渲染模板时提供数据
15
+ */
15
16
  static create<T extends Record<Keyable, any> = Record<Keyable, any>>(context?: T): Promise<Hbs<T>>;
16
17
  /**渲染模板
17
18
  * @param template - 要渲染的 Handlebars 模板字符串
@@ -31,8 +31,9 @@ class Hbs {
31
31
  });
32
32
  }
33
33
  /**创建一个新的 Hbs 实例
34
- * @param context - 上下文对象,用于在渲染模板时提供数据
35
- */
34
+ * 依赖于 handlebars@4.7.8 但不会自动安装
35
+ * @param context - 上下文对象,用于在渲染模板时提供数据
36
+ */
36
37
  static async create(context = {}) {
37
38
  const Handlebars = await js_utils_1.JsFunc.dynamicImport('handlebars');
38
39
  if (Handlebars == undefined)
@@ -0,0 +1,28 @@
1
+ import { stringify } from 'yaml';
2
+ type ExtractBlockOpt = {
3
+ /**要提取的标题 必须为 "# 标题" 的格式 */
4
+ title: string;
5
+ /**将标题从结构中排除 */
6
+ trimTitle: boolean;
7
+ };
8
+ /**Markdown解析器 */
9
+ export declare class Markdown {
10
+ data: Record<string, any>;
11
+ content: string;
12
+ constructor(data: Record<string, any>, content: string);
13
+ /**从内容文本构建Md */
14
+ static parse(ctx?: string): Promise<Markdown>;
15
+ /**从文件构建Md */
16
+ static fromFile(filepath: string): Promise<Markdown>;
17
+ /**输出md文本 */
18
+ stringify(opt: Exclude<Parameters<typeof stringify>[2], string | number>): Promise<string>;
19
+ /**根据标题提取块
20
+ * @param opt - 选项
21
+ */
22
+ extractBlock(opt: ExtractBlockOpt): string | undefined;
23
+ /**根据标题提取块内第一个json代码块
24
+ * @param opt - 选项
25
+ */
26
+ extractJson(title: string): string | undefined;
27
+ }
28
+ export {};
@@ -0,0 +1,72 @@
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.Markdown = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const js_utils_1 = require("@zwa73/js-utils");
9
+ const UtilLogger_1 = require("../UtilLogger");
10
+ const yaml_1 = require("yaml");
11
+ const getMatter = async () => {
12
+ const matter = await js_utils_1.JsFunc.dynamicImport('gray-matter');
13
+ if (matter == undefined)
14
+ js_utils_1.JsFunc.throwError(`npm包 gray-matter 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i gray-matter@4.0.3 来安装`);
15
+ return matter;
16
+ };
17
+ /**Markdown解析器 */
18
+ class Markdown {
19
+ data;
20
+ content;
21
+ constructor(data, content) {
22
+ this.data = data;
23
+ this.content = content;
24
+ }
25
+ /**从内容文本构建Md */
26
+ static async parse(ctx = '') {
27
+ const { data, content } = (await getMatter())(ctx);
28
+ return new Markdown(data, content);
29
+ }
30
+ /**从文件构建Md */
31
+ static async fromFile(filepath) {
32
+ const context = (await fs_1.default.promises.readFile(filepath, 'utf-8')).replace(/\r\n/g, '\n');
33
+ return Markdown.parse(context);
34
+ }
35
+ /**输出md文本 */
36
+ async stringify(opt) {
37
+ const yamlText = Object.values(this.data).length > 0 ? `---\n${(0, yaml_1.stringify)(this.data, opt)}---\n` : '';
38
+ return `${yamlText}${this.content}`;
39
+ //return (await getMatter()).stringify(this.content,this.data);
40
+ }
41
+ /**根据标题提取块
42
+ * @param opt - 选项
43
+ */
44
+ extractBlock(opt) {
45
+ const { title, trimTitle = false } = opt;
46
+ // 匹配标题格式,要求为 "# 标题" 或 "## 标题" 等
47
+ const matchTitle = title.match(/(#+) (.+)/);
48
+ if (matchTitle == null) {
49
+ UtilLogger_1.SLogger.warn(`${title} 不是有效的md标题, 必须为 "(#+) (标题)"`);
50
+ return undefined;
51
+ }
52
+ const [, level, content] = matchTitle;
53
+ /**构造正则:
54
+ * - (^|\n)${level} ${content}:匹配标题行(支持开头或换行)
55
+ * - [\s\S]*?:非贪婪匹配标题后的所有内容
56
+ * - (?=\n${level} |$):直到下一个同级标题或文件结束
57
+ */
58
+ const pattern = new RegExp(`(^|\\n)${level} ${content}[\\s\\S]*?(?=\\n${level} |$)`);
59
+ const match = this.content.match(pattern);
60
+ const result = match ? match[0].trim() : undefined;
61
+ return trimTitle && result !== undefined
62
+ ? result.replace(new RegExp(`^${level} ${content}\\n?`), '')
63
+ : result;
64
+ }
65
+ /**根据标题提取块内第一个json代码块
66
+ * @param opt - 选项
67
+ */
68
+ extractJson(title) {
69
+ return this.extractBlock({ title, trimTitle: true })?.trim().replace(/```json\n([\s\S]+)\n```/, '$1');
70
+ }
71
+ }
72
+ exports.Markdown = Markdown;
@@ -11,31 +11,37 @@ export declare namespace UtilCodec {
11
11
  */
12
12
  function encodeHtmlEntities(str: string): string;
13
13
  /**token长度计算器 Turbo模型
14
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
14
15
  * @param str = 所要计算的消息
15
16
  * @returns 整数长度结果
16
17
  */
17
18
  function tokenNumTurbo(str: string): Promise<number>;
18
19
  /**token长度计算器 Davinci模型
20
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
19
21
  * @param str = 所要计算的消息
20
22
  * @returns 整数长度结果
21
23
  */
22
24
  function tokenNumDavinci(str: string): Promise<number>;
23
25
  /**token编码 Turbo模型
26
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
24
27
  * @param str = 所要计算的消息
25
28
  * @returns Token数组
26
29
  */
27
30
  function encodeTokenTurbo(str: string): Promise<Uint32Array>;
28
31
  /**token编码 Davinci模型
32
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
29
33
  * @param str = 所要计算的消息
30
34
  * @returns Token数组
31
35
  */
32
36
  function encodeTokenDavinci(str: string): Promise<Uint32Array>;
33
37
  /**token解码 Turbo模型
38
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
34
39
  * @param arr = Token数组
35
40
  * @returns 消息字符串
36
41
  */
37
42
  function decodeTokenTurbo(arr: Uint32Array | number[]): Promise<string>;
38
43
  /**token解码 Davinci模型
44
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
39
45
  * @param arr = Token数组
40
46
  * @returns 消息字符串
41
47
  */
@@ -26,20 +26,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.UtilCodec = void 0;
27
27
  const he = __importStar(require("html-entities"));
28
28
  const UtilFunctions_1 = require("./UtilFunctions");
29
+ /**引入tiktoken
30
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
31
+ */
29
32
  async function importTikToken() {
30
33
  const tik = await UtilFunctions_1.UtilFunc.dynamicImport("tiktoken");
31
34
  if (tik == undefined)
32
35
  UtilFunctions_1.UtilFunc.throwError(`npm包 tiktoken 动态导入失败, 此包不会随@zwa73/utils自动安装, 可能是未安装, 可使用 npm i tiktoken@1.0.7 来安装`);
33
36
  return tik;
34
37
  }
38
+ //#endregion
35
39
  /**编码/解码器 */
36
40
  var UtilCodec;
37
41
  (function (UtilCodec) {
38
- /**gpt-4, gpt-3.5-turbo, text-embedding-ada-002, text-embedding-3-small, text-embedding-3-large
39
- */
42
+ /**gpt-4, gpt-3.5-turbo, text-embedding-ada-002, text-embedding-3-small, text-embedding-3-large */
40
43
  let encoderCl100kBase = null;
41
- /**Codex models, text-davinci-002, text-davinci-003
42
- */
44
+ /**Codex models, text-davinci-002, text-davinci-003 */
43
45
  let encoderP50kBase = null;
44
46
  const textDecoder = new TextDecoder();
45
47
  /**HTML实体解码 将一个字符串中的HTML实体转换为对应的字符
@@ -62,8 +64,10 @@ var UtilCodec;
62
64
  //token长度计算器
63
65
  //cl100k_base ChatGPT models, text-embedding-ada-002
64
66
  //p50k_base Code models, text-davinci-002, text-davinci-003
65
- //r50k_base (or gpt2) GPT-3 models like davinci
66
- //避免在nextjs调用时出错
67
+ //r50k_base (or gpt2) GPT-3 models like davinci
68
+ /**避免在nextjs调用时出错
69
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
70
+ */
67
71
  async function initTikTokenEncoder() {
68
72
  if (encoderCl100kBase != null && encoderP50kBase != null)
69
73
  return;
@@ -72,6 +76,7 @@ var UtilCodec;
72
76
  encoderP50kBase = get_encoding("p50k_base");
73
77
  }
74
78
  /**token长度计算器 Turbo模型
79
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
75
80
  * @param str = 所要计算的消息
76
81
  * @returns 整数长度结果
77
82
  */
@@ -82,6 +87,7 @@ var UtilCodec;
82
87
  }
83
88
  UtilCodec.tokenNumTurbo = tokenNumTurbo;
84
89
  /**token长度计算器 Davinci模型
90
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
85
91
  * @param str = 所要计算的消息
86
92
  * @returns 整数长度结果
87
93
  */
@@ -91,6 +97,7 @@ var UtilCodec;
91
97
  }
92
98
  UtilCodec.tokenNumDavinci = tokenNumDavinci;
93
99
  /**token编码 Turbo模型
100
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
94
101
  * @param str = 所要计算的消息
95
102
  * @returns Token数组
96
103
  */
@@ -100,6 +107,7 @@ var UtilCodec;
100
107
  }
101
108
  UtilCodec.encodeTokenTurbo = encodeTokenTurbo;
102
109
  /**token编码 Davinci模型
110
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
103
111
  * @param str = 所要计算的消息
104
112
  * @returns Token数组
105
113
  */
@@ -109,6 +117,7 @@ var UtilCodec;
109
117
  }
110
118
  UtilCodec.encodeTokenDavinci = encodeTokenDavinci;
111
119
  /**token解码 Turbo模型
120
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
112
121
  * @param arr = Token数组
113
122
  * @returns 消息字符串
114
123
  */
@@ -120,6 +129,7 @@ var UtilCodec;
120
129
  }
121
130
  UtilCodec.decodeTokenTurbo = decodeTokenTurbo;
122
131
  /**token解码 Davinci模型
132
+ * 依赖于 tiktoken@1.0.7 但不会自动安装
123
133
  * @param arr = Token数组
124
134
  * @returns 消息字符串
125
135
  */
@@ -144,7 +144,7 @@ var UtilFT;
144
144
  UtilFT.ensurePathExistsSync = ensurePathExistsSync;
145
145
  function loadJSONFileSync(filePath, opt) {
146
146
  try {
147
- if (opt?.forceExt !== true && pathe_1.default.extname(filePath) !== '.json')
147
+ if (opt?.forceExt !== true && pathe_1.default.extname(filePath) == '')
148
148
  filePath += '.json';
149
149
  const str = pathExistsSync(filePath)
150
150
  ? fs.readFileSync(filePath, "utf-8")
@@ -167,7 +167,7 @@ var UtilFT;
167
167
  UtilFT.loadJSONFileSync = loadJSONFileSync;
168
168
  async function loadJSONFile(filePath, opt) {
169
169
  try {
170
- if (opt?.forceExt !== true && pathe_1.default.extname(filePath) !== '.json')
170
+ if (opt?.forceExt !== true && pathe_1.default.extname(filePath) == '')
171
171
  filePath += '.json';
172
172
  const str = (await pathExists(filePath))
173
173
  ? await fs.promises.readFile(filePath, "utf-8")
@@ -202,7 +202,7 @@ var UtilFT;
202
202
  */
203
203
  async function writeJSONFile(filePath, token, opt) {
204
204
  const str = UtilFunctions_1.UtilFunc.stringifyJToken(token, opt);
205
- if (opt?.forceExt !== true && pathe_1.default.extname(filePath) !== '.json')
205
+ if (opt?.forceExt !== true && pathe_1.default.extname(filePath) == '')
206
206
  filePath += '.json';
207
207
  // 判断文件路径是否存在 不存在则创建
208
208
  if (!(await pathExists(filePath)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.266",
3
+ "version": "1.0.268",
4
4
  "description": "my utils",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -27,7 +27,8 @@
27
27
  "pathe": "^1.1.2",
28
28
  "querystring": "^0.2.1",
29
29
  "winston": "^3.10.0",
30
- "winston-daily-rotate-file": "^4.7.1"
30
+ "winston-daily-rotate-file": "^4.7.1",
31
+ "yaml": "^2.8.1"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@deepkit/type": "^1.0.1-alpha.153",