@donghanh/hono 0.3.2 → 0.3.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donghanh/hono",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Hono routes for GPT Store and LLM chat — renderers for ChatGPT and OpenAI-compatible APIs",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -31,8 +31,8 @@ const info = { title: "Test API", version: "1.0.0" };
31
31
  const servers = [{ url: "https://api.example.com" }];
32
32
  const basePath = "/api/gpt";
33
33
 
34
- describe("generateOpenApi", () => {
35
- test("emits 3.1.0 spec with info + servers + bearerAuth scheme", () => {
34
+ describe("generateOpenApi common", () => {
35
+ test("emits 3.1.0 spec with info + servers + bearerAuth + empty schemas", () => {
36
36
  const spec = generateOpenApi({
37
37
  registry: registry({ a: makeOp("a") }),
38
38
  info,
@@ -46,14 +46,94 @@ describe("generateOpenApi", () => {
46
46
  type: "http",
47
47
  scheme: "bearer",
48
48
  });
49
+ expect(spec.components.schemas).toEqual({});
49
50
  });
50
51
 
51
- test("auth=required emits default path only with bearerAuth", () => {
52
+ test("includeDescription is off by default — no description field", () => {
52
53
  const spec = generateOpenApi({
53
- registry: registry({ a: makeOp("a", { auth: "required" }) }),
54
+ registry: registry({ a: makeOp("a") }),
55
+ info,
56
+ servers,
57
+ basePath,
58
+ pathStyle: "per-op",
59
+ }) as any;
60
+ const entry = spec.paths["/api/gpt/query/a"].get;
61
+ expect(entry.description).toBeUndefined();
62
+ expect(entry.summary).toBe("a desc");
63
+ });
64
+
65
+ test("includeDescription: true emits description built from desc+instruction", () => {
66
+ const spec = generateOpenApi({
67
+ registry: registry({ a: makeOp("a") }),
68
+ info,
69
+ servers,
70
+ basePath,
71
+ pathStyle: "per-op",
72
+ includeDescription: true,
73
+ }) as any;
74
+ const d = spec.paths["/api/gpt/query/a"].get.description as string;
75
+ expect(d).toContain("a desc");
76
+ expect(d).toContain("call a");
77
+ });
78
+
79
+ test("description truncated at maxDescriptionLength when included", () => {
80
+ const spec = generateOpenApi({
81
+ registry: registry({
82
+ a: makeOp("a", { instruction: "x".repeat(500) }),
83
+ }),
54
84
  info,
55
85
  servers,
56
86
  basePath,
87
+ pathStyle: "per-op",
88
+ includeDescription: true,
89
+ }) as any;
90
+ const d = spec.paths["/api/gpt/query/a"].get.description as string;
91
+ expect(d.length).toBeLessThanOrEqual(300);
92
+ expect(d.endsWith("…")).toBe(true);
93
+ });
94
+
95
+ test("summary capped at 120 chars", () => {
96
+ const spec = generateOpenApi({
97
+ registry: registry({
98
+ a: makeOp("a", { description: "y".repeat(200) }),
99
+ }),
100
+ info,
101
+ servers,
102
+ basePath,
103
+ pathStyle: "per-op",
104
+ }) as any;
105
+ const s = spec.paths["/api/gpt/query/a"].get.summary as string;
106
+ expect(s.length).toBeLessThanOrEqual(120);
107
+ });
108
+
109
+ test("custom bearerSchemeName", () => {
110
+ const spec = generateOpenApi({
111
+ registry: registry({ a: makeOp("a") }),
112
+ info,
113
+ servers,
114
+ basePath,
115
+ pathStyle: "per-op",
116
+ bearerSchemeName: "oauthToken",
117
+ }) as any;
118
+ expect(spec.components.securitySchemes.oauthToken).toBeDefined();
119
+ expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
120
+ { oauthToken: [] },
121
+ ]);
122
+ });
123
+ });
124
+
125
+ describe("generateOpenApi pathStyle: 'per-op'", () => {
126
+ const opts = {
127
+ info,
128
+ servers,
129
+ basePath,
130
+ pathStyle: "per-op" as const,
131
+ };
132
+
133
+ test("auth=required emits default path only with bearerAuth", () => {
134
+ const spec = generateOpenApi({
135
+ ...opts,
136
+ registry: registry({ a: makeOp("a", { auth: "required" }) }),
57
137
  }) as any;
58
138
  expect(Object.keys(spec.paths)).toEqual(["/api/gpt/query/a"]);
59
139
  expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
@@ -63,36 +143,26 @@ describe("generateOpenApi", () => {
63
143
 
64
144
  test("auth=none emits /public path with empty security", () => {
65
145
  const spec = generateOpenApi({
146
+ ...opts,
66
147
  registry: registry({ a: makeOp("a", { auth: "none" }) }),
67
- info,
68
- servers,
69
- basePath,
70
148
  }) as any;
71
149
  expect(Object.keys(spec.paths)).toEqual(["/api/gpt/public/query/a"]);
72
150
  expect(spec.paths["/api/gpt/public/query/a"].get.security).toEqual([]);
73
151
  });
74
152
 
75
- test("auth=optional emits BOTH default and /public paths", () => {
153
+ test("auth=optional emits both default and /public paths", () => {
76
154
  const spec = generateOpenApi({
155
+ ...opts,
77
156
  registry: registry({ a: makeOp("a", { auth: "optional" }) }),
78
- info,
79
- servers,
80
- basePath,
81
157
  }) as any;
82
158
  const ks = Object.keys(spec.paths).sort();
83
159
  expect(ks).toEqual(["/api/gpt/public/query/a", "/api/gpt/query/a"]);
84
- expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
85
- { bearerAuth: [] },
86
- ]);
87
- expect(spec.paths["/api/gpt/public/query/a"].get.security).toEqual([]);
88
160
  });
89
161
 
90
162
  test("mutation emits POST with requestBody", () => {
91
163
  const spec = generateOpenApi({
164
+ ...opts,
92
165
  registry: registry({ m: makeOp("m", { type: "mutation" }) }),
93
- info,
94
- servers,
95
- basePath,
96
166
  }) as any;
97
167
  const entry = spec.paths["/api/gpt/mutate/m"];
98
168
  expect(entry.post.requestBody).toBeDefined();
@@ -101,51 +171,40 @@ describe("generateOpenApi", () => {
101
171
 
102
172
  test("query has $variables parameter", () => {
103
173
  const spec = generateOpenApi({
174
+ ...opts,
104
175
  registry: registry({ q: makeOp("q") }),
105
- info,
106
- servers,
107
- basePath,
108
176
  }) as any;
109
177
  const p = spec.paths["/api/gpt/query/q"].get.parameters;
110
178
  expect(p).toHaveLength(1);
111
179
  expect(p[0].name).toBe("$variables");
112
- expect(p[0].in).toBe("query");
113
- });
114
-
115
- test("description combines op description + instruction", () => {
116
- const spec = generateOpenApi({
117
- registry: registry({ a: makeOp("a") }),
118
- info,
119
- servers,
120
- basePath,
121
- }) as any;
122
- const op = spec.paths["/api/gpt/query/a"].get;
123
- expect(op.summary).toBe("a desc");
124
- expect(op.description).toContain("a desc");
125
- expect(op.description).toContain("call a");
126
180
  });
181
+ });
127
182
 
128
- test("operationId is unique per method+opId", () => {
183
+ describe("generateOpenApi pathStyle: 'parametric' (default)", () => {
184
+ test("collapses all query ops under one /query/{operation} path with enum", () => {
129
185
  const spec = generateOpenApi({
130
186
  registry: registry({
131
- a: makeOp("a", { auth: "optional" }),
187
+ a: makeOp("a", { auth: "required" }),
188
+ b: makeOp("b", { auth: "required" }),
132
189
  }),
133
190
  info,
134
191
  servers,
135
192
  basePath,
136
193
  }) as any;
137
- const authedId = spec.paths["/api/gpt/query/a"].get.operationId;
138
- const publicId = spec.paths["/api/gpt/public/query/a"].get.operationId;
139
- expect(authedId).toBe("get_a");
140
- expect(publicId).toBe("get_a"); // Same handler, different path — OAS allows same operationId across paths
194
+ const ks = Object.keys(spec.paths);
195
+ expect(ks).toEqual(["/api/gpt/query/{operation}"]);
196
+ const opParam = spec.paths["/api/gpt/query/{operation}"].get.parameters[0];
197
+ expect(opParam.name).toBe("operation");
198
+ expect(opParam.in).toBe("path");
199
+ expect(opParam.schema.enum).toEqual(["a", "b"]);
141
200
  });
142
201
 
143
- test("mixed registry — three auth tiers coexist", () => {
202
+ test("emits /public/{operation} when any op is auth=none or optional", () => {
144
203
  const spec = generateOpenApi({
145
204
  registry: registry({
146
205
  priv: makeOp("priv", { auth: "required" }),
147
- mixed: makeOp("mixed", { auth: "optional" }),
148
206
  pub: makeOp("pub", { auth: "none" }),
207
+ both: makeOp("both", { auth: "optional" }),
149
208
  }),
150
209
  info,
151
210
  servers,
@@ -153,44 +212,57 @@ describe("generateOpenApi", () => {
153
212
  }) as any;
154
213
  const ks = Object.keys(spec.paths).sort();
155
214
  expect(ks).toEqual([
156
- "/api/gpt/public/query/mixed",
157
- "/api/gpt/public/query/pub",
158
- "/api/gpt/query/mixed",
159
- "/api/gpt/query/priv",
215
+ "/api/gpt/public/query/{operation}",
216
+ "/api/gpt/query/{operation}",
160
217
  ]);
218
+ // Default enum contains authed ops: required + optional (not "none")
219
+ expect(
220
+ spec.paths["/api/gpt/query/{operation}"].get.parameters[0].schema.enum,
221
+ ).toEqual(["priv", "both"]);
222
+ // Public enum contains guest-callable ops: none + optional (not "required")
223
+ expect(
224
+ spec.paths["/api/gpt/public/query/{operation}"].get.parameters[0].schema
225
+ .enum,
226
+ ).toEqual(["pub", "both"]);
161
227
  });
162
228
 
163
- test("includeSiblingsInDescription appends sibling list to each path description", () => {
229
+ test("separate /mutate/{operation} path for mutations", () => {
164
230
  const spec = generateOpenApi({
165
231
  registry: registry({
166
- a: makeOp("a", { auth: "required" }),
167
- b: makeOp("b", { auth: "none", type: "mutation" }),
168
- c: makeOp("c", { auth: "optional" }),
232
+ m: makeOp("m", { type: "mutation" }),
169
233
  }),
170
234
  info,
171
235
  servers,
172
236
  basePath,
173
- includeSiblingsInDescription: true,
174
237
  }) as any;
175
- const description = spec.paths["/api/gpt/query/a"].get.description;
176
- expect(description).toContain("Other operations");
177
- // Contains id, type, auth, and description for each sibling
178
- expect(description).toContain("`a` (query, auth: required) — a desc");
179
- expect(description).toContain("`b` (mutation, auth: none) — b desc");
180
- expect(description).toContain("`c` (query, auth: optional) — c desc");
238
+ expect(spec.paths["/api/gpt/mutate/{operation}"]).toBeDefined();
239
+ expect(
240
+ spec.paths["/api/gpt/mutate/{operation}"].post.requestBody,
241
+ ).toBeDefined();
181
242
  });
182
243
 
183
- test("custom bearerSchemeName", () => {
244
+ test("no description field by default (ChatGPT-safe)", () => {
184
245
  const spec = generateOpenApi({
185
246
  registry: registry({ a: makeOp("a") }),
186
247
  info,
187
248
  servers,
188
249
  basePath,
189
- bearerSchemeName: "oauthToken",
190
250
  }) as any;
191
- expect(spec.components.securitySchemes.oauthToken).toBeDefined();
192
- expect(spec.paths["/api/gpt/query/a"].get.security).toEqual([
193
- { oauthToken: [] },
194
- ]);
251
+ const entry = spec.paths["/api/gpt/query/{operation}"].get;
252
+ expect(entry.description).toBeUndefined();
253
+ });
254
+
255
+ test("includeDescription: true emits a short description", () => {
256
+ const spec = generateOpenApi({
257
+ registry: registry({ a: makeOp("a") }),
258
+ info,
259
+ servers,
260
+ basePath,
261
+ includeDescription: true,
262
+ }) as any;
263
+ const d = spec.paths["/api/gpt/query/{operation}"].get
264
+ .description as string;
265
+ expect(typeof d).toBe("string");
266
+ expect(d.length).toBeLessThanOrEqual(300);
195
267
  });
196
268
  });
package/src/openapi.ts CHANGED
@@ -22,11 +22,39 @@ export interface GenerateOpenApiConfig {
22
22
  /** When true, adds an info note about the $variables encoding (default true). */
23
23
  describeVariables?: boolean;
24
24
  /**
25
- * When true, append a "Other operations" section listing sibling op ids +
26
- * descriptions to each path's OpenAPI `description`. Helps ChatGPT Actions
27
- * learn the full surface from any single path. Default false.
25
+ * When true, each path emits a `description` built from the op's
26
+ * description + instruction. Default `false` — only `summary` is emitted,
27
+ * which keeps the spec compact and sidesteps ChatGPT Actions' 300-char
28
+ * description limit. Turn on when you want richer Action instructions in
29
+ * the OAS. (For listing sibling operations, prefer `includeOperationsInDetail`
30
+ * on `gptRoutes` — the GPT fetches `GET /operations/:name` to learn
31
+ * available ops, a cleaner channel than inlining them into OAS.)
28
32
  */
29
- includeSiblingsInDescription?: boolean;
33
+ includeDescription?: boolean;
34
+ /**
35
+ * Max length for each path's OpenAPI `description` when emitted. ChatGPT
36
+ * Actions rejects descriptions over 300 characters, so the default is 300.
37
+ * No effect when `includeDescription` is false.
38
+ */
39
+ maxDescriptionLength?: number;
40
+ /**
41
+ * How to lay out paths:
42
+ * - "parametric" (default) — single path with `{operation}` as a path param,
43
+ * matching gptRoutes' route shape (`/query/:operation`). 2–4 paths total
44
+ * regardless of registry size; the model picks the op by filling the
45
+ * `operation` param. Mirrors the existing REST shape and matches the
46
+ * convention most donghanh apps already use in their ChatGPT Action config.
47
+ * - "per-op" — one OAS path per operation, e.g. `/query/start`,
48
+ * `/public/query/check-offer`. Each op gets its own summary + description,
49
+ * so ChatGPT Actions discovers them as separate actions. Larger spec;
50
+ * useful when you want each op to be a discrete ChatGPT Action.
51
+ */
52
+ pathStyle?: "parametric" | "per-op";
53
+ }
54
+
55
+ function truncate(s: string, max: number): string {
56
+ if (s.length <= max) return s;
57
+ return `${s.slice(0, Math.max(0, max - 1))}…`;
30
58
  }
31
59
 
32
60
  type Sec = Array<Record<string, string[]>>;
@@ -59,19 +87,12 @@ export function generateOpenApi(config: GenerateOpenApiConfig): object {
59
87
  basePath = "",
60
88
  bearerSchemeName = "bearerAuth",
61
89
  describeVariables = true,
62
- includeSiblingsInDescription = false,
90
+ includeDescription = false,
91
+ maxDescriptionLength = 300,
92
+ pathStyle = "parametric",
63
93
  } = config;
64
94
 
65
95
  const ops = registry.list();
66
-
67
- const siblingsBlock = includeSiblingsInDescription
68
- ? `\n\nOther operations:\n${ops
69
- .map(
70
- (o) =>
71
- `- \`${o.id}\` (${o.type}, auth: ${o.auth ?? "required"}) — ${o.description}`,
72
- )
73
- .join("\n")}`
74
- : "";
75
96
  const paths: Record<string, PathItem> = {};
76
97
 
77
98
  const variablesParam = {
@@ -161,29 +182,24 @@ export function generateOpenApi(config: GenerateOpenApiConfig): object {
161
182
  security: Sec,
162
183
  ) => {
163
184
  const detail = registry.detail(op.id);
164
- const pascal = op.id
165
- .split(/[-_]/)
166
- .map((s) => (s ? s[0].toUpperCase() + s.slice(1) : ""))
167
- .join("");
168
185
  const entry: Operation = {
169
186
  operationId: `${method}_${op.id}`.replace(/[^A-Za-z0-9_]/g, "_"),
170
- summary: op.description,
171
- description:
172
- (detail?.instruction
173
- ? `${op.description}\n\n${detail.instruction}`
174
- : op.description) + siblingsBlock,
187
+ summary: truncate(op.description, 120),
175
188
  security,
176
189
  responses: successResponse,
177
190
  };
191
+ if (includeDescription) {
192
+ const full = detail?.instruction
193
+ ? `${op.description}\n\n${detail.instruction}`
194
+ : op.description;
195
+ entry.description = truncate(full, maxDescriptionLength);
196
+ }
178
197
  if (method === "get") {
179
198
  entry.parameters = [variablesParam];
180
199
  } else {
181
200
  entry.requestBody = variablesBody;
182
201
  }
183
- // Tag by op type to help OpenAPI UIs group them.
184
202
  (entry as Record<string, unknown>).tags = [op.type];
185
- // Hint: unused `pascal` to keep id stable if we later switch to camelCase.
186
- void pascal;
187
203
 
188
204
  let item = paths[path];
189
205
  if (!item) {
@@ -196,25 +212,35 @@ export function generateOpenApi(config: GenerateOpenApiConfig): object {
196
212
  const authedSec: Sec = [{ [bearerSchemeName]: [] }];
197
213
  const noSec: Sec = [];
198
214
 
199
- for (const op of ops) {
200
- const method: "get" | "post" = op.type === "query" ? "get" : "post";
201
- const auth = op.auth ?? "required";
215
+ if (pathStyle === "parametric") {
216
+ emitParametric(paths, basePath, authedSec, noSec, ops, {
217
+ includeDescription,
218
+ maxDescriptionLength,
219
+ variablesParam,
220
+ variablesBody,
221
+ successResponse,
222
+ });
223
+ } else {
224
+ for (const op of ops) {
225
+ const method: "get" | "post" = op.type === "query" ? "get" : "post";
226
+ const auth = op.auth ?? "required";
202
227
 
203
- const methodPath = op.type === "query" ? "query" : "mutate";
204
- const defaultPath = `${basePath}/${methodPath}/${op.id}`;
205
- const publicPath = `${basePath}/public/${methodPath}/${op.id}`;
228
+ const methodPath = op.type === "query" ? "query" : "mutate";
229
+ const defaultPath = `${basePath}/${methodPath}/${op.id}`;
230
+ const publicPath = `${basePath}/public/${methodPath}/${op.id}`;
206
231
 
207
- if (auth === "none") {
208
- emit(publicPath, method, op, noSec);
209
- continue;
210
- }
211
- if (auth === "required") {
232
+ if (auth === "none") {
233
+ emit(publicPath, method, op, noSec);
234
+ continue;
235
+ }
236
+ if (auth === "required") {
237
+ emit(defaultPath, method, op, authedSec);
238
+ continue;
239
+ }
240
+ // optional → expose both
212
241
  emit(defaultPath, method, op, authedSec);
213
- continue;
242
+ emit(publicPath, method, op, noSec);
214
243
  }
215
- // optional → expose both
216
- emit(defaultPath, method, op, authedSec);
217
- emit(publicPath, method, op, noSec);
218
244
  }
219
245
 
220
246
  return {
@@ -223,6 +249,7 @@ export function generateOpenApi(config: GenerateOpenApiConfig): object {
223
249
  servers,
224
250
  paths,
225
251
  components: {
252
+ schemas: {},
226
253
  securitySchemes: {
227
254
  [bearerSchemeName]: {
228
255
  type: "http",
@@ -232,3 +259,126 @@ export function generateOpenApi(config: GenerateOpenApiConfig): object {
232
259
  },
233
260
  };
234
261
  }
262
+
263
+ function emitParametric(
264
+ paths: Record<string, PathItem>,
265
+ basePath: string,
266
+ authedSec: Sec,
267
+ noSec: Sec,
268
+ ops: ReturnType<Registry["list"]>,
269
+ ctx: {
270
+ includeDescription: boolean;
271
+ maxDescriptionLength: number;
272
+ variablesParam: Record<string, unknown>;
273
+ variablesBody: Record<string, unknown>;
274
+ successResponse: Record<string, unknown>;
275
+ },
276
+ ): void {
277
+ const queryIds = ops.filter((o) => o.type === "query").map((o) => o.id);
278
+ const mutationIds = ops.filter((o) => o.type === "mutation").map((o) => o.id);
279
+ const authedQueryIds = ops
280
+ .filter((o) => o.type === "query" && (o.auth ?? "required") !== "none")
281
+ .map((o) => o.id);
282
+ const authedMutationIds = ops
283
+ .filter((o) => o.type === "mutation" && (o.auth ?? "required") !== "none")
284
+ .map((o) => o.id);
285
+ const publicQueryIds = ops
286
+ .filter((o) => o.type === "query" && (o.auth ?? "required") !== "required")
287
+ .map((o) => o.id);
288
+ const publicMutationIds = ops
289
+ .filter(
290
+ (o) => o.type === "mutation" && (o.auth ?? "required") !== "required",
291
+ )
292
+ .map((o) => o.id);
293
+
294
+ const opParam = (enumIds: string[]): Record<string, unknown> => ({
295
+ name: "operation",
296
+ in: "path",
297
+ required: true,
298
+ description: `Operation slug. One of: ${enumIds.join(", ")}.`,
299
+ schema: { type: "string", enum: enumIds },
300
+ });
301
+
302
+ const make = (
303
+ opName: string,
304
+ summary: string,
305
+ _method: "get" | "post",
306
+ security: Sec,
307
+ enumIds: string[],
308
+ bodyBased: boolean,
309
+ description: string,
310
+ ): Operation => {
311
+ const entry: Operation = {
312
+ operationId: opName,
313
+ summary: truncate(summary, 120),
314
+ security,
315
+ responses: ctx.successResponse as Record<string, unknown>,
316
+ parameters: bodyBased
317
+ ? [opParam(enumIds)]
318
+ : [opParam(enumIds), ctx.variablesParam],
319
+ };
320
+ if (ctx.includeDescription) {
321
+ entry.description = truncate(description, ctx.maxDescriptionLength);
322
+ }
323
+ if (bodyBased) entry.requestBody = ctx.variablesBody;
324
+ return entry;
325
+ };
326
+
327
+ if (queryIds.length) {
328
+ if (authedQueryIds.length) {
329
+ paths[`${basePath}/query/{operation}`] = {
330
+ get: make(
331
+ "queryOperation",
332
+ "Execute a query operation",
333
+ "get",
334
+ authedSec,
335
+ authedQueryIds,
336
+ false,
337
+ "Execute a read-only query by name. Pass variables as a JSON or TOON string in $variables.",
338
+ ),
339
+ };
340
+ }
341
+ if (publicQueryIds.length) {
342
+ paths[`${basePath}/public/query/{operation}`] = {
343
+ get: make(
344
+ "publicQueryOperation",
345
+ "Execute a public query operation",
346
+ "get",
347
+ noSec,
348
+ publicQueryIds,
349
+ false,
350
+ "Execute a public query by name — no authentication required.",
351
+ ),
352
+ };
353
+ }
354
+ }
355
+
356
+ if (mutationIds.length) {
357
+ if (authedMutationIds.length) {
358
+ paths[`${basePath}/mutate/{operation}`] = {
359
+ post: make(
360
+ "mutateOperation",
361
+ "Execute a mutation operation",
362
+ "post",
363
+ authedSec,
364
+ authedMutationIds,
365
+ true,
366
+ "Execute a mutation by name. Pass variables in the JSON body's $variables field.",
367
+ ),
368
+ };
369
+ }
370
+ if (publicMutationIds.length) {
371
+ paths[`${basePath}/public/mutate/{operation}`] = {
372
+ post: make(
373
+ "publicMutateOperation",
374
+ "Execute a public mutation operation",
375
+ "post",
376
+ noSec,
377
+ publicMutationIds,
378
+ true,
379
+ "Execute a public mutation by name — no authentication required.",
380
+ ),
381
+ };
382
+ }
383
+ }
384
+ }