@h-ai/kit 0.1.0-alpha.67 → 0.1.0-alpha.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.en.md +39 -13
  2. package/README.ja.md +39 -13
  3. package/README.md +39 -13
  4. package/dist/adapter/index.d.ts +17 -2
  5. package/dist/adapter/index.js.map +1 -1
  6. package/dist/browser.d.ts +12 -6
  7. package/dist/browser.js +6 -7
  8. package/dist/browser.js.map +1 -1
  9. package/dist/{chunk-DVW7CQ3H.js → chunk-2PWGJCWX.js} +3 -3
  10. package/dist/chunk-2PWGJCWX.js.map +1 -0
  11. package/dist/{chunk-VOTDAVCB.js → chunk-2YYRP7HH.js} +17 -33
  12. package/dist/chunk-2YYRP7HH.js.map +1 -0
  13. package/dist/{chunk-MLSP67JF.js → chunk-333FGMGQ.js} +59 -111
  14. package/dist/chunk-333FGMGQ.js.map +1 -0
  15. package/dist/chunk-OVRZIDCD.js +175 -0
  16. package/dist/chunk-OVRZIDCD.js.map +1 -0
  17. package/dist/{chunk-L7BTMAKX.js → chunk-P6XH7G4N.js} +3 -6
  18. package/dist/chunk-P6XH7G4N.js.map +1 -0
  19. package/dist/{chunk-NVYIUBU7.js → chunk-XC7I2L3G.js} +2 -2
  20. package/dist/chunk-XC7I2L3G.js.map +1 -0
  21. package/dist/client/index.d.ts +47 -1
  22. package/dist/client/index.js +3 -3
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/index.d.ts +217 -347
  25. package/dist/index.js +138 -83
  26. package/dist/index.js.map +1 -1
  27. package/dist/kit-a2a-types-CwT1AFQu.d.ts +136 -0
  28. package/dist/{index-B7s-0mZl.d.ts → kit-client-auth-HnZIYUia.d.ts} +220 -101
  29. package/dist/kit-crypto-types-Dd24aJ4m.d.ts +194 -0
  30. package/dist/{kit-i18n-D9Qqk-1k.d.ts → kit-i18n-DEzmzE5T.d.ts} +142 -29
  31. package/dist/{kit-types-ByWdbCeO.d.ts → kit-types-CnzhN-AS.d.ts} +240 -162
  32. package/dist/modules/a2a/index.d.ts +13 -111
  33. package/dist/modules/a2a/index.js +2 -2
  34. package/dist/modules/crypto/index.d.ts +28 -195
  35. package/dist/modules/crypto/index.js +3 -3
  36. package/dist/modules/crypto/index.js.map +1 -1
  37. package/package.json +10 -10
  38. package/dist/chunk-DVW7CQ3H.js.map +0 -1
  39. package/dist/chunk-L7BTMAKX.js.map +0 -1
  40. package/dist/chunk-MLSP67JF.js.map +0 -1
  41. package/dist/chunk-NVYIUBU7.js.map +0 -1
  42. package/dist/chunk-QHYNL24G.js +0 -117
  43. package/dist/chunk-QHYNL24G.js.map +0 -1
  44. package/dist/chunk-VOTDAVCB.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,20 +1,21 @@
1
- import { c as createKitClient, a as createKitAuthActions, i as installBrowserTransport, b as installBrowserTransportFetch, q as login, t as loginWithOtp, u as loginWithLdap, v as loginWithApiKey, w as registerAndLogin, x as logout, s as setBrowserToken, d as clearBrowserToken, e as createTokenStore } from './index-B7s-0mZl.js';
2
- export { C as ClientTransportConfig, K as KitClient, f as KitClientConfig, g as KitConfig, h as KitConfigInput, j as KitConfigSchema, k as KitServerConfig, l as KitServerConfigInput, m as KitTransportConfig, n as KitTransportConfigInput, o as createSvelteKitNavAdapter, r as resolveKitConfig, p as resolveKitTransportConfig } from './index-B7s-0mZl.js';
3
- import { d as defineCrud, s as setAllModulesLocale } from './kit-i18n-D9Qqk-1k.js';
4
- export { C as CrudApiDef, a as CrudFieldDef, b as CrudFieldOption, c as CrudFieldOptions, e as CrudFieldType, f as CrudFieldValidation, g as CrudFilterParams, h as CrudOperations, i as CrudPaginatedResult, j as CrudPaginationParams, k as CrudResourceDef, l as CrudTableColumn, m as CrudText, r as resolveOptions, n as resolveText } from './kit-i18n-D9Qqk-1k.js';
5
- import { S as SessionData, k as RouteGuard, l as SessionLike, h as HandleConfig, C as CorsConfig, M as Middleware } from './kit-types-ByWdbCeO.js';
6
- export { A as ApiResponse, a as AuthOperations, b as AuthOperationsProvider, F as FormError, c as FormValidationResult, G as GuardConfig, d as GuardResult, H as HaiRequestEvent, e as HandleA2AConfig, f as HandleA2AOperations, g as HandleAuthConfig, i as HookCryptoConfig, m as MemoryRateLimitStore, j as MiddlewareContext, R as RateLimitConfig, n as RateLimitEntry, o as RateLimitStore, T as TransportEncryptionOptions, r as rateLimitMiddleware } from './kit-types-ByWdbCeO.js';
7
- import * as _sveltejs_kit from '@sveltejs/kit';
8
- import { RequestEvent, Cookies, Handle, RequestHandler } from '@sveltejs/kit';
1
+ import { c as createKitClient, a as createKitAuthActions, i as installBrowserTransport, b as installBrowserTransportFetch, o as login, p as loginWithOtp, q as loginWithLdap, t as loginWithApiKey, u as registerAndLogin, v as logout, s as setBrowserToken, d as clearBrowserToken } from './kit-client-auth-HnZIYUia.js';
2
+ export { C as ClientTransportConfig, K as KitClient, e as KitClientConfig, f as KitConfig, g as KitConfigInput, h as KitConfigSchema, j as KitServerConfig, k as KitServerConfigInput, l as KitTransportConfig, m as KitTransportConfigInput, r as resolveKitConfig, n as resolveKitTransportConfig } from './kit-client-auth-HnZIYUia.js';
3
+ import { d as defineCrud, s as setAllModulesLocale } from './kit-i18n-DEzmzE5T.js';
4
+ export { C as CrudApiDef, a as CrudFieldDef, b as CrudFieldOption, c as CrudFieldOptions, e as CrudFieldType, f as CrudFieldValidation, g as CrudFilterParams, h as CrudOperations, i as CrudPaginatedResult, j as CrudPaginationParams, k as CrudResourceDef, l as CrudTableColumn, m as CrudText, r as resolveOptions, n as resolveText } from './kit-i18n-DEzmzE5T.js';
5
+ import { S as SessionData, l as SessionLike, h as HandleConfig, r as rateLimitMiddleware, m as createCacheRateLimitStore, n as createMemoryRateLimitStore } from './kit-types-CnzhN-AS.js';
6
+ export { A as ApiResponse, a as AuthOperations, b as AuthOperationsProvider, C as CorsConfig, F as FormError, c as FormValidationResult, G as GuardConfig, d as GuardResult, H as HaiRequestEvent, e as HandleA2AConfig, f as HandleA2AOperations, g as HandleAuthConfig, i as HookCryptoConfig, o as MemoryRateLimitStore, M as Middleware, j as MiddlewareContext, p as RateLimitCache, R as RateLimitConfig, q as RateLimitEntry, s as RateLimitStore, k as RouteGuard, T as TransportEncryptionOptions } from './kit-types-CnzhN-AS.js';
9
7
  import { CryptoFunctions } from '@h-ai/crypto';
10
8
  export { EncryptedPayload, TransportEncryptionManager, TransportKeyPair } from '@h-ai/crypto';
9
+ import * as _h_ai_core from '@h-ai/core';
10
+ import { HaiError } from '@h-ai/core';
11
11
  import * as zod_v4_core from 'zod/v4/core';
12
12
  import * as zod from 'zod';
13
13
  import { z } from 'zod';
14
+ import * as _sveltejs_kit from '@sveltejs/kit';
15
+ import { Handle, RequestEvent, RequestHandler } from '@sveltejs/kit';
14
16
  import { IamFunctions } from '@h-ai/iam';
15
- import { HaiError } from '@h-ai/core';
16
- export { A2AApiKeyAuthConfig, KitA2AHandlerConfig, ResolvedA2AConfig, createA2AApiKeyAuthenticator, createA2AHandler, createAgentCardHandler, handleA2ARequest, resolveA2AConfig } from './modules/a2a/index.js';
17
- export { CryptoCsrfConfig, CryptoServiceLike, EncryptedCookieConfig, TransportEncryptionConfig, WebhookVerifyConfig, createCsrfManager, createEncryptedCookie, signRequest, transportEncryptionMiddleware, verifyWebhookSignature } from './modules/crypto/index.js';
17
+ export { A as A2AApiKeyAuthConfig, K as KitA2AHandlerConfig, R as ResolvedA2AConfig } from './kit-a2a-types-CwT1AFQu.js';
18
+ export { C as CryptoCsrfConfig, a as CryptoServiceLike, E as EncryptedCookieConfig, T as TransportEncryptionConfig, W as WebhookVerifyConfig } from './kit-crypto-types-Dd24aJ4m.js';
18
19
  import '@h-ai/api-contract';
19
20
 
20
21
  /**
@@ -26,6 +27,13 @@ import '@h-ai/api-contract';
26
27
 
27
28
  /**
28
29
  * 认证守卫配置
30
+ * @example
31
+ * ```ts
32
+ * import type { AuthGuardConfig } from '@h-ai/kit'
33
+ *
34
+ * const value: AuthGuardConfig = { apiMode: true }
35
+ * void value
36
+ * ```
29
37
  */
30
38
  interface AuthGuardConfig {
31
39
  /** 未登录时重定向 URL(默认 `'/login'`) */
@@ -35,6 +43,13 @@ interface AuthGuardConfig {
35
43
  }
36
44
  /**
37
45
  * 会话守卫配置
46
+ * @example
47
+ * ```ts
48
+ * import type { SessionGuardConfig } from '@h-ai/kit'
49
+ *
50
+ * const value: SessionGuardConfig = { validateSession: async () => null }
51
+ * void value
52
+ * ```
38
53
  */
39
54
  interface SessionGuardConfig {
40
55
  /** 会话校验函数(通常由应用注入 iam.auth.verifyToken 封装) */
@@ -44,122 +59,6 @@ interface SessionGuardConfig {
44
59
  /** 为 `true` 时返回 JSON 401 而非重定向(适用于 API 路由) */
45
60
  apiMode?: boolean;
46
61
  }
47
- /**
48
- * 创建认证守卫
49
- *
50
- * 检查会话是否存在;未认证时:
51
- * - 页面模式:重定向到 `loginUrl`,并携带 `returnUrl` 参数以便登录后返回。
52
- * - API 模式:返回 JSON `{ allowed: false, status: 401 }`。
53
- *
54
- * @param config - 守卫配置
55
- * @returns RouteGuard 实例
56
- *
57
- * @example
58
- * ```ts
59
- * // Hook 配置
60
- * guards: [
61
- * { guard: kit.guard.auth({ apiMode: true }), paths: ['/api/*'] },
62
- * { guard: kit.guard.auth(), paths: ['/dashboard/*'] },
63
- * ]
64
- * ```
65
- */
66
- declare function authGuard(config?: AuthGuardConfig): RouteGuard;
67
- /**
68
- * 创建会话守卫(支持 Bearer + 固定 Access Token Cookie 自动恢复)。
69
- *
70
- * 处理流程:
71
- * 1. 若上游已注入 session,直接放行
72
- * 2. 否则从 request/cookies 解析 token(Bearer 优先)
73
- * 3. 调用 validateSession 恢复并写入 event.locals.session
74
- * 4. 失败则按页面/API模式返回重定向或 401
75
- */
76
- declare function sessionGuard(config: SessionGuardConfig): RouteGuard;
77
-
78
- /**
79
- * @h-ai/kit — 组合守卫
80
- *
81
- * 提供守卫组合器,支持 AND(allGuards)/ OR(anyGuard)/ NOT(notGuard)/ 条件分支(conditionalGuard)等逻辑组合,将多个 RouteGuard 聚合为一个。
82
- * @module kit-compose
83
- */
84
-
85
- /**
86
- * 所有守卫都通过才允许访问(AND 逻辑)
87
- *
88
- * 短路求值:第一个拒绝的守卫结果会被直接返回。
89
- *
90
- * @param guards - 需要全部通过的守卫列表
91
- * @returns 组合后的 RouteGuard
92
- *
93
- * @example
94
- * ```ts
95
- * const adminOnly = kit.guard.all(
96
- * kit.guard.auth(),
97
- * kit.guard.role({ roles: ['admin'] }),
98
- * )
99
- * ```
100
- */
101
- declare function allGuards(...guards: RouteGuard[]): RouteGuard;
102
- /**
103
- * 任意一个守卫通过就允许访问(OR 逻辑)
104
- *
105
- * 短路求值:第一个允许的守卫结果会被直接返回。
106
- * 全部拒绝时返回最后一个拒绝结果。
107
- *
108
- * @param guards - 守卫列表
109
- * @returns 组合后的 RouteGuard
110
- *
111
- * @example
112
- * ```ts
113
- * const canView = kit.guard.any(
114
- * kit.guard.role({ roles: ['admin'] }),
115
- * kit.guard.permission({ permissions: ['article:read'] }),
116
- * )
117
- * ```
118
- */
119
- declare function anyGuard(...guards: RouteGuard[]): RouteGuard;
120
- /**
121
- * 取反守卫
122
- *
123
- * 将原守卫的判定逻辑反转:原本放行变为拒绝,原本拒绝变为放行。
124
- * 典型场景:「仅未登录用户可访问登录页」。
125
- *
126
- * @param guard - 需要取反的守卫
127
- * @param options - 拒绝时的重定向/消息
128
- * @param options.redirect - 拒绝时重定向 URL
129
- * @param options.message - 拒绝时的提示消息
130
- * @returns 取反后的 RouteGuard
131
- *
132
- * @example
133
- * ```ts
134
- * // 仅未登录用户可访问
135
- * const guestOnly = kit.guard.not(kit.guard.auth(), { redirect: '/dashboard' })
136
- * ```
137
- */
138
- declare function notGuard(guard: RouteGuard, options?: {
139
- redirect?: string;
140
- message?: string;
141
- }): RouteGuard;
142
- /** 条件判断函数类型:返回 `true` 时才执行后续守卫 */
143
- type ConditionFn = (event: RequestEvent, session: SessionData | undefined) => boolean | Promise<boolean>;
144
- /**
145
- * 条件守卫
146
- *
147
- * 仅当 `condition` 返回 `true` 时才执行 `guard`;否则直接放行。
148
- *
149
- * @param condition - 条件判断函数
150
- * @param guard - 条件满足时执行的守卫
151
- * @returns 包装后的 RouteGuard
152
- *
153
- * @example
154
- * ```ts
155
- * // 仅 POST 请求检查 CSRF
156
- * kit.guard.conditional(
157
- * (event) => event.request.method === 'POST',
158
- * csrfGuard,
159
- * )
160
- * ```
161
- */
162
- declare function conditionalGuard(condition: ConditionFn, guard: RouteGuard): RouteGuard;
163
62
 
164
63
  /**
165
64
  * @h-ai/kit — 权限守卫
@@ -170,6 +69,13 @@ declare function conditionalGuard(condition: ConditionFn, guard: RouteGuard): Ro
170
69
 
171
70
  /**
172
71
  * 权限守卫配置
72
+ * @example
73
+ * ```ts
74
+ * import type { PermissionGuardConfig } from '@h-ai/kit'
75
+ *
76
+ * const value: PermissionGuardConfig = { permissions: ['article:read'] }
77
+ * void value
78
+ * ```
173
79
  */
174
80
  interface PermissionGuardConfig {
175
81
  /** 需要的权限列表(默认 OR 逻辑,满足任一即通过) */
@@ -181,24 +87,6 @@ interface PermissionGuardConfig {
181
87
  /** 为 `true` 时返回 JSON 403 而非重定向 */
182
88
  apiMode?: boolean;
183
89
  }
184
- /**
185
- * 创建权限守卫
186
- *
187
- * 检查用户 `session.permissions` 是否满足配置中的权限要求。
188
- * 支持通配符匹配:`admin:*` 可匹配 `admin:read`、`admin:write` 等。
189
- * 未认证时返回 401;权限不匹配时根据 `apiMode` 返回 JSON 403 或重定向。
190
- *
191
- * @param config - 权限守卫配置
192
- * @returns RouteGuard 实例
193
- *
194
- * @example
195
- * ```ts
196
- * guards: [
197
- * { guard: kit.guard.permission({ permissions: ['user:read', 'user:write'], requireAll: true }), paths: ['/api/users/*'] },
198
- * ]
199
- * ```
200
- */
201
- declare function permissionGuard(config: PermissionGuardConfig): RouteGuard;
202
90
  /**
203
91
  * 匹配权限
204
92
  *
@@ -209,6 +97,13 @@ declare function permissionGuard(config: PermissionGuardConfig): RouteGuard;
209
97
  * @param required - 需要的权限码
210
98
  * @param userPermissions - 用户已有的权限列表
211
99
  * @returns 是否匹配
100
+ * @example
101
+ * ```ts
102
+ * import { matchPermission } from '@h-ai/kit'
103
+ *
104
+ * const allowed = matchPermission('article:read', ['article:*'])
105
+ * void allowed
106
+ * ```
212
107
  */
213
108
  declare function matchPermission(required: string, userPermissions: string[]): boolean;
214
109
  /**
@@ -219,35 +114,15 @@ declare function matchPermission(required: string, userPermissions: string[]): b
219
114
  * @param session - 当前会话数据,null/undefined 视为无权限
220
115
  * @param permission - 需要的权限码,如 `user:read`
221
116
  * @returns 是否拥有权限
222
- *
223
117
  * @example
224
118
  * ```ts
225
- * if (kit.guard.check(locals.session, 'user:read')) {
226
- * // 有权限
227
- * }
228
- * ```
229
- */
230
- declare function hasPermission(session: SessionLike | null | undefined, permission: string): boolean;
231
- /**
232
- * 断言会话具有指定权限,不满足时返回 403 Response
233
- *
234
- * 适用于 SvelteKit API Handler 内部,不满足权限时直接返回 JSON 错误响应。
235
- * 调用者需检查返回值:若有返回值则表示权限不足,应直接 return。
119
+ * import { kit } from '@h-ai/kit'
236
120
  *
237
- * @param session - 当前会话数据,null/undefined 视为未认证
238
- * @param permission - 需要的权限码,如 `user:create`
239
- * @returns 权限不足时返回 Response;有权限时返回 undefined
240
- *
241
- * @example
242
- * ```ts
243
- * export const POST: RequestHandler = async ({ locals }) => {
244
- * const denied = kit.guard.assertPermission(locals.session, 'user:create')
245
- * if (denied) return denied
246
- * // ... 正常逻辑
247
- * }
121
+ * const allowed = kit.guard.check({ userId: 'user_1', roles: ['editor'], permissions: ['article:read'] }, 'article:read')
122
+ * void allowed
248
123
  * ```
249
124
  */
250
- declare function assertPermission(session: SessionLike | null | undefined, permission: string): Response | undefined;
125
+ declare function hasPermission(session: SessionLike | null | undefined, permission: string): boolean;
251
126
  /**
252
127
  * 要求会话具有指定权限,不满足时 throw Response
253
128
  *
@@ -257,47 +132,14 @@ declare function assertPermission(session: SessionLike | null | undefined, permi
257
132
  * @param session - 当前会话数据,null/undefined 视为未认证
258
133
  * @param permission - 需要的权限码,如 `user:create`
259
134
  * @throws Response - 未认证 401 / 无权限 403
260
- *
261
135
  * @example
262
136
  * ```ts
263
- * export const GET = kit.handler(async ({ locals }) => {
264
- * kit.guard.require(locals.session, 'user:read')
265
- * // 执行到这里说明权限已通过
266
- * return kit.response.ok(data)
267
- * })
268
- * ```
269
- */
270
- declare function requirePermission(session: SessionLike | null | undefined, permission: string): void;
271
- /**
272
- * 权限守卫高阶函数包装器
273
- *
274
- * 将权限检查从业务逻辑中提取到装饰层,handler 内部无需关心权限。
275
- * 未认证返回 401、无权限返回 403(均通过 SvelteKit throw 控制流抛出)。
276
- *
277
- * 适用于 page load、API handler 等所有 SvelteKit server 函数。
137
+ * import { kit } from '@h-ai/kit'
278
138
  *
279
- * @param permission - 需要的权限码,如 `'user:read'`
280
- * @param handler - 原始处理函数
281
- * @returns 包装后的处理函数(签名不变)
282
- *
283
- * @example
284
- * ```ts
285
- * // +page.server.ts
286
- * export const load = kit.guard.withPermission('user:read', async ({ locals }) => {
287
- * const result = await iam.user.listUsers()
288
- * return { users: result.success ? result.data.items : [] }
289
- * })
290
- *
291
- * // +server.ts (API handler)
292
- * export const GET = kit.handler(kit.guard.withPermission('user:list', async ({ locals }) => {
293
- * const result = await iam.user.listUsers()
294
- * return kit.response.ok(result.data)
295
- * }))
139
+ * kit.guard.require({ userId: 'user_1', roles: ['editor'], permissions: ['article:read'] }, 'article:read') // 拒绝时抛出 Response,由框架传递。
296
140
  * ```
297
141
  */
298
- declare function withPermission<TEvent extends {
299
- locals: Record<string, unknown>;
300
- }, TReturn>(permission: string, handler: (event: TEvent) => Promise<TReturn>): (event: TEvent) => Promise<TReturn>;
142
+ declare function requirePermission(session: SessionLike | null | undefined, permission: string): void;
301
143
 
302
144
  /**
303
145
  * @h-ai/kit — 角色守卫
@@ -308,6 +150,13 @@ declare function withPermission<TEvent extends {
308
150
 
309
151
  /**
310
152
  * 角色守卫配置
153
+ * @example
154
+ * ```ts
155
+ * import type { RoleGuardConfig } from '@h-ai/kit'
156
+ *
157
+ * const value: RoleGuardConfig = { roles: ['editor'] }
158
+ * void value
159
+ * ```
311
160
  */
312
161
  interface RoleGuardConfig {
313
162
  /** 需要的角色列表(默认 OR 逻辑,满足任一即通过) */
@@ -319,23 +168,6 @@ interface RoleGuardConfig {
319
168
  /** 为 `true` 时返回 JSON 403 而非重定向 */
320
169
  apiMode?: boolean;
321
170
  }
322
- /**
323
- * 创建角色守卫
324
- *
325
- * 检查用户 `session.roles` 是否满足配置中的角色要求。
326
- * 未认证时返回 401;角色不匹配时根据 `apiMode` 返回 JSON 403 或重定向。
327
- *
328
- * @param config - 角色守卫配置
329
- * @returns RouteGuard 实例
330
- *
331
- * @example
332
- * ```ts
333
- * guards: [
334
- * { guard: kit.guard.role({ roles: ['admin'], apiMode: true }), paths: ['/api/admin/*'] },
335
- * ]
336
- * ```
337
- */
338
- declare function roleGuard(config: RoleGuardConfig): RouteGuard;
339
171
 
340
172
  /**
341
173
  * @h-ai/kit — Cookie 加密代理
@@ -346,6 +178,15 @@ declare function roleGuard(config: RoleGuardConfig): RouteGuard;
346
178
 
347
179
  /**
348
180
  * Cookie 加密代理配置
181
+ * @example
182
+ * ```ts
183
+ * import type { CookieProxyConfig } from '@h-ai/kit'
184
+ * import { crypto } from '@h-ai/crypto'
185
+ *
186
+ * function config(encryptionKey: string): CookieProxyConfig {
187
+ * return { names: new Set(['session']), symmetric: crypto.symmetric, encryptionKey }
188
+ * }
189
+ * ```
349
190
  */
350
191
  interface CookieProxyConfig {
351
192
  /** 需要加密的 Cookie 名称集合 */
@@ -355,20 +196,6 @@ interface CookieProxyConfig {
355
196
  /** 加密密钥(32 字符十六进制) */
356
197
  encryptionKey: string;
357
198
  }
358
- /**
359
- * 创建加密 Cookie 代理
360
- *
361
- * 返回一个 Proxy 包装的 Cookies 对象:
362
- * - `get(name)` —— 若 name 在加密列表中,自动解密后返回明文;格式或解密失败时返回 `undefined`
363
- * - `set(name, value, opts)` —— 若 name 在加密列表中,自动加密后存储;加密失败时拒绝写入
364
- * - `delete(name, opts)` —— 透传,无需解密
365
- * - 其他方法原样透传
366
- *
367
- * @param cookies - SvelteKit 原始 Cookies 对象
368
- * @param config - 加密配置
369
- * @returns 代理后的 Cookies 对象(类型不变)
370
- */
371
- declare function createEncryptedCookieProxy(cookies: Cookies, config: CookieProxyConfig): Cookies;
372
199
 
373
200
  /**
374
201
  * @h-ai/kit — SvelteKit Handle Hook
@@ -393,19 +220,12 @@ declare function createEncryptedCookieProxy(cookies: Cookies, config: CookieProx
393
220
  *
394
221
  * @param config - Handle 配置(均有合理默认值,可零配置使用)
395
222
  * @returns SvelteKit Handle 函数
396
- *
397
223
  * @example
398
224
  * ```ts
399
- * export const handle = kit.createHandle({
400
- * auth: {
401
- * verifyToken: validateSession,
402
- * loginUrl: '/auth/login',
403
- * protectedPaths: ['/admin/*', '/api/*'],
404
- * publicPaths: ['/api/auth/*', '/api/public/*'],
405
- * },
406
- * rateLimit: { maxRequests: 100 },
407
- * crypto: { crypto, transport: true },
408
- * })
225
+ * import { kit } from '@h-ai/kit'
226
+ *
227
+ * const handle = kit.createHandle({ auth: { verifyToken: async () => null, protectedPaths: ['/admin/**'] } })
228
+ * void handle
409
229
  * ```
410
230
  */
411
231
  declare function createHandle(config?: HandleConfig): Handle;
@@ -416,16 +236,27 @@ declare function createHandle(config?: HandleConfig): Handle;
416
236
  *
417
237
  * @param handles - 待组合的 handle 函数列表
418
238
  * @returns 组合后的单一 Handle 函数
419
- *
420
239
  * @example
421
240
  * ```ts
422
- * const haiHandle = kit.createHandle({ ... })
423
- * export const handle = kit.sequence(i18nHandle, haiHandle)
241
+ * import { kit } from '@h-ai/kit'
242
+ *
243
+ * const handle = kit.sequence(kit.createHandle({ logging: true }), kit.createHandle())
244
+ * void handle
424
245
  * ```
425
246
  */
426
247
  declare function sequence(...handles: Handle[]): Handle;
427
248
 
428
- /** 应用路由直接导出对应 handler;认证 ops 仍由 createHandle 注入。 */
249
+ /**
250
+ * 应用路由直接导出对应 handler;认证 ops 仍由 createHandle 注入。
251
+ * @param iam - 已由应用初始化的 IAM 服务对象。
252
+ * @returns 标准认证端点的 RequestHandler 集合。
253
+ * @example 模块内部上下文
254
+ * ```ts
255
+ * function build(iam: IamFunctions) {
256
+ * return createAuthApi(iam) // 调用方负责初始化 IAM;工厂只装配 handler。
257
+ * }
258
+ * ```
259
+ */
429
260
  declare function createAuthApi(iam: IamFunctions): {
430
261
  publicConfig: _sveltejs_kit.RequestHandler;
431
262
  login: _sveltejs_kit.RequestHandler;
@@ -455,13 +286,12 @@ declare function createAuthApi(iam: IamFunctions): {
455
286
  *
456
287
  * @param fn - 业务处理函数
457
288
  * @returns SvelteKit RequestHandler
458
- *
459
289
  * @example
460
290
  * ```ts
461
- * export const GET = kit.handler(async ({ locals }) => {
462
- * kit.guard.require(locals.session, 'user:read')
463
- * return kit.response.ok(await getUsers())
464
- * })
291
+ * import { kit } from '@h-ai/kit'
292
+ *
293
+ * const GET = kit.handler(() => kit.response.ok({ healthy: true }))
294
+ * void GET
465
295
  * ```
466
296
  */
467
297
  declare function handler(fn: (event: RequestEvent) => Promise<Response> | Response): RequestHandler;
@@ -482,10 +312,12 @@ declare function handler(fn: (event: RequestEvent) => Promise<Response> | Respon
482
312
  * @param data - 响应数据,序列化为 JSON
483
313
  * @param requestId - 可选请求 ID,用于链路追踪
484
314
  * @returns `{ success: true, data, requestId }` 格式的 JSON Response
485
- *
486
315
  * @example
487
316
  * ```ts
488
- * return kit.response.ok({ id: '1', name: 'Alice' })
317
+ * import { kit } from '@h-ai/kit'
318
+ *
319
+ * const response = kit.response.ok({ id: 'article_1' })
320
+ * void response.status
489
321
  * ```
490
322
  */
491
323
  declare function ok<T>(data: T, requestId?: string): Response;
@@ -495,10 +327,12 @@ declare function ok<T>(data: T, requestId?: string): Response;
495
327
  * @param data - 新创建的资源数据
496
328
  * @param requestId - 可选请求 ID
497
329
  * @returns `{ success: true, data }` 格式的 JSON Response(status 201)
498
- *
499
330
  * @example
500
331
  * ```ts
501
- * return kit.response.created({ id: 'new_1' })
332
+ * import { kit } from '@h-ai/kit'
333
+ *
334
+ * const response = kit.response.created({ id: 'article_1' })
335
+ * void response.status
502
336
  * ```
503
337
  */
504
338
  declare function created<T>(data: T, requestId?: string): Response;
@@ -508,6 +342,13 @@ declare function created<T>(data: T, requestId?: string): Response;
508
342
  * 通常用于 DELETE 成功或无返回值的更新操作。
509
343
  *
510
344
  * @returns 空 body、status 204 的 Response
345
+ * @example
346
+ * ```ts
347
+ * import { kit } from '@h-ai/kit'
348
+ *
349
+ * const response = kit.response.noContent()
350
+ * void response.status
351
+ * ```
511
352
  */
512
353
  declare function noContent(): Response;
513
354
  /**
@@ -519,10 +360,12 @@ declare function noContent(): Response;
519
360
  * @param requestId - 可选请求 ID
520
361
  * @param details - 可选额外详情
521
362
  * @returns `{ success: false, error: { code, message, details } }` 格式的 JSON Response
522
- *
523
363
  * @example
524
364
  * ```ts
525
- * return kit.response.error('QUOTA_EXCEEDED', '配额已用尽', 429)
365
+ * import { kit } from '@h-ai/kit'
366
+ *
367
+ * const response = kit.response.error('ARTICLE_MISSING', 'Article missing', 404)
368
+ * void response.status
526
369
  * ```
527
370
  */
528
371
  declare function error(code: string, message: string, status?: number, requestId?: string, details?: unknown): Response;
@@ -533,6 +376,13 @@ declare function error(code: string, message: string, status?: number, requestId
533
376
  * @param requestId - 可选请求 ID
534
377
  * @param details - 可选额外详情
535
378
  * @returns error code 为 `'BAD_REQUEST'` 的 JSON Response
379
+ * @example
380
+ * ```ts
381
+ * import { kit } from '@h-ai/kit'
382
+ *
383
+ * const response = kit.response.badRequest('Invalid article')
384
+ * void response.status
385
+ * ```
536
386
  */
537
387
  declare function badRequest(message: string, requestId?: string, details?: unknown): Response;
538
388
  /**
@@ -541,6 +391,13 @@ declare function badRequest(message: string, requestId?: string, details?: unkno
541
391
  * @param message - 错误消息,默认 `'Authentication required'`
542
392
  * @param requestId - 可选请求 ID
543
393
  * @returns error code 为 `'UNAUTHORIZED'` 的 JSON Response
394
+ * @example
395
+ * ```ts
396
+ * import { kit } from '@h-ai/kit'
397
+ *
398
+ * const response = kit.response.unauthorized()
399
+ * void response.status
400
+ * ```
544
401
  */
545
402
  declare function unauthorized(message?: string, requestId?: string): Response;
546
403
  /**
@@ -549,6 +406,13 @@ declare function unauthorized(message?: string, requestId?: string): Response;
549
406
  * @param message - 错误消息,默认 `'Access denied'`
550
407
  * @param requestId - 可选请求 ID
551
408
  * @returns error code 为 `'FORBIDDEN'` 的 JSON Response
409
+ * @example
410
+ * ```ts
411
+ * import { kit } from '@h-ai/kit'
412
+ *
413
+ * const response = kit.response.forbidden()
414
+ * void response.status
415
+ * ```
552
416
  */
553
417
  declare function forbidden(message?: string, requestId?: string): Response;
554
418
  /**
@@ -557,6 +421,13 @@ declare function forbidden(message?: string, requestId?: string): Response;
557
421
  * @param message - 错误消息,默认 `'Resource not found'`
558
422
  * @param requestId - 可选请求 ID
559
423
  * @returns error code 为 `'NOT_FOUND'` 的 JSON Response
424
+ * @example
425
+ * ```ts
426
+ * import { kit } from '@h-ai/kit'
427
+ *
428
+ * const response = kit.response.notFound()
429
+ * void response.status
430
+ * ```
560
431
  */
561
432
  declare function notFound(message?: string, requestId?: string): Response;
562
433
  /**
@@ -565,6 +436,13 @@ declare function notFound(message?: string, requestId?: string): Response;
565
436
  * @param message - 冲突描述(如重复创建等)
566
437
  * @param requestId - 可选请求 ID
567
438
  * @returns error code 为 `'CONFLICT'` 的 JSON Response
439
+ * @example
440
+ * ```ts
441
+ * import { kit } from '@h-ai/kit'
442
+ *
443
+ * const response = kit.response.conflict('Already updated')
444
+ * void response.status
445
+ * ```
568
446
  */
569
447
  declare function conflict(message: string, requestId?: string): Response;
570
448
  /**
@@ -573,12 +451,12 @@ declare function conflict(message: string, requestId?: string): Response;
573
451
  * @param errors - 字段级别的验证错误列表
574
452
  * @param requestId - 可选请求 ID
575
453
  * @returns error code 为 `'VALIDATION_ERROR'`,details 包含 `errors` 数组
576
- *
577
454
  * @example
578
455
  * ```ts
579
- * return kit.response.validationError([
580
- * { field: 'email', message: '格式无效' },
581
- * ])
456
+ * import { kit } from '@h-ai/kit'
457
+ *
458
+ * const response = kit.response.validationError([{ field: 'title', message: 'Title is required' }])
459
+ * void response.status
582
460
  * ```
583
461
  */
584
462
  declare function validationError(errors: Array<{
@@ -591,6 +469,13 @@ declare function validationError(errors: Array<{
591
469
  * @param message - 错误消息,默认 `'Internal server error'`
592
470
  * @param requestId - 可选请求 ID
593
471
  * @returns error code 为 `'INTERNAL_ERROR'` 的 JSON Response
472
+ * @example
473
+ * ```ts
474
+ * import { kit } from '@h-ai/kit'
475
+ *
476
+ * const response = kit.response.internalError()
477
+ * void response.status
478
+ * ```
594
479
  */
595
480
  declare function internalError(message?: string, requestId?: string): Response;
596
481
  /**
@@ -599,10 +484,12 @@ declare function internalError(message?: string, requestId?: string): Response;
599
484
  * @param url - 目标 URL
600
485
  * @param status - HTTP 状态码,默认 302;常用 303(POST 后重定向)
601
486
  * @returns 带 `Location` 头的空 body Response
602
- *
603
487
  * @example
604
488
  * ```ts
605
- * return kit.response.redirect('/dashboard', 303)
489
+ * import { kit } from '@h-ai/kit'
490
+ *
491
+ * const response = kit.response.redirect('/articles', 303)
492
+ * void response.status
606
493
  * ```
607
494
  */
608
495
  declare function redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
@@ -616,14 +503,12 @@ declare function redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Re
616
503
  * @param httpStatusMap - 模块导出的错误码 → HTTP 状态码映射表(如 IamErrorHttpStatus)
617
504
  * @param requestId - 可选请求 ID,用于链路追踪
618
505
  * @returns 标准化 JSON Response
619
- *
620
506
  * @example
621
507
  * ```ts
622
- * // 无映射(默认 400)
623
- * return kit.response.fromResult(result)
508
+ * import { kit } from '@h-ai/kit'
624
509
  *
625
- * // 带模块错误码映射
626
- * return kit.response.fromResult(result, IamErrorHttpStatus)
510
+ * const response = kit.response.fromResult({ success: true, data: { id: 'article_1' } })
511
+ * void response.status
627
512
  * ```
628
513
  */
629
514
  declare function fromResult<T>(result: {
@@ -637,6 +522,19 @@ declare function fromResult<T>(result: {
637
522
  [key: string]: unknown;
638
523
  };
639
524
  }, httpStatusMap?: Record<number | string, number>, requestId?: string): Response;
525
+ /**
526
+ * 按模块错误的 HTTP 状态构建安全的统一 API 错误响应。
527
+ * @param haiError - 包含 code、message 和可选 httpStatus 的模块错误。
528
+ * @param requestId - 可选的请求追踪标识。
529
+ * @returns 包含统一错误结构和对应 HTTP 状态的 Response。
530
+ * @example
531
+ * ```ts
532
+ * import { kit } from '@h-ai/kit'
533
+ *
534
+ * const response = kit.response.fromError({ code: 'app:articles:001', message: 'Article missing', httpStatus: 404 })
535
+ * void response.status
536
+ * ```
537
+ */
640
538
  declare function fromError(haiError: HaiError, requestId?: string): Response;
641
539
 
642
540
  /**
@@ -662,13 +560,12 @@ declare function fromError(haiError: HaiError, requestId?: string): Response;
662
560
  * @param schema - Zod Schema
663
561
  * @returns 校验通过的数据(类型安全)
664
562
  * @throws Response - 400 BadRequest(含首条错误消息)
665
- *
666
- * @example
563
+ * @example 模块内部上下文
667
564
  * ```ts
668
- * export const POST = kit.handler(async ({ request }) => {
669
- * const data = await kit.validate.body(request, CreateUserSchema)
670
- * // data 类型安全,校验已通过
671
- * })
565
+ * const schema = zod.object({ title: zod.string().min(1) })
566
+ * const result = await validateFormOrFail(new Request('https://app.example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Example' }) }), schema)
567
+ * // 校验失败抛出 Response,由框架错误边界透传。
568
+ * void result.title
672
569
  * ```
673
570
  */
674
571
  declare function validateFormOrFail<T extends z.ZodType>(request: Request, schema: T): Promise<z.infer<T>>;
@@ -679,10 +576,12 @@ declare function validateFormOrFail<T extends z.ZodType>(request: Request, schem
679
576
  * @param schema - Zod Schema
680
577
  * @returns 校验通过的数据
681
578
  * @throws Response - 400 BadRequest
682
- *
683
- * @example
579
+ * @example 模块内部上下文
684
580
  * ```ts
685
- * const query = kit.validate.query(event.url, PaginationSchema)
581
+ * const schema = zod.object({ title: zod.string().min(1) })
582
+ * const result = validateQueryOrFail(new URL('https://app.example.com/articles?title=Example'), schema)
583
+ * // 校验失败抛出 Response,由框架错误边界透传。
584
+ * void result.title
686
585
  * ```
687
586
  */
688
587
  declare function validateQueryOrFail<T extends z.ZodType>(url: URL, schema: T): z.infer<T>;
@@ -693,10 +592,12 @@ declare function validateQueryOrFail<T extends z.ZodType>(url: URL, schema: T):
693
592
  * @param schema - Zod Schema
694
593
  * @returns 校验通过的数据
695
594
  * @throws Response - 400 BadRequest
696
- *
697
- * @example
595
+ * @example 模块内部上下文
698
596
  * ```ts
699
- * const { id } = kit.validate.params(event.params, IdParamSchema)
597
+ * const schema = zod.object({ title: zod.string().min(1) })
598
+ * const result = validateParamsOrFail({ title: 'Example' }, schema)
599
+ * // 校验失败抛出 Response,由框架错误边界透传。
600
+ * void result.title
700
601
  * ```
701
602
  */
702
603
  declare function validateParamsOrFail<T extends z.ZodType>(params: Record<string, string>, schema: T): z.infer<T>;
@@ -704,10 +605,12 @@ declare function validateParamsOrFail<T extends z.ZodType>(params: Record<string
704
605
  * 路径参数 id 校验 Schema
705
606
  *
706
607
  * 验证 `event.params.id` 为非空字符串。
707
- *
708
608
  * @example
709
609
  * ```ts
710
- * const { id } = kit.validate.params(event.params, IdParamSchema)
610
+ * import { IdParamSchema } from '@h-ai/kit'
611
+ *
612
+ * const value = IdParamSchema.parse({ id: 'article_1' })
613
+ * void value
711
614
  * ```
712
615
  */
713
616
  declare const IdParamSchema: z.ZodObject<{
@@ -718,16 +621,12 @@ declare const IdParamSchema: z.ZodObject<{
718
621
  *
719
622
  * 包含 page(默认 1)、pageSize(默认 20,上限 100)、search(可选)。
720
623
  * 可通过 `.extend()` 扩展业务字段。
721
- *
722
624
  * @example
723
625
  * ```ts
724
- * // 直接使用
725
- * const { page, pageSize, search } = kit.validate.query(url, PaginationQuerySchema)
626
+ * import { PaginationQuerySchema } from '@h-ai/kit'
726
627
  *
727
- * // 扩展业务字段
728
- * const ListUsersSchema = PaginationQuerySchema.extend({
729
- * enabled: z.enum(['true', 'false']).transform(v => v === 'true').optional(),
730
- * })
628
+ * const value = PaginationQuerySchema.parse({ page: '1', pageSize: '20' })
629
+ * void value
731
630
  * ```
732
631
  */
733
632
  declare const PaginationQuerySchema: z.ZodObject<{
@@ -740,9 +639,22 @@ declare const PaginationQuerySchema: z.ZodObject<{
740
639
  * Kit 模块统一出口。
741
640
  *
742
641
  * 作为纯工具模块,kit 不需要 init/close 生命周期,
743
- * 所有功能均为无状态工厂函数或工具函数。
642
+ * 依赖服务、请求上下文和创建后句柄的状态由调用方按各自契约管理。
643
+ * @example
644
+ * ```ts
645
+ * import { kit } from '@h-ai/kit'
646
+ *
647
+ * const handle = kit.createHandle({ logging: true })
648
+ * void handle
649
+ * ```
744
650
  */
745
651
  declare const kit: {
652
+ /** 原子限流工厂;共享store生命周期由应用管理。 */
653
+ middleware: {
654
+ rateLimit: typeof rateLimitMiddleware;
655
+ createCacheRateLimitStore: typeof createCacheRateLimitStore;
656
+ createMemoryRateLimitStore: typeof createMemoryRateLimitStore;
657
+ };
746
658
  /** 创建 SvelteKit Handle Hook(含 auth / logging / rateLimit 内置配置) */
747
659
  createHandle: typeof createHandle;
748
660
  /** 组合多个 Handle */
@@ -837,8 +749,6 @@ declare const kit: {
837
749
  setBrowserToken: typeof setBrowserToken;
838
750
  /** 清除浏览器端 Access Token(客户端 logout 用) */
839
751
  clearBrowserToken: typeof clearBrowserToken;
840
- /** 创建浏览器端 Token 存储器(自定义 key 时使用) */
841
- createTokenStore: typeof createTokenStore;
842
752
  };
843
753
  crud: {
844
754
  /** 定义 CRUD 资源(声明式配置 → 操作对象) */
@@ -847,38 +757,11 @@ declare const kit: {
847
757
  i18n: {
848
758
  /** 统一设置所有 hai 模块的默认语言 */
849
759
  setLocale: typeof setAllModulesLocale;
760
+ /** 请求/SSR 语言隔离;异步处理使用同一请求上下文。 */
761
+ runWithLocale: <T>(locale: _h_ai_core.Locale, operation: () => T) => T;
850
762
  };
851
763
  };
852
764
 
853
- /**
854
- * @h-ai/kit — CORS 中间件
855
- *
856
- * 配置跨域资源共享(CORS)策略,自动处理 OPTIONS 预检请求与响应头注入。
857
- * 支持精确 origin、数组白名单、通配符模式与函数匹配四种模式。
858
- * 自动预置 Capacitor WebView origin(Android/iOS)。
859
- * @module kit-cors
860
- */
861
-
862
- /**
863
- * 创建 CORS 中间件
864
- *
865
- * 处理跨域资源共享:
866
- * - OPTIONS 预检请求返回 204 + CORS 头
867
- * - 其他请求在业务响应上附加 CORS 头
868
- * - 默认预置 Capacitor WebView origin
869
- *
870
- * @param config - CORS 配置(省略则允许所有 origin)
871
- * @returns Middleware 实例
872
- *
873
- * @example
874
- * ```ts
875
- * middleware: [
876
- * kit.middleware.cors({ origin: ['https://example.com'], credentials: true }),
877
- * ]
878
- * ```
879
- */
880
- declare function corsMiddleware(config?: CorsConfig): Middleware;
881
-
882
765
  /**
883
766
  * @h-ai/kit — 日志中间件
884
767
  *
@@ -889,6 +772,13 @@ declare function corsMiddleware(config?: CorsConfig): Middleware;
889
772
 
890
773
  /**
891
774
  * 日志中间件配置
775
+ * @example
776
+ * ```ts
777
+ * import type { LoggingMiddlewareConfig } from '@h-ai/kit'
778
+ *
779
+ * const value: LoggingMiddlewareConfig = { logBody: false }
780
+ * void value
781
+ * ```
892
782
  */
893
783
  interface LoggingMiddlewareConfig {
894
784
  /** 为 `true` 时记录非 GET 请求体(自动脱敏) */
@@ -898,25 +788,5 @@ interface LoggingMiddlewareConfig {
898
788
  /** 指定需要脱敏的字段名(默认 `['password', 'token', 'secret']`) */
899
789
  redactFields?: string[];
900
790
  }
901
- /**
902
- * 创建日志中间件
903
- *
904
- * 以 `core.logger.trace` 级别记录请求进出信息,包含:
905
- * - 请求:method / path / query / userAgent / ip
906
- * - 响应:status / duration
907
- *
908
- * 敏感字段会被自动替换为 `[REDACTED]`。
909
- *
910
- * @param config - 日志配置
911
- * @returns Middleware 实例
912
- *
913
- * @example
914
- * ```ts
915
- * middleware: [
916
- * kit.middleware.logging({ logBody: true, redactFields: ['password', 'creditCard'] }),
917
- * ]
918
- * ```
919
- */
920
- declare function loggingMiddleware(config?: LoggingMiddlewareConfig): Middleware;
921
791
 
922
- export { type AuthGuardConfig, type CookieProxyConfig, CorsConfig, HandleConfig, IdParamSchema, type LoggingMiddlewareConfig, Middleware, PaginationQuerySchema, type PermissionGuardConfig, type RoleGuardConfig, RouteGuard, SessionData, type SessionGuardConfig, SessionLike, allGuards, anyGuard, assertPermission, authGuard, conditionalGuard, corsMiddleware, createEncryptedCookieProxy, createHandle, createKitAuthActions, createKitClient, defineCrud, hasPermission, installBrowserTransport, installBrowserTransportFetch, kit, loggingMiddleware, matchPermission, notGuard, permissionGuard, requirePermission, roleGuard, sequence, sessionGuard, withPermission };
792
+ export { type AuthGuardConfig, type CookieProxyConfig, HandleConfig, IdParamSchema, type LoggingMiddlewareConfig, PaginationQuerySchema, type PermissionGuardConfig, type RoleGuardConfig, SessionData, type SessionGuardConfig, SessionLike, defineCrud, kit, matchPermission };