@h-ai/core 0.1.0-alpha5
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/LICENSE +202 -0
- package/README.md +422 -0
- package/dist/browser.d.ts +43 -0
- package/dist/browser.js +115 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-2GTCDC56.js +14761 -0
- package/dist/chunk-2GTCDC56.js.map +1 -0
- package/dist/core-util-module-B-wH5_ZT.d.ts +1626 -0
- package/dist/node.d.ts +82 -0
- package/dist/node.js +643 -0
- package/dist/node.js.map +1 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [2026] [idealworld.group]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
# @h-ai/core
|
|
2
|
+
|
|
3
|
+
> hai Agent Framework 核心模块 — 提供统一的基础工具、类型定义、配置管理和日志功能。
|
|
4
|
+
|
|
5
|
+
## 支持的能力
|
|
6
|
+
|
|
7
|
+
- **HaiResult 类型** — 函数式错误处理(`ok` / `err`),所有模块统一返回值
|
|
8
|
+
- **统一日志** — Node.js 基于 pino,浏览器基于 loglevel,API 一致
|
|
9
|
+
- **国际化(i18n)** — 集中式 locale 管理 + 类型安全的消息获取器
|
|
10
|
+
- **配置管理** — YAML 加载、环境变量插值、Zod 校验、文件监听(Node.js 专用)
|
|
11
|
+
- **ID 生成** — nanoid 与 UUID v4
|
|
12
|
+
- **错误定义** — 标准化错误码体系,支持跨模块统一的错误定义与实例创建
|
|
13
|
+
- **模块工具** — NotInitializedKit 代理模式,各模块共用的生命周期基础设施
|
|
14
|
+
- **工具函数库** — 类型检查、对象 / 字符串 / 数组 / 异步 / 时间操作
|
|
15
|
+
|
|
16
|
+
## 快速开始
|
|
17
|
+
|
|
18
|
+
### Node.js 环境
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { core } from '@h-ai/core'
|
|
22
|
+
|
|
23
|
+
// 初始化:加载配置目录(可选)
|
|
24
|
+
core.init({ configDir: './config', watchConfig: true })
|
|
25
|
+
|
|
26
|
+
// 日志
|
|
27
|
+
core.logger.info('Server started', { port: 3000 })
|
|
28
|
+
core.logger.warn('Slow query', { duration: 2500 })
|
|
29
|
+
core.logger.error('Connection failed', { error })
|
|
30
|
+
|
|
31
|
+
// 创建模块级 logger(独立名称空间)
|
|
32
|
+
const dbLogger = core.logger.create({ name: 'db' })
|
|
33
|
+
dbLogger.info('Connected to PostgreSQL')
|
|
34
|
+
|
|
35
|
+
// 创建子 logger(自动携带固定上下文,适合请求级/操作级追踪)
|
|
36
|
+
const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
|
|
37
|
+
reqLogger.info('Request started') // 日志自动包含 requestId + userId
|
|
38
|
+
reqLogger.error('Request failed') // 同上
|
|
39
|
+
|
|
40
|
+
// 子 logger 可嵌套
|
|
41
|
+
const opLogger = reqLogger.child({ operation: 'createOrder' })
|
|
42
|
+
opLogger.info('Order created') // 包含 requestId + userId + operation
|
|
43
|
+
|
|
44
|
+
// i18n
|
|
45
|
+
core.i18n.setGlobalLocale('zh-CN')
|
|
46
|
+
const getMessage = core.i18n.createMessageGetter({
|
|
47
|
+
'zh-CN': { welcome: '欢迎 {name}', error: '发生错误:{msg}' },
|
|
48
|
+
'en-US': { welcome: 'Welcome {name}', error: 'Error: {msg}' },
|
|
49
|
+
})
|
|
50
|
+
getMessage('welcome', { params: { name: 'Alice' } }) // '欢迎 Alice'
|
|
51
|
+
|
|
52
|
+
// ID 生成
|
|
53
|
+
const nanoid = core.id.generate()
|
|
54
|
+
const shortId = core.id.short()
|
|
55
|
+
const uuid = core.id.uuid()
|
|
56
|
+
const prefixed = core.id.withPrefix('order_')
|
|
57
|
+
|
|
58
|
+
// 工具函数
|
|
59
|
+
core.object.deepMerge(objA, objB)
|
|
60
|
+
core.string.capitalize('hello')
|
|
61
|
+
core.array.unique([1, 1, 2, 3])
|
|
62
|
+
core.array.chunk([1, 2, 3, 4, 5], 2) // [[1,2], [3,4], [5]]
|
|
63
|
+
await core.async.delay(1000)
|
|
64
|
+
await core.async.retry(() => fetchData(), { maxRetries: 3, delay: 1000 })
|
|
65
|
+
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
66
|
+
core.typeUtils.isDefined(value)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### 浏览器环境
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { core } from '@h-ai/core'
|
|
73
|
+
|
|
74
|
+
// 初始化日志级别(浏览器不支持配置加载)
|
|
75
|
+
core.init({ logging: { level: 'warn' } })
|
|
76
|
+
|
|
77
|
+
core.logger.info('Page ready')
|
|
78
|
+
const id = core.id.generate()
|
|
79
|
+
|
|
80
|
+
// 其他工具函数与 Node.js 相同
|
|
81
|
+
core.string.capitalize('hello')
|
|
82
|
+
core.array.unique([1, 1, 2])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## 详细 API
|
|
86
|
+
|
|
87
|
+
### 日志(Logger)
|
|
88
|
+
|
|
89
|
+
`core.logger` 既是默认 Logger 实例,也是日志管理的统一入口。
|
|
90
|
+
|
|
91
|
+
#### 日志记录
|
|
92
|
+
|
|
93
|
+
6 个级别:`trace` / `debug` / `info` / `warn` / `error` / `fatal`
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
core.logger.info('User created', { userId: '123' })
|
|
97
|
+
core.logger.error('Failed to connect', { error })
|
|
98
|
+
core.logger.debug('Processing item', { id, step: 'validation' })
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
#### 创建模块级 logger
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// 独立名称空间,适合模块内全局使用
|
|
105
|
+
const logger = core.logger.create({ name: 'payment' })
|
|
106
|
+
logger.info('Payment processed')
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
#### 子 logger(child)
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
// 携带固定上下文,每条日志自动附带这些字段
|
|
113
|
+
const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
|
|
114
|
+
reqLogger.info('Request started') // 输出包含 requestId + userId
|
|
115
|
+
reqLogger.warn('Slow response') // 同上
|
|
116
|
+
|
|
117
|
+
// 嵌套 child:子上下文递归合并
|
|
118
|
+
const opLogger = reqLogger.child({ operation: 'login' })
|
|
119
|
+
opLogger.info('Login succeeded') // 输出包含 requestId + userId + operation
|
|
120
|
+
opLogger.error('Login failed', { reason: 'invalid_password' })
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
> **典型用法**:在请求入口创建 `reqLogger`,传入 service 层,service 层再 `child` 添加操作上下文,最终日志自动串联完整链路。
|
|
124
|
+
|
|
125
|
+
#### 日志管理
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
// 配置输出格式和级别(Node.js)
|
|
129
|
+
core.logger.configure({
|
|
130
|
+
level: 'info',
|
|
131
|
+
format: 'json', // 'json' | 'pretty'
|
|
132
|
+
context: { app: 'my-service' }, // 全局默认上下文
|
|
133
|
+
redact: ['password', 'token'], // 脱敏字段
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
core.logger.setLevel('debug')
|
|
137
|
+
const level = core.logger.getLevel() // 'debug'
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### 日志级别规范
|
|
141
|
+
|
|
142
|
+
| 级别 | 适用场景 |
|
|
143
|
+
| ------- | ---------------------------------- |
|
|
144
|
+
| `trace` | 循环内详细调试数据 |
|
|
145
|
+
| `debug` | 函数进入、参数概要、读操作 |
|
|
146
|
+
| `info` | 业务事件(初始化完成、写操作成功) |
|
|
147
|
+
| `warn` | 异常但可恢复(校验失败、重试) |
|
|
148
|
+
| `error` | 操作失败(需人工排查) |
|
|
149
|
+
| `fatal` | 致命错误(服务无法继续) |
|
|
150
|
+
|
|
151
|
+
### 国际化(i18n)
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
// 设置全局语言(所有 getMessage 函数自动响应)
|
|
155
|
+
core.i18n.setGlobalLocale('en-US')
|
|
156
|
+
const current = core.i18n.getGlobalLocale() // 'en-US'
|
|
157
|
+
|
|
158
|
+
// 为每个模块创建消息获取器
|
|
159
|
+
const getMessage = core.i18n.createMessageGetter({
|
|
160
|
+
'zh-CN': { welcome: '欢迎 {name}', error: '错误:{code}' },
|
|
161
|
+
'en-US': { welcome: 'Welcome {name}', error: 'Error: {code}' },
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
// 使用:自动读取全局 locale,支持参数插值
|
|
165
|
+
getMessage('welcome', { params: { name: 'Alice' } }) // 'Welcome Alice'
|
|
166
|
+
|
|
167
|
+
// 支持 locale 参数覆盖
|
|
168
|
+
getMessage('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) // '欢迎 Alice'
|
|
169
|
+
|
|
170
|
+
// 常量
|
|
171
|
+
core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }]
|
|
172
|
+
core.i18n.DEFAULT_LOCALE // 'zh-CN'
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### 配置管理(Node.js 专用)
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
import { core, HaiConfigError } from '@h-ai/core'
|
|
179
|
+
import { z } from 'zod'
|
|
180
|
+
|
|
181
|
+
// 方式 1:init 时自动加载整个配置目录
|
|
182
|
+
core.init({
|
|
183
|
+
configDir: './config', // 扫描该目录所有 .yml 文件
|
|
184
|
+
watchConfig: true, // 监听变更并自动重载
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
// 方式 2:手动加载单个文件(可选 Schema 校验)
|
|
188
|
+
const AppSchema = z.object({
|
|
189
|
+
name: z.string(),
|
|
190
|
+
port: z.number().default(3000),
|
|
191
|
+
})
|
|
192
|
+
const result = core.config.load('app', './config/app.yml', AppSchema)
|
|
193
|
+
if (result.success) {
|
|
194
|
+
core.logger.info('Config loaded', { name: result.data.name })
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
core.logger.error('Config load failed', { code: result.error.code })
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// 校验已加载的配置
|
|
201
|
+
const validResult = core.config.validate('app', AppSchema)
|
|
202
|
+
|
|
203
|
+
// 查询和获取
|
|
204
|
+
if (core.config.has('app')) {
|
|
205
|
+
const cfg = core.config.get<typeof AppSchema>('app') // undefined 或配置
|
|
206
|
+
const cfg2 = core.config.getOrThrow<typeof AppSchema>('app') // 未加载时抛异常
|
|
207
|
+
}
|
|
208
|
+
core.config.keys() // ['core', 'app', 'db', ...]
|
|
209
|
+
|
|
210
|
+
// 重新加载
|
|
211
|
+
const reloadResult = core.config.reload('app')
|
|
212
|
+
|
|
213
|
+
// 监听文件变更
|
|
214
|
+
const unwatch = core.config.watch('app', (newConfig, error) => {
|
|
215
|
+
if (error) {
|
|
216
|
+
core.logger.error('Config reload failed', { error })
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
core.logger.info('Config updated', { config: newConfig })
|
|
220
|
+
})
|
|
221
|
+
unwatch() // 取消监听
|
|
222
|
+
|
|
223
|
+
// 清除缓存(同时停止对应监听)
|
|
224
|
+
core.config.clear('app') // 清除单个
|
|
225
|
+
core.config.clear() // 清除全部
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
#### 环境变量插值
|
|
229
|
+
|
|
230
|
+
`core.config.load()` 加载 YAML 时,自动对字符串值做 `${VAR}` 环境变量替换。
|
|
231
|
+
|
|
232
|
+
- `${VAR}` — 读取 `process.env.VAR`;若不存在则返回 `CONFIG_ENV_VAR_MISSING` 错误
|
|
233
|
+
- `${VAR:default}` — 读取 `process.env.VAR`;若不存在则使用冒号后的默认值
|
|
234
|
+
|
|
235
|
+
**类型还原:** 当整个值恰好是单个变量表达式(如 `${PORT:3000}`)时,插值结果按 YAML 规则还原为原生类型(number / boolean 等)。混合文本始终为字符串。
|
|
236
|
+
|
|
237
|
+
```yaml
|
|
238
|
+
# config/app.yml
|
|
239
|
+
debug: ${DEBUG:false} # → boolean false
|
|
240
|
+
port: ${PORT:3000} # → number 3000
|
|
241
|
+
database: ${DB_CONNECTION} # → 环境变量缺失时报错
|
|
242
|
+
url: http://${HOST}:${PORT} # → string(混合文本)
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### ID 生成
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
const id = core.id.generate() // nanoid 21 字符
|
|
249
|
+
const id8 = core.id.generate(8) // 自定义长度
|
|
250
|
+
const shortId = core.id.short() // 10 字符短 ID
|
|
251
|
+
const prefixed = core.id.withPrefix('user_') // 'user_V1StGXR...'
|
|
252
|
+
const traceId = core.id.trace() // 'trace-V1StGXR...'
|
|
253
|
+
const reqId = core.id.request() // 'req-V1StGXR...'
|
|
254
|
+
const uuid = core.id.uuid() // UUID v4
|
|
255
|
+
|
|
256
|
+
// 校验
|
|
257
|
+
core.id.isValidUUID('f47ac10b-...') // true/false
|
|
258
|
+
core.id.isValidNanoId('abc123', 6) // true/false
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
### 工具函数
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
// 类型检查
|
|
265
|
+
core.typeUtils.isDefined(x) // x !== undefined
|
|
266
|
+
core.typeUtils.isObject(x) // plain object
|
|
267
|
+
core.typeUtils.isFunction(x)
|
|
268
|
+
core.typeUtils.isPromise(x)
|
|
269
|
+
core.typeUtils.isString(x)
|
|
270
|
+
core.typeUtils.isNumber(x)
|
|
271
|
+
core.typeUtils.isBoolean(x)
|
|
272
|
+
core.typeUtils.isArray(x)
|
|
273
|
+
|
|
274
|
+
// 对象操作
|
|
275
|
+
core.object.deepClone(obj)
|
|
276
|
+
core.object.deepMerge(a, b) // 递归合并(防原型污染)
|
|
277
|
+
core.object.deepMerge(a, b, c) // 支持多个对象
|
|
278
|
+
core.object.pick(obj, ['a', 'b'])
|
|
279
|
+
core.object.omit(obj, ['c', 'd'])
|
|
280
|
+
core.object.keys(obj) // typed Object.keys
|
|
281
|
+
core.object.values(obj)
|
|
282
|
+
core.object.entries(obj)
|
|
283
|
+
core.object.fromEntries(entries)
|
|
284
|
+
|
|
285
|
+
// 字符串操作
|
|
286
|
+
core.string.capitalize('hello') // 'Hello'
|
|
287
|
+
core.string.kebabCase('helloWorld') // 'hello-world'
|
|
288
|
+
core.string.camelCase('hello-world') // 'helloWorld'
|
|
289
|
+
core.string.snakeCase('helloWorld') // 'hello_world'
|
|
290
|
+
core.string.pascalCase('hello-world') // 'HelloWorld'
|
|
291
|
+
core.string.truncate('long text', 5) // 'long ...'
|
|
292
|
+
core.string.trim(' hello ') // 'hello'
|
|
293
|
+
core.string.isBlank('') // true
|
|
294
|
+
core.string.isNotBlank('x') // true
|
|
295
|
+
core.string.padStart('5', 3, '0') // '005'
|
|
296
|
+
core.string.padEnd('5', 3, '0') // '500'
|
|
297
|
+
core.string.constantTimeEqual(a, b) // 防时序攻击比较
|
|
298
|
+
|
|
299
|
+
// 数组操作
|
|
300
|
+
core.array.unique([1, 1, 2]) // [1, 2]
|
|
301
|
+
core.array.chunk([1, 2, 3, 4], 2) // [[1,2], [3,4]]
|
|
302
|
+
core.array.groupBy(items, item => item.type) // Record<string, T[]>
|
|
303
|
+
core.array.first([1, 2, 3]) // 1
|
|
304
|
+
core.array.last([1, 2, 3]) // 3
|
|
305
|
+
core.array.flatten([[1], [2, 3]]) // [1, 2, 3]
|
|
306
|
+
core.array.compact([1, null, 2]) // [1, 2]
|
|
307
|
+
core.array.shuffle([1, 2, 3]) // 随机排列
|
|
308
|
+
core.array.intersection([1, 2], [2, 3]) // [2]
|
|
309
|
+
core.array.difference([1, 2], [2, 3]) // [1]
|
|
310
|
+
|
|
311
|
+
// 异步操作
|
|
312
|
+
await core.async.delay(1000)
|
|
313
|
+
await core.async.withTimeout(fetch('/api'), 5000)
|
|
314
|
+
await core.async.retry(fn, { maxRetries: 3, delay: 1000 })
|
|
315
|
+
await core.async.parallel(items, processFn, 5) // 并发限制
|
|
316
|
+
await core.async.serial(items, processFn)
|
|
317
|
+
const debouncedFn = core.async.debounce(fn, 300)
|
|
318
|
+
const throttledFn = core.async.throttle(fn, 200)
|
|
319
|
+
|
|
320
|
+
// 时间操作
|
|
321
|
+
core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
|
|
322
|
+
core.time.timeAgo(new Date(Date.now() - 60000)) // '1 分钟前'
|
|
323
|
+
core.time.now() // Date.now()
|
|
324
|
+
core.time.nowSeconds() // Math.floor(Date.now() / 1000)
|
|
325
|
+
core.time.parseDate('2024-01-01')
|
|
326
|
+
core.time.isValidDate(date)
|
|
327
|
+
core.time.addDays(date, 7)
|
|
328
|
+
core.time.addHours(date, 2)
|
|
329
|
+
core.time.startOfDay(date)
|
|
330
|
+
core.time.endOfDay(date)
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
### 模块基础工具(module)
|
|
334
|
+
|
|
335
|
+
提供各模块共用的初始化错误处理:
|
|
336
|
+
|
|
337
|
+
```typescript
|
|
338
|
+
import { core } from '@h-ai/core'
|
|
339
|
+
|
|
340
|
+
const notInitialized = core.module.createNotInitializedKit(
|
|
341
|
+
HaiDbError.NOT_INITIALIZED,
|
|
342
|
+
() => dbM('db_notInitialized'),
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
// 创建占位 Proxy(异步接口,默认)
|
|
346
|
+
const currentDdl: DdlOperations = notInitialized.proxy<DdlOperations>()
|
|
347
|
+
// 创建占位 Proxy(同步接口)
|
|
348
|
+
const currentHash: HashOperations = notInitialized.proxy<HashOperations>('sync')
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
## 错误处理
|
|
352
|
+
|
|
353
|
+
### HaiResult 类型
|
|
354
|
+
|
|
355
|
+
所有可能失败的操作返回 `HaiResult<T>`:
|
|
356
|
+
|
|
357
|
+
```typescript
|
|
358
|
+
import type { HaiResult } from '@h-ai/core'
|
|
359
|
+
import { core, err, HaiCommonError, ok } from '@h-ai/core'
|
|
360
|
+
|
|
361
|
+
function divide(a: number, b: number): HaiResult<number> {
|
|
362
|
+
if (b === 0)
|
|
363
|
+
return err(HaiCommonError.VALIDATION_ERROR, 'Division by zero')
|
|
364
|
+
return ok(a / b)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const result = divide(10, 2)
|
|
368
|
+
if (result.success) {
|
|
369
|
+
core.logger.info('Result', { data: result.data })
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
core.logger.error('Error', { error: result.error })
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### 自定义错误码(模块级)
|
|
377
|
+
|
|
378
|
+
```typescript
|
|
379
|
+
import type { ErrorInfo } from '@h-ai/core'
|
|
380
|
+
import { core } from '@h-ai/core'
|
|
381
|
+
|
|
382
|
+
// 定义错误码(格式 'code:httpStatus')
|
|
383
|
+
const DbErrorInfo = {
|
|
384
|
+
NOT_INITIALIZED: '001:500',
|
|
385
|
+
CONNECTION_FAILED: '010:500',
|
|
386
|
+
QUERY_FAILED: '011:500',
|
|
387
|
+
} as const satisfies ErrorInfo
|
|
388
|
+
|
|
389
|
+
// 生成错误定义对象
|
|
390
|
+
export const DbError = core.error.buildHaiErrorsDef('db', DbErrorInfo)
|
|
391
|
+
// DbError.CONNECTION_FAILED → { code: 'hai:db:010', httpStatus: 500, system: 'hai', module: 'db' }
|
|
392
|
+
|
|
393
|
+
// 创建错误实例
|
|
394
|
+
const errorInst = core.error.buildHaiErrorInst(
|
|
395
|
+
DbError.CONNECTION_FAILED,
|
|
396
|
+
'Unable to connect to PostgreSQL',
|
|
397
|
+
originalError, // cause(可选)
|
|
398
|
+
'Check connection string', // suggestion(可选)
|
|
399
|
+
)
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
### 配置错误码
|
|
403
|
+
|
|
404
|
+
```typescript
|
|
405
|
+
import { HaiConfigError } from '@h-ai/core'
|
|
406
|
+
|
|
407
|
+
HaiConfigError.CONFIG_FILE_NOT_FOUND // hai:core:010 - 配置文件不存在
|
|
408
|
+
HaiConfigError.CONFIG_PARSE_ERROR // hai:core:011 - YAML 解析失败
|
|
409
|
+
HaiConfigError.CONFIG_VALIDATION_ERROR // hai:core:012 - Schema 校验失败
|
|
410
|
+
HaiConfigError.CONFIG_ENV_VAR_MISSING // hai:core:013 - 环境变量缺失
|
|
411
|
+
HaiConfigError.CONFIG_NOT_LOADED // hai:core:014 - 配置未加载
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
## 测试
|
|
415
|
+
|
|
416
|
+
```bash
|
|
417
|
+
pnpm --filter @h-ai/core test
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
## License
|
|
421
|
+
|
|
422
|
+
Apache-2.0
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { C as CoreOptions, b as CoreLogger, I as I18nFn, c as IdFn, T as TypeUtilFn, O as ObjectFn, S as StringFn, A as ArrayFn, d as AsyncFn, e as TimeFn, E as ErrorFn, M as ModuleFn } from './core-util-module-B-wH5_ZT.js';
|
|
2
|
+
export { f as CoreConfig, g as CoreConfigSchema, h as CoreFunctions, i as Env, j as EnvSchema, k as ErrorInfo, l as ErrorInfoValue, m as HaiCommonError, n as HaiConfigError, H as HaiError, o as HaiErrorDef, a as HaiResult, p as IdConfig, q as IdConfigSchema, r as InterpolationParams, L as Locale, s as LocaleInfo, t as LocaleMessages, u as LogContext, v as LogFormat, w as LogFormatSchema, x as LogLevel, y as LogLevelSchema, z as Logger, B as LoggerFunctions, D as LoggerOptions, F as LoggingConfig, G as LoggingConfigSchema, J as MatchHandlers, K as MessageDictionary, N as MessageOptions, P as PaginatedResult, Q as PaginationOptions, R as PaginationOptionsInput, U as err, V as ok } from './core-util-module-B-wH5_ZT.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Core 服务对象 - 聚合常用功能(浏览器)。
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { core } from '@h-ai/core'
|
|
11
|
+
* core.logger.info('browser ready')
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
declare const core: {
|
|
15
|
+
/** 初始化 Core */
|
|
16
|
+
init: typeof initCore;
|
|
17
|
+
logger: CoreLogger;
|
|
18
|
+
i18n: I18nFn;
|
|
19
|
+
id: IdFn;
|
|
20
|
+
typeUtils: TypeUtilFn;
|
|
21
|
+
object: ObjectFn;
|
|
22
|
+
string: StringFn;
|
|
23
|
+
array: ArrayFn;
|
|
24
|
+
async: AsyncFn;
|
|
25
|
+
time: TimeFn;
|
|
26
|
+
error: ErrorFn;
|
|
27
|
+
module: ModuleFn;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* 初始化 Core(内部实现,通过 core.init() 调用)。
|
|
31
|
+
* 注意:浏览器环境不支持 config 和 watchConfig 选项。
|
|
32
|
+
*
|
|
33
|
+
* @param options - 初始化选项
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* import { core } from '@h-ai/core'
|
|
38
|
+
* core.init({ logging: { level: 'debug' } })
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
declare function initCore(options?: CoreOptions): void;
|
|
42
|
+
|
|
43
|
+
export { CoreLogger, CoreOptions, core };
|