@longzai-intelligence-server/openapi 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # @longzai-intelligence-server/openapi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Longzai Intelligence 契约执行引擎的文档派生包。从 `RouteDefinition` 契约派生 OpenAPI 3.1 文档。运行时无关,不依赖内核,可在 Bun 与 Node 的工具链进程里使用。
4
+
5
+ ## 定位
6
+
7
+ 契约是唯一真源,文档是契约的投影。本包只做一件事,就是把路由字典变成一份可序列化的 OpenAPI 3.1 文档对象,不拥有任何契约,也不提供任何 Schema 体系。
8
+
9
+ 三个特点:
10
+
11
+ 1. 文档与运行时逐字段一致。成功响应写成内核实际写出的成功信封 `{ success: true, data }`,不是契约描述的数据面本身。
12
+ 2. 同样的输入必然得到逐字节相同的输出。路径依码元次序排列,方法按固定次序排列,与路由字典的键序无关。
13
+ 3. 无法表达的形态响亮抛错。契约里出现 JSON Schema 表达不了的东西时直接报出是哪个操作的哪个字段,不降级为空对象。
14
+
15
+ ## 导出面
16
+
17
+ 值:
18
+
19
+ | 导出 | 用途 |
20
+ | ---------------------- | ---------------------- |
21
+ | `buildOpenApiDocument` | 从路由字典清单派生文档 |
22
+
23
+ 类型:
24
+
25
+ | 导出 | 用途 |
26
+ | ----------------------------------------------------------------------------------------------- | ------------------------------ |
27
+ | `OpenApiDocument`、`OpenApiDocumentOptions` | 文档对象与生成选项 |
28
+ | `OpenApiInfo`、`OpenApiContact`、`OpenApiLicense` | 文档的元信息 |
29
+ | `OpenApiServer`、`OpenApiServerVariable`、`OpenApiTag`、`OpenApiExternalDocs` | 服务地址、标签与外部文档 |
30
+ | `OpenApiPathItem`、`OpenApiOperation`、`OpenApiMethod` | 路径条目与操作 |
31
+ | `OpenApiParameter`、`OpenApiParameterLocation`、`OpenApiRequestBody` | 参数与请求体 |
32
+ | `OpenApiResponse`、`OpenApiResponses`、`OpenApiMediaTypes`、`OpenApiMediaType`、`OpenApiHeader` | 响应面 |
33
+ | `OpenApiRouteDictionary` | 以操作标识为键的路由字典 |
34
+ | `JsonSchemaObject`、`JsonValue`、`JsonObject`、`JsonArray`、`JsonPrimitive` | 文档里的 JSON 值与 JSON Schema |
35
+
36
+ 契约类型不从本包转发,`RouteDefinition` 一律从 `@longzai-intelligence-transport/http-core` 取。
37
+
38
+ ## 接入配方
39
+
40
+ 交给内核挂载的那份路由字典,原样再交给本包一次即可。
41
+
42
+ ```ts
43
+ import type { RouteDefinition } from '@longzai-intelligence-transport/http-core';
44
+
45
+ import { buildOpenApiDocument } from '@longzai-intelligence-server/openapi';
46
+ import * as z from 'zod';
47
+
48
+ const specRoutes = {
49
+ listSpecs: {
50
+ method: 'GET',
51
+ path: '/specs',
52
+ query: z.object({ limit: z.coerce.number().optional() }),
53
+ response: z.array(z.object({ name: z.string() })),
54
+ summary: '列出规格',
55
+ tags: ['规格'],
56
+ },
57
+ readSpec: {
58
+ method: 'GET',
59
+ path: '/specs/:specId',
60
+ params: z.object({ specId: z.string() }),
61
+ response: z.object({ id: z.string(), name: z.string() }),
62
+ errorResponses: { '404': z.object({ hint: z.string() }) },
63
+ },
64
+ downloadSpec: {
65
+ method: 'GET',
66
+ path: '/specs/:specId/file',
67
+ params: z.object({ specId: z.string() }),
68
+ responseType: 'stream',
69
+ stream: { mimeType: 'text/plain', fileName: 'spec.txt' },
70
+ },
71
+ } as const satisfies Record<string, RouteDefinition>;
72
+
73
+ const document = buildOpenApiDocument({
74
+ info: { title: '规格服务', version: '1.0.0' },
75
+ routes: [specRoutes],
76
+ servers: [{ url: 'http://localhost:3000' }],
77
+ });
78
+
79
+ // 可直接作为响应体写出,也可落盘
80
+ const text = JSON.stringify(document);
81
+ ```
82
+
83
+ `routes` 是路由字典清单,一个服务挂载了几份字典就列几份。清单内与清单之间的操作标识都不得重复。
84
+
85
+ 上面这份字典的输出里,读取规格这个操作节选如下。
86
+
87
+ ```json
88
+ {
89
+ "/specs/{specId}": {
90
+ "get": {
91
+ "operationId": "readSpec",
92
+ "parameters": [
93
+ { "name": "specId", "in": "path", "required": true, "schema": { "type": "string" } }
94
+ ],
95
+ "responses": {
96
+ "200": {
97
+ "description": "请求成功",
98
+ "content": {
99
+ "application/json": {
100
+ "schema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "success": { "type": "boolean", "const": true },
104
+ "data": {
105
+ "type": "object",
106
+ "properties": { "id": { "type": "string" }, "name": { "type": "string" } },
107
+ "required": ["id", "name"],
108
+ "additionalProperties": false
109
+ }
110
+ },
111
+ "required": ["success", "data"],
112
+ "additionalProperties": false
113
+ }
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
123
+ 完整输出共三个路径,依次是 `/specs`、`/specs/{specId}` 与 `/specs/{specId}/file`,`readSpec` 另有一个 404 响应未在节选里列出。
124
+
125
+ ## 派生规则
126
+
127
+ | 契约 | 文档里的落点 |
128
+ | ----------------------- | -------------------------------------------------------------------------------------------------- |
129
+ | `method` 与 `path` | `paths` 下的路径条目,路径模板的 `:name` 段改写为 `{name}`,收尾斜杠被去掉 |
130
+ | 路由字典的键 | `operationId` |
131
+ | `summary` 与 `tags` | 同名键,未声明则不出现 |
132
+ | `params` | `parameters` 里的路径参数,恒为必填,依路径里的出现顺序,契约未声明该 Schema 时按字符串描述 |
133
+ | `query` | `parameters` 里的查询参数,依 Schema 的声明顺序,必填与否取自 Schema |
134
+ | `body` 与 `contentType` | `requestBody`,媒体类型是 `application/json`,内容类型声明为 `formData` 时是 `multipart/form-data` |
135
+ | `response` | 成功状态码的响应 |
136
+ | `errorResponses` | 逐个列出的非成功响应 |
137
+
138
+ 路径参数与 `params` 必须对得上。路径里有某个路径参数而 `params` 没声明它,或 `params` 声明了路径里没有的参数,都抛错。
139
+
140
+ 响应表里成功状态码排最前,其后是契约声明的非成功响应。精确状态码依数值排列,`4XX` 这样一整类的状态码排在全部精确状态码之后,`default` 恒排最后。
141
+
142
+ ## 响应面
143
+
144
+ 契约的 `responseType` 决定每个状态码的响应体怎么写。
145
+
146
+ | 分支 | 每个状态码的响应体 |
147
+ | -------- | ---------------------------------------------------------------------------------- |
148
+ | `json` | 成功信封 `{ success: true, data }` 包裹契约描述的数据面 |
149
+ | `raw` | 契约描述的数据面本身 |
150
+ | `stream` | 合成的二进制文档,媒体类型取 `stream.mimeType`,声明了文件名时一并声明下载类响应头 |
151
+
152
+ `responseType` 的语义作用于全部状态码。JSON 路由上 `errorResponses` 声明的 Schema 同样经成功信封包裹,raw 路由上同样是数据面本身。契约没有声明的状态码由内核按统一失败信封 `{ success: false, error: { code, message, details } }` 写出,不在文档里逐个列出。
153
+
154
+ 流式路由的媒体类型未声明时回退为 `application/octet-stream`。下载类响应头的说明文字与对照基准一致。内核实际写出的 `Content-Disposition` 另带按 RFC 5987 编码的 `filename*`。
155
+
156
+ ## Schema 转换
157
+
158
+ 契约里的 zod Schema 经 zod 4 的 `z.toJSONSchema` 转成 JSON Schema 2020-12,与 OpenAPI 3.1 同构。
159
+
160
+ | 方向 | 用于 | 取的形态 |
161
+ | -------- | -------------------------- | -------------------------------------------- |
162
+ | 入站方向 | 路径参数、查询参数与请求体 | 调用方发送的形态,带默认值的属性不算必须给出 |
163
+ | 出站方向 | 成功响应与非成功响应 | 服务写出的形态,对象不允许多余属性 |
164
+
165
+ 强制转换的数字如 `z.coerce.number()` 按数字描述。文件字段 `z.file()` 按二进制字符串描述。zod 在顶层附带的版本声明不会带进文档。
166
+
167
+ 下列形态 JSON Schema 表达不了,遇到即抛错。
168
+
169
+ - 日期与时间,如 `z.date()`。
170
+ - 大整数,如 `z.bigint()`。
171
+ - 出站方向上的转换,如 `z.string().transform`。
172
+
173
+ ## 抛错的情形
174
+
175
+ 以下情形都在派生时抛错,不带上下文的错误消息不出现。
176
+
177
+ | 情形 | 消息里的上下文 |
178
+ | ----------------------------------------------- | ----------------------------------------------- |
179
+ | 方法与路径都相同的路由出现两条 | 两个操作标识 |
180
+ | 操作标识重复 | 两处各自的方法与路径 |
181
+ | 契约不是对象,或方法不在契约支持的方法集合里 | 操作标识或方法名 |
182
+ | 路径不以斜杠开头,路径段含花括号 | 路径模板与路径段 |
183
+ | 路径参数名不合法,或同一路径里重复出现 | 路径模板 |
184
+ | 路径参数与 `params` 对不上 | 操作标识与参数名 |
185
+ | `params` 或 `query` 不是对象形态的 Schema | 操作标识与字段名 |
186
+ | `errorResponses` 的键不合法,或声明了成功状态码 | 操作标识与状态码 |
187
+ | Schema 含 JSON Schema 无法表达的形态 | 操作标识、字段名与状态码,原始错误在 `cause` 上 |
188
+
189
+ ## 与对照基准的出入
190
+
191
+ 等价性以 `@longzai-intelligence-transport/http-adapter-elysia` 为对照基准,有测试守护。每个状态码的数据面与对照基准同状态码的 Schema 相等,流式路由的成功响应与对照基准合成的文档一致。
192
+
193
+ 出入在信封。对照基准给出的成功响应是契约描述的数据面本身,不带信封。本包按 ADR 0174 给 JSON 路由的每个状态码加上成功信封,因为内核实际写出的响应就是这个形状,文档如实描述运行时。
194
+
195
+ ## 边界
196
+
197
+ - 包清单上运行时依赖只有 `@longzai-intelligence-transport/http-core`,对等依赖是 `zod`。前者只在类型上被引用,构建产物在运行时只导入 `zod`。不导入内核、Bun 模块与 node 内置模块,有测试守护。
198
+ - 只派生契约声明了的东西。内核隐含的失败响应、认证方案与限流声明不在契约里,文档不凭空补。
199
+ - 不是 OpenAPI 校验器,也不做文档与实现的一致性比对。
@@ -0,0 +1,364 @@
1
+ import { RouteDefinition } from "@longzai-intelligence-transport/http-core";
2
+ /**
3
+ * 文档采用的 OpenAPI 版本
4
+ */
5
+ declare const OPENAPI_VERSION = "3.1.0";
6
+ /**
7
+ * JSON 的标量值
8
+ */
9
+ type JsonPrimitive = null | boolean | number | string;
10
+ /**
11
+ * JSON 的数组值
12
+ */
13
+ type JsonArray = readonly JsonValue[];
14
+ /**
15
+ * JSON 的对象值
16
+ */
17
+ type JsonObject = {
18
+ readonly [key: string]: JsonValue;
19
+ };
20
+ /**
21
+ * 任意 JSON 值
22
+ */
23
+ type JsonValue = JsonPrimitive | JsonArray | JsonObject;
24
+ /**
25
+ * JSON Schema 对象
26
+ */
27
+ type JsonSchemaObject = JsonObject;
28
+ /**
29
+ * OpenAPI 路径条目里的方法键,恒为小写
30
+ */
31
+ type OpenApiMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
32
+ /**
33
+ * 文档的联系人信息
34
+ */
35
+ type OpenApiContact = {
36
+ /**
37
+ * 联系人或团队名
38
+ */
39
+ readonly name?: string;
40
+ /**
41
+ * 联系页面的地址
42
+ */
43
+ readonly url?: string;
44
+ /**
45
+ * 联系邮箱
46
+ */
47
+ readonly email?: string;
48
+ };
49
+ /**
50
+ * 文档的许可证信息
51
+ */
52
+ type OpenApiLicense = {
53
+ /**
54
+ * 许可证名
55
+ */
56
+ readonly name: string;
57
+ /**
58
+ * 许可证的标准化标识,与 `url` 二者取一
59
+ */
60
+ readonly identifier?: string;
61
+ /**
62
+ * 许可证正文的地址
63
+ */
64
+ readonly url?: string;
65
+ };
66
+ /**
67
+ * 文档的元信息
68
+ */
69
+ type OpenApiInfo = {
70
+ /**
71
+ * 文档标题
72
+ */
73
+ readonly title: string;
74
+ /**
75
+ * 文档版本
76
+ */
77
+ readonly version: string;
78
+ /**
79
+ * 一句话摘要
80
+ */
81
+ readonly summary?: string;
82
+ /**
83
+ * 详细描述
84
+ */
85
+ readonly description?: string;
86
+ /**
87
+ * 服务条款的地址
88
+ */
89
+ readonly termsOfService?: string;
90
+ /**
91
+ * 联系人信息
92
+ */
93
+ readonly contact?: OpenApiContact;
94
+ /**
95
+ * 许可证信息
96
+ */
97
+ readonly license?: OpenApiLicense;
98
+ };
99
+ /**
100
+ * 服务地址里的模板变量
101
+ */
102
+ type OpenApiServerVariable = {
103
+ /**
104
+ * 变量的取值范围
105
+ */
106
+ readonly enum?: readonly string[];
107
+ /**
108
+ * 调用方未指定时的取值
109
+ */
110
+ readonly default?: string;
111
+ /**
112
+ * 变量的说明
113
+ */
114
+ readonly description?: string;
115
+ };
116
+ /**
117
+ * 一个服务地址
118
+ */
119
+ type OpenApiServer = {
120
+ /**
121
+ * 服务地址,可含模板变量
122
+ */
123
+ readonly url: string;
124
+ /**
125
+ * 服务地址的说明
126
+ */
127
+ readonly description?: string;
128
+ /**
129
+ * 地址里模板变量的声明
130
+ */
131
+ readonly variables?: Readonly<Record<string, OpenApiServerVariable>>;
132
+ };
133
+ /**
134
+ * 外部文档的指向
135
+ */
136
+ type OpenApiExternalDocs = {
137
+ /**
138
+ * 外部文档的地址
139
+ */
140
+ readonly url: string;
141
+ /**
142
+ * 外部文档的说明
143
+ */
144
+ readonly description?: string;
145
+ };
146
+ /**
147
+ * 文档顶层的标签声明
148
+ */
149
+ type OpenApiTag = {
150
+ /**
151
+ * 标签名
152
+ */
153
+ readonly name: string;
154
+ /**
155
+ * 标签说明
156
+ */
157
+ readonly description?: string;
158
+ /**
159
+ * 该标签的外部文档
160
+ */
161
+ readonly externalDocs?: OpenApiExternalDocs;
162
+ };
163
+ /**
164
+ * 参数所在的位置,路径参数或查询参数
165
+ */
166
+ type OpenApiParameterLocation = 'path' | 'query';
167
+ /**
168
+ * 操作的一个参数
169
+ */
170
+ type OpenApiParameter = {
171
+ /**
172
+ * 参数名
173
+ */
174
+ readonly name: string;
175
+ /**
176
+ * 参数所在的位置
177
+ */
178
+ readonly in: OpenApiParameterLocation;
179
+ /**
180
+ * 调用方是否必须给出
181
+ */
182
+ readonly required: boolean;
183
+ /**
184
+ * 参数说明
185
+ */
186
+ readonly description?: string;
187
+ /**
188
+ * 参数的 JSON Schema
189
+ */
190
+ readonly schema: JsonSchemaObject;
191
+ };
192
+ /**
193
+ * 一种媒体类型下的载荷结构
194
+ */
195
+ type OpenApiMediaType = {
196
+ /**
197
+ * 载荷的 JSON Schema
198
+ */
199
+ readonly schema: JsonSchemaObject;
200
+ };
201
+ /**
202
+ * 以媒体类型为键的载荷结构表
203
+ */
204
+ type OpenApiMediaTypes = Readonly<Record<string, OpenApiMediaType>>;
205
+ /**
206
+ * 响应头的声明
207
+ */
208
+ type OpenApiHeader = {
209
+ /**
210
+ * 响应头说明
211
+ */
212
+ readonly description?: string;
213
+ /**
214
+ * 响应头的 JSON Schema
215
+ */
216
+ readonly schema: JsonSchemaObject;
217
+ };
218
+ /**
219
+ * 一个状态码的响应
220
+ */
221
+ type OpenApiResponse = {
222
+ /**
223
+ * 响应说明,OpenAPI 规范要求必填
224
+ */
225
+ readonly description: string;
226
+ /**
227
+ * 响应头的声明
228
+ */
229
+ readonly headers?: Readonly<Record<string, OpenApiHeader>>;
230
+ /**
231
+ * 响应体的结构,按媒体类型给出
232
+ */
233
+ readonly content?: OpenApiMediaTypes;
234
+ };
235
+ /**
236
+ * 以状态码为键的响应表,`default` 表示其余全部状态码
237
+ */
238
+ type OpenApiResponses = Readonly<Record<string, OpenApiResponse>>;
239
+ /**
240
+ * 操作的请求体
241
+ */
242
+ type OpenApiRequestBody = {
243
+ /**
244
+ * 请求体说明
245
+ */
246
+ readonly description?: string;
247
+ /**
248
+ * 调用方是否必须给出请求体
249
+ */
250
+ readonly required: boolean;
251
+ /**
252
+ * 请求体的结构,按媒体类型给出
253
+ */
254
+ readonly content: OpenApiMediaTypes;
255
+ };
256
+ /**
257
+ * 路径条目下的一个操作
258
+ */
259
+ type OpenApiOperation = {
260
+ /**
261
+ * 操作标识,取路由字典的键
262
+ */
263
+ readonly operationId: string;
264
+ /**
265
+ * 一句话摘要
266
+ */
267
+ readonly summary?: string;
268
+ /**
269
+ * 详细描述
270
+ */
271
+ readonly description?: string;
272
+ /**
273
+ * 标签分组
274
+ */
275
+ readonly tags?: readonly string[];
276
+ /**
277
+ * 路径参数在前,查询参数在后
278
+ */
279
+ readonly parameters?: readonly OpenApiParameter[];
280
+ /**
281
+ * 请求体
282
+ */
283
+ readonly requestBody?: OpenApiRequestBody;
284
+ /**
285
+ * 契约声明的全部响应
286
+ */
287
+ readonly responses: OpenApiResponses;
288
+ };
289
+ /**
290
+ * 一个路径下按方法排列的操作
291
+ */
292
+ type OpenApiPathItem = Readonly<Partial<Record<OpenApiMethod, OpenApiOperation>>>;
293
+ /**
294
+ * OpenAPI 3.1 文档对象
295
+ */
296
+ type OpenApiDocument = {
297
+ /**
298
+ * OpenAPI 版本
299
+ */
300
+ readonly openapi: typeof OPENAPI_VERSION;
301
+ /**
302
+ * 文档的元信息
303
+ */
304
+ readonly info: OpenApiInfo;
305
+ /**
306
+ * 服务地址清单
307
+ */
308
+ readonly servers?: readonly OpenApiServer[];
309
+ /**
310
+ * 文档顶层的标签声明
311
+ */
312
+ readonly tags?: readonly OpenApiTag[];
313
+ /**
314
+ * 外部文档的指向
315
+ */
316
+ readonly externalDocs?: OpenApiExternalDocs;
317
+ /**
318
+ * 以路径为键的全部路径条目,路径已改写为 OpenAPI 的模板形态
319
+ */
320
+ readonly paths: Readonly<Record<string, OpenApiPathItem>>;
321
+ };
322
+ /**
323
+ * 以操作标识为键的路由字典
324
+ */
325
+ type OpenApiRouteDictionary = Readonly<Record<string, RouteDefinition>>;
326
+ /**
327
+ * 生成文档的选项
328
+ */
329
+ type OpenApiDocumentOptions = {
330
+ /**
331
+ * 文档的元信息
332
+ */
333
+ readonly info: OpenApiInfo;
334
+ /**
335
+ * 路由字典清单,清单内与清单之间的操作标识都不得重复
336
+ */
337
+ readonly routes: readonly OpenApiRouteDictionary[];
338
+ /**
339
+ * 服务地址清单,原样写入文档
340
+ */
341
+ readonly servers?: readonly OpenApiServer[];
342
+ /**
343
+ * 文档顶层的标签声明,原样写入文档
344
+ */
345
+ readonly tags?: readonly OpenApiTag[];
346
+ /**
347
+ * 外部文档的指向,原样写入文档
348
+ */
349
+ readonly externalDocs?: OpenApiExternalDocs;
350
+ };
351
+ /**
352
+ * 从契约派生 OpenAPI 3.1 文档
353
+ *
354
+ * @remarks
355
+ * 每条路由派生一个操作对象,路径模板的 `:name` 段改写为 `{name}`,操作标识取路由字典的键
356
+ * 路径依码元次序排列,方法按固定次序排列,同样的输入必然得到逐字节相同的序列化结果
357
+ * 契约里 JSON Schema 无法表达的形态一律抛错,不降级为空对象
358
+ * 运行时无关,可在 Bun 与 Node 的工具链进程中使用
359
+ * @param options - 生成文档的选项
360
+ * @returns OpenAPI 3.1 文档对象
361
+ * @throws {@link Error} 方法与路径重复,操作标识重复,或契约无法派生时抛错
362
+ */
363
+ declare function buildOpenApiDocument(options: OpenApiDocumentOptions): OpenApiDocument;
364
+ export { type JsonArray, type JsonObject, type JsonPrimitive, type JsonSchemaObject, type JsonValue, type OpenApiContact, type OpenApiDocument, type OpenApiDocumentOptions, type OpenApiExternalDocs, type OpenApiHeader, type OpenApiInfo, type OpenApiLicense, type OpenApiMediaType, type OpenApiMediaTypes, type OpenApiMethod, type OpenApiOperation, type OpenApiParameter, type OpenApiParameterLocation, type OpenApiPathItem, type OpenApiRequestBody, type OpenApiResponse, type OpenApiResponses, type OpenApiRouteDictionary, type OpenApiServer, type OpenApiServerVariable, type OpenApiTag, buildOpenApiDocument };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import"./rolldown-runtime-BqT_7tdF.js";import*as e from"zod";const t=`application/json`,n=`导出文件下载`,r=/^[A-Za-z_][A-Za-z0-9_]*$/,i=/^\d{3}$/,a=/^[1-5][Xx][Xx]$/,o=[`get`,`post`,`put`,`patch`,`delete`],s={type:`string`},c={type:`string`,format:`binary`},l={type:`boolean`,const:!0},u={GET:`get`,POST:`post`,PUT:`put`,PATCH:`patch`,DELETE:`delete`};function d(e){let t=u[e];if(t===void 0)throw Error(`不支持的 HTTP 方法:${String(e)}`);return t}function f(e,t){return t===void 0?{}:{[e]:t}}function p(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function m(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(m);if(typeof e==`object`)return h(e);throw Error(`取值不是 JSON 值,实际类型是 ${typeof e}`)}function h(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=m(r));return t}function g(e){let t=h(e);return delete t.$schema,t}function _(t,n,r){try{return g(e.toJSONSchema(t,{io:n}))}catch(e){throw Error(`操作 ${r.operation} 的${r.field}含 JSON Schema 无法表达的形态`,{cause:e})}}function v(e,t){let n=_(e,`input`,t),r=n.properties;if(!p(r))throw Error(`操作 ${t.operation} 的${t.field}不是对象形态的 Schema`);let i={};for(let[e,n]of Object.entries(r)){if(!p(n))throw Error(`操作 ${t.operation} 的${t.field}的属性 ${e} 不是对象形态的 Schema`);i[e]=n}let a=Array.isArray(n.required)?n.required:[];return{properties:i,required:new Set(a)}}function y(e,t,n){let r=n.properties[t];if(r===void 0)throw Error(`操作 ${e} 的路径含路径参数 ${t},但路径参数 Schema 没有声明它`);return r}function b(e,t,n){return t.params.map(t=>({name:t,in:`path`,required:!0,schema:n===void 0?s:y(e,t,n)}))}function x(e){return Object.entries(e.properties).map(([t,n])=>({name:t,in:`query`,required:e.required.has(t),schema:n}))}function S(e,t,n){for(let r of Object.keys(n.properties))if(!t.params.includes(r))throw Error(`操作 ${e} 的路径参数 Schema 声明了 ${r},但路径里没有这个路径参数`)}function C(e,t,n){let r=n.params===void 0?void 0:v(n.params,{operation:e,field:`路径参数`});r!==void 0&&S(e,t,r);let i=b(e,t,r);return n.query!==void 0&&i.push(...x(v(n.query,{operation:e,field:`查询参数`}))),i.length===0?void 0:i}function w(e,n){let r=n.body;if(r!==void 0)return{required:!r.isOptional(),content:{[n.contentType===`formData`?`multipart/form-data`:t]:{schema:_(r,`input`,{operation:e,field:`请求体`})}}}}function T(e){let t={[e.mimeType??`application/octet-stream`]:{schema:c}},r=e.fileName;if(r===void 0||r.length===0)return{description:n,content:t};let i={"Content-Disposition":{schema:s,description:`attachment; filename="${r}"`}};return{description:n,content:t,headers:i}}const E=[`success`,`data`],D=`响应`;function O(e){return e==="default"?1/0:a.test(e)?1e3+Number(e.slice(0,1))*100:Number(e)}function k(e,t){return O(e)-O(t)}function A(e,t){return k(e[0],t[0])}function j(e){return{type:`object`,properties:{success:l,data:e},required:E,additionalProperties:!1}}function M(e,n,r,i){return{description:i,content:{[t]:{schema:r?j(n):n}}}}function N(e,t){if(t===`200`)throw Error(`操作 ${e} 的非成功响应里声明了成功状态码 200`);if(t!=="default"&&!i.test(t)&&!a.test(t))throw Error(`操作 ${e} 的非成功响应状态码不合法:${t}`)}function P(e,t){let n={200:M({operation:e,field:D},_(t.response,`output`,{operation:e,field:D}),t.responseType!==`raw`,`请求成功`)},r=Object.entries(t.errorResponses??{}).sort(A);for(let[i,a]of r)N(e,i),n[i]=M({operation:e,field:`状态码 ${i} 的响应`},_(a,`output`,{operation:e,field:`状态码 ${i} 的响应`}),t.responseType!==`raw`,`请求未成功`);return n}function F(e,t){return t.responseType===`stream`?{200:T(t.stream)}:P(e,t)}function I(e,t,n){return{operationId:e,...f(`summary`,n.summary),...f(`tags`,n.tags),...f(`parameters`,C(e,t,n)),...f(`requestBody`,w(e,n)),responses:F(e,n)}}const L=[`{`,`}`];function R(e){return e.startsWith(`:`)}function z(e,t){if(!R(e)){if(L.some(t=>e.includes(t)))throw Error(`路径模板 ${t} 的路径段 ${e} 含花括号,无法原样写入文档`);return{text:e,name:void 0}}let n=e.slice(1);if(!r.test(n))throw Error(`路径模板 ${t} 的路径参数名不合法:${e}`);return{text:`{${n}}`,name:n}}function B(e){if(!e.startsWith(`/`))throw Error(`路径模板必须以斜杠开头:${e}`);let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=[];return{template:`/`+t.slice(1).split(`/`).map(t=>{let r=z(t,e);if(r.name!==void 0){if(n.includes(r.name))throw Error(`路径模板 ${e} 里路径参数 ${r.name} 重复出现`);n.push(r.name)}return r.text}).join(`/`),params:n}}function V(e,t){if(typeof t!=`object`||!t)throw Error(`操作 ${e} 的契约不是对象`)}function H(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;function r(r,i){let a=B(i.path),o=d(i.method),s=`${i.method} ${a.template}`,c=t.get(s);if(c!==void 0)throw Error(`方法与路径 ${s} 被重复登记,操作标识 ${c} 与 ${r}`);let l=n.get(r);if(l!==void 0)throw Error(`操作标识 ${r} 被重复登记,分别对应 ${l} 与 ${s}`);t.set(s,r),n.set(r,s);let u=e[a.template]??{};u[o]=I(r,a,i),e[a.template]=u}return{register:r}}function U(e){let t={};for(let n of o){let r=e?.[n];r!==void 0&&(t[n]=r)}return t}function W(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=U(e[r]);return t}function G(e){let t={},n=H(t);for(let t of e.routes)for(let[e,r]of Object.entries(t))V(e,r),n.register(e,r);return{openapi:`3.1.0`,info:e.info,...f(`servers`,e.servers),...f(`tags`,e.tags),...f(`externalDocs`,e.externalDocs),paths:W(t)}}export{G as buildOpenApiDocument};
@@ -0,0 +1 @@
1
+ import"node:module";export{};
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@longzai-intelligence-server/openapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Longzai Intelligence 契约执行引擎文档派生包",
5
+ "keywords": [
6
+ "contract",
7
+ "documentation",
8
+ "longzai-intelligence",
9
+ "openapi",
10
+ "server"
11
+ ],
12
+ "license": "UNLICENSED",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "type": "module",
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "scripts": {
26
+ "build": "lzi-builder",
27
+ "build:prod": "NODE_ENV=production bun run build",
28
+ "prepublishOnly": "bun run build:prod",
29
+ "clean": "lzi-clean",
30
+ "test": "lzi-bun test",
31
+ "test:watch": "lzi-bun test --watch",
32
+ "test:coverage": "lzi-bun test --coverage",
33
+ "lint": "lzi-lint lint",
34
+ "lint:fix": "lzi-lint fix",
35
+ "typecheck": "lzi-typecheck"
36
+ },
37
+ "dependencies": {
38
+ "@longzai-intelligence-transport/http-core": "^0.2.5"
39
+ },
40
+ "devDependencies": {
41
+ "@longzai-intelligence-transport/http-adapter-elysia": "^0.2.5",
42
+ "expect-type": "^1.4.0",
43
+ "zod": "^4.6.7"
44
+ },
45
+ "peerDependencies": {
46
+ "zod": "^4.4.3"
47
+ },
48
+ "packageManager": "bun@1.4.5"
49
+ }