@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.
- package/LICENSE +202 -0
- package/README.md +121 -0
- package/dist/adapter/index.d.ts +44 -0
- package/dist/adapter/index.js +28 -0
- package/dist/adapter/index.js.map +1 -0
- package/dist/browser.d.ts +38 -0
- package/dist/browser.js +26 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-475WECWK.js +110 -0
- package/dist/chunk-475WECWK.js.map +1 -0
- package/dist/chunk-6TMSXG7J.js +169 -0
- package/dist/chunk-6TMSXG7J.js.map +1 -0
- package/dist/chunk-AD6S473Y.js +137 -0
- package/dist/chunk-AD6S473Y.js.map +1 -0
- package/dist/chunk-FRYJMRTP.js +71 -0
- package/dist/chunk-FRYJMRTP.js.map +1 -0
- package/dist/chunk-PHS7ZD5L.js +274 -0
- package/dist/chunk-PHS7ZD5L.js.map +1 -0
- package/dist/client/index.d.ts +5 -0
- package/dist/client/index.js +4 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index-BotXLTck.d.ts +203 -0
- package/dist/index.d.ts +963 -0
- package/dist/index.js +886 -0
- package/dist/index.js.map +1 -0
- package/dist/kit-crypto-types-C-gEvx04.d.ts +253 -0
- package/dist/kit-i18n-CgpNTh9G.d.ts +206 -0
- package/dist/kit-types-BHlDNNpd.d.ts +618 -0
- package/dist/modules/a2a/index.d.ts +150 -0
- package/dist/modules/a2a/index.js +57 -0
- package/dist/modules/a2a/index.js.map +1 -0
- package/dist/modules/crypto/index.d.ts +180 -0
- package/dist/modules/crypto/index.js +151 -0
- package/dist/modules/crypto/index.js.map +1 -0
- package/package.json +81 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [2026] [idealworld.group]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# @h-ai/kit
|
|
2
|
+
|
|
3
|
+
`@h-ai/kit` 是 hai-framework 的 SvelteKit 集成模块,提供统一的请求管道与 API 工具:
|
|
4
|
+
|
|
5
|
+
- `kit.createHandle()`:会话解析、路由守卫、中间件链、可选传输加密与 Cookie 加密
|
|
6
|
+
- `kit.handler()`:API 端点异常边界
|
|
7
|
+
- `kit.guard` / `kit.response` / `kit.validate` / `kit.auth` / `kit.client` / `kit.crud`
|
|
8
|
+
|
|
9
|
+
## 支持的能力
|
|
10
|
+
|
|
11
|
+
- Handle Hook 组合(`createHandle` / `sequence`)
|
|
12
|
+
- 认证/角色/权限守卫(`guard.require` / `guard.check`)
|
|
13
|
+
- 内置 Logging / RateLimit / CORS 中间件(通过 `createHandle` 配置启用)
|
|
14
|
+
- 统一 API 响应与请求验证(Zod)
|
|
15
|
+
- Bearer Token 工具(服务端 login/logout + 浏览器端 Token 存储)
|
|
16
|
+
- 浏览器端统一客户端(自动 CSRF,支持传输加密)
|
|
17
|
+
- 基于 EndpointDef 的契约模式(`fromContract`)
|
|
18
|
+
- 声明式 CRUD 资源定义(`crud.define`)
|
|
19
|
+
- A2A 协议集成
|
|
20
|
+
- 双构建模式(`createAdapter()`)
|
|
21
|
+
|
|
22
|
+
## 依赖
|
|
23
|
+
|
|
24
|
+
- `@h-ai/iam` — 身份认证与授权(A2A 认证),可选;使用 A2A 功能时需在 kit 使用前初始化
|
|
25
|
+
- `@h-ai/crypto` — 加密(传输加密 / Cookie 加密),可选;启用加密时需在 kit 使用前初始化
|
|
26
|
+
|
|
27
|
+
## 快速开始
|
|
28
|
+
|
|
29
|
+
### 搭建请求管道
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { kit } from '@h-ai/kit'
|
|
33
|
+
|
|
34
|
+
export const handle = kit.createHandle({
|
|
35
|
+
auth: {
|
|
36
|
+
verifyToken: async (token) => {
|
|
37
|
+
// 返回 SessionData 或 null
|
|
38
|
+
return token ? { userId: 'u_1', roles: ['admin'], permissions: ['user:read'] } : null
|
|
39
|
+
},
|
|
40
|
+
loginUrl: '/auth/login',
|
|
41
|
+
protectedPaths: ['/admin/*', '/api/*'],
|
|
42
|
+
publicPaths: ['/api/auth/*', '/api/public/*'],
|
|
43
|
+
},
|
|
44
|
+
rateLimit: { windowMs: 60_000, maxRequests: 100 },
|
|
45
|
+
logging: true,
|
|
46
|
+
})
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### API 端点
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { kit } from '@h-ai/kit'
|
|
53
|
+
import { z } from 'zod'
|
|
54
|
+
|
|
55
|
+
const CreateUserSchema = z.object({
|
|
56
|
+
name: z.string().min(1),
|
|
57
|
+
email: z.string().email(),
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
export const POST = kit.handler(async ({ request, locals }) => {
|
|
61
|
+
kit.guard.require(locals.session, 'user:create')
|
|
62
|
+
const payload = await kit.validate.body(request, CreateUserSchema)
|
|
63
|
+
return kit.response.created(payload)
|
|
64
|
+
})
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 契约模式(推荐)
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
import { iamEndpoints } from '@h-ai/iam/api'
|
|
71
|
+
import { kit } from '@h-ai/kit'
|
|
72
|
+
|
|
73
|
+
export const POST = kit.fromContract(iamEndpoints.login, async (input) => {
|
|
74
|
+
const result = await iam.auth.login(input)
|
|
75
|
+
if (!result.success)
|
|
76
|
+
return kit.response.unauthorized(result.error.message)
|
|
77
|
+
return kit.response.ok(result.data)
|
|
78
|
+
})
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 浏览器客户端(可选)
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
import { createKitClient } from '@h-ai/kit/client'
|
|
85
|
+
|
|
86
|
+
const client = createKitClient()
|
|
87
|
+
const response = await client.apiFetch('/api/users', { method: 'GET' })
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
> CSRF Header 注入由 `createKitClient()` 在浏览器端自动处理;`@h-ai/kit` 不提供独立的 CSRF 中间件工厂。
|
|
91
|
+
|
|
92
|
+
## 配置
|
|
93
|
+
|
|
94
|
+
`kit.createHandle()` 配置项:
|
|
95
|
+
|
|
96
|
+
| 字段 | 类型 | 说明 |
|
|
97
|
+
| ------------ | ---------------------------------------- | ----------------------------------------------------------------- |
|
|
98
|
+
| `auth` | `HandleAuthConfig` | 认证配置(verifyToken / protectedPaths / publicPaths / loginUrl) |
|
|
99
|
+
| `rateLimit` | `object \| false` | 速率限制(windowMs / maxRequests) |
|
|
100
|
+
| `logging` | `boolean \| object` | 请求日志(默认 `true`,`{ logBody: true }` 记录请求体) |
|
|
101
|
+
| `crypto` | `HookCryptoConfig` | 传输加密 + Cookie 加密 |
|
|
102
|
+
| `guards` | `GuardConfig[]` | 自定义守卫(在 auth 自动守卫之后执行) |
|
|
103
|
+
| `middleware` | `Middleware[]` | 自定义中间件(在内置中间件之后执行) |
|
|
104
|
+
| `a2a` | `HandleA2AOperations \| HandleA2AConfig` | A2A 协议集成(Agent Card + JSON-RPC) |
|
|
105
|
+
| `onError` | `function` | 自定义错误处理 |
|
|
106
|
+
|
|
107
|
+
## 错误处理
|
|
108
|
+
|
|
109
|
+
- 推荐使用 `kit.handler()` 包装 API 端点。
|
|
110
|
+
- `kit.validate.body` / `kit.guard.require` 会抛出 `Response`(SvelteKit 控制流)。
|
|
111
|
+
- 非控制流异常会由 `kit.handler()` 统一转换为 `500 INTERNAL_ERROR` 响应。
|
|
112
|
+
|
|
113
|
+
## 测试
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pnpm --filter @h-ai/kit test
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## License
|
|
120
|
+
|
|
121
|
+
Apache-2.0
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as _sveltejs_kit from '@sveltejs/kit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* SvelteKit 双构建模式 — 适配器工厂
|
|
5
|
+
*
|
|
6
|
+
* 根据 `VITE_ADAPTER` 环境变量自动选择 adapter-node 或 adapter-static,
|
|
7
|
+
* 使同一个 SvelteKit 应用能同时产出 SSR(Web + API)和 SPA(H5/App)两种构建产物。
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```js
|
|
11
|
+
* // svelte.config.js
|
|
12
|
+
* import { createAdapter } from '@h-ai/kit/adapter'
|
|
13
|
+
*
|
|
14
|
+
* export default {
|
|
15
|
+
* kit: {
|
|
16
|
+
* adapter: createAdapter(),
|
|
17
|
+
* },
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @module kit-adapter
|
|
22
|
+
*/
|
|
23
|
+
/** 双构建适配器配置 */
|
|
24
|
+
interface AdapterOptions {
|
|
25
|
+
/** adapter-node 输出目录,默认 `'build'` */
|
|
26
|
+
nodeBuildDir?: string;
|
|
27
|
+
/** adapter-static 输出目录,默认 `'build-static'` */
|
|
28
|
+
staticBuildDir?: string;
|
|
29
|
+
/** adapter-static 的 SPA fallback 页面,默认 `'index.html'` */
|
|
30
|
+
staticFallback?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 根据环境变量 `VITE_ADAPTER` 选择 SvelteKit adapter
|
|
34
|
+
*
|
|
35
|
+
* - `VITE_ADAPTER=node` → `@sveltejs/adapter-node`(SSR + API)
|
|
36
|
+
* - `VITE_ADAPTER=static` → `@sveltejs/adapter-static`(SPA,可被 Capacitor 包装)
|
|
37
|
+
* - 未设置时默认使用 `node`
|
|
38
|
+
*
|
|
39
|
+
* **注意**:adapter-node / adapter-static 仍然需要在应用的 devDependencies 中声明。
|
|
40
|
+
* 本函数只做动态 import + 统一配置。
|
|
41
|
+
*/
|
|
42
|
+
declare function createAdapter(options?: AdapterOptions): Promise<_sveltejs_kit.Adapter>;
|
|
43
|
+
|
|
44
|
+
export { type AdapterOptions, createAdapter };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import process from 'process';
|
|
2
|
+
|
|
3
|
+
// src/kit-adapter.ts
|
|
4
|
+
async function createAdapter(options) {
|
|
5
|
+
const {
|
|
6
|
+
nodeBuildDir = "build",
|
|
7
|
+
staticBuildDir = "build-static",
|
|
8
|
+
staticFallback = "index.html"
|
|
9
|
+
} = options ?? {};
|
|
10
|
+
const mode = process.env.VITE_ADAPTER ?? "node";
|
|
11
|
+
if (mode === "static") {
|
|
12
|
+
const { default: adapterStatic } = await import('@sveltejs/adapter-static');
|
|
13
|
+
return adapterStatic({
|
|
14
|
+
pages: staticBuildDir,
|
|
15
|
+
assets: staticBuildDir,
|
|
16
|
+
fallback: staticFallback,
|
|
17
|
+
precompress: false
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
const { default: adapterNode } = await import('@sveltejs/adapter-node');
|
|
21
|
+
return adapterNode({
|
|
22
|
+
out: nodeBuildDir
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { createAdapter };
|
|
27
|
+
//# sourceMappingURL=index.js.map
|
|
28
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/kit-adapter.ts"],"names":[],"mappings":";;;AA2CA,eAAsB,cAAc,OAAA,EAA0B;AAC5D,EAAA,MAAM;AAAA,IACJ,YAAA,GAAe,OAAA;AAAA,IACf,cAAA,GAAiB,cAAA;AAAA,IACjB,cAAA,GAAiB;AAAA,GACnB,GAAI,WAAW,EAAC;AAEhB,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,YAAA,IAAgB,MAAA;AAEzC,EAAA,IAAI,SAAS,QAAA,EAAU;AACrB,IAAA,MAAM,EAAE,OAAA,EAAS,aAAA,EAAc,GAAI,MAAM,OAAO,0BAA0B,CAAA;AAC1E,IAAA,OAAO,aAAA,CAAc;AAAA,MACnB,KAAA,EAAO,cAAA;AAAA,MACP,MAAA,EAAQ,cAAA;AAAA,MACR,QAAA,EAAU,cAAA;AAAA,MACV,WAAA,EAAa;AAAA,KACd,CAAA;AAAA,EACH;AAGA,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAY,GAAI,MAAM,OAAO,wBAAwB,CAAA;AACtE,EAAA,OAAO,WAAA,CAAY;AAAA,IACjB,GAAA,EAAK;AAAA,GACN,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * SvelteKit 双构建模式 — 适配器工厂\n *\n * 根据 `VITE_ADAPTER` 环境变量自动选择 adapter-node 或 adapter-static,\n * 使同一个 SvelteKit 应用能同时产出 SSR(Web + API)和 SPA(H5/App)两种构建产物。\n *\n * @example\n * ```js\n * // svelte.config.js\n * import { createAdapter } from '@h-ai/kit/adapter'\n *\n * export default {\n * kit: {\n * adapter: createAdapter(),\n * },\n * }\n * ```\n *\n * @module kit-adapter\n */\n\nimport process from 'node:process'\n\n/** 双构建适配器配置 */\nexport interface AdapterOptions {\n /** adapter-node 输出目录,默认 `'build'` */\n nodeBuildDir?: string\n /** adapter-static 输出目录,默认 `'build-static'` */\n staticBuildDir?: string\n /** adapter-static 的 SPA fallback 页面,默认 `'index.html'` */\n staticFallback?: string\n}\n\n/**\n * 根据环境变量 `VITE_ADAPTER` 选择 SvelteKit adapter\n *\n * - `VITE_ADAPTER=node` → `@sveltejs/adapter-node`(SSR + API)\n * - `VITE_ADAPTER=static` → `@sveltejs/adapter-static`(SPA,可被 Capacitor 包装)\n * - 未设置时默认使用 `node`\n *\n * **注意**:adapter-node / adapter-static 仍然需要在应用的 devDependencies 中声明。\n * 本函数只做动态 import + 统一配置。\n */\nexport async function createAdapter(options?: AdapterOptions) {\n const {\n nodeBuildDir = 'build',\n staticBuildDir = 'build-static',\n staticFallback = 'index.html',\n } = options ?? {}\n\n const mode = process.env.VITE_ADAPTER ?? 'node'\n\n if (mode === 'static') {\n const { default: adapterStatic } = await import('@sveltejs/adapter-static')\n return adapterStatic({\n pages: staticBuildDir,\n assets: staticBuildDir,\n fallback: staticFallback,\n precompress: false,\n })\n }\n\n // 默认 node\n const { default: adapterNode } = await import('@sveltejs/adapter-node')\n return adapterNode({\n out: nodeBuildDir,\n })\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { c as createKitClient, 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 { 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, h as HandleConfig, i as HookCryptoConfig, M as Middleware, j as MiddlewareContext, R as RateLimitConfig, k as RouteGuard, S as SessionData, l as SessionLike, T as TransportEncryptionOptions } from './kit-types-BHlDNNpd.js';
|
|
5
|
+
import '@h-ai/core';
|
|
6
|
+
import '@h-ai/iam';
|
|
7
|
+
import '@sveltejs/kit';
|
|
8
|
+
import './kit-crypto-types-C-gEvx04.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @h-ai/kit — 浏览器入口
|
|
12
|
+
*
|
|
13
|
+
* 为客户端提供精简且安全的运行时导出,避免将服务端 Hook/A2A/IAM 运行时代码打入浏览器包。
|
|
14
|
+
* @module browser
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 浏览器端 kit 对象(仅暴露 client-safe 能力)
|
|
19
|
+
*/
|
|
20
|
+
declare const kit: {
|
|
21
|
+
client: {
|
|
22
|
+
create: typeof createKitClient;
|
|
23
|
+
};
|
|
24
|
+
crud: {
|
|
25
|
+
define: typeof defineCrud;
|
|
26
|
+
};
|
|
27
|
+
auth: {
|
|
28
|
+
setBrowserToken: typeof setBrowserToken;
|
|
29
|
+
clearBrowserToken: typeof clearBrowserToken;
|
|
30
|
+
createTokenStore: typeof createTokenStore;
|
|
31
|
+
createHandleFetch: typeof createHandleFetch;
|
|
32
|
+
};
|
|
33
|
+
i18n: {
|
|
34
|
+
setLocale: typeof setAllModulesLocale;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export { createKitClient, kit };
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { defineCrud } from './chunk-FRYJMRTP.js';
|
|
2
|
+
import { createHandleFetch, createTokenStore, clearBrowserToken, setBrowserToken, createKitClient } from './chunk-PHS7ZD5L.js';
|
|
3
|
+
import { setAllModulesLocale } from './chunk-6TMSXG7J.js';
|
|
4
|
+
|
|
5
|
+
// src/browser.ts
|
|
6
|
+
var kit = {
|
|
7
|
+
client: {
|
|
8
|
+
create: createKitClient
|
|
9
|
+
},
|
|
10
|
+
crud: {
|
|
11
|
+
define: defineCrud
|
|
12
|
+
},
|
|
13
|
+
auth: {
|
|
14
|
+
setBrowserToken,
|
|
15
|
+
clearBrowserToken,
|
|
16
|
+
createTokenStore,
|
|
17
|
+
createHandleFetch
|
|
18
|
+
},
|
|
19
|
+
i18n: {
|
|
20
|
+
setLocale: setAllModulesLocale
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export { kit };
|
|
25
|
+
//# sourceMappingURL=browser.js.map
|
|
26
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/browser.ts"],"names":[],"mappings":";;;;;AAeO,IAAM,GAAA,GAAM;AAAA,EACjB,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,gBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,IAAA,EAAM;AAAA,IACJ,SAAA,EAAW;AAAA;AAEf","file":"browser.js","sourcesContent":["/**\n * @h-ai/kit — 浏览器入口\n *\n * 为客户端提供精简且安全的运行时导出,避免将服务端 Hook/A2A/IAM 运行时代码打入浏览器包。\n * @module browser\n */\n\nimport { createKitClient } from './client/kit-client.js'\nimport { defineCrud } from './crud/kit-crud.js'\nimport { clearBrowserToken, createHandleFetch, createTokenStore, setBrowserToken } from './kit-auth.js'\nimport { setAllModulesLocale } from './kit-i18n.js'\n\n/**\n * 浏览器端 kit 对象(仅暴露 client-safe 能力)\n */\nexport const kit = {\n client: {\n create: createKitClient,\n },\n crud: {\n define: defineCrud,\n },\n auth: {\n setBrowserToken,\n clearBrowserToken,\n createTokenStore,\n createHandleFetch,\n },\n i18n: {\n setLocale: setAllModulesLocale,\n },\n}\n\nexport type * from './client/index.js'\nexport type * from './kit-types.js'\n"]}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { iam } from '@h-ai/iam';
|
|
2
|
+
|
|
3
|
+
// src/modules/a2a/kit-a2a-auth.ts
|
|
4
|
+
function createA2AApiKeyAuthenticator(config) {
|
|
5
|
+
return async (event) => {
|
|
6
|
+
const rawKey = config.in === "header" ? event.request.headers.get(config.name) : event.url.searchParams.get(config.name);
|
|
7
|
+
if (!rawKey)
|
|
8
|
+
return null;
|
|
9
|
+
const result = await iam.apiKey.verifyApiKey(rawKey);
|
|
10
|
+
if (!result.success)
|
|
11
|
+
return null;
|
|
12
|
+
return {
|
|
13
|
+
agentId: result.data.userId,
|
|
14
|
+
apiKeyId: result.data.id,
|
|
15
|
+
scopes: result.data.scopes
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/modules/a2a/kit-a2a-handle.ts
|
|
21
|
+
function resolveA2AConfig(input) {
|
|
22
|
+
if (!input)
|
|
23
|
+
return null;
|
|
24
|
+
if ("getAgentCard" in input && "handleRequest" in input) {
|
|
25
|
+
return {
|
|
26
|
+
operations: input,
|
|
27
|
+
cardPath: "/.well-known/agent.json",
|
|
28
|
+
rpcPath: "/a2a"
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const cfg = input;
|
|
32
|
+
return {
|
|
33
|
+
operations: cfg.operations,
|
|
34
|
+
cardPath: cfg.cardPath ?? "/.well-known/agent.json",
|
|
35
|
+
rpcPath: cfg.rpcPath ?? "/a2a",
|
|
36
|
+
authenticate: resolveAuthenticate(cfg.authenticate, cfg.operations)
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function resolveAuthenticate(authenticate, operations) {
|
|
40
|
+
if (!authenticate)
|
|
41
|
+
return void 0;
|
|
42
|
+
if (typeof authenticate === "function")
|
|
43
|
+
return authenticate;
|
|
44
|
+
const cardResult = operations.getAgentCard();
|
|
45
|
+
const security = cardResult.success && cardResult.data ? cardResult.data.security : void 0;
|
|
46
|
+
const apiKeyCfg = security?.apiKey;
|
|
47
|
+
return createA2AApiKeyAuthenticator({
|
|
48
|
+
in: apiKeyCfg?.in ?? "header",
|
|
49
|
+
name: apiKeyCfg?.name ?? "x-api-key"
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
async function handleA2ARequest(event, requestId, config) {
|
|
53
|
+
const { pathname } = event.url;
|
|
54
|
+
if (pathname === config.cardPath && event.request.method === "GET") {
|
|
55
|
+
const result = config.operations.getAgentCard();
|
|
56
|
+
if (result.success) {
|
|
57
|
+
return new Response(JSON.stringify(result.data), {
|
|
58
|
+
headers: { "Content-Type": "application/json", "X-Request-Id": requestId }
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return new Response(
|
|
62
|
+
JSON.stringify({ error: { code: "A2A_NOT_CONFIGURED", message: "Agent card not available" } }),
|
|
63
|
+
{ status: 503, headers: { "Content-Type": "application/json", "X-Request-Id": requestId } }
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (pathname === config.rpcPath && event.request.method === "POST") {
|
|
67
|
+
let context;
|
|
68
|
+
if (config.authenticate) {
|
|
69
|
+
const authResult = await config.authenticate(event);
|
|
70
|
+
if (authResult) {
|
|
71
|
+
context = authResult;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const body = await event.request.json();
|
|
75
|
+
const result = await config.operations.handleRequest(body, context);
|
|
76
|
+
if (result.streaming && result.stream) {
|
|
77
|
+
const stream = result.stream;
|
|
78
|
+
const readable = new ReadableStream({
|
|
79
|
+
async start(controller) {
|
|
80
|
+
const encoder = new TextEncoder();
|
|
81
|
+
try {
|
|
82
|
+
for await (const chunk of stream) {
|
|
83
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}
|
|
84
|
+
|
|
85
|
+
`));
|
|
86
|
+
}
|
|
87
|
+
} finally {
|
|
88
|
+
controller.close();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
return new Response(readable, {
|
|
93
|
+
headers: {
|
|
94
|
+
"Content-Type": "text/event-stream",
|
|
95
|
+
"Cache-Control": "no-cache",
|
|
96
|
+
"Connection": "keep-alive",
|
|
97
|
+
"X-Request-Id": requestId
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return new Response(JSON.stringify(result.body), {
|
|
102
|
+
headers: { "Content-Type": "application/json", "X-Request-Id": requestId }
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export { createA2AApiKeyAuthenticator, handleA2ARequest, resolveA2AConfig };
|
|
109
|
+
//# sourceMappingURL=chunk-475WECWK.js.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SAAS,QAAA,EAAU;AAAA,QAC5B,OAAA,EAAS;AAAA,UACP,cAAA,EAAgB,mBAAA;AAAA,UAChB,eAAA,EAAiB,UAAA;AAAA,UACjB,YAAA,EAAc,YAAA;AAAA,UACd,cAAA,EAAgB;AAAA;AAClB,OACD,CAAA;AAAA,IACH;AAEA,IAAA,OAAO,IAAI,QAAA,CAAS,IAAA,CAAK,SAAA,CAAU,MAAA,CAAO,IAAI,CAAA,EAAG;AAAA,MAC/C,OAAA,EAAS,EAAE,cAAA,EAAgB,kBAAA,EAAoB,gBAAgB,SAAA;AAAU,KAC1E,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,IAAA;AACT","file":"chunk-475WECWK.js","sourcesContent":["/**\n * @h-ai/kit — A2A API Key 认证器\n *\n * 从请求头或 query 参数中提取 API Key,调用 IAM apiKey.verifyApiKey 验证。\n * @module kit-a2a-auth\n */\n\nimport type { RequestEvent } from '@sveltejs/kit'\nimport { iam } from '@h-ai/iam'\n\n/** A2A API Key 认证器配置 */\nexport interface A2AApiKeyAuthConfig {\n /** API Key 的传递位置 */\n in: 'header' | 'query'\n /** 参数名 */\n name: string\n}\n\n/**\n * 创建 A2A API Key 认证函数\n *\n * 根据配置从请求头或 query 参数中提取 API Key,\n * 通过 `iam.apiKey.verifyApiKey()` 验证后返回调用方上下文。\n *\n * - 无 API Key → 返回 `null`(匿名请求)\n * - 验证失败 → 返回 `null`(拒绝)\n * - 验证成功 → 返回 `{ agentId, apiKeyId, scopes }`\n *\n * @param config - API Key 提取配置\n * @returns authenticate 函数,可直接赋给 HandleA2AConfig.authenticate\n */\nexport function createA2AApiKeyAuthenticator(\n config: A2AApiKeyAuthConfig,\n): (event: RequestEvent) => Promise<Record<string, unknown> | null> {\n return async (event: RequestEvent) => {\n const rawKey = config.in === 'header'\n ? event.request.headers.get(config.name)\n : event.url.searchParams.get(config.name)\n\n if (!rawKey)\n return null\n\n const result = await iam.apiKey.verifyApiKey(rawKey)\n if (!result.success)\n return null\n\n return {\n agentId: result.data.userId,\n apiKeyId: result.data.id,\n scopes: result.data.scopes,\n }\n }\n}\n","/**\n * @h-ai/kit — A2A Handle 拦截器\n *\n * 在 SvelteKit Handle Hook 中拦截 A2A 端点(Agent Card 发现 + JSON-RPC 处理),\n * 自动处理请求并返回 Response,不匹配时返回 null 由 Handle 继续后续流程。\n * @module kit-a2a-handle\n */\n\nimport type { RequestEvent } from '@sveltejs/kit'\nimport type { HandleA2AConfig, HandleA2AOperations, HandleConfig } from '../../kit-types.js'\nimport { createA2AApiKeyAuthenticator } from './kit-a2a-auth.js'\n\n// ─── 解析后的 A2A 内部配置 ───\n\n/** A2A 解析后的内部配置 */\nexport interface ResolvedA2AConfig {\n operations: HandleA2AOperations\n cardPath: string\n rpcPath: string\n authenticate?: (event: RequestEvent) => Promise<Record<string, unknown> | null | undefined>\n}\n\n// ─── A2A 配置解析 ───\n\n/**\n * 解析 A2A 配置(简单模式 / 配置模式)\n *\n * - 简单模式:直接传入 `ai.a2a` 操作对象,使用默认路径\n * - 配置模式:传入 `{ operations, rpcPath?, cardPath?, authenticate? }`\n *\n * @param input - HandleConfig.a2a 配置\n * @returns 解析后的配置,或 `null` 表示未配置\n */\nexport function resolveA2AConfig(\n input: HandleConfig['a2a'],\n): ResolvedA2AConfig | null {\n if (!input)\n return null\n\n // 简单模式:直接传入操作对象\n if ('getAgentCard' in input && 'handleRequest' in input) {\n return {\n operations: input as HandleA2AOperations,\n cardPath: '/.well-known/agent.json',\n rpcPath: '/a2a',\n }\n }\n\n // 配置模式:带 operations 字段\n const cfg = input as HandleA2AConfig\n return {\n operations: cfg.operations,\n cardPath: cfg.cardPath ?? '/.well-known/agent.json',\n rpcPath: cfg.rpcPath ?? '/a2a',\n authenticate: resolveAuthenticate(cfg.authenticate, cfg.operations),\n }\n}\n\n/**\n * 解析 authenticate 配置\n *\n * - `undefined` → 无认证\n * - `'apiKey'` → 从 Agent Card security 配置创建 API Key 认证器\n * - 函数 → 直接使用\n */\nfunction resolveAuthenticate(\n authenticate: HandleA2AConfig['authenticate'],\n operations: HandleA2AOperations,\n): ResolvedA2AConfig['authenticate'] {\n if (!authenticate)\n return undefined\n\n if (typeof authenticate === 'function')\n return authenticate\n\n // 'apiKey' 快捷方式:从 Agent Card 获取 security 配置\n const cardResult = operations.getAgentCard()\n const security = cardResult.success && cardResult.data\n ? (cardResult.data as Record<string, unknown>).security as { apiKey?: { in: 'header' | 'query', name: string } } | undefined\n : undefined\n const apiKeyCfg = security?.apiKey\n\n return createA2AApiKeyAuthenticator({\n in: apiKeyCfg?.in ?? 'header',\n name: apiKeyCfg?.name ?? 'x-api-key',\n })\n}\n\n// ─── A2A 请求处理 ───\n\n/**\n * 处理 A2A 端点请求\n *\n * 匹配 Agent Card GET 和 JSON-RPC POST 端点,返回 Response。\n * 不匹配时返回 `null`,由 Handle 继续后续流程。\n *\n * @param event - SvelteKit RequestEvent\n * @param requestId - 当前请求 ID(用于响应头)\n * @param config - 解析后的 A2A 配置\n * @returns 匹配时返回 Response,不匹配返回 null\n */\nexport async function handleA2ARequest(\n event: RequestEvent,\n requestId: string,\n config: ResolvedA2AConfig,\n): Promise<Response | null> {\n const { pathname } = event.url\n\n // Agent Card 发现端点\n if (pathname === config.cardPath && event.request.method === 'GET') {\n const result = config.operations.getAgentCard()\n if (result.success) {\n return new Response(JSON.stringify(result.data), {\n headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId },\n })\n }\n return new Response(\n JSON.stringify({ error: { code: 'A2A_NOT_CONFIGURED', message: 'Agent card not available' } }),\n { status: 503, headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId } },\n )\n }\n\n // A2A JSON-RPC 端点\n if (pathname === config.rpcPath && event.request.method === 'POST') {\n // 可选认证\n let context: Record<string, unknown> | undefined\n if (config.authenticate) {\n const authResult = await config.authenticate(event)\n if (authResult) {\n context = authResult\n }\n }\n\n const body = await event.request.json()\n const result = await config.operations.handleRequest(body, context)\n\n if (result.streaming && result.stream) {\n const stream = result.stream\n const readable = new ReadableStream({\n async start(controller) {\n const encoder = new TextEncoder()\n try {\n for await (const chunk of stream) {\n controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\\n\\n`))\n }\n }\n finally {\n controller.close()\n }\n },\n })\n return new Response(readable, {\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'X-Request-Id': requestId,\n },\n })\n }\n\n return new Response(JSON.stringify(result.body), {\n headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId },\n })\n }\n\n return null\n}\n"]}
|