@h-ai/kit 0.1.0-alpha5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,963 @@
1
+ import { c as createKitClient, l as login, f as loginWithOtp, g as loginWithLdap, h as loginWithApiKey, r as registerAndLogin, i as logout, s as setBrowserToken, a as clearBrowserToken, b as createTokenStore, d as createHandleFetch } from './index-BotXLTck.js';
2
+ export { C as ClientTransportConfig, K as KitClient, e as KitClientConfig } from './index-BotXLTck.js';
3
+ import { d as defineCrud, s as setAllModulesLocale } from './kit-i18n-CgpNTh9G.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-CgpNTh9G.js';
5
+ import { S as SessionData, k as RouteGuard, l as SessionLike, h as HandleConfig, C as CorsConfig, M as Middleware } from './kit-types-BHlDNNpd.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-BHlDNNpd.js';
7
+ import { RequestEvent, Cookies, Handle, RequestHandler } from '@sveltejs/kit';
8
+ import { T as TransportCryptoServiceLike } from './kit-crypto-types-C-gEvx04.js';
9
+ export { C as CryptoCsrfConfig, a as CryptoServiceLike, E as EncryptedCookieConfig, b as EncryptedPayload, c as TransportEncryptionConfig, d as TransportEncryptionManager, e as TransportKeyPair, W as WebhookVerifyConfig } from './kit-crypto-types-C-gEvx04.js';
10
+ import * as zod from 'zod';
11
+ import { z } from 'zod';
12
+ import * as zod_v4_core from 'zod/v4/core';
13
+ import { HaiError } from '@h-ai/core';
14
+ export { A2AApiKeyAuthConfig, KitA2AHandlerConfig, ResolvedA2AConfig, createA2AApiKeyAuthenticator, createA2AHandler, createAgentCardHandler, handleA2ARequest, resolveA2AConfig } from './modules/a2a/index.js';
15
+ export { createCsrfManager, createEncryptedCookie, createKeyExchangeHandler, createTransportEncryption, isValidEncryptedPayload, signRequest, transportEncryptionMiddleware, verifyWebhookSignature } from './modules/crypto/index.js';
16
+ import '@h-ai/iam';
17
+
18
+ /**
19
+ * @h-ai/kit — 认证守卫
20
+ *
21
+ * 验证用户是否已登录
22
+ * @module kit-auth
23
+ */
24
+
25
+ /**
26
+ * 认证守卫配置
27
+ */
28
+ interface AuthGuardConfig {
29
+ /** 未登录时重定向 URL(默认 `'/login'`) */
30
+ loginUrl?: string;
31
+ /** 为 `true` 时返回 JSON 401 而非重定向(适用于 API 路由) */
32
+ apiMode?: boolean;
33
+ }
34
+ /**
35
+ * 会话守卫配置
36
+ */
37
+ interface SessionGuardConfig {
38
+ /** 会话校验函数(通常由应用注入 iam.auth.verifyToken 封装) */
39
+ validateSession: (token: string) => Promise<SessionData | null>;
40
+ /** 未登录时重定向 URL(默认 `'/login'`) */
41
+ loginUrl?: string;
42
+ /** 为 `true` 时返回 JSON 401 而非重定向(适用于 API 路由) */
43
+ apiMode?: boolean;
44
+ }
45
+ /**
46
+ * 创建认证守卫
47
+ *
48
+ * 检查会话是否存在;未认证时:
49
+ * - 页面模式:重定向到 `loginUrl`,并携带 `returnUrl` 参数以便登录后返回。
50
+ * - API 模式:返回 JSON `{ allowed: false, status: 401 }`。
51
+ *
52
+ * @param config - 守卫配置
53
+ * @returns RouteGuard 实例
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * // Hook 配置
58
+ * guards: [
59
+ * { guard: kit.guard.auth({ apiMode: true }), paths: ['/api/*'] },
60
+ * { guard: kit.guard.auth(), paths: ['/dashboard/*'] },
61
+ * ]
62
+ * ```
63
+ */
64
+ declare function authGuard(config?: AuthGuardConfig): RouteGuard;
65
+ /**
66
+ * 创建会话守卫(支持 Bearer + 固定 Access Token Cookie 自动恢复)。
67
+ *
68
+ * 处理流程:
69
+ * 1. 若上游已注入 session,直接放行
70
+ * 2. 否则从 request/cookies 解析 token(Bearer 优先)
71
+ * 3. 调用 validateSession 恢复并写入 event.locals.session
72
+ * 4. 失败则按页面/API模式返回重定向或 401
73
+ */
74
+ declare function sessionGuard(config: SessionGuardConfig): RouteGuard;
75
+
76
+ /**
77
+ * @h-ai/kit — 组合守卫
78
+ *
79
+ * 提供守卫组合器,支持 AND(allGuards)/ OR(anyGuard)/ NOT(notGuard)/ 条件分支(conditionalGuard)等逻辑组合,将多个 RouteGuard 聚合为一个。
80
+ * @module kit-compose
81
+ */
82
+
83
+ /**
84
+ * 所有守卫都通过才允许访问(AND 逻辑)
85
+ *
86
+ * 短路求值:第一个拒绝的守卫结果会被直接返回。
87
+ *
88
+ * @param guards - 需要全部通过的守卫列表
89
+ * @returns 组合后的 RouteGuard
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const adminOnly = kit.guard.all(
94
+ * kit.guard.auth(),
95
+ * kit.guard.role({ roles: ['admin'] }),
96
+ * )
97
+ * ```
98
+ */
99
+ declare function allGuards(...guards: RouteGuard[]): RouteGuard;
100
+ /**
101
+ * 任意一个守卫通过就允许访问(OR 逻辑)
102
+ *
103
+ * 短路求值:第一个允许的守卫结果会被直接返回。
104
+ * 全部拒绝时返回最后一个拒绝结果。
105
+ *
106
+ * @param guards - 守卫列表
107
+ * @returns 组合后的 RouteGuard
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * const canView = kit.guard.any(
112
+ * kit.guard.role({ roles: ['admin'] }),
113
+ * kit.guard.permission({ permissions: ['article:read'] }),
114
+ * )
115
+ * ```
116
+ */
117
+ declare function anyGuard(...guards: RouteGuard[]): RouteGuard;
118
+ /**
119
+ * 取反守卫
120
+ *
121
+ * 将原守卫的判定逻辑反转:原本放行变为拒绝,原本拒绝变为放行。
122
+ * 典型场景:「仅未登录用户可访问登录页」。
123
+ *
124
+ * @param guard - 需要取反的守卫
125
+ * @param options - 拒绝时的重定向/消息
126
+ * @param options.redirect - 拒绝时重定向 URL
127
+ * @param options.message - 拒绝时的提示消息
128
+ * @returns 取反后的 RouteGuard
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * // 仅未登录用户可访问
133
+ * const guestOnly = kit.guard.not(kit.guard.auth(), { redirect: '/dashboard' })
134
+ * ```
135
+ */
136
+ declare function notGuard(guard: RouteGuard, options?: {
137
+ redirect?: string;
138
+ message?: string;
139
+ }): RouteGuard;
140
+ /** 条件判断函数类型:返回 `true` 时才执行后续守卫 */
141
+ type ConditionFn = (event: RequestEvent, session: SessionData | undefined) => boolean | Promise<boolean>;
142
+ /**
143
+ * 条件守卫
144
+ *
145
+ * 仅当 `condition` 返回 `true` 时才执行 `guard`;否则直接放行。
146
+ *
147
+ * @param condition - 条件判断函数
148
+ * @param guard - 条件满足时执行的守卫
149
+ * @returns 包装后的 RouteGuard
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * // 仅 POST 请求检查 CSRF
154
+ * kit.guard.conditional(
155
+ * (event) => event.request.method === 'POST',
156
+ * csrfGuard,
157
+ * )
158
+ * ```
159
+ */
160
+ declare function conditionalGuard(condition: ConditionFn, guard: RouteGuard): RouteGuard;
161
+
162
+ /**
163
+ * @h-ai/kit — 权限守卫
164
+ *
165
+ * 验证用户是否具有指定权限。
166
+ * @module kit-permission
167
+ */
168
+
169
+ /**
170
+ * 权限守卫配置
171
+ */
172
+ interface PermissionGuardConfig {
173
+ /** 需要的权限列表(默认 OR 逻辑,满足任一即通过) */
174
+ permissions: string[];
175
+ /** 为 `true` 时要求用户拥有 **全部** 权限(AND 逻辑) */
176
+ requireAll?: boolean;
177
+ /** 无权限时重定向 URL(默认 `'/403'`) */
178
+ forbiddenUrl?: string;
179
+ /** 为 `true` 时返回 JSON 403 而非重定向 */
180
+ apiMode?: boolean;
181
+ }
182
+ /**
183
+ * 创建权限守卫
184
+ *
185
+ * 检查用户 `session.permissions` 是否满足配置中的权限要求。
186
+ * 支持通配符匹配:`admin:*` 可匹配 `admin:read`、`admin:write` 等。
187
+ * 未认证时返回 401;权限不匹配时根据 `apiMode` 返回 JSON 403 或重定向。
188
+ *
189
+ * @param config - 权限守卫配置
190
+ * @returns RouteGuard 实例
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * guards: [
195
+ * { guard: kit.guard.permission({ permissions: ['user:read', 'user:write'], requireAll: true }), paths: ['/api/users/*'] },
196
+ * ]
197
+ * ```
198
+ */
199
+ declare function permissionGuard(config: PermissionGuardConfig): RouteGuard;
200
+ /**
201
+ * 匹配权限
202
+ *
203
+ * 支持通配符:
204
+ * - `admin:*` 匹配 `admin:read`、`admin:write` 等
205
+ * - `*` 匹配所有权限
206
+ *
207
+ * @param required - 需要的权限码
208
+ * @param userPermissions - 用户已有的权限列表
209
+ * @returns 是否匹配
210
+ */
211
+ declare function matchPermission(required: string, userPermissions: string[]): boolean;
212
+ /**
213
+ * 检查会话是否具有指定权限(布尔判断)
214
+ *
215
+ * 适用于条件分支场景(如菜单过滤、按钮显示等)。
216
+ *
217
+ * @param session - 当前会话数据,null/undefined 视为无权限
218
+ * @param permission - 需要的权限码,如 `user:read`
219
+ * @returns 是否拥有权限
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * if (kit.guard.check(locals.session, 'user:read')) {
224
+ * // 有权限
225
+ * }
226
+ * ```
227
+ */
228
+ declare function hasPermission(session: SessionLike | null | undefined, permission: string): boolean;
229
+ /**
230
+ * 断言会话具有指定权限,不满足时返回 403 Response
231
+ *
232
+ * 适用于 SvelteKit API Handler 内部,不满足权限时直接返回 JSON 错误响应。
233
+ * 调用者需检查返回值:若有返回值则表示权限不足,应直接 return。
234
+ *
235
+ * @param session - 当前会话数据,null/undefined 视为未认证
236
+ * @param permission - 需要的权限码,如 `user:create`
237
+ * @returns 权限不足时返回 Response;有权限时返回 undefined
238
+ *
239
+ * @example
240
+ * ```ts
241
+ * export const POST: RequestHandler = async ({ locals }) => {
242
+ * const denied = kit.guard.assertPermission(locals.session, 'user:create')
243
+ * if (denied) return denied
244
+ * // ... 正常逻辑
245
+ * }
246
+ * ```
247
+ */
248
+ declare function assertPermission(session: SessionLike | null | undefined, permission: string): Response | undefined;
249
+ /**
250
+ * 要求会话具有指定权限,不满足时 throw Response
251
+ *
252
+ * 利用 SvelteKit 控制流机制:throw 的 Response 对象会被框架捕获并直接作为响应返回。
253
+ * 搭配 `kit.handler()` 使用时,无需手动检查返回值。
254
+ *
255
+ * @param session - 当前会话数据,null/undefined 视为未认证
256
+ * @param permission - 需要的权限码,如 `user:create`
257
+ * @throws Response - 未认证 401 / 无权限 403
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * export const GET = kit.handler(async ({ locals }) => {
262
+ * kit.guard.require(locals.session, 'user:read')
263
+ * // 执行到这里说明权限已通过
264
+ * return kit.response.ok(data)
265
+ * })
266
+ * ```
267
+ */
268
+ declare function requirePermission(session: SessionLike | null | undefined, permission: string): void;
269
+ /**
270
+ * 权限守卫高阶函数包装器
271
+ *
272
+ * 将权限检查从业务逻辑中提取到装饰层,handler 内部无需关心权限。
273
+ * 未认证返回 401、无权限返回 403(均通过 SvelteKit throw 控制流抛出)。
274
+ *
275
+ * 适用于 page load、API handler 等所有 SvelteKit server 函数。
276
+ *
277
+ * @param permission - 需要的权限码,如 `'user:read'`
278
+ * @param handler - 原始处理函数
279
+ * @returns 包装后的处理函数(签名不变)
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * // +page.server.ts
284
+ * export const load = kit.guard.withPermission('user:read', async ({ locals }) => {
285
+ * const result = await iam.user.listUsers()
286
+ * return { users: result.success ? result.data.items : [] }
287
+ * })
288
+ *
289
+ * // +server.ts (API handler)
290
+ * export const GET = kit.handler(kit.guard.withPermission('user:list', async ({ locals }) => {
291
+ * const result = await iam.user.listUsers()
292
+ * return kit.response.ok(result.data)
293
+ * }))
294
+ * ```
295
+ */
296
+ declare function withPermission<TEvent extends {
297
+ locals: Record<string, unknown>;
298
+ }, TReturn>(permission: string, handler: (event: TEvent) => Promise<TReturn>): (event: TEvent) => Promise<TReturn>;
299
+
300
+ /**
301
+ * @h-ai/kit — 角色守卫
302
+ *
303
+ * 验证用户是否具有指定角色
304
+ * @module kit-role
305
+ */
306
+
307
+ /**
308
+ * 角色守卫配置
309
+ */
310
+ interface RoleGuardConfig {
311
+ /** 需要的角色列表(默认 OR 逻辑,满足任一即通过) */
312
+ roles: string[];
313
+ /** 为 `true` 时要求用户拥有 **全部** 角色(AND 逻辑) */
314
+ requireAll?: boolean;
315
+ /** 无权限时重定向 URL(默认 `'/403'`) */
316
+ forbiddenUrl?: string;
317
+ /** 为 `true` 时返回 JSON 403 而非重定向 */
318
+ apiMode?: boolean;
319
+ }
320
+ /**
321
+ * 创建角色守卫
322
+ *
323
+ * 检查用户 `session.roles` 是否满足配置中的角色要求。
324
+ * 未认证时返回 401;角色不匹配时根据 `apiMode` 返回 JSON 403 或重定向。
325
+ *
326
+ * @param config - 角色守卫配置
327
+ * @returns RouteGuard 实例
328
+ *
329
+ * @example
330
+ * ```ts
331
+ * guards: [
332
+ * { guard: kit.guard.role({ roles: ['admin'], apiMode: true }), paths: ['/api/admin/*'] },
333
+ * ]
334
+ * ```
335
+ */
336
+ declare function roleGuard(config: RoleGuardConfig): RouteGuard;
337
+
338
+ /**
339
+ * @h-ai/kit — Cookie 加密代理
340
+ *
341
+ * 通过 Proxy 拦截 SvelteKit Cookies 对象的 get/set 方法, 对指定名称的 Cookie 自动进行 SM4-CBC 加解密。
342
+ * @module kit-cookie-proxy
343
+ */
344
+
345
+ /**
346
+ * Cookie 加密代理配置
347
+ */
348
+ interface CookieProxyConfig {
349
+ /** 需要加密的 Cookie 名称集合 */
350
+ names: Set<string>;
351
+ /** 对称加密服务(SM4) */
352
+ symmetric: TransportCryptoServiceLike['symmetric'];
353
+ /** 加密密钥(32 字符十六进制) */
354
+ encryptionKey: string;
355
+ }
356
+ /**
357
+ * 创建加密 Cookie 代理
358
+ *
359
+ * 返回一个 Proxy 包装的 Cookies 对象:
360
+ * - `get(name)` —— 若 name 在加密列表中,自动解密后返回明文
361
+ * - `set(name, value, opts)` —— 若 name 在加密列表中,自动加密后存储
362
+ * - `delete(name, opts)` —— 透传,无需解密
363
+ * - 其他方法原样透传
364
+ *
365
+ * @param cookies - SvelteKit 原始 Cookies 对象
366
+ * @param config - 加密配置
367
+ * @returns 代理后的 Cookies 对象(类型不变)
368
+ */
369
+ declare function createEncryptedCookieProxy(cookies: Cookies, config: CookieProxyConfig): Cookies;
370
+
371
+ /**
372
+ * @h-ai/kit — SvelteKit Handle Hook
373
+ *
374
+ * 创建 SvelteKit Handle Hook,集成请求 ID 生成、会话验证、Cookie 加密代理、
375
+ * 路由守卫、中间件链与可选传输加密;同时提供 `sequence()` 组合多个 Handle。
376
+ * @module kit-handle
377
+ */
378
+
379
+ /**
380
+ * 创建 hai handle hook
381
+ *
382
+ * 整合会话解析、路由守卫、中间件链与统一错误处理的 SvelteKit Handle 工厂。
383
+ *
384
+ * 执行顺序:
385
+ * 1. 生成 `requestId` 并写入 `event.locals`
386
+ * 2. 根据 `auth` 配置从 Bearer / Cookie 解析会话
387
+ * 3. 根据 `auth.protectedPaths` 自动执行路由守卫 + 额外自定义守卫
388
+ * 4. 构建中间件链(内置 logging / rateLimit + 自定义)并执行
389
+ * 5. 调用 `resolve(event)` 获取业务响应
390
+ * 6. 附加 `X-Request-Id` 响应头
391
+ *
392
+ * @param config - Handle 配置(均有合理默认值,可零配置使用)
393
+ * @returns SvelteKit Handle 函数
394
+ *
395
+ * @example
396
+ * ```ts
397
+ * export const handle = kit.createHandle({
398
+ * auth: {
399
+ * verifyToken: validateSession,
400
+ * loginUrl: '/auth/login',
401
+ * protectedPaths: ['/admin/*', '/api/*'],
402
+ * publicPaths: ['/api/auth/*', '/api/public/*'],
403
+ * },
404
+ * rateLimit: { maxRequests: 100 },
405
+ * crypto: { crypto, transport: true },
406
+ * })
407
+ * ```
408
+ */
409
+ declare function createHandle(config?: HandleConfig): Handle;
410
+ /**
411
+ * 组合多个 SvelteKit handle 为单一 handle
412
+ *
413
+ * 洋葱模型:`sequence(a, b, c)` 执行顺序为 a → b → c → resolve → c → b → a。
414
+ *
415
+ * @param handles - 待组合的 handle 函数列表
416
+ * @returns 组合后的单一 Handle 函数
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * const haiHandle = kit.createHandle({ ... })
421
+ * export const handle = kit.sequence(i18nHandle, haiHandle)
422
+ * ```
423
+ */
424
+ declare function sequence(...handles: Handle[]): Handle;
425
+
426
+ /**
427
+ * @h-ai/kit — 契约 Handler
428
+ *
429
+ * 基于 EndpointDef 契约创建类型安全的 API handler:
430
+ * - 自动从 request body/query 提取参数
431
+ * - 自动使用契约的 input schema 校验
432
+ * - handler 返回值类型必须匹配 output schema
433
+ * - 自动包装为标准 kit.response.ok() 响应
434
+ * @module kit-contract
435
+ */
436
+
437
+ /**
438
+ * API 端点契约定义
439
+ *
440
+ * 客户端和服务端共享的唯一真相源,保证路径、入参、出参编译时一致。
441
+ */
442
+ interface EndpointDef<TInput = unknown, TOutput = unknown> {
443
+ /** HTTP 方法 */
444
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
445
+ /** 相对路径(相对于 API 前缀,如 '/auth/login') */
446
+ path: string;
447
+ /** 入参 Zod Schema(GET 请求为 query params,其他为 body) */
448
+ input: z.ZodType<TInput>;
449
+ /** 出参 Zod Schema */
450
+ output: z.ZodType<TOutput>;
451
+ /** 是否需要认证(默认 true) */
452
+ requireAuth?: boolean;
453
+ /** OpenAPI 描述元数据(可选) */
454
+ meta?: {
455
+ summary?: string;
456
+ tags?: string[];
457
+ };
458
+ }
459
+ /**
460
+ * 辅助函数:创建端点定义(获得类型推导)
461
+ *
462
+ * @param def - 端点定义对象
463
+ * @returns 同一个对象(类型安全)
464
+ */
465
+ declare function defineEndpoint<TInput, TOutput>(def: EndpointDef<TInput, TOutput>): EndpointDef<TInput, TOutput>;
466
+ /**
467
+ * 基于契约创建 API handler
468
+ *
469
+ * - 自动从 request body/query 提取参数
470
+ * - 自动使用契约的 input schema 校验
471
+ * - handler 返回值类型必须匹配 output schema
472
+ * - 自动包装为标准 kit.response.ok() 响应
473
+ *
474
+ * @param endpoint - 端点契约定义
475
+ * @param fn - 业务处理函数(接收校验后的 input 和 RequestEvent)
476
+ * @returns SvelteKit RequestHandler
477
+ *
478
+ * @example
479
+ * ```ts
480
+ * import { iamEndpoints } from '@h-ai/iam/api'
481
+ *
482
+ * export const POST = kit.fromContract(iamEndpoints.login, async (input, event) => {
483
+ * const result = await iam.auth.login(input)
484
+ * if (!result.success) {
485
+ * throw kit.response.error('AUTH_FAILED', result.error.message, 401)
486
+ * }
487
+ * return result.data
488
+ * })
489
+ * ```
490
+ */
491
+ declare function fromContract<TInput, TOutput>(endpoint: EndpointDef<TInput, TOutput>, fn: (input: TInput, event: RequestEvent) => Promise<TOutput>): RequestHandler;
492
+
493
+ /**
494
+ * @h-ai/kit — API Handler 包装器
495
+ *
496
+ * 统一封装 SvelteKit API Handler 的错误处理逻辑。
497
+ * @module kit-handler
498
+ */
499
+
500
+ /**
501
+ * 创建 API Handler 包装器
502
+ *
503
+ * 将业务逻辑包裹在统一的异常边界中:
504
+ * 1. 正常执行 `fn(event)` 返回 Response
505
+ * 2. 若 `fn` throw 了 `Response`(如 `kit.guard.require` / `kit.validate.body`),直接返回该 Response
506
+ * 3. 若 `fn` throw 了 SvelteKit 控制流(`redirect()` / `error()`),继续抛出
507
+ * 4. 其他异常:记录日志 → 返回 `kit.response.internalError()`
508
+ *
509
+ * @param fn - 业务处理函数
510
+ * @returns SvelteKit RequestHandler
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * export const GET = kit.handler(async ({ locals }) => {
515
+ * kit.guard.require(locals.session, 'user:read')
516
+ * return kit.response.ok(await getUsers())
517
+ * })
518
+ * ```
519
+ */
520
+ declare function handler(fn: (event: RequestEvent) => Promise<Response> | Response): RequestHandler;
521
+
522
+ /**
523
+ * @h-ai/kit — API 响应工具
524
+ *
525
+ * 标准化 API 响应工具集,统一 `{ success, data?, error?, requestId? }` 结构。
526
+ * 提供成功响应(ok / created / noContent)、错误响应
527
+ * (badRequest / unauthorized / forbidden / notFound / conflict / validationError / internalError)
528
+ * 以及重定向响应。
529
+ * @module kit-response
530
+ */
531
+
532
+ /**
533
+ * 创建 200 成功响应
534
+ *
535
+ * @param data - 响应数据,序列化为 JSON
536
+ * @param requestId - 可选请求 ID,用于链路追踪
537
+ * @returns `{ success: true, data, requestId }` 格式的 JSON Response
538
+ *
539
+ * @example
540
+ * ```ts
541
+ * return kit.response.ok({ id: '1', name: 'Alice' })
542
+ * ```
543
+ */
544
+ declare function ok<T>(data: T, requestId?: string): Response;
545
+ /**
546
+ * 创建 201 资源创建成功响应
547
+ *
548
+ * @param data - 新创建的资源数据
549
+ * @param requestId - 可选请求 ID
550
+ * @returns `{ success: true, data }` 格式的 JSON Response(status 201)
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * return kit.response.created({ id: 'new_1' })
555
+ * ```
556
+ */
557
+ declare function created<T>(data: T, requestId?: string): Response;
558
+ /**
559
+ * 创建 204 无内容响应
560
+ *
561
+ * 通常用于 DELETE 成功或无返回值的更新操作。
562
+ *
563
+ * @returns 空 body、status 204 的 Response
564
+ */
565
+ declare function noContent(): Response;
566
+ /**
567
+ * 创建自定义错误响应
568
+ *
569
+ * @param code - 错误码(如 `'CUSTOM_ERROR'`)
570
+ * @param message - 人可读错误消息
571
+ * @param status - HTTP 状态码,默认 400
572
+ * @param requestId - 可选请求 ID
573
+ * @param details - 可选额外详情
574
+ * @returns `{ success: false, error: { code, message, details } }` 格式的 JSON Response
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * return kit.response.error('QUOTA_EXCEEDED', '配额已用尽', 429)
579
+ * ```
580
+ */
581
+ declare function error(code: string, message: string, status?: number, requestId?: string, details?: unknown): Response;
582
+ /**
583
+ * 创建 400 Bad Request 响应
584
+ *
585
+ * @param message - 错误消息
586
+ * @param requestId - 可选请求 ID
587
+ * @param details - 可选额外详情
588
+ * @returns error code 为 `'BAD_REQUEST'` 的 JSON Response
589
+ */
590
+ declare function badRequest(message: string, requestId?: string, details?: unknown): Response;
591
+ /**
592
+ * 创建 401 Unauthorized 响应
593
+ *
594
+ * @param message - 错误消息,默认 `'Authentication required'`
595
+ * @param requestId - 可选请求 ID
596
+ * @returns error code 为 `'UNAUTHORIZED'` 的 JSON Response
597
+ */
598
+ declare function unauthorized(message?: string, requestId?: string): Response;
599
+ /**
600
+ * 创建 403 Forbidden 响应
601
+ *
602
+ * @param message - 错误消息,默认 `'Access denied'`
603
+ * @param requestId - 可选请求 ID
604
+ * @returns error code 为 `'FORBIDDEN'` 的 JSON Response
605
+ */
606
+ declare function forbidden(message?: string, requestId?: string): Response;
607
+ /**
608
+ * 创建 404 Not Found 响应
609
+ *
610
+ * @param message - 错误消息,默认 `'Resource not found'`
611
+ * @param requestId - 可选请求 ID
612
+ * @returns error code 为 `'NOT_FOUND'` 的 JSON Response
613
+ */
614
+ declare function notFound(message?: string, requestId?: string): Response;
615
+ /**
616
+ * 创建 409 Conflict 响应
617
+ *
618
+ * @param message - 冲突描述(如重复创建等)
619
+ * @param requestId - 可选请求 ID
620
+ * @returns error code 为 `'CONFLICT'` 的 JSON Response
621
+ */
622
+ declare function conflict(message: string, requestId?: string): Response;
623
+ /**
624
+ * 创建 422 Unprocessable Entity 响应(验证错误)
625
+ *
626
+ * @param errors - 字段级别的验证错误列表
627
+ * @param requestId - 可选请求 ID
628
+ * @returns error code 为 `'VALIDATION_ERROR'`,details 包含 `errors` 数组
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * return kit.response.validationError([
633
+ * { field: 'email', message: '格式无效' },
634
+ * ])
635
+ * ```
636
+ */
637
+ declare function validationError(errors: Array<{
638
+ field: string;
639
+ message: string;
640
+ }>, requestId?: string): Response;
641
+ /**
642
+ * 创建 500 Internal Server Error 响应
643
+ *
644
+ * @param message - 错误消息,默认 `'Internal server error'`
645
+ * @param requestId - 可选请求 ID
646
+ * @returns error code 为 `'INTERNAL_ERROR'` 的 JSON Response
647
+ */
648
+ declare function internalError(message?: string, requestId?: string): Response;
649
+ /**
650
+ * 创建重定向响应
651
+ *
652
+ * @param url - 目标 URL
653
+ * @param status - HTTP 状态码,默认 302;常用 303(POST 后重定向)
654
+ * @returns 带 `Location` 头的空 body Response
655
+ *
656
+ * @example
657
+ * ```ts
658
+ * return kit.response.redirect('/dashboard', 303)
659
+ * ```
660
+ */
661
+ declare function redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
662
+ /**
663
+ * 将 HaiResult<T> 转换为标准 API Response
664
+ *
665
+ * 成功时返回 200 ok(data),失败时从 error 对象中提取 code、message,
666
+ * 并根据 httpStatusMap 映射 HTTP 状态码(未命中时默认 400)。
667
+ *
668
+ * @param result - core HaiResult 对象({ success, data } 或 { success: false, error })
669
+ * @param httpStatusMap - 模块导出的错误码 → HTTP 状态码映射表(如 IamErrorHttpStatus)
670
+ * @param requestId - 可选请求 ID,用于链路追踪
671
+ * @returns 标准化 JSON Response
672
+ *
673
+ * @example
674
+ * ```ts
675
+ * // 无映射(默认 400)
676
+ * return kit.response.fromResult(result)
677
+ *
678
+ * // 带模块错误码映射
679
+ * return kit.response.fromResult(result, IamErrorHttpStatus)
680
+ * ```
681
+ */
682
+ declare function fromResult<T>(result: {
683
+ success: true;
684
+ data: T;
685
+ } | {
686
+ success: false;
687
+ error: {
688
+ code: number | string;
689
+ message: string;
690
+ [key: string]: unknown;
691
+ };
692
+ }, httpStatusMap?: Record<number | string, number>, requestId?: string): Response;
693
+ declare function fromError(haiError: HaiError, requestId?: string): Response;
694
+
695
+ /**
696
+ * @h-ai/kit — 请求数据验证
697
+ *
698
+ * 基于 Zod 的请求数据验证工具,支持表单/JSON Body、URL 查询参数与路由参数。
699
+ * 每种数据源都提供两类 API:
700
+ * - 安全返回:`FormValidationResult`
701
+ * - 失败抛出:`OrFail`(抛出 `Response` 以走 SvelteKit 控制流)
702
+ * @module kit-validation
703
+ */
704
+
705
+ /**
706
+ * 从 Request 解析并验证表单数据,失败时 throw Response
707
+ *
708
+ * 与 `validateForm` 功能相同,但校验失败时 throw 400 Response(SvelteKit 控制流),
709
+ * 搭配 `kit.handler()` 使用可精简 handler 代码。
710
+ *
711
+ * @param request - SvelteKit 请求对象
712
+ * @param schema - Zod Schema
713
+ * @returns 校验通过的数据(类型安全)
714
+ * @throws Response - 400 BadRequest(含首条错误消息)
715
+ *
716
+ * @example
717
+ * ```ts
718
+ * export const POST = kit.handler(async ({ request }) => {
719
+ * const data = await kit.validate.body(request, CreateUserSchema)
720
+ * // data 类型安全,校验已通过
721
+ * })
722
+ * ```
723
+ */
724
+ declare function validateFormOrFail<T extends z.ZodType>(request: Request, schema: T): Promise<z.infer<T>>;
725
+ /**
726
+ * 从 URL 查询参数验证,失败时 throw Response
727
+ *
728
+ * @param url - 请求 URL 对象
729
+ * @param schema - Zod Schema
730
+ * @returns 校验通过的数据
731
+ * @throws Response - 400 BadRequest
732
+ *
733
+ * @example
734
+ * ```ts
735
+ * const query = kit.validate.query(event.url, PaginationSchema)
736
+ * ```
737
+ */
738
+ declare function validateQueryOrFail<T extends z.ZodType>(url: URL, schema: T): z.infer<T>;
739
+ /**
740
+ * 验证路径参数,失败时 throw Response
741
+ *
742
+ * @param params - SvelteKit 路由参数
743
+ * @param schema - Zod Schema
744
+ * @returns 校验通过的数据
745
+ * @throws Response - 400 BadRequest
746
+ *
747
+ * @example
748
+ * ```ts
749
+ * const { id } = kit.validate.params(event.params, IdParamSchema)
750
+ * ```
751
+ */
752
+ declare function validateParamsOrFail<T extends z.ZodType>(params: Record<string, string>, schema: T): z.infer<T>;
753
+ /**
754
+ * 路径参数 id 校验 Schema
755
+ *
756
+ * 验证 `event.params.id` 为非空字符串。
757
+ *
758
+ * @example
759
+ * ```ts
760
+ * const { id } = kit.validate.params(event.params, IdParamSchema)
761
+ * ```
762
+ */
763
+ declare const IdParamSchema: z.ZodObject<{
764
+ id: z.ZodString;
765
+ }, z.core.$strip>;
766
+ /**
767
+ * 通用分页查询参数 Schema
768
+ *
769
+ * 包含 page(默认 1)、pageSize(默认 20,上限 100)、search(可选)。
770
+ * 可通过 `.extend()` 扩展业务字段。
771
+ *
772
+ * @example
773
+ * ```ts
774
+ * // 直接使用
775
+ * const { page, pageSize, search } = kit.validate.query(url, PaginationQuerySchema)
776
+ *
777
+ * // 扩展业务字段
778
+ * const ListUsersSchema = PaginationQuerySchema.extend({
779
+ * enabled: z.enum(['true', 'false']).transform(v => v === 'true').optional(),
780
+ * })
781
+ * ```
782
+ */
783
+ declare const PaginationQuerySchema: z.ZodObject<{
784
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
785
+ pageSize: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
786
+ search: z.ZodOptional<z.ZodString>;
787
+ }, z.core.$strip>;
788
+
789
+ /**
790
+ * Kit 模块统一出口。
791
+ *
792
+ * 作为纯工具模块,kit 不需要 init/close 生命周期,
793
+ * 所有功能均为无状态工厂函数或工具函数。
794
+ */
795
+ declare const kit: {
796
+ /** 创建 SvelteKit Handle Hook(含 auth / logging / rateLimit 内置配置) */
797
+ createHandle: typeof createHandle;
798
+ /** 组合多个 Handle */
799
+ sequence: typeof sequence;
800
+ /** API Handler 包装器(自动错误边界) */
801
+ handler: typeof handler;
802
+ /** 基于 API 契约创建类型安全的路由 handler */
803
+ fromContract: typeof fromContract;
804
+ guard: {
805
+ /** 要求权限,不满足时 throw Response(SvelteKit 控制流) */
806
+ require: typeof requirePermission;
807
+ /** 检查会话是否具有指定权限(布尔) */
808
+ check: typeof hasPermission;
809
+ };
810
+ response: {
811
+ /** 200 成功 */
812
+ ok: typeof ok;
813
+ /** 201 创建成功 */
814
+ created: typeof created;
815
+ /** 204 无内容 */
816
+ noContent: typeof noContent;
817
+ /** 自定义错误响应 */
818
+ error: typeof error;
819
+ /** 400 BadRequest */
820
+ badRequest: typeof badRequest;
821
+ /** 401 Unauthorized */
822
+ unauthorized: typeof unauthorized;
823
+ /** 403 Forbidden */
824
+ forbidden: typeof forbidden;
825
+ /** 404 NotFound */
826
+ notFound: typeof notFound;
827
+ /** 409 Conflict */
828
+ conflict: typeof conflict;
829
+ /** 422 验证错误 */
830
+ validationError: typeof validationError;
831
+ /** 500 InternalError */
832
+ internalError: typeof internalError;
833
+ /** 重定向 */
834
+ redirect: typeof redirect;
835
+ /** 将 HaiResult<T> 转为标准 API Response(支持 httpStatusMap) */
836
+ fromResult: typeof fromResult;
837
+ /** 将模块错误码映射为标准 HTTP Response */
838
+ fromError: typeof fromError;
839
+ };
840
+ validate: {
841
+ /** 验证请求体(JSON/表单),失败 throw Response */
842
+ body: typeof validateFormOrFail;
843
+ /** 验证查询参数,失败 throw Response */
844
+ query: typeof validateQueryOrFail;
845
+ /** 验证路径参数,失败 throw Response */
846
+ params: typeof validateParamsOrFail;
847
+ /** 路径参数 id Schema({id: string}) */
848
+ IdParamSchema: zod.ZodObject<{
849
+ id: zod.ZodString;
850
+ }, zod_v4_core.$strip>;
851
+ /** 通用分页查询 Schema(page / pageSize / search) */
852
+ PaginationQuerySchema: zod.ZodObject<{
853
+ page: zod.ZodDefault<zod.ZodCoercedNumber<unknown>>;
854
+ pageSize: zod.ZodDefault<zod.ZodCoercedNumber<unknown>>;
855
+ search: zod.ZodOptional<zod.ZodString>;
856
+ }, zod_v4_core.$strip>;
857
+ };
858
+ client: {
859
+ /** 创建统一客户端(CSRF + 传输加密透明合并) */
860
+ create: typeof createKitClient;
861
+ };
862
+ auth: {
863
+ /** 服务端登录(密码):内部调用 iam.auth.login + 自动写入 Token Cookie */
864
+ login: typeof login;
865
+ /** 服务端登录(OTP 验证码):内部调用 iam.auth.loginWithOtp + 自动写入 Token Cookie */
866
+ loginWithOtp: typeof loginWithOtp;
867
+ /** 服务端登录(LDAP):内部调用 iam.auth.loginWithLdap + 自动写入 Token Cookie */
868
+ loginWithLdap: typeof loginWithLdap;
869
+ /** 服务端登录(API Key):内部调用 iam.auth.loginWithApiKey + 自动写入 Token Cookie */
870
+ loginWithApiKey: typeof loginWithApiKey;
871
+ /** 服务端注册并登录:内部调用 iam.auth.registerAndLogin + 自动写入 Token Cookie */
872
+ registerAndLogin: typeof registerAndLogin;
873
+ /** 服务端登出:内部调用 iam.auth.logout + 清除 Token Cookie */
874
+ logout: typeof logout;
875
+ /** 写入浏览器端 Access Token(客户端 login/register 用) */
876
+ setBrowserToken: typeof setBrowserToken;
877
+ /** 清除浏览器端 Access Token(客户端 logout 用) */
878
+ clearBrowserToken: typeof clearBrowserToken;
879
+ /** 创建浏览器端 Token 存储器(自定义 key 时使用) */
880
+ createTokenStore: typeof createTokenStore;
881
+ /** 创建浏览器端同源请求自动附加 Authorization 的 HandleFetch */
882
+ createHandleFetch: typeof createHandleFetch;
883
+ };
884
+ crud: {
885
+ /** 定义 CRUD 资源(声明式配置 → 操作对象) */
886
+ define: typeof defineCrud;
887
+ };
888
+ i18n: {
889
+ /** 统一设置所有 hai 模块的默认语言 */
890
+ setLocale: typeof setAllModulesLocale;
891
+ };
892
+ };
893
+
894
+ /**
895
+ * @h-ai/kit — CORS 中间件
896
+ *
897
+ * 配置跨域资源共享(CORS)策略,自动处理 OPTIONS 预检请求与响应头注入。
898
+ * 支持精确 origin、数组白名单、通配符模式与函数匹配四种模式。
899
+ * 自动预置 Capacitor WebView origin(Android/iOS)。
900
+ * @module kit-cors
901
+ */
902
+
903
+ /**
904
+ * 创建 CORS 中间件
905
+ *
906
+ * 处理跨域资源共享:
907
+ * - OPTIONS 预检请求返回 204 + CORS 头
908
+ * - 其他请求在业务响应上附加 CORS 头
909
+ * - 默认预置 Capacitor WebView origin
910
+ *
911
+ * @param config - CORS 配置(省略则允许所有 origin)
912
+ * @returns Middleware 实例
913
+ *
914
+ * @example
915
+ * ```ts
916
+ * middleware: [
917
+ * kit.middleware.cors({ origin: ['https://example.com'], credentials: true }),
918
+ * ]
919
+ * ```
920
+ */
921
+ declare function corsMiddleware(config?: CorsConfig): Middleware;
922
+
923
+ /**
924
+ * @h-ai/kit — 日志中间件
925
+ *
926
+ * HTTP 请求日志中间件,记录请求/响应摘要(方法、路径、状态码、耗时),
927
+ * 并自动脱敏敏感字段(password / token / secret 等)。
928
+ * @module kit-logging
929
+ */
930
+
931
+ /**
932
+ * 日志中间件配置
933
+ */
934
+ interface LoggingMiddlewareConfig {
935
+ /** 为 `true` 时记录非 GET 请求体(自动脱敏) */
936
+ logBody?: boolean;
937
+ /** 为 `true` 时记录响应头 */
938
+ logResponse?: boolean;
939
+ /** 指定需要脱敏的字段名(默认 `['password', 'token', 'secret']`) */
940
+ redactFields?: string[];
941
+ }
942
+ /**
943
+ * 创建日志中间件
944
+ *
945
+ * 以 `core.logger.trace` 级别记录请求进出信息,包含:
946
+ * - 请求:method / path / query / userAgent / ip
947
+ * - 响应:status / duration
948
+ *
949
+ * 敏感字段会被自动替换为 `[REDACTED]`。
950
+ *
951
+ * @param config - 日志配置
952
+ * @returns Middleware 实例
953
+ *
954
+ * @example
955
+ * ```ts
956
+ * middleware: [
957
+ * kit.middleware.logging({ logBody: true, redactFields: ['password', 'creditCard'] }),
958
+ * ]
959
+ * ```
960
+ */
961
+ declare function loggingMiddleware(config?: LoggingMiddlewareConfig): Middleware;
962
+
963
+ export { type AuthGuardConfig, type CookieProxyConfig, CorsConfig, type EndpointDef, HandleConfig, IdParamSchema, type LoggingMiddlewareConfig, Middleware, PaginationQuerySchema, type PermissionGuardConfig, type RoleGuardConfig, RouteGuard, SessionData, type SessionGuardConfig, SessionLike, TransportCryptoServiceLike, allGuards, anyGuard, assertPermission, authGuard, conditionalGuard, corsMiddleware, createEncryptedCookieProxy, createHandle, createKitClient, defineCrud, defineEndpoint, hasPermission, kit, loggingMiddleware, matchPermission, notGuard, permissionGuard, requirePermission, roleGuard, sequence, sessionGuard, withPermission };