@h-ai/core 1.0.0-beta.1 → 1.0.0-beta.10

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/README.en.md CHANGED
@@ -6,647 +6,814 @@
6
6
 
7
7
  ## Introduction
8
8
 
9
- The core of hai Agent Framework: shared utilities, types, configuration management, and logging.
9
+ `@h-ai/core` is the shared foundation of Hai Framework. It gives applications and framework modules consistent configuration, errors, logging, and internationalization. Utilities work directly; call `core.init()` when a Node application needs file configuration.
10
10
 
11
- ## Core features
11
+ ## Core capabilities
12
12
 
13
- - **HaiResult types**: functional error handling (`ok` / `err`) with a shared result format across modules.
14
- - **Unified logging**: pino on Node.js and loglevel in browsers, with the same API.
15
- - **Internationalization (i18n)**: centralized locale management and typed message getters.
16
- - **Zod validation error mapping**: Zod v3/v4 issue extraction and localization of default English messages.
17
- - **Configuration management**: YAML loading, convention-based environment mapping, explicit interpolation, Zod validation, and file watching (Node.js only).
18
- - **ID generation**: nanoid and UUID v4.
19
- - **Error definitions**: standardized codes and consistent error definitions and instances across modules.
20
- - **Module utilities**: NotInitializedKit proxies and shared lifecycle infrastructure.
21
- - **Utility library**: type checks and object / string / array / async / time operations.
13
+ | Capability | Purpose | Main entry points |
14
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
15
+ | Configuration and startup | Load YAML, merge environment overrides, validate settings, and orchestrate module startup and shutdown | `core.config`, `core.init`, `core.module.createRuntime` |
16
+ | Results and errors | Express business success/failure, define error codes, and produce safe messages at API boundaries | `HaiResult`, `ok` / `err`, `core.error` |
17
+ | Logging and diagnostics | Structured logs, request correlation, credential masking, and log observation | `core.logger`, `core.context`, `core.sanitize` |
18
+ | Internationalization and validation messages | Manage message languages, isolate concurrent request locales, and localize Zod field errors | `core.i18n`, `core.zodValidation` |
19
+ | Request access control | Resolve trusted client addresses and check paths, methods, IPs, and time windows | `core.access` (Node only) |
20
+ | General utilities | Generate identifiers and reuse type, object, string, array, async, and time operations, plus consistent errors before module initialization | `core.id`, `core.typeUtils`, `core.object`, and others |
21
+
22
+ ### Node and browser boundaries
23
+
24
+ Both environments use `import { core } from '@h-ai/core'`; the bundler selects the code for the target environment.
25
+
26
+ | Capability | Node.js | Browser |
27
+ | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
28
+ | Logging, results/errors, messages, utilities, and ordered module startup/shutdown | Supported | Supported |
29
+ | YAML, dotenv, environment mapping, file watching | Reads and watches local configuration files | Cannot read or watch local files; loading methods return failure |
30
+ | Request correlation with `core.context.run` | Each request retains its own IDs after asynchronous work, without mixing them with other requests | Values exist only during synchronous callback code and are no longer available after `await` |
31
+ | Request locale with `core.i18n.runWithLocale` | Each request keeps its chosen language after asynchronous work; other requests do not change it | Throws; set the page language with `setGlobalLocale()` or pass a locale when getting a message |
32
+ | Request policies with `core.access` | Checks request addresses, paths, and time windows | This tool is unavailable |
33
+
34
+ `core.init()` configures Core settings and logging synchronously, returns `void`, and Core provides no `close()` method. Applications starting databases, caches, or other modules can manage them with `core.module.createRuntime()`: its returned object's `start()` initializes them in order, and `close()` cleans them up in reverse. A complete example follows under “Application startup and shutdown”.
22
35
 
23
36
  ## Getting started
24
37
 
25
- ### Quick start
38
+ Each Core feature below has a purpose, examples, and relevant limits. Start with initialization when loading configuration; logging, messages, and general utilities work directly.
26
39
 
27
- #### Node.js environment
40
+ Call runtime functions through `core.xxx()` or `core.<feature>.xxx()`. Import the result constructors `ok` / `err`, types, schemas, and error constants separately from the package entry. Their sections below show the usage.
28
41
 
29
- ```typescript
30
- import { core } from '@h-ai/core'
42
+ ```bash
43
+ pnpm add @h-ai/core
44
+ ```
31
45
 
32
- // 初始化:加载配置目录(可选)
33
- core.init({ configDir: './config', watchConfig: true })
46
+ The custom configuration and form-validation examples also use Zod; install it with `pnpm add zod` before running them. Database and cache examples list their additional dependencies in their section.
34
47
 
35
- // 日志
36
- core.logger.info('Server started', { port: 3000 })
37
- core.logger.warn('Slow query', { duration: 2500 })
38
- core.logger.error('Connection failed', { error })
48
+ ### Initialization: `core.init`
39
49
 
40
- // 创建模块级 logger(独立名称空间)
41
- const dbLogger = core.logger.create({ name: 'db' })
42
- dbLogger.info('Connected to PostgreSQL')
50
+ Load YAML and configure logging at Node startup, or configure logging in a browser. Initializing Core does not start databases or other modules.
43
51
 
44
- // 创建子 logger(自动携带固定上下文,适合请求级/操作级追踪)
45
- const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
46
- reqLogger.info('Request started') // 日志自动包含 requestId + userId
47
- reqLogger.error('Request failed') // 同上
52
+ #### Node.js
48
53
 
49
- // 子 logger 可嵌套
50
- const opLogger = reqLogger.child({ operation: 'createOrder' })
51
- opLogger.info('Order created') // 包含 requestId + userId + operation
54
+ Create `config/_core.yml`:
52
55
 
53
- // i18n
54
- core.i18n.setGlobalLocale('zh-CN')
55
- const getMessage = core.i18n.createMessageGetter({
56
- 'zh-CN': { welcome: '欢迎 {name}', error: '发生错误:{msg}' },
57
- 'en-US': { welcome: 'Welcome {name}', error: 'Error: {msg}' },
58
- })
59
- getMessage('welcome', { params: { name: 'Alice' } }) // '欢迎 Alice'
56
+ ```yaml
57
+ # 应用元信息,供启动代码和页面读取。
58
+ name: orders
59
+ version: 0.1.0
60
+ env: development
61
+ # 默认消息语言;启动代码读取后调用 setGlobalLocale 应用。
62
+ defaultLocale: zh-CN
63
+ logging:
64
+ level: info # 输出 info 及以上级别。
65
+ format: pretty # 本地开发使用便于阅读的日志。
66
+ ```
67
+
68
+ ```ts
69
+ import { core, CoreConfigSchema } from '@h-ai/core'
70
+
71
+ // 1. 读取 config 目录中的 YAML,_core.yml 对应名称 core。
72
+ core.init({ configDir: './config' }) // 返回 undefined;配置缓存中可读取 core。
73
+
74
+ // 2. 检查应用必需的配置;失败时停止启动,保留原始错误供排查。
75
+ const config = core.config.validate('core', CoreConfigSchema)
76
+ if (!config.success)
77
+ throw new Error(config.error.message, { cause: config.error })
60
78
 
61
- // ID 生成
62
- const nanoid = core.id.generate()
63
- const shortId = core.id.short()
64
- const uuid = core.id.uuid()
65
- const prefixed = core.id.withPrefix('order_')
79
+ // 成功时 config.success 为 true;config.data.name 为 'orders',defaultLocale 为 'zh-CN'。
66
80
 
67
- // 工具函数
68
- core.object.deepMerge(objA, objB)
69
- core.sanitize.sanitizeSensitiveFields({ password: 'secret', email: 'user@example.com' })
70
- core.string.capitalize('hello')
71
- core.array.unique([1, 1, 2, 3])
72
- core.array.chunk([1, 2, 3, 4, 5], 2) // [[1,2], [3,4], [5]]
73
- await core.async.delay(1000)
74
- await core.async.retry(() => fetchData(), { maxRetries: 3, delay: 1000 })
75
- core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
76
- core.typeUtils.isDefined(value)
81
+ // 3. 将配置中的语言应用到默认消息;读取 YAML 本身不会切换语言。
82
+ core.i18n.setGlobalLocale(config.data.defaultLocale) // 返回 undefined;后续默认消息使用中文。
83
+
84
+ // 4. 记录已验证的应用名称,确认启动完成。
85
+ core.logger.info('Application ready', { name: config.data.name }) // 返回 undefined;info 日志包含 name: 'orders'。
77
86
  ```
78
87
 
79
- #### Browser environment
88
+ The startup boundary stops when required configuration is unavailable. `core.init()` logs individual load failures and continues, so completion does not mean every configuration is valid. Directory scanning and logger setup can still throw.
89
+
90
+ #### Browser
80
91
 
81
- ```typescript
92
+ ```ts
82
93
  import { core } from '@h-ai/core'
83
94
 
84
- // 初始化日志级别(浏览器不支持配置加载)
85
- core.init({ logging: { level: 'warn' } })
95
+ // 浏览器不读取 YAML;此处只设置日志,输出 warn 及以上级别。
96
+ core.init({ logging: { level: 'warn' } }) // 返回 undefined;之后 info 日志被过滤。
86
97
 
87
- core.logger.info('Page ready')
88
- const id = core.id.generate()
98
+ // 设置当前页面使用的默认消息语言。
99
+ core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;页面默认消息使用中文。
89
100
 
90
- // 其他工具函数与 Node.js 相同
91
- core.string.capitalize('hello')
92
- core.array.unique([1, 1, 2])
101
+ // 给一次请求生成编号,后续日志可用同一编号关联排查。
102
+ const requestId = core.id.request() // 返回随机字符串,如 'req-V1StGXR8_Z5jdHi6B-myT'。
103
+ core.logger.warn('Request needs attention', { requestId }) // 返回 undefined;浏览器输出 warn 消息及同一个 requestId。
93
104
  ```
94
105
 
95
- The browser retains the `core.config` API shape for type compatibility, but does not support file configuration:
106
+ The host supplies public configuration fields; never send complete server settings or secrets. Browser `core.config.get()` / `has()` / `keys()` return `undefined` / `false` / `[]`. `loadEnvFiles()`, `load()`, `validate()`, and `reload()` return `SERVICE_UNAVAILABLE`; `getOrThrow()` throws. `watch()` immediately calls back with the same unavailable error and returns a no-op unsubscribe function.
96
107
 
97
- - `core.config.get()` returns `undefined`, `has()` returns `false`, and `keys()` returns `[]`.
98
- - `loadEnvFiles()` / `load()` / `validate()` / `reload()` return `HaiCommonError.SERVICE_UNAVAILABLE`.
99
- - `watch()` immediately calls its callback with the same error and returns a safe no-op unsubscribe function.
100
- - Read configuration on the server and deliver it through an API, or use `core.init({ logging })` only to configure browser logging.
108
+ ### Files and environment settings: `core.config`
101
109
 
102
- ### Detailed API
110
+ Read YAML, apply environment overrides, validate configuration types, and manage cached settings and file watchers. The file and environment operations below require Node.
103
111
 
104
- #### Logging (Logger)
112
+ #### Loading, validating, and reading
105
113
 
106
- `core.logger` is both the default Logger instance and the shared entry point for logger management.
114
+ `core.init({ configDir, configSchemas?, watchConfig? })` scans direct `.yml` / `.yaml` children of the directory. `_core.yml` becomes `core`, `_db.yml` becomes `db`, and `app.yml` becomes `app`. The CLI reads build/deploy settings from root `hai.json`; they are separate from runtime YAML.
107
115
 
108
- ##### Write logs
116
+ `_core.yml` is validated with `CoreConfigSchema`, accepting only `name`, `version`, `env`, `defaultLocale`, and `logging`. The metadata defaults are `hai Admin`, `0.1.0`, `development`, and `zh-CN`; `logging` is optional. Metadata does not set `NODE_ENV`, switch message languages, or register application translations. Configure logging here; explicit `core.init({ logging })` overrides the application of YAML logging settings during that initialization.
109
117
 
110
- Six levels: `trace` / `debug` / `info` / `warn` / `error` / `fatal`.
118
+ For other files, host-supplied `configSchemas` provide structural and type hints during scanning. Full business validation stays in module initialization or explicit `validate()`. A direct `load(name, file, schema)` validates immediately.
111
119
 
112
- ```typescript
113
- core.logger.info('User created', { userId: '123' })
114
- core.logger.error('Failed to connect', { error })
115
- core.logger.debug('Processing item', { id, step: 'validation' })
120
+ The following file examples use this `config/app.yml` with no additional environment overrides:
121
+
122
+ ```yaml
123
+ # config/app.yml
124
+ port: 3000
116
125
  ```
117
126
 
118
- ##### Create a module logger
127
+ load() reads a file and can validate it immediately; validate() validates cached settings. get() returns undefined for a missing entry, while getOrThrow() throws. Generic arguments help TypeScript and do not validate data. has()/keys() show which entries exist.
119
128
 
120
- ```typescript
121
- // 独立名称空间,适合模块内全局使用
122
- const logger = core.logger.create({ name: 'payment' })
123
- logger.info('Payment processed')
124
- ```
129
+ ```ts
130
+ import { core } from '@h-ai/core'
131
+ import { z } from 'zod'
132
+
133
+ // 读取上方 config/app.yml;Schema 同时描述类型和校验规则。
134
+ const AppSchema = z.object({ port: z.number().int().min(1).max(65535) })
135
+ const loaded = core.config.load('app', './config/app.yml', AppSchema)
136
+ if (!loaded.success)
137
+ throw new Error(loaded.error.message, { cause: loaded.error })
125
138
 
126
- ##### Child loggers
139
+ // loaded:{ success: true, data: { port: 3000 } }。
127
140
 
128
- ```typescript
129
- // 携带固定上下文,每条日志自动附带这些字段
130
- const reqLogger = core.logger.child({ requestId: 'req-001', userId: 'u-123' })
131
- reqLogger.info('Request started') // 输出包含 requestId + userId
132
- reqLogger.warn('Slow response') // 同上
141
+ // validate 用于重新校验缓存;加载时未传 Schema 的配置也可在这里校验。
142
+ const validated = core.config.validate('app', AppSchema)
143
+ if (!validated.success)
144
+ throw new Error(validated.error.message, { cause: validated.error })
133
145
 
134
- // 嵌套 child:子上下文递归合并
135
- const opLogger = reqLogger.child({ operation: 'login' })
136
- opLogger.info('Login succeeded') // 输出包含 requestId + userId + operation
137
- opLogger.error('Login failed', { reason: 'invalid_password' })
146
+ // validated:{ success: true, data: { port: 3000 } }。
147
+
148
+ // get 适合可选配置;getOrThrow 适合已确认存在的必需配置。
149
+ if (core.config.has('app')) { // true:上方已成功加载 app。
150
+ const optional = core.config.get<z.infer<typeof AppSchema>>('app') // { port: 3000 }。
151
+ const required = core.config.getOrThrow<z.infer<typeof AppSchema>>('app') // { port: 3000 };缺失则抛错。
152
+ core.logger.info('App config ready', { port: required.port, available: optional !== undefined })
153
+ }
154
+ core.config.keys() // 仅运行本节 load 示例时为 ['app']。
138
155
  ```
139
156
 
140
- > **Typical usage**: create `reqLogger` at the request entry, pass it to the service layer, and add operation context with `child`. Logs then include the complete request context.
157
+ #### Reloading, watching, and cleanup
141
158
 
142
- ##### Logger management
159
+ Use reload() to reread a file or watch() to receive new values and errors. Watching survives ordinary saves, atomic replacement, and file deletion/recreation. Failures retain the last successful cache. unwatch() stops watchers; clear() also removes the cache. Omitting the name affects all entries.
143
160
 
144
- ```typescript
145
- // 配置输出格式和级别(Node.js / Browser)
146
- core.logger.configure({
147
- level: 'info',
148
- format: 'json', // 'json' | 'pretty'
149
- context: { app: 'my-service' }, // 全局默认上下文
150
- redact: ['password', 'token'], // 脱敏字段
151
- })
161
+ watchConfig defaults to false. Reloading settings does not reinitialize running database modules. Use the cleanup calls below when the setting is no longer needed.
152
162
 
153
- core.logger.setLevel('debug')
154
- const level = core.logger.getLevel() // 'debug'
163
+ ```ts
164
+ import { core } from '@h-ai/core'
165
+
166
+ // 前提:app 已由 init/load 加载。回调需先处理读取或校验失败。
167
+ const stop = core.config.watch('app', (_settings, error) => {
168
+ // 文件改成 port: 4000 后,成功回调收到 { port: 4000 }、error 为 undefined;失败时为 null 和错误对象。
169
+ if (error)
170
+ core.logger.error('Config reload failed', { error })
171
+ else
172
+ core.logger.info('Config reloaded')
173
+ })
174
+ // watch 返回取消函数 stop,不立即返回配置值。
175
+ core.config.isWatching('app') // true。
176
+ const reloaded = core.config.reload('app') // 文件仍为 port: 3000 时返回 { success: true, data: { port: 3000 } }。
177
+ if (!reloaded.success)
178
+ core.logger.warn('Manual reload failed', { error: reloaded.error })
179
+
180
+ stop() // 返回 undefined;取消当前回调,没有其他回调时停止底层监听。
181
+ core.config.unwatch('app') // 返回 undefined;isWatching('app') 变为 false。
182
+ core.config.clear('app') // 返回 undefined;get('app') 变为 undefined,has('app') 变为 false。
155
183
  ```
156
184
 
157
- After `core.init()` loads `_core.yml.logging`, or after `configure` / `setLevel`, default, module and nested child loggers use current global configuration for subsequent output, including instances created before initialization. Explicit `create({ level, format, context })` options retain priority; omitted options inherit global configuration dynamically, and per-call context overrides fixed context. Additional `redact` rules apply to all these instances without recreating module loggers.
185
+ #### How environment variables change YAML settings
158
186
 
159
- Browser logs still use the DevTools console: `pretty` prints readable messages with context, while `json` prints a JSON string containing `level` / `msg`. Default credential masking and configured path redaction both apply, including nested dot/bracket paths and `*`. Callers remain responsible for redacting message text.
187
+ The framework derives environment override names from the configuration name and field path. For app.yml, port maps to HAI_APP_PORT and http.maxRetries maps to HAI_APP_HTTP_MAXRETRIES. Segments are uppercased and joined with underscores without splitting camelCase. YAML does not need a ${...} expression for this override to work.
160
188
 
161
- Native `Error` values in log context are copied into diagnostics containing `name`, `message`, `stack`, `cause`, `AggregateError.errors`, and enumerable own context before default field/URL masking and configured `redact` paths run. Both backends use the same rules and leave the original error unchanged. Error-subgraph cycles become `[Circular]` and the 32-level limit becomes `[MaxDepth]`; custom replacements in these subgraphs follow the same normalization, while ordinary-object replacement behavior is unchanged. Ordinary-object cycles without an Error retain their original structure and are not guaranteed to be directly JSON-serializable. Error text masks explicitly labeled credentials such as `passwordHash=...` and `secretKey=...`, authorization headers and URL credentials. Arbitrary unlabeled secrets cannot be reliably detected; callers must still clean them or mask whole paths such as `error.message` / `error.stack`.
189
+ For a fixed YAML value `port: 3000`, the result is 3000 without HAI_APP_PORT and 5000 after setting HAI_APP_PORT=5000.
162
190
 
163
- `core.logger` redacts log context by default: credentials such as `password`, `passwordHash`, `passwd`, `token`, `secret`, `secretKey`, `privateKey`, and `apiV3Key` become `[REDACTED]`. Fields such as `url` / `baseUrl` / `endpoint` mask embedded usernames/passwords, sensitive query parameters, and OAuth key/value fragments; malformed URLs return a fixed placeholder. Email addresses and phone numbers are not masked by default.
191
+ Write `${VARIABLE}` in YAML to replace the expression with its environment value when loading. Text after the colon is the fallback when the variable is unset:
164
192
 
165
- ##### Log level conventions
193
+ | YAML | Environment input | Result |
194
+ | ---------------------------- | ---------------------------- | ------------------------------------------------------- |
195
+ | `port: ${PORT}` | PORT=4000 | Uses 4000; an unset PORT returns CONFIG_ENV_VAR_MISSING |
196
+ | `port: ${PORT:3000}` | No PORT | Uses the expression's fallback, 3000 |
197
+ | `port: ${PORT:3000}` | PORT=4000, HAI_APP_PORT=5000 | Uses 5000: the convention variable wins |
198
+ | `label: server-${PORT:3000}` | PORT=4000 | Produces the string server-4000 |
166
199
 
167
- | Level | Use case |
168
- | ------- | --------------------------------------------------- |
169
- | `trace` | Detailed debugging data inside loops |
170
- | `debug` | Function entry, parameter summaries, reads |
171
- | `info` | Business events (initialized, write succeeded) |
172
- | `warn` | Recoverable problems (validation failures, retries) |
173
- | `error` | Operation failures requiring investigation |
174
- | `fatal` | Fatal errors preventing continued service |
200
+ The loader first checks HAI_APP_PORT. If set, it replaces this field and does not evaluate its ${PORT...} expression. Otherwise it reads YAML: an expression looks up PORT, while a fixed value is used directly. Therefore PORT need not exist when HAI_APP_PORT already overrides the field.
175
201
 
176
- #### Internationalization (i18n)
202
+ Within one source, parent JSON can supply a base and child variables refine it. HAI_APP='{"port":3000,"label":"local"}' plus HAI_APP_PORT=4000 produces port=4000 and label=local regardless of line order. A higher-priority whole-object replacement removes lower-priority child overrides. Array JSON replaces the list; indexed variables only update existing items and out-of-range indexes fail.
177
203
 
178
- Built-in locales are `zh-CN`, `en-US` and `ja-JP`. The `ja` alias normalizes to `ja-JP`; all modules share this setting.
204
+ #### Reading .env files
179
205
 
180
- ```typescript
181
- // 设置全局语言(所有 getMessage 函数自动响应)
182
- core.i18n.setGlobalLocale('en-US')
183
- const current = core.i18n.getGlobalLocale() // 'en-US'
206
+ core.init() does not read .env files. Call loadEnvFiles(), check success, assign its results to process.env, then load YAML. development/production map to dev/prod; missing files are skipped and duplicate keys in a file fail. Highest priority first: **process environment > `.env.<mode>.local` > `.env.local` > `.env.<mode>` > `.env` > YAML**. Keep private .local files out of Git.
184
207
 
185
- // 为每个模块创建消息获取器
186
- const getMessage = core.i18n.createMessageGetter({
187
- 'zh-CN': { welcome: '欢迎 {name}', error: '错误:{code}' },
188
- 'en-US': { welcome: 'Welcome {name}', error: 'Error: {code}' },
189
- })
208
+ ```ts
209
+ import { core } from '@h-ai/core'
190
210
 
191
- // 使用:自动读取全局 locale,支持参数插值
192
- getMessage('welcome', { params: { name: 'Alice' } }) // 'Welcome Alice'
211
+ // 前提:.env 写 HAI_APP_PORT=4000,没有其他来源覆盖这个变量。
212
+ // 先读取并合并 .env 文件与进程环境,失败时停止启动。
213
+ const result = core.config.loadEnvFiles({ mode: 'dev', envDir: '.' })
214
+ if (!result.success)
215
+ throw new Error(result.error.message, { cause: result.error })
216
+ // 成功时 result.success 为 true,result.data.HAI_APP_PORT 为 '4000';其他键来自合并后的环境。
217
+ // 返回值不会自动写入进程;显式应用后再初始化。
218
+ Object.assign(process.env, result.data)
219
+ core.init({ configDir: './config' }) // 返回 undefined;app.yml 中 port: 3000 被覆盖为数字 4000。
220
+ ```
193
221
 
194
- // 支持 locale 参数覆盖
195
- getMessage('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) // '欢迎 Alice'
222
+ #### What type does the replacement produce?
196
223
 
197
- // 常量
198
- core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }, { code: 'ja-JP', label: '日本語' }]
199
- core.i18n.DEFAULT_LOCALE // 'zh-CN'
200
- ```
224
+ Environment variables start as text. Pass a Zod schema to `load()` / `resolve()` to convert replacements by field type: `z.number()` produces numbers, `z.boolean()` produces booleans, and `z.string()` preserves strings.
201
225
 
202
- #### Redaction utilities
226
+ A full-value ${PORT:3000} can produce number 3000, and ${ENABLED:false} boolean false. Mixed text such as server-${PORT:3000} stays a string. A string field code preserves the fallback 00123 as '00123', including leading zeros. This example supplies the equivalent YAML values and environment in memory without reading a file:
203
227
 
204
- `core.sanitize.sanitizeSensitiveFields()` recursively redacts objects and arrays. By default it handles password/passwordHash, passwd, token, secret/secretKey, privateKey, apiV3Key, and similar credentials, and masks embedded credentials in `url` / `baseUrl` / `endpoint`. `core.sanitize.sanitizeUrl(url, options)` also handles individual URLs and returns `(invalid url)` for malformed input. Custom matchers apply to parameter names as well. `sanitizeText` masks labeled credentials and URLs and accepts known secret values from the caller; it does not detect arbitrary unlabeled secrets.
228
+ ```ts
229
+ import { core } from '@h-ai/core'
230
+ import { z } from 'zod'
205
231
 
206
- ```typescript
207
- core.sanitize.sanitizeSensitiveFields({
208
- email: 'user@example.com',
209
- password: 'secret',
210
- baseUrl: 'https://user:pass@example.com/api/v1',
211
- profile: { token: 'jwt-token' },
232
+ // 用显式环境数据演示覆盖顺序、数值/布尔转换与字符串保留。
233
+ const AppSchema = z.object({ port: z.number(), enabled: z.boolean(), label: z.string(), code: z.string() })
234
+ const resolved = core.config.resolve({
235
+ name: 'app',
236
+ // eslint-disable-next-line no-template-curly-in-string -- 保留 YAML 中等待框架解析的字面表达式。
237
+ value: { port: '${PORT:3000}', enabled: '${ENABLED:false}', label: 'server-${PORT:3000}', code: '${APP_CODE:00123}' },
238
+ environment: { PORT: '4000', HAI_APP_PORT: '5000' },
239
+ schema: AppSchema,
212
240
  })
213
- // => { email: 'user@example.com', password: '[REDACTED]', baseUrl: 'https://[REDACTED]:[REDACTED]@example.com/api/v1', profile: { token: '[REDACTED]' } }
241
+ if (!resolved.success)
242
+ throw new Error(resolved.error.message, { cause: resolved.error })
214
243
 
215
- core.sanitize.sanitizeSensitiveFields({ email: 'user@example.com' }, {
216
- matcher: /email/i,
217
- replacement: '***',
218
- })
219
- // => { email: '***' }
244
+ // resolved:{ success: true, data: { port: 5000, enabled: false, label: 'server-4000', code: '00123' } }。
245
+
246
+ // resolve 只做替换和类型还原;再用 Schema 确认最终数据符合要求。
247
+ const validated = AppSchema.safeParse(resolved.data)
248
+ if (!validated.success)
249
+ throw new Error(validated.error.message, { cause: validated.error })
250
+ core.logger.info('Config resolved', { settings: validated.data })
251
+ // settings: { port: 5000, enabled: false, label: 'server-4000', code: '00123' }
220
252
  ```
221
253
 
222
- #### Zod validation error localization
254
+ An empty string means the variable is set with no characters; it is not missing, null, false, or zero. APP_CODE='' leaves code as '' instead of using 00123. The schema decides whether this is allowed; numeric fields usually reject empty strings.
255
+
256
+ Substitution processes expressions in YAML; `server-${PORT}` inside an environment value or parent JSON remains literal text. For example, HAI_APP_LABEL='server-${PORT}' stays server-${PORT}. Put the expression in YAML when substitution is intended.
223
257
 
224
- `core.zodValidation` converts Zod `SafeParseError` / `ZodError` into flat form errors and maps Zod's
225
- default English messages to the caller's own localized messages.
258
+ Without a schema, paths come from existing YAML/JSON structure and single expressions use YAML scalar rules for numbers/booleans. configSchemas can supply optional legal paths missing from YAML. Final business validation still belongs in validate() or module initialization.
226
259
 
227
- Unknown fields rejected by strict schemas map to `validationUnexpectedFields` without exposing internal field names. Custom message getters must handle this key; Kit and Serv provide Chinese, English and Japanese messages. Explicit business messages in a schema remain unchanged.
260
+ #### Tools for generating configuration files
228
261
 
229
- - Two public entry points:
230
- - `createPrefixedZodMessageGetter()`: derive keys such as `serv_validation*` / `kit_validation*` from module prefixes without a manual `KEY_MAP`.
231
- - `mapZodErrorToFormErrors()`: extract, localize, and flatten in one step.
232
- - Custom business messages are preserved; only Zod's default English messages are replaced.
262
+ resolve() also lets build/deploy tools calculate settings in memory. toEnv() converts objects to environment variables, mergeEnv() merges sources, and stringifyEnv()/parseEnv() encode/decode literal .env text. These tools do not mask secrets.
233
263
 
234
- ```typescript
235
- import type { ZodMessageGetter } from '@h-ai/core'
264
+ ```ts
236
265
  import { core } from '@h-ai/core'
237
- import { z } from 'zod'
238
266
 
239
- const LoginSchema = z.object({
240
- email: z.string().email(),
241
- password: z.string().min(8),
242
- nickname: z.string().min(1, '请填写昵称'),
243
- })
267
+ // 配置生成器把普通对象转成 HAI_APP_PORT 等变量;数组保留为 JSON。
268
+ const values = core.config.toEnv({ prefix: 'HAI_APP', value: { port: 3000, tags: ['local'] } })
269
+ // values:{ HAI_APP_PORT: '3000', HAI_APP_TAGS: '["local"]' }。
270
+ const merged = core.config.mergeEnv([values, { HAI_APP_PORT: '4000' }])
271
+ // merged:{ HAI_APP_PORT: '4000', HAI_APP_TAGS: '["local"]' }。
272
+ const text = core.config.stringifyEnv(merged) // 编码为可写入 .env 的文本。
273
+ // text 含以下两行,每行以换行符结尾:
274
+ // HAI_APP_PORT='4000'
275
+ // HAI_APP_TAGS='["local"]'
276
+ const restored = core.config.parseEnv(text) // 解析回字面字符串,不执行其中的变量。
277
+ // restored:{ HAI_APP_PORT: '4000', HAI_APP_TAGS: '["local"]' }。
278
+ core.logger.info('Generated config verified', { port: restored.HAI_APP_PORT })
279
+ ```
244
280
 
245
- const getMessage: ZodMessageGetter = (key, params) => {
246
- switch (key) {
247
- case 'validationEmail':
248
- return '请输入合法邮箱地址'
249
- case 'validationStringMin':
250
- return `至少输入 ${params?.min} 个字符`
251
- case 'validationRequired':
252
- return '此项为必填项'
253
- default:
254
- return '输入不合法'
255
- }
256
- }
281
+ Plain objects expand by default; arrays, dynamic dictionaries, and empty objects retain JSON. See the [runtime configuration guide](../../docs/usage/configuration/runtime.md) for replacement generation rules, full precedence, and application integration.
257
282
 
258
- const result = LoginSchema.safeParse({
259
- email: 'bad',
260
- password: '123',
261
- nickname: '',
262
- })
283
+ ### Logging: `core.logger`
263
284
 
264
- if (!result.success) {
265
- const getMessage = core.zodValidation.createPrefixedZodMessageGetter(
266
- 'kit',
267
- (messageKey, params) => {
268
- if (messageKey === 'kit_validationEmail')
269
- return '请输入合法邮箱地址'
270
- if (messageKey === 'kit_validationStringMin')
271
- return `至少输入 ${params?.min} 个字符`
272
- return '输入不合法'
273
- },
274
- )
275
- const errors = core.zodValidation.mapZodErrorToFormErrors(result.error, getMessage)
276
-
277
- errors[0]?.field // 'email'
278
- errors[0]?.message // '请输入合法邮箱地址'
279
- errors[2]?.message // '请填写昵称'(schema 自定义消息原样保留)
285
+ core.logger records structured logs. Levels progress from detail to severity: trace, debug, info, warn, error, fatal. fatal records a log; the application decides whether to exit.
280
286
 
281
- core.logger.info('Validation failed', { errors })
282
- }
287
+ `core.logger` supports `trace` / `debug` / `info` / `warn` / `error` / `fatal`. Node uses pino and browsers use loglevel. Unconfigured loggers default to `info` / `pretty`; a `logging` object parsed by `LoggingConfigSchema` defaults its format to `json`. Node falls back to JSON when optional `pino-pretty` is unavailable.
288
+
289
+ ```ts
290
+ import { core } from '@h-ai/core'
291
+
292
+ // 先设置级别;低于当前级别的日志不会输出。
293
+ core.logger.setLevel('trace') // 返回 undefined;以下六个级别均会输出。
294
+ core.logger.trace('Processing detail', { step: 1 })
295
+ core.logger.debug('Read started')
296
+ core.logger.info('Order created', { orderId: 'order-1' })
297
+ core.logger.warn('Retry scheduled')
298
+ core.logger.error('Operation failed', { error: new Error('Example failure') })
299
+ core.logger.fatal('Service cannot continue')
300
+ // 六次日志调用均返回 undefined;分别输出对应级别、上面的消息及所传字段。
301
+ // 例如 info 日志的消息为 'Order created',字段 orderId 为 'order-1'。
283
302
  ```
284
303
 
285
- #### Configuration management (Node.js only)
304
+ create() makes a named logger; child() attaches fixed context. configure() sets output and extra redaction paths; setLevel()/getLevel() change or inspect the global level.
286
305
 
287
- > Browsers have no filesystem access. `core.config` offers placeholder APIs only: file-related methods return `SERVICE_UNAVAILABLE` and do not load YAML.
306
+ ```ts
307
+ import { core } from '@h-ai/core'
288
308
 
289
- Node automatically loads and watches all `.yml` / `.yaml` files in the configuration directory. The CLI reads `build` / `deploy` from the project root `hai.json`; no YAML filename needs special handling. A failed per-file load result is logged and loading continues; applications must validate required configuration and check `success`. Directory scanning, logger setup and other exceptions may still propagate.
309
+ // 全局配置可作用于已经创建的 Logger;redact 补充业务隐私字段。
310
+ core.logger.configure({ level: 'info', format: 'json', redact: ['customer.email'] }) // 返回 undefined;后续日志按此配置输出。
311
+ const orders = core.logger.create({ name: 'orders' }) // 返回 Logger 对象,可调用 info/warn 等方法。
312
+ const request = core.logger.child({ requestId: 'request-1' }) // 返回带固定 requestId 的 Logger。
313
+ orders.info('Order created', { customer: { email: 'user@example.com' } }) // 返回 undefined;输出中 customer.email 为 '[REDACTED]'。
314
+ request.warn('Request needs attention') // 返回 undefined;输出中 requestId 为 'request-1'。
315
+ core.logger.getLevel() // 'info'。
316
+ ```
290
317
 
291
- ```typescript
292
- import { core, HaiConfigError } from '@h-ai/core'
293
- import { z } from 'zod'
318
+ Existing default, module, and nested child loggers use current global settings on subsequent writes; `setLevel()` also takes effect immediately. Explicit `create()` level/format/context options take precedence; unspecified options inherit dynamically. Per-call context overrides fixed context, then `core.context` adds current request correlation fields. Browser JSON includes `level` / `msg`; pretty output includes readable text and context.
294
319
 
295
- // 方式 1:init 时自动加载运行时配置
296
- core.init({
297
- configDir: './config', // 扫描配置目录内所有 .yml / .yaml
298
- watchConfig: true, // 监听变更并自动重载
299
- })
320
+ observe() supports diagnostics collection, receiving records after level filtering and masking and returning an unsubscribe function. Collect bounded memory data in the callback and persist asynchronously elsewhere. Observation is not persistence; exceptions and synchronous reentry are isolated.
300
321
 
301
- // 方式 2:手动加载单个文件(可选 Schema 校验)
302
- const AppSchema = z.object({
303
- name: z.string(),
304
- port: z.number().default(3000),
305
- })
306
- const result = core.config.load('app', './config/app.yml', AppSchema)
307
- if (result.success) {
308
- core.logger.info('Config loaded', { name: result.data.name })
309
- }
310
- else {
311
- core.logger.error('Config load failed', { code: result.error.code })
312
- }
322
+ ```ts
323
+ import { core } from '@h-ai/core'
313
324
 
314
- // 校验已加载的配置
315
- const validResult = core.config.validate('app', AppSchema)
325
+ // 观察经过级别过滤和脱敏的记录;内存收集设置上限。
326
+ const recentMessages: string[] = []
327
+ const stop = core.logger.observe((record) => {
328
+ if (recentMessages.length === 100)
329
+ recentMessages.shift()
330
+ recentMessages.push(record.message)
331
+ })
332
+ // observe 返回取消函数 stop;本例 warn 日志触发一次回调,record.message 为 'Observed event'。
333
+ core.logger.warn('Observed event')
334
+ recentMessages // ['Observed event']。
335
+ stop() // 返回 undefined;后续日志不再进入这个回调。
336
+ ```
316
337
 
317
- // 查询和获取
318
- if (core.config.has('app')) {
319
- const cfg = core.config.get<z.infer<typeof AppSchema>>('app') // undefined 或配置
320
- const cfg2 = core.config.getOrThrow<z.infer<typeof AppSchema>>('app') // 未加载时抛异常
321
- }
322
- core.config.keys() // ['core', 'app', 'db', ...]
338
+ ### Request correlation: `core.context`
323
339
 
324
- // 重新加载
325
- const reloadResult = core.config.reload('app')
340
+ run() gives a request/task its requestId, userId, scopeId, jobId, and other correlation fields; get() reads them. On Node they remain available after database or other asynchronous work, without another request overwriting them. Existing loggers automatically include these fields.
326
341
 
327
- // 监听文件变更
328
- const unwatch = core.config.watch('app', (newConfig, error) => {
329
- if (error) {
330
- core.logger.error('Config reload failed', { error })
331
- return
332
- }
333
- core.logger.info('Config updated', { config: newConfig })
334
- })
335
- unwatch() // 取消监听
342
+ ```ts
343
+ import { core } from '@h-ai/core'
336
344
 
337
- // 清除缓存(同时停止对应监听)
338
- core.config.clear('app') // 清除单个
339
- core.config.clear() // 清除全部
345
+ // Node 示例:同一请求等待异步处理后,仍能取得自己的编号。
346
+ await core.context.run({ requestId: 'request-1', userId: 'user-1' }, async () => {
347
+ await core.async.delay(1)
348
+ const current = core.context.get() // 包含 requestId: 'request-1'、traceId: 'request-1'、userId: 'user-1';其他字段为 undefined。
349
+ core.logger.info('Request continued', { requestId: current.requestId })
350
+ return current.requestId
351
+ }) // run 返回回调的结果;此处 await 后得到 'request-1'。
352
+ core.context.get() // {},回到外层后不保留上面请求的上下文。
353
+
354
+ // 采集器自身写日志时,可暂停观察回调,正常日志输出仍然执行。
355
+ core.context.run({ suppressLogObservers: true }, () => core.logger.warn('Collector diagnostic'))
356
+ // 返回 undefined;输出 warn 日志,但不会触发日志观察回调。
340
357
  ```
341
358
 
342
- ##### Dotenv files and environment modes
359
+ In browsers values exist only in synchronous callback code and are not retained after await. Correlation IDs do not authorize access; trusted server code must provide identity and tenant scope.
360
+
361
+ ### Cleaning diagnostic data: `core.sanitize`
343
362
 
344
- Node-only `core.config.loadEnvFiles({ mode, envDir })` returns HaiResult and merges `.env` → `.env.<mode>` → `.env.local`, with existing process variables taking priority. development/production map to dev/prod; missing files are skipped. It does not mutate the process: check success before assigning. Track public environment files and `.env.example`; ignore private `.env.local`. core.init does not load dotenv. Browser calls return SERVICE_UNAVAILABLE.
363
+ Clean credentials before logs, diagnostic exports, or public errors. Check sensitive names, mask a single value or object tree, clean URL credentials, or remove labeled/known secrets from text.
345
364
 
346
365
  ```ts
347
- const env = core.config.loadEnvFiles({ mode: 'dev', envDir: '.' })
348
- if (!env.success)
349
- throw new Error(env.error.message)
350
- Object.assign(process.env, env.data)
351
- core.init({ configDir: './config' })
366
+ import { core } from '@h-ai/core'
367
+
368
+ core.sanitize.isSensitiveKey('apiKey') // true。
369
+ core.sanitize.sanitizeSensitiveValue('example-only', 'password') // '[REDACTED]'。
370
+ const safe = core.sanitize.sanitizeSensitiveFields({ password: 'example-only', email: 'user@example.com' })
371
+ // safe:{ password: '[REDACTED]', email: 'user@example.com' },原对象不变。
372
+ // 默认仅遮蔽凭据;额外业务隐私可在已处理凭据的副本上继续清理。
373
+ core.sanitize.sanitizeSensitiveFields(safe, { matcher: ['email'], replacement: '***' })
374
+ // => { password: '[REDACTED]', email: '***' }
375
+ core.sanitize.sanitizeUrl('https://user:example-only@example.com/?token=example-only')
376
+ // => 'https://[REDACTED]:[REDACTED]@example.com/?token=[REDACTED]'
377
+ core.sanitize.sanitizeText('Bearer example-only') // '[REDACTED]'。
378
+ core.sanitize.sanitizeText('Request failed with a known private value', ['private value'])
379
+ // => 'Request failed with a known [REDACTED]'
352
380
  ```
353
381
 
354
- ##### Environment variable mapping and interpolation
382
+ defaultSensitiveKeyRegex/defaultSensitiveReplacement expose the default matching rule and [REDACTED] value. A custom matcher replaces the default rule, so retain default credential masking before applying extra business privacy rules.
355
383
 
356
- `core.config.load(name, ...)` automatically maps each YAML leaf to an
357
- environment variable named `HAI_<CONFIG_NAME>_<YAML_PATH>`. Configuration names and keys are uppercased, levels are separated by `_`,
358
- and camelCase is not split. For example, `ai.llm.apiKey` maps to `HAI_AI_LLM_APIKEY`,
359
- and `ai.llm.maxTokens` to `HAI_AI_LLM_MAXTOKENS`. Array indexes are also levels:
360
- `ai.llm.models[0].temperature` maps to `HAI_AI_LLM_MODELS_0_TEMPERATURE`.
384
+ Logs mask credential fields such as password/passwordHash, token, secretKey, and privateKey, plus URL userinfo, sensitive query parameters, and OAuth key-value fragments. Invalid URLs return `(invalid url)`. `redact` adds business privacy paths using dots, brackets, and single-level `*`, case sensitively. Email addresses and phone numbers remain visible by default.
361
385
 
362
- Existing environment variables override YAML and are parsed with YAML scalar rules into numbers, booleans, and other native types.
363
- Absent variables leave YAML unchanged. Object/array nodes can also be replaced wholesale with same-name JSON variables, such as HAI_DB for connection configuration or HAI_REACH_PROVIDERS for channel arrays. A parent replacement takes precedence over child variables; schema validation still runs afterward.
386
+ Native `Error` values are copied with name/message/stack/cause, aggregate errors, and enumerable context before masking; originals are unchanged. Error-subgraph cycles and the 32-level depth limit use `[Circular]` / `[MaxDepth]`. Ordinary object cycles remain and may prevent JSON serialization. Message and error text masking handles explicit credential labels and URLs, not arbitrary unlabeled secrets; callers must clean these or redact the whole path.
364
387
 
365
- ```yaml
366
- # config/_ai.yml(core.init 扫描后配置名为 ai)
367
- llm:
368
- apiKey: ''
369
- baseUrl: https://api.xiaomimimo.com/v1
370
- model: mimo-v2.5
371
- maxTokens: 4096
388
+ Masked results contain data only. Plain objects and class instances contribute their own enumerable data properties; prototypes, accessors, and custom `toJSON()` methods are not retained or invoked. Dates become ISO strings and URLs become masked strings, without changing the original. Still select only useful diagnostic fields from SDK/business objects and explicitly clean unlabeled secrets and business privacy data.
389
+
390
+ ### Results and errors: `core.error`
391
+
392
+ core.error defines module errors, creates failure instances, and builds safe HTTP/UI messages. Codes stay stable and messages can follow the current locale. Serv/Kit or another HTTP framework handles response status and headers.
393
+
394
+ ```ts
395
+ import { core } from '@h-ai/core'
396
+
397
+ // 定义稳定错误码,消息在创建实例时根据当前语言获取。
398
+ const OrderError = core.error.buildHaiErrorsDef('orders', { NOT_FOUND: '300:404' })
399
+ // OrderError.NOT_FOUND:{ code: 'hai:orders:300', httpStatus: 404, system: 'hai', module: 'orders' }。
400
+ const failure = core.error.buildHaiErrorInst(OrderError.NOT_FOUND, core.i18n.coreM('core_errorNotFound', { locale: 'zh-CN' }))
401
+ // failure:上面的错误定义加上 message: '资源不存在'。
402
+ const publicError = core.error.toPublic(failure, 'request-1')
403
+ // publicError:保留 code/httpStatus/system/module,增加 traceId: 'request-1';
404
+ // message 为 '资源不存在 (traceId: request-1)'。
405
+ const message = core.error.formatMessage(publicError) // '资源不存在 (traceId: request-1)',编号不会重复追加。
406
+ core.logger.warn('Order unavailable', { error: failure, publicMessage: message })
372
407
  ```
373
408
 
374
- ```dotenv
375
- HAI_AI_LLM_APIKEY=your-api-key
376
- HAI_AI_LLM_MAXTOKENS=8192
409
+ #### Shared result type and standalone constructors
410
+
411
+ `HaiResult<T>` uses success to distinguish data from error. Import `ok` / `err` to construct successful or failed results. Check success after business operations. Getters, utilities, and factories follow their direct-value or throwing signatures.
412
+
413
+ ```ts
414
+ import type { HaiResult } from '@h-ai/core'
415
+ import { core, err, HaiCommonError, ok } from '@h-ai/core'
416
+
417
+ // 业务失败返回 err,成功返回 ok;共用构造器保持独立导入。
418
+ function divide(a: number, b: number): HaiResult<number> {
419
+ if (b === 0)
420
+ return err(HaiCommonError.VALIDATION_ERROR, core.i18n.coreM('core_errorValidation', { locale: 'zh-CN' }))
421
+ return ok(a / b) // 如 ok(5) 返回 { success: true, data: 5 }。
422
+ }
423
+
424
+ // 先检查 success,再读取 data 或 error。
425
+ const result = divide(10, 2) // { success: true, data: 5 }。
426
+ if (!result.success)
427
+ core.logger.warn('Calculation failed', { error: result.error })
428
+ else
429
+ core.logger.info('Calculation completed', { value: result.data })
430
+
431
+ const failed = divide(10, 0)
432
+ // failed:{ success: false, error: { code: 'hai:common:200', httpStatus: 400,
433
+ // system: 'hai', module: 'common', message: '验证失败' } },无 data。
434
+ if (!failed.success)
435
+ core.logger.warn('Calculation rejected', { code: failed.error.code })
377
436
  ```
378
437
 
379
- For special variable names, use explicit `${VAR}` interpolation. Precedence is fixed:
380
- Convention-based environment variables > explicit environment variables > YAML defaults.
438
+ Use `core.error.toPublic(error, traceId?, locale?)` at HTTP/UI boundaries. It replaces 5xx details with a localized generic message, removes known credentials from other messages, and retains safe fields. Correlation IDs are selected from the explicit argument, context traceId/requestId, or the error's traceId, otherwise generated. `formatMessage()` appends a valid ID without duplicating the same suffix.
381
439
 
382
- - `${VAR}`: read `process.env.VAR`; return `CONFIG_ENV_VAR_MISSING` if absent.
383
- - `${VAR:default}`: read `process.env.VAR`; use the value after the colon if absent.
440
+ Internal `cause` / `ext` are private by default. Field errors for 400/422 can retain `field` / `message`; explicitly approved, business-schema-validated `publicExt` is masked and exposed as `ext`. Core does not validate its business safety automatically. Serv/Kit/UI hosts handle HTTP status, headers, and message components.
384
441
 
385
- **Type restoration:** when the whole value is one variable expression (such as `${PORT:3000}`), YAML rules restore native types (number / boolean, etc.). Mixed text always stays a string.
442
+ | Configuration error | Code | Meaning |
443
+ | ------------------------- | -------------- | -------------------------------------------- |
444
+ | `CONFIG_FILE_NOT_FOUND` | `hai:core:010` | Missing file |
445
+ | `CONFIG_PARSE_ERROR` | `hai:core:011` | YAML/dotenv reading or parsing failed |
446
+ | `CONFIG_VALIDATION_ERROR` | `hai:core:012` | Invalid schema input or environment override |
447
+ | `CONFIG_ENV_VAR_MISSING` | `hai:core:013` | Required interpolation variable missing |
448
+ | `CONFIG_NOT_LOADED` | `hai:core:014` | Configuration not loaded |
386
449
 
387
- `${VAR:}` or `${VAR}` resolving to an empty string stays `''`, rather than becoming YAML `null`. Modules that treat empty strings as unset should normalize them to `undefined` in their own schemas.
450
+ These constants belong to `HaiConfigError`; cross-module failures use `HaiCommonError`.
388
451
 
389
- ```yaml
390
- # config/app.yml
391
- debug: ${DEBUG:false} # → boolean false
392
- port: ${PORT:3000} # → number 3000
393
- database: ${DB_CONNECTION} # → 环境变量缺失时报错
394
- url: http://${HOST}:${PORT} # → string(混合文本)
395
- ```
396
-
397
- #### ID generation
398
-
399
- ```typescript
400
- const id = core.id.generate() // nanoid 21 字符
401
- const id8 = core.id.generate(8) // 自定义长度
402
- const shortId = core.id.short() // 10 字符短 ID
403
- const prefixed = core.id.withPrefix('user_') // 'user_V1StGXR...'
404
- const traceId = core.id.trace() // 'trace-V1StGXR...'
405
- const reqId = core.id.request() // 'req-V1StGXR...'
406
- const uuid = core.id.uuid() // UUID v4
407
-
408
- // 校验
409
- core.id.isValidUUID('f47ac10b-...') // true/false
410
- core.id.isValidNanoId('abc123', 6) // true/false
411
- ```
412
-
413
- UUID generation requires cryptographic randomUUID/getRandomValues and throws if neither is available; it never falls back to Math.random.
414
-
415
- #### Utilities
416
-
417
- ```typescript
418
- // 类型检查
419
- core.typeUtils.isDefined(x) // x !== undefined
420
- core.typeUtils.isObject(x) // plain object
421
- core.typeUtils.isFunction(x)
422
- core.typeUtils.isPromise(x)
423
- core.typeUtils.isString(x)
424
- core.typeUtils.isNumber(x)
425
- core.typeUtils.isBoolean(x)
426
- core.typeUtils.isArray(x)
427
-
428
- // 对象操作
429
- core.object.deepClone(obj)
430
- core.object.deepMerge(a, b) // 递归合并(防原型污染)
431
- core.object.deepMerge(a, b, c) // 支持多个对象
432
- core.object.pick(obj, ['a', 'b'])
433
- core.object.omit(obj, ['c', 'd'])
434
- core.object.keys(obj) // typed Object.keys
435
- core.object.values(obj)
436
- core.object.entries(obj)
437
- core.object.fromEntries(entries)
438
-
439
- // 字符串操作
440
- core.string.capitalize('hello') // 'Hello'
441
- core.string.kebabCase('helloWorld') // 'hello-world'
442
- core.string.camelCase('hello-world') // 'helloWorld'
443
- core.string.snakeCase('helloWorld') // 'hello_world'
444
- core.string.pascalCase('hello-world') // 'HelloWorld'
445
- core.string.truncate('long text', 5) // 'long ...'
446
- core.string.trim(' hello ') // 'hello'
447
- core.string.isBlank('') // true
448
- core.string.isNotBlank('x') // true
449
- core.string.padStart('5', 3, '0') // '005'
450
- core.string.padEnd('5', 3, '0') // '500'
451
- core.string.constantTimeEqual(a, b) // Node 使用原生等长比较;浏览器不保证恒时
452
-
453
- // 数组操作
454
- core.array.unique([1, 1, 2]) // [1, 2]
455
- core.array.chunk([1, 2, 3, 4], 2) // [[1,2], [3,4]]
456
- core.array.groupBy(items, item => item.type) // Record<string, T[]>
457
- core.array.first([1, 2, 3]) // 1
458
- core.array.last([1, 2, 3]) // 3
459
- core.array.flatten([[1], [2, 3]]) // [1, 2, 3]
460
- core.array.compact([1, null, 2]) // [1, 2]
461
- core.array.shuffle([1, 2, 3]) // 随机排列
462
- core.array.intersection([1, 2], [2, 3]) // [2]
463
- core.array.difference([1, 2], [2, 3]) // [1]
464
-
465
- // 异步操作
466
- await core.async.delay(1000)
467
- await core.async.withTimeout(fetch('/api'), 5000)
468
- await core.async.retry(fn, { maxRetries: 3, delay: 1000 })
469
- await core.async.parallel(items, processFn, 5) // 并发限制
470
- await core.async.serial(items, processFn)
471
- const debouncedFn = core.async.debounce(fn, 300)
472
- const throttledFn = core.async.throttle(fn, 200)
473
-
474
- // 时间操作
475
- core.time.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
476
- core.time.timeAgo(new Date(Date.now() - 60000)) // '1 分钟前'
477
- core.time.now() // Date.now()
478
- core.time.nowSeconds() // Math.floor(Date.now() / 1000)
479
- core.time.parseDate('2024-01-01')
480
- core.time.isValidDate(date)
481
- core.time.addDays(date, 7)
482
- core.time.addHours(date, 2)
483
- core.time.startOfDay(date)
484
- core.time.endOfDay(date)
485
- ```
486
-
487
- The Node entry uses node:crypto.timingSafeEqual over equal-length UTF-16LE code units. Different lengths return false; length is not hidden. The browser implementation avoids content-based early returns but has no JavaScript-engine timing guarantee and is not a server credential boundary. Surrounding branches, encoding and request handling are not made timing-safe by this helper.
488
-
489
- #### Module utilities (module)
490
-
491
- Shared initialization error handling for modules:
492
-
493
- ```typescript
452
+ ### Messages and locales: `core.i18n`
453
+
454
+ Create message getters with parameter interpolation, read built-in Core messages, and manage locale selection. Constants list framework locales and do not register application translations.
455
+
456
+ ```ts
494
457
  import { core } from '@h-ai/core'
495
458
 
496
- const notInitialized = core.module.createNotInitializedKit(
497
- HaiDbError.NOT_INITIALIZED,
498
- () => dbM('db_notInitialized'),
499
- )
459
+ // 页面语言或服务进程的启动默认值;请求中使用 runWithLocale 单独选择语言。
460
+ core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;后续默认消息使用中文。
461
+ core.i18n.getGlobalLocale() // 'zh-CN'。
462
+ core.i18n.coreM('core_errorNotFound') // '资源不存在'。
463
+ core.i18n.DEFAULT_LOCALE // zh-CN。
464
+ core.i18n.DEFAULT_LOCALES // [{ code: 'zh-CN', label: '简体中文' }, { code: 'en-US', label: 'English' }, { code: 'ja-JP', label: '日本語' }]。
465
+ ```
466
+
467
+ Message locales are `zh-CN`, `en-US`, and `ja-JP`; `zh` / `en` / `ja` aliases are normalized. Explicit locale takes priority over Node request locale and then the application default. Unsupported locales fall back to `zh-CN`; missing keys return the key itself.
468
+
469
+ ```ts
470
+ import { core } from '@h-ai/core'
500
471
 
501
- // 创建占位 Proxy(异步接口,默认)
502
- const currentDdl: DdlOperations = notInitialized.proxy<DdlOperations>()
503
- // 创建占位 Proxy(同步接口)
504
- const currentHash: HashOperations = notInitialized.proxy<HashOperations>('sync')
472
+ // 业务字典按语言组织;占位参数在取消息时传入。
473
+ const message = core.i18n.createMessageGetter({
474
+ 'zh-CN': { welcome: '欢迎 {name}' },
475
+ 'en-US': { welcome: 'Welcome {name}' },
476
+ 'ja-JP': { welcome: 'ようこそ {name}' },
477
+ })
478
+ // createMessageGetter 返回消息函数;如 message('welcome', { locale: 'zh-CN', params: { name: 'Alice' } }) 得到 '欢迎 Alice'。
479
+ const greeting = await core.i18n.runWithLocale('en-US', async () => {
480
+ await Promise.resolve()
481
+ return message('welcome', { params: { name: 'Alice' } })
482
+ })
483
+ // greeting:'Welcome Alice';runWithLocale 返回回调的结果,此处等待 Promise 得到字符串。
484
+ core.logger.info('Greeting prepared', { greeting })
505
485
  ```
506
486
 
507
- ### Error handling
487
+ Wrap actual asynchronous Node request/SSR work in `runWithLocale()`. Serv establishes the request locale automatically; Kit provides the same entry point. Within a request, `setGlobalLocale()` changes only that request. Outside it, use it only for startup defaults. Browsers use application-level `setGlobalLocale()` or explicit locales. SSR UI stores should not modify process defaults.
508
488
 
509
- #### HaiResult types
489
+ ### Field validation messages: `core.zodValidation`
510
490
 
511
- All operations that may fail return `HaiResult<T>`:
491
+ Convert Zod errors into { field, message }[] for form hints. createPrefixedZodMessageGetter() selects translation keys by prefix; mapZodErrorToFormErrors() extracts, translates, and flattens field paths.
512
492
 
513
- ```typescript
514
- import type { HaiResult } from '@h-ai/core'
515
- import { core, err, HaiCommonError, ok } from '@h-ai/core'
493
+ ```ts
494
+ import { core } from '@h-ai/core'
495
+ import { z } from 'zod'
516
496
 
517
- function divide(a: number, b: number): HaiResult<number> {
518
- if (b === 0)
519
- return err(HaiCommonError.VALIDATION_ERROR, 'Division by zero')
520
- return ok(a / b)
497
+ // 此例复用 Core 已有翻译;业务表单可注入自己的消息获取器。
498
+ const message = core.zodValidation.createPrefixedZodMessageGetter('core', key =>
499
+ key === 'core_validationEmail'
500
+ ? core.i18n.coreM('core_validationEmail', { locale: 'zh-CN' })
501
+ : core.i18n.coreM('core_errorValidation', { locale: 'zh-CN' }))
502
+ // 返回消息函数;message('validationEmail') 得到 '请输入有效的邮箱地址'。
503
+ const parsed = z.object({ email: z.email() }).safeParse({ email: 'invalid' })
504
+ if (!parsed.success) {
505
+ const errors = core.zodValidation.mapZodErrorToFormErrors(parsed.error, message)
506
+ // errors:[{ field: 'email', message: '请输入有效的邮箱地址' }]。
507
+ core.logger.info('Validation failed', { errors })
521
508
  }
509
+ ```
510
+
511
+ Supports Zod v3/v4 issues/errors. Default English messages are translated; explicit business messages remain unchanged. Paths use dots and global errors use _. Unknown fields in strict schemas use validationUnexpectedFields without exposing internal names.
512
+
513
+ ### Module startup and helpers: `core.module`
514
+
515
+ Applications and module implementations can reuse these helpers to manage several modules or return consistent failures before initialization. The application chooses its actual modules.
516
+
517
+ #### Application startup and shutdown
518
+
519
+ Applications using several modules need to initialize resources such as databases before handling business work, then release them afterward. `core.module.createRuntime()` accepts each module's startup and cleanup functions and returns an object the application can call. Creating it does not start the modules.
522
520
 
523
- const result = divide(10, 2)
524
- if (result.success) {
525
- core.logger.info('Result', { data: result.data })
521
+ This local development example additionally requires `@h-ai/reldb` and `@h-ai/cache`. Both use in-memory settings for demonstration; production must use the shared backends required by each module.
522
+
523
+ ```ts
524
+ import { cache } from '@h-ai/cache'
525
+ import { core } from '@h-ai/core'
526
+ import { reldb } from '@h-ai/reldb'
527
+
528
+ // 按需要的启动顺序,列出各模块的初始化和关闭函数。
529
+ const runtime = core.module.createRuntime([
530
+ {
531
+ name: 'database',
532
+ start: () => reldb.init({ type: 'sqlite', database: ':memory:' }),
533
+ close: () => reldb.close(),
534
+ },
535
+ {
536
+ name: 'cache',
537
+ start: () => cache.init({ type: 'memory' }),
538
+ close: () => cache.close(),
539
+ },
540
+ ])
541
+
542
+ // createRuntime 返回带 start()/close() 的对象;到这里数据库和缓存尚未启动。
543
+
544
+ // 依次启动数据库、缓存;失败时自动清理已尝试启动的模块。
545
+ const started = await runtime.start() // 成功为 { success: true, data: undefined };两个模块均已初始化。
546
+ if (!started.success)
547
+ throw new Error(started.error.message, { cause: started.error })
548
+
549
+ try {
550
+ // 启动成功后再执行应用业务;这里演示记录启动结果。
551
+ core.logger.info('Application modules ready')
526
552
  }
527
- else {
528
- core.logger.error('Error', { error: result.error })
553
+ finally {
554
+ // 演示结束后先关闭缓存,再关闭数据库,并检查清理结果。
555
+ const closed = await runtime.close() // 成功为 { success: true, data: undefined };两个模块均已关闭。
556
+ if (!closed.success)
557
+ core.logger.error('Application cleanup failed', { error: closed.error })
529
558
  }
530
559
  ```
531
560
 
532
- #### Custom error codes (per module)
561
+ Startup here is database → cache; shutdown is cache → database. This demonstration cleans up immediately afterward. A long-running service should call the same `runtime.close()` when exiting.
533
562
 
534
- ```typescript
535
- import type { ErrorInfo } from '@h-ai/core'
536
- import { core } from '@h-ai/core'
563
+ A startup failure cleans up modules whose startup was attempted. A shutdown failure stops cleanup at that module and retains dependencies it still needs; the next `close()` or `start()` retries cleanup. Simultaneous `start()` calls do not initialize twice. An optional `enabled()` returning false skips its step.
564
+
565
+ Both methods return `HaiResult`; check `success`. Errors include the module, phase, code, and necessary configuration field hints while keeping configuration secrets and raw SDK exceptions out of public startup errors.
537
566
 
538
- // 定义错误码(格式 'code:httpStatus')
539
- const DbErrorInfo = {
540
- NOT_INITIALIZED: '001:500',
541
- CONNECTION_FAILED: '010:500',
542
- QUERY_FAILED: '011:500',
543
- } as const satisfies ErrorInfo
567
+ #### Returning errors before initialization
544
568
 
545
- // 生成错误定义对象
546
- export const DbError = core.error.buildHaiErrorsDef('db', DbErrorInfo)
547
- // DbError.CONNECTION_FAILED → { code: 'hai:db:010', httpStatus: 500, system: 'hai', module: 'db' }
569
+ createNotInitializedKit() provides error/result/proxy forms. Proxies return a consistent sync/async failure until the implementation switches to real operations. The message function reads the locale at call time.
548
570
 
549
- // 创建错误实例
550
- const errorInst = core.error.buildHaiErrorInst(
551
- DbError.CONNECTION_FAILED,
552
- 'Unable to connect to PostgreSQL',
553
- originalError, // cause(可选)
554
- 'Check connection string', // suggestion(可选)
555
- )
571
+ ```ts
572
+ import type { HaiResult } from '@h-ai/core'
573
+ import { core, HaiCommonError } from '@h-ai/core'
574
+
575
+ const message = core.i18n.createMessageGetter({
576
+ 'zh-CN': { notReady: '请先初始化模块' },
577
+ 'en-US': { notReady: 'Initialize the module first' },
578
+ 'ja-JP': { notReady: '先にモジュールを初期化してください' },
579
+ })
580
+ // 本例固定使用中文消息,便于观察返回值。
581
+ core.i18n.setGlobalLocale('zh-CN') // 返回 undefined。
582
+ const waiting = core.module.createNotInitializedKit(HaiCommonError.NOT_INITIALIZED, () => message('notReady'))
583
+ // waiting 是带 error/result/proxy 的对象。
584
+ waiting.error() // { code: 'hai:common:001', httpStatus: 500, system: 'hai', module: 'common', message: '请先初始化模块' }。
585
+ waiting.result<string>() // { success: false, error: 上方错误对象 },无 data。
586
+
587
+ // 模块实现可把尚未就绪的操作暂时指向这些代理。
588
+ const asyncOperations = waiting.proxy<{ read: () => Promise<HaiResult<string>> }>()
589
+ const syncOperations = waiting.proxy<{ read: () => HaiResult<string> }>('sync')
590
+ // 两次 proxy 调用分别返回异步和同步操作对象。
591
+ const result = await asyncOperations.read() // { success: false, error: 上方错误对象 }。
592
+ if (!result.success)
593
+ core.logger.warn('Read before initialization', { error: result.error })
594
+ syncOperations.read() // 直接返回 { success: false, error: 上方错误对象 },不返回 Promise。
556
595
  ```
557
596
 
558
- #### Configuration error codes
597
+ #### Checking shared-state requirements
598
+
599
+ requiresSharedState() decides whether a production process should reject backends limited to one host. It only returns a decision; it does not connect or switch databases. Server code supplies the real environment.
559
600
 
560
- ```typescript
561
- import { HaiConfigError } from '@h-ai/core'
601
+ ```ts
602
+ import { core } from '@h-ai/core'
562
603
 
563
- HaiConfigError.CONFIG_FILE_NOT_FOUND // hai:core:010 - 配置文件不存在
564
- HaiConfigError.CONFIG_PARSE_ERROR // hai:core:011 - YAML 解析失败
565
- HaiConfigError.CONFIG_VALIDATION_ERROR // hai:core:012 - Schema 校验失败
566
- HaiConfigError.CONFIG_ENV_VAR_MISSING // hai:core:013 - 环境变量缺失
567
- HaiConfigError.CONFIG_NOT_LOADED // hai:core:014 - 配置未加载
604
+ // 此例用显式数据演示;服务端实际使用时传入 process.env。
605
+ core.module.requiresSharedState({ NODE_ENV: 'production' }) // true:应使用跨主机共享后端。
606
+ core.module.requiresSharedState({ NODE_ENV: 'production', HAI_E2E: '1' }) // false:显式 E2E 例外。
568
607
  ```
569
608
 
570
- ### Request locale isolation
609
+ ### Request access checks: `core.access` (Node)
571
610
 
572
- Wrap Node requests and SSR in `core.i18n.runWithLocale(locale, () => handleRequest())`. SvelteKit can use `kit.i18n.runWithLocale(locale, () => resolve(event))`; serv creates the scope automatically from request headers. Async descendants inherit it. Explicit `MessageOptions.locale` takes precedence over the request locale and the startup default. Within a scope, `setGlobalLocale` only changes that request; outside a scope it configures the startup default and must not be called by request hooks.
611
+ At HTTP entry points, resolve a trusted client IP and check addresses, paths, methods, and time windows. Core returns decisions; Serv http.access or Kit createHandle({ access }) connects them to request processing.
573
612
 
574
- Browsers keep application-level `setGlobalLocale` / `createLocaleStore`. During SSR, UI store initialization and setters only update the store; messages read the request scope. `runWithLocale` requires the Node entry; browser translations use explicit locale options or application state.
613
+ #### Resolving and checking client addresses
575
614
 
576
- ## Trusted addresses and request access policies (Node)
615
+ ```ts
616
+ import { AccessConditionSchema, core } from '@h-ai/core'
617
+
618
+ core.access.normalizeClientIp('::ffff:198.51.100.23') // 198.51.100.23。
619
+ const resolve = core.access.createClientIpResolver(['192.0.2.10']) // 返回 IP 解析函数,只信任这个代理。
620
+ const request = new Request('https://example.test/api/orders', { headers: { 'x-forwarded-for': '198.51.100.23' } })
621
+ // 第二参数必须来自真实 socket/可信平台;这里用测试地址模拟代理对端。
622
+ const clientIp = resolve(request, '192.0.2.10') // '198.51.100.23',读取受信代理的转发头。
623
+ const check = core.access.createConditionCheck(AccessConditionSchema.parse({ allowIps: ['198.51.100.0/24'] }))
624
+ // createConditionCheck 返回检查函数;check(clientIp) 得到 { allowed: true }。
625
+ core.logger.info('Address checked', { allowed: check(clientIp).allowed })
626
+ ```
577
627
 
578
- `core.access` supplies shared IP, time and path checks to HTTP hosts; it does not install HTTP interception itself. Serv uses `http.access`, SvelteKit uses `kit.createHandle({ access })`, and IAM `loginAccess` checks login only.
628
+ #### Loading policies and checking requests
579
629
 
580
630
  ```ts
581
631
  import { core } from '@h-ai/core'
582
632
 
583
- const check = core.access.createRequestCheck({
584
- rules: [{ id: 'external-api', paths: ['/api/v1/external/**'], allowIps: ['192.0.2.0/24'], encryption: 'disabled' }],
633
+ // 可改为 loadPolicy({ file: './config/security/request-access.yml' }) 在启动时读独立文件。
634
+ const policy = core.access.loadPolicy({
635
+ rules: [{ id: 'external-api', paths: ['/api/external/**'], methods: ['POST'], allowIps: ['192.0.2.0/24'], encryption: 'disabled' }],
585
636
  })
586
- const decision = check('/api/v1/external/sync', 'POST', '192.0.2.10')
587
- const mode = check.encryption('/api/v1/external/sync', 'POST') // disabled
637
+ // policy.rules[0] 保留上方规则,并补 denyIps: []、windows: []、timezone: 'UTC'。
638
+ const check = core.access.createRequestCheck(policy) // 返回请求检查函数,另带 encryption 方法和 requiresEncryption 属性。
639
+ const decision = check('/api/external/sync', 'POST', '192.0.2.10') // { allowed: true }。
640
+ check.encryption('/api/external/sync', 'POST') // disabled,供 HTTP 框架选择传输模式。
641
+ check.requiresEncryption // false;本例没有 required 规则。
642
+ core.logger.info('Request access checked', { allowed: decision.allowed })
588
643
  ```
589
644
 
590
- `createRequestCheck` validates and compiles at creation. `loadPolicy({ file: './config/security/request-access.yml' })` reads YAML once at startup, with a 1 MiB limit; invalid configuration throws and must stop host startup. Global conditions and all matching rules must pass. Denied IPs take precedence; empty IP and time lists impose no restriction, and the default timezone is UTC. Paths are actual URL pathnames including the deployment prefix, with exact or trailing `/**` matching. GET does not imply HEAD.
645
+ - Creating a checker validates and compiles rules. `loadPolicy({ file })` reads independent YAML at startup, limited to 1 MiB. Invalid configuration throws and must stop the host. File references cannot be mixed with inline rules.
646
+ - Global conditions and all matching rules must pass; deny addresses take priority. Empty IP/time lists leave that dimension unrestricted, and timezone defaults to UTC. Paths include deployment prefixes, match exactly or end in `/**`, and GET does not imply HEAD.
647
+ - Default `auto` in `createClientIpResolver()` ignores forwarded headers on ordinary hosts; only managed private Compose uses the container subnet. `[]` disables proxy trust. Self-managed hosts explicitly list proxy IPs/CIDRs; peer addresses must come from sockets or trusted platforms.
648
+ - Path `encryption` can be `required` / `disabled`; omission inherits the host setting. Opposing modes on overlapping paths and methods fail at creation. Hosts use `check.encryption()` / `requiresEncryption` to wire transport behavior. Core does not hold keys or encrypt/decrypt; HTTPS and authentication are still required.
591
649
 
592
- `core.access.createClientIpResolver()` resolves trusted addresses. Default `auto` ignores forwarded headers on ordinary hosts and uses container networks only in managed Compose topologies with a private backend. Use `[]` to disable proxy trust, or explicit proxy IPs/CIDRs for custom ingress. Never treat arbitrary headers as socket metadata. Request checks perform no file reads, CIDR parsing or full path-rule scan; timezone results are reused within each minute and recomputed across minute boundaries. Only the Node entry exposes `core.access`. Configuration schemas come through `core-config`, public types live in `core-types`, and functions are called through `core.access` registered in `core-main`.
650
+ See the [request access guide](../../docs/usage/configuration/request-access.md) for defaults, policy files, proxy topology, and deployment steps.
593
651
 
594
- Rules accept `encryption: required` or `disabled`; omission inherits the host. The selector uses the path index without evaluating IP or time conditions. Conflicting modes on overlapping paths and methods fail at compilation regardless of declaration order; matching modes and separate methods can be combined. `check.requiresEncryption` tells the host when transport encryption must be installed. Core owns neither keys nor encryption. HTTPS, authentication and access checks remain necessary.
652
+ ### Creating and checking identifiers: `core.id`
595
653
 
596
- See the [request access handbook](../../docs/usage/configuration/request-access.md) for defaults, ingress conditions, policy files, deployment and verification.
654
+ Create business identifiers and log correlation IDs, or validate UUID v4/nanoid inputs.
597
655
 
598
- ## Configuration consumption
656
+ ```ts
657
+ import { core } from '@h-ai/core'
599
658
 
600
- `_core.yml` accepts only name/version/env/defaultLocale metadata and logging; unknown fields fail loading. Core has no global debug, ID length/prefix, business features or locale registration list. Use logging.level, per-call core.id arguments, and application-owned app.yml with its own schema. defaultLocale is metadata, not automatic translation registration or a Paraglide switch. Importing Logger preserves LANG, LC_ALL and PYTHONIOENCODING, including Windows TTY. See the [configuration-to-consumer map (Chinese)](../../.agents/skills/hai-module-create/configuration.md).
659
+ // 以下随机值仅展示格式,每次执行都不同。
660
+ core.id.generate() // 如 'V1StGXR8_Z5jdHi6B-myT',默认 21 字符;generate(8) 返回 8 字符。
661
+ const shortId = core.id.short() // 如 'V1StGXR8_Z',10 字符。
662
+ core.id.withPrefix('order_') // 如 'order_V1StGXR8_Z5jdHi6B-myT',前缀后接 21 字符。
663
+ core.id.trace() // 如 'trace-V1StGXR8_Z5jdHi6B-myT'。
664
+ core.id.request() // 如 'req-V1StGXR8_Z5jdHi6B-myT'。
665
+ const uuid = core.id.uuid() // 如 '550e8400-e29b-41d4-a716-446655440000',UUID v4。
666
+ core.id.isValidUUID(uuid) // true。
667
+ core.id.isValidNanoId(shortId, 10) // true。
668
+ ```
669
+
670
+ IDs are not secrets. UUID requires cryptographic randomness and throws if unavailable. _core.yml has no global ID length/prefix settings; pass options per call.
671
+
672
+ ### Checking value types: `core.typeUtils`
601
673
 
602
- ## Request correlation and log observation
674
+ Check boundary values and narrow their TypeScript types in branches. These checks do not replace business schema validation.
675
+
676
+ ```ts
677
+ import { core } from '@h-ai/core'
603
678
 
604
- Collection persistence and upload paths can use `core.context.run({ suppressLogObservers: true }, operation)` to prevent observing their own asynchronous logs. Normal output such as stdout remains enabled; observation resumes outside the scope.
679
+ core.typeUtils.isDefined(null) // false,同时排除 null 和 undefined。
680
+ core.typeUtils.isObject({ name: 'orders' }) // true;排除 null/数组,但也接受 Date 和类实例。
681
+ core.typeUtils.isFunction(() => {}) // true。
682
+ core.typeUtils.isPromise(Promise.resolve('ready')) // true。
683
+ core.typeUtils.isString('orders') // true。
684
+ core.typeUtils.isNumber(3000) // true;传 NaN 返回 false。
685
+ core.typeUtils.isBoolean(false) // true。
686
+ core.typeUtils.isArray([1, 2]) // true。
687
+ ```
605
688
 
606
- `core.logger.observe` receives records permitted by the current log level after default and custom field redaction, and returns an unsubscribe function. Subscribers should collect into bounded memory and persist asynchronously; observation does not imply persistence. Observer failures and synchronous reentry are isolated. Free text and images still require capture-specific privacy rules.
689
+ ### Objects: `core.object`
607
690
 
608
- On Node, `core.context.run` uses AsyncLocalStorage to isolate concurrent requests and child tasks. Existing module loggers inherit requestId/userId/scopeId/jobId. Only trusted server code supplies identities; correlation IDs do not authorize access. The browser exposes the same API but run only establishes a synchronous scope, without isolation across await.
691
+ Clone, merge, and select object fields, with typed keys/values/entries and fromEntries.
609
692
 
610
693
  ```ts
611
- import type { LogRecord } from '@h-ai/core'
612
694
  import { core } from '@h-ai/core'
613
695
 
614
- const records: LogRecord[] = []
615
- const unsubscribe = core.logger.observe((record) => {
616
- if (records.length === 100)
617
- records.shift()
618
- records.push(record)
619
- })
620
- await core.context.run({ requestId: 'request-1', scopeId: 'tenant-1', userId: 'user-1' }, async () => {
621
- await Promise.resolve()
622
- core.logger.warn('Business operation failed')
623
- })
624
- unsubscribe()
696
+ const defaults = { name: 'orders', port: 3000 }
697
+ const copy = core.object.deepClone(defaults) // { name: 'orders', port: 3000 },新副本。
698
+ // 合并局部覆盖时,显式保留包含 name/port 的完整配置类型。
699
+ const settings = core.object.deepMerge<typeof defaults>(copy, { port: 4000 }) // { name: 'orders', port: 4000 }。
700
+ core.object.pick(settings, ['name']) // { name: 'orders' }。
701
+ core.object.omit(settings, ['port']) // { name: 'orders' }。
702
+ core.object.keys(settings) // ['name', 'port'],元素类型为 'name' | 'port'。
703
+ core.object.values(settings) // ['orders', 4000]。
704
+ core.object.entries(settings) // [['name', 'orders'], ['port', 4000]]。
705
+ core.object.fromEntries([['mode', 'local']]) // { mode: 'local' }。
625
706
  ```
626
707
 
627
- ## Application lifecycle
708
+ deepClone uses structuredClone for cloneable Date/Map/Set/cyclic values and throws for unsupported values such as functions. deepMerge recursively merges plain objects only; later arrays, dates, collections, and class instances replace earlier values without modifying inputs. It does not clone instances.
628
709
 
629
- `core.module.createRuntime([{ name, enabled?, start, close }])` starts in declaration order, closes in reverse order and merges concurrent calls. It registers cleanup before partial initialization. Failed close retains that module and dependencies for the next close/start retry. Errors expose module, phase, code and configuration paths, never raw configuration or SDK exceptions. Base/API/fullstack and the admin use this helper.
710
+ ### Strings: `core.string`
630
711
 
631
- Startup errors explain configuration failures and suggest a fix. With `ext.fields`, `HaiConfigError.CONFIG_ENV_VAR_MISSING` identifies unset environment variables; `CONFIG_VALIDATION_ERROR` or Schema errors identify failed validation. Field paths alone produce a “missing or invalid configuration” hint without guessing the cause. Even when the startup boundary prints only `error.message`, it includes the fields, next steps and underlying error code. A custom initialization hook can report missing required environment variables by throwing an error with `code: HaiConfigError.CONFIG_ENV_VAR_MISSING.code` and `ext: { fields: ['VARIABLE_NAME'] }`; the fullstack template uses this for the initial administrator password.
712
+ Convert naming formats, prepare display strings, detect whitespace, and compare strings.
632
713
 
633
- ## Error messages and correlated logs
714
+ ```ts
715
+ import { core } from '@h-ai/core'
716
+
717
+ core.string.capitalize('hello') // 'Hello'。
718
+ core.string.kebabCase('helloWorld') // 'hello-world'。
719
+ core.string.camelCase('hello-world') // 'helloWorld'。
720
+ core.string.snakeCase('helloWorld') // 'hello_world'。
721
+ core.string.pascalCase('hello-world') // 'HelloWorld'。
722
+ core.string.truncate('abcdef', 3) // 'abc...'。
723
+ core.string.trim(' hello ') // 'hello'。
724
+ core.string.isBlank(' ') // true。
725
+ core.string.isNotBlank('hello') // true。
726
+ core.string.padStart('5', 3, '0') // '005'。
727
+ core.string.padEnd('5', 3, '0') // '500'。
728
+ core.string.constantTimeEqual('same', 'same') // true;安全边界见下方说明。
729
+ ```
634
730
 
635
- HTTP errors carry safe localized messages and a reference ID. ToastContainer hides the ID by default and reveals it through its diagnostic icon. The same ID remains in `error.traceId` and `X-Trace-Id`. The framework reuses the request ID to correlate browser and server logs. Sanitized exceptions, stacks and operation context remain in logs; internal cause/ext are not exposed. Field validation returns localized field names and messages only.
731
+ Node constantTimeEqual uses native timingSafeEqual on equal-length UTF-16 bytes and rejects unequal lengths immediately. Browser engines provide no constant-time guarantee; do not use this for server credential checks.
636
732
 
637
- Use `core.error.toPublic(error, traceId?)` at HTTP/UI boundaries and `core.error.formatMessage(error)` after translating messages; formatting is idempotent. Pass complete Error objects to logs instead of discarding their context. Database failures log driver codes, sanitized messages/stacks and table/column context; SQL text, bound values and connection credentials are excluded.
733
+ ### Arrays: `core.array`
638
734
 
639
- ### Public business progress
735
+ Deduplicate, chunk, group, remove nullish values, or calculate intersections/differences while retaining the input array.
640
736
 
641
- Internal ext is private. Explicitly approved and schema-validated business progress uses publicExt and is serialized as ext; no internal exception should be placed there.
737
+ ```ts
738
+ import { core } from '@h-ai/core'
739
+
740
+ core.array.unique([1, 1, 2]) // [1, 2]。
741
+ core.array.chunk([1, 2, 3], 2) // [[1, 2], [3]]。
742
+ core.array.groupBy([{ role: 'admin' }, { role: 'user' }], item => item.role)
743
+ // => { admin: [{ role: 'admin' }], user: [{ role: 'user' }] }
744
+ core.array.first([1, 2, 3]) // 1;空数组为 undefined。
745
+ core.array.last([1, 2, 3]) // 3;空数组为 undefined。
746
+ core.array.flatten([[1], [2, 3]]) // [1, 2, 3],只展开一层。
747
+ core.array.compact([0, null, 1, undefined]) // [0, 1],保留 0/false/空字符串。
748
+ core.array.shuffle([1, 2, 3]) // 如 [2, 3, 1],次序随机;新数组不修改输入。
749
+ core.array.intersection([1, 2], [2, 3]) // [2]。
750
+ core.array.difference([1, 2], [2, 3]) // [1]。
751
+ ```
752
+
753
+ groupBy supports prototype names such as `constructor` and `__proto__`. chunk expects a positive integer size and returns an empty array for size<=0.
754
+
755
+ ### Asynchronous work: `core.async`
756
+
757
+ Schedule delays, timeouts, retries, bounded/serial work, or debounce/throttle input and scroll events.
758
+
759
+ ```ts
760
+ import { core } from '@h-ai/core'
761
+
762
+ await core.async.delay(1) // 等待约 1ms 后得到 undefined;计时以运行环境为准。
763
+ await core.async.withTimeout(Promise.resolve('ready'), 1000) // 'ready';超时则 reject 为 Error。
764
+ await core.async.retry(async () => 'ready', { maxRetries: 3, delay: 10 }) // 'ready',本例首次即成功。
765
+ await core.async.parallel([1, 2, 3], async value => value * 2, 2) // [2, 4, 6],最多同时执行两项。
766
+ await core.async.serial([1, 2, 3], async value => value * 2) // [2, 4, 6],按输入顺序逐项执行。
767
+
768
+ // 两种包装保留回调参数类型;调用 search/scroll 时传入同样类型的参数。
769
+ const search = core.async.debounce((term: string) => core.logger.debug('Search requested', { term }), 100)
770
+ const scroll = core.async.throttle((position: number) => core.logger.debug('Scroll position', { position }), 100)
771
+ // debounce/throttle 均返回包装函数,调用时返回 undefined。
772
+ core.logger.setLevel('debug') // 返回 undefined;确保下面的 debug 日志可见。
773
+ search('orders') // 约 100ms 后回调收到 'orders';100ms 内连续调用只处理最后一次。
774
+ scroll(100) // 本例第一次调用立即回调,position 为 100;100ms 内最多执行一次。
775
+ ```
776
+
777
+ withTimeout limits waiting but does not cancel work. retry handles throws/rejections, not failed HaiResult values; current maxRetries includes the first attempt, so 3 means at most three executions. parallel requires positive safe integer concurrency; invalid values reject with RangeError before any task runs. Result order follows input order.
778
+
779
+ ### Dates and time: `core.time`
780
+
781
+ Convert timestamps, Date values, and display text, and calculate local calendar boundaries or relative time.
782
+
783
+ ```ts
784
+ import { core } from '@h-ai/core'
785
+
786
+ // date 与以下日期运算使用本机时区;parseDate 中的 Z 表示 UTC。
787
+ const date = new Date(2026, 0, 1, 12, 0, 0)
788
+ core.time.formatDate(date, 'YYYY-MM-DD HH:mm:ss') // '2026-01-01 12:00:00'。
789
+ core.i18n.setGlobalLocale('zh-CN') // 返回 undefined;相对时间使用中文。
790
+ core.time.timeAgo(new Date(Date.now() - 60_000)) // '1 分钟前'(立即执行时)。
791
+ core.time.now() // 当前毫秒时间戳,如 1767268800000;每次执行随时间变化。
792
+ core.time.nowSeconds() // 当前秒时间戳,如 1767268800;相当于当前毫秒时间戳除以 1000 后向下取整。
793
+ const parsed = core.time.parseDate('2026-01-01T00:00:00Z') // Date 对象,toISOString() 为 '2026-01-01T00:00:00.000Z'。
794
+ core.time.isValidDate(parsed) // true;Invalid Date 返回 false。
795
+ core.time.addDays(date, 7) // 新 Date,本机时间 2026-01-08 12:00:00。
796
+ core.time.addHours(date, 2) // 新 Date,本机时间 2026-01-01 14:00:00。
797
+ core.time.startOfDay(date) // 新 Date,本机时间 2026-01-01 00:00:00.000。
798
+ core.time.endOfDay(date) // 新 Date,本机时间 2026-01-01 23:59:59.999。
799
+ ```
800
+
801
+ formatDate supports YYYY/MM/DD/HH/mm/ss tokens and defaults to YYYY-MM-DD. Date arithmetic returns new Date values. Invalid parseDate input produces an invalid date rather than automatically throwing; check isValidDate.
802
+
803
+ See the [Core reference](../cli/templates/skills/hai-core/reference.md) for complete parameters and less common options. Current published declarations define the contract.
642
804
 
643
805
  ## Development and testing
644
806
 
807
+ Run from the repository root (use `pnpm.cmd` in PowerShell):
808
+
645
809
  ```bash
810
+ pnpm --filter @h-ai/core typecheck
811
+ pnpm --filter @h-ai/core lint
812
+ pnpm --filter @h-ai/core build
646
813
  pnpm --filter @h-ai/core test
647
814
  ```
648
815
 
649
- See the [module JSDoc conventions (Chinese)](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证) for declaration comments and compilable examples. Node core.init is synchronous and returns void. A failed per-file config.load result is logged and loading continues; validate required configuration and check success. Directory scanning and other exceptions may still throw. Business HaiResult APIs require a success check.
816
+ See the [module JSDoc conventions](../../.agents/instructions/module-conventions.md#jsdoc-与示例验证) for declaration and example checks.
650
817
 
651
818
  ## License
652
819