@kajidog/connpass-mcp-server 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +72 -149
  2. package/dist/index.d.ts +0 -2
  3. package/dist/index.js +4729 -162
  4. package/dist/index.js.map +1 -1
  5. package/dist/mcp-app.html +139 -0
  6. package/dist/stdio.d.ts +1 -0
  7. package/dist/stdio.js +2120 -0
  8. package/dist/stdio.js.map +1 -0
  9. package/package.json +21 -20
  10. package/dist/apps-sdk.d.ts +0 -8
  11. package/dist/apps-sdk.d.ts.map +0 -1
  12. package/dist/apps-sdk.js +0 -79
  13. package/dist/apps-sdk.js.map +0 -1
  14. package/dist/config.d.ts +0 -7
  15. package/dist/config.d.ts.map +0 -1
  16. package/dist/config.js +0 -82
  17. package/dist/config.js.map +0 -1
  18. package/dist/index.d.ts.map +0 -1
  19. package/dist/tools/events.d.ts +0 -82
  20. package/dist/tools/events.d.ts.map +0 -1
  21. package/dist/tools/events.js +0 -385
  22. package/dist/tools/events.js.map +0 -1
  23. package/dist/tools/formatting.d.ts +0 -74
  24. package/dist/tools/formatting.d.ts.map +0 -1
  25. package/dist/tools/formatting.js +0 -211
  26. package/dist/tools/formatting.js.map +0 -1
  27. package/dist/tools/groups.d.ts +0 -48
  28. package/dist/tools/groups.d.ts.map +0 -1
  29. package/dist/tools/groups.js +0 -106
  30. package/dist/tools/groups.js.map +0 -1
  31. package/dist/tools/index.d.ts +0 -58
  32. package/dist/tools/index.d.ts.map +0 -1
  33. package/dist/tools/index.js +0 -21
  34. package/dist/tools/index.js.map +0 -1
  35. package/dist/tools/shared.d.ts +0 -24
  36. package/dist/tools/shared.d.ts.map +0 -1
  37. package/dist/tools/shared.js +0 -113
  38. package/dist/tools/shared.js.map +0 -1
  39. package/dist/tools/users.d.ts +0 -51
  40. package/dist/tools/users.d.ts.map +0 -1
  41. package/dist/tools/users.js +0 -239
  42. package/dist/tools/users.js.map +0 -1
  43. package/dist/transports/http.d.ts +0 -17
  44. package/dist/transports/http.d.ts.map +0 -1
  45. package/dist/transports/http.js +0 -185
  46. package/dist/transports/http.js.map +0 -1
  47. package/dist/transports/sse.d.ts +0 -21
  48. package/dist/transports/sse.d.ts.map +0 -1
  49. package/dist/transports/sse.js +0 -161
  50. package/dist/transports/sse.js.map +0 -1
  51. package/dist/widgets/connpass-events.d.ts +0 -29
  52. package/dist/widgets/connpass-events.d.ts.map +0 -1
  53. package/dist/widgets/connpass-events.html +0 -2269
  54. package/dist/widgets/connpass-events.js +0 -58
  55. package/dist/widgets/connpass-events.js.map +0 -1
  56. package/dist/widgets/index.d.ts +0 -6
  57. package/dist/widgets/index.d.ts.map +0 -1
  58. package/dist/widgets/index.js +0 -34
  59. package/dist/widgets/index.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,189 +1,4756 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const connpass_api_client_1 = require("@kajidog/connpass-api-client");
5
- const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
6
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
7
- const apps_sdk_js_1 = require("./apps-sdk.js");
8
- const config_js_1 = require("./config.js");
9
- const index_js_2 = require("./tools/index.js");
10
- const http_js_1 = require("./transports/http.js");
11
- const sse_js_1 = require("./transports/sse.js");
12
- const index_js_3 = require("./widgets/index.js");
13
- const rateLimitEnabled = (0, config_js_1.getRateLimitEnabled)();
14
- const rateLimitDelay = (0, config_js_1.getRateLimitDelayMs)();
15
- const envApiKey = process.env.CONNPASS_API_KEY;
16
- if (!envApiKey) {
17
- console.warn("[mcp-server] CONNPASS_API_KEY not set. Using dummy-key (Connpass API will reject most requests)");
18
- }
19
- else {
20
- console.log(`[mcp-server] CONNPASS_API_KEY detected (length: ${envApiKey.length}).`);
21
- }
22
- const connpassClient = new connpass_api_client_1.ConnpassClient({
23
- apiKey: envApiKey || "dummy-key",
24
- ...(rateLimitEnabled !== undefined ? { rateLimitEnabled } : {}),
25
- ...(rateLimitDelay !== undefined ? { rateLimitDelay } : {}),
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // ../../node_modules/.pnpm/@hono+node-server@1.19.7_hono@4.11.3/node_modules/@hono/node-server/dist/index.mjs
13
+ var dist_exports = {};
14
+ __export(dist_exports, {
15
+ RequestError: () => RequestError,
16
+ createAdaptorServer: () => createAdaptorServer,
17
+ getRequestListener: () => getRequestListener,
18
+ serve: () => serve
26
19
  });
27
- function createConnpassServer() {
28
- const appsSdkOutputEnabled = (0, config_js_1.isAppsSdkOutputEnabled)();
29
- console.log(`[mcp-server] Apps SDK output ${appsSdkOutputEnabled ? "enabled" : "disabled"}.`);
30
- const server = new index_js_1.Server({
31
- name: "connpass-mcp-server",
32
- version: "1.0.0",
33
- }, {
34
- capabilities: {
35
- tools: {},
36
- resources: {},
37
- resourceTemplates: {},
38
- },
39
- });
40
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
41
- return { tools: index_js_2.tools };
42
- });
43
- server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
44
- const resources = (0, index_js_3.listResources)();
45
- console.log("[mcp-server] list_resources", resources);
46
- return { resources };
47
- });
48
- server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => {
49
- const templates = (0, index_js_3.listResourceTemplates)();
50
- console.log("[mcp-server] list_resource_templates", templates);
51
- return { resourceTemplates: templates };
52
- });
53
- server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
54
- const content = (0, index_js_3.getResourceContent)(request.params.uri);
55
- if (!content) {
56
- throw new Error(`Unknown resource: ${request.params.uri}`);
57
- }
58
- const meta = Object.prototype.hasOwnProperty.call(content, "_meta")
59
- ? content._meta
60
- : undefined;
61
- console.log("[mcp-server] read_resource", request.params.uri, meta);
62
- return {
63
- contents: [content],
64
- };
20
+ import { createServer as createServerHTTP } from "http";
21
+ import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
22
+ import { Http2ServerRequest } from "http2";
23
+ import { Readable } from "stream";
24
+ import crypto from "crypto";
25
+ async function readWithoutBlocking(readPromise) {
26
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
27
+ }
28
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
29
+ const cancel = (error) => {
30
+ reader.cancel(error).catch(() => {
65
31
  });
66
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
32
+ };
33
+ writable.on("close", cancel);
34
+ writable.on("error", cancel);
35
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
36
+ return reader.closed.finally(() => {
37
+ writable.off("close", cancel);
38
+ writable.off("error", cancel);
39
+ });
40
+ function handleStreamError(error) {
41
+ if (error) {
42
+ writable.destroy(error);
43
+ }
44
+ }
45
+ function onDrain() {
46
+ reader.read().then(flow, handleStreamError);
47
+ }
48
+ function flow({ done, value }) {
49
+ try {
50
+ if (done) {
51
+ writable.end();
52
+ } else if (!writable.write(value)) {
53
+ writable.once("drain", onDrain);
54
+ } else {
55
+ return reader.read().then(flow, handleStreamError);
56
+ }
57
+ } catch (e) {
58
+ handleStreamError(e);
59
+ }
60
+ }
61
+ }
62
+ function writeFromReadableStream(stream, writable) {
63
+ if (stream.locked) {
64
+ throw new TypeError("ReadableStream is locked.");
65
+ } else if (writable.destroyed) {
66
+ return;
67
+ }
68
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
69
+ }
70
+ var RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, outgoingEnded, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
71
+ var init_dist = __esm({
72
+ "../../node_modules/.pnpm/@hono+node-server@1.19.7_hono@4.11.3/node_modules/@hono/node-server/dist/index.mjs"() {
73
+ "use strict";
74
+ RequestError = class extends Error {
75
+ constructor(message, options) {
76
+ super(message, options);
77
+ this.name = "RequestError";
78
+ }
79
+ };
80
+ toRequestError = (e) => {
81
+ if (e instanceof RequestError) {
82
+ return e;
83
+ }
84
+ return new RequestError(e.message, { cause: e });
85
+ };
86
+ GlobalRequest = global.Request;
87
+ Request2 = class extends GlobalRequest {
88
+ constructor(input, options) {
89
+ if (typeof input === "object" && getRequestCache in input) {
90
+ input = input[getRequestCache]();
91
+ }
92
+ if (typeof options?.body?.getReader !== "undefined") {
93
+ ;
94
+ options.duplex ??= "half";
95
+ }
96
+ super(input, options);
97
+ }
98
+ };
99
+ newHeadersFromIncoming = (incoming) => {
100
+ const headerRecord = [];
101
+ const rawHeaders = incoming.rawHeaders;
102
+ for (let i = 0; i < rawHeaders.length; i += 2) {
103
+ const { [i]: key, [i + 1]: value } = rawHeaders;
104
+ if (key.charCodeAt(0) !== /*:*/
105
+ 58) {
106
+ headerRecord.push([key, value]);
107
+ }
108
+ }
109
+ return new Headers(headerRecord);
110
+ };
111
+ wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
112
+ newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
113
+ const init = {
114
+ method,
115
+ headers,
116
+ signal: abortController.signal
117
+ };
118
+ if (method === "TRACE") {
119
+ init.method = "GET";
120
+ const req = new Request2(url, init);
121
+ Object.defineProperty(req, "method", {
122
+ get() {
123
+ return "TRACE";
124
+ }
125
+ });
126
+ return req;
127
+ }
128
+ if (!(method === "GET" || method === "HEAD")) {
129
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
130
+ init.body = new ReadableStream({
131
+ start(controller) {
132
+ controller.enqueue(incoming.rawBody);
133
+ controller.close();
134
+ }
135
+ });
136
+ } else if (incoming[wrapBodyStream]) {
137
+ let reader;
138
+ init.body = new ReadableStream({
139
+ async pull(controller) {
140
+ try {
141
+ reader ||= Readable.toWeb(incoming).getReader();
142
+ const { done, value } = await reader.read();
143
+ if (done) {
144
+ controller.close();
145
+ } else {
146
+ controller.enqueue(value);
147
+ }
148
+ } catch (error) {
149
+ controller.error(error);
150
+ }
151
+ }
152
+ });
153
+ } else {
154
+ init.body = Readable.toWeb(incoming);
155
+ }
156
+ }
157
+ return new Request2(url, init);
158
+ };
159
+ getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
160
+ requestCache = /* @__PURE__ */ Symbol("requestCache");
161
+ incomingKey = /* @__PURE__ */ Symbol("incomingKey");
162
+ urlKey = /* @__PURE__ */ Symbol("urlKey");
163
+ headersKey = /* @__PURE__ */ Symbol("headersKey");
164
+ abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
165
+ getAbortController = /* @__PURE__ */ Symbol("getAbortController");
166
+ requestPrototype = {
167
+ get method() {
168
+ return this[incomingKey].method || "GET";
169
+ },
170
+ get url() {
171
+ return this[urlKey];
172
+ },
173
+ get headers() {
174
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
175
+ },
176
+ [getAbortController]() {
177
+ this[getRequestCache]();
178
+ return this[abortControllerKey];
179
+ },
180
+ [getRequestCache]() {
181
+ this[abortControllerKey] ||= new AbortController();
182
+ return this[requestCache] ||= newRequestFromIncoming(
183
+ this.method,
184
+ this[urlKey],
185
+ this.headers,
186
+ this[incomingKey],
187
+ this[abortControllerKey]
188
+ );
189
+ }
190
+ };
191
+ [
192
+ "body",
193
+ "bodyUsed",
194
+ "cache",
195
+ "credentials",
196
+ "destination",
197
+ "integrity",
198
+ "mode",
199
+ "redirect",
200
+ "referrer",
201
+ "referrerPolicy",
202
+ "signal",
203
+ "keepalive"
204
+ ].forEach((k) => {
205
+ Object.defineProperty(requestPrototype, k, {
206
+ get() {
207
+ return this[getRequestCache]()[k];
208
+ }
209
+ });
210
+ });
211
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
212
+ Object.defineProperty(requestPrototype, k, {
213
+ value: function() {
214
+ return this[getRequestCache]()[k]();
215
+ }
216
+ });
217
+ });
218
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
219
+ newRequest = (incoming, defaultHostname) => {
220
+ const req = Object.create(requestPrototype);
221
+ req[incomingKey] = incoming;
222
+ const incomingUrl = incoming.url || "";
223
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
224
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
225
+ if (incoming instanceof Http2ServerRequest) {
226
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
227
+ }
67
228
  try {
68
- const { name, arguments: args } = request.params;
69
- const result = await (0, index_js_2.handleToolCall)(name, args, connpassClient);
70
- return (0, apps_sdk_js_1.buildCallToolResult)({
71
- toolName: name,
72
- result,
73
- includeAppsSdkPayload: appsSdkOutputEnabled,
229
+ const url2 = new URL(incomingUrl);
230
+ req[urlKey] = url2.href;
231
+ } catch (e) {
232
+ throw new RequestError("Invalid absolute URL", { cause: e });
233
+ }
234
+ return req;
235
+ }
236
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
237
+ if (!host) {
238
+ throw new RequestError("Missing host header");
239
+ }
240
+ let scheme;
241
+ if (incoming instanceof Http2ServerRequest) {
242
+ scheme = incoming.scheme;
243
+ if (!(scheme === "http" || scheme === "https")) {
244
+ throw new RequestError("Unsupported scheme");
245
+ }
246
+ } else {
247
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
248
+ }
249
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
250
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
251
+ throw new RequestError("Invalid host header");
252
+ }
253
+ req[urlKey] = url.href;
254
+ return req;
255
+ };
256
+ responseCache = /* @__PURE__ */ Symbol("responseCache");
257
+ getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
258
+ cacheKey = /* @__PURE__ */ Symbol("cache");
259
+ GlobalResponse = global.Response;
260
+ Response2 = class _Response {
261
+ #body;
262
+ #init;
263
+ [getResponseCache]() {
264
+ delete this[cacheKey];
265
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
266
+ }
267
+ constructor(body, init) {
268
+ let headers;
269
+ this.#body = body;
270
+ if (init instanceof _Response) {
271
+ const cachedGlobalResponse = init[responseCache];
272
+ if (cachedGlobalResponse) {
273
+ this.#init = cachedGlobalResponse;
274
+ this[getResponseCache]();
275
+ return;
276
+ } else {
277
+ this.#init = init.#init;
278
+ headers = new Headers(init.#init.headers);
279
+ }
280
+ } else {
281
+ this.#init = init;
282
+ }
283
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
284
+ headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
285
+ this[cacheKey] = [init?.status || 200, body, headers];
286
+ }
287
+ }
288
+ get headers() {
289
+ const cache = this[cacheKey];
290
+ if (cache) {
291
+ if (!(cache[2] instanceof Headers)) {
292
+ cache[2] = new Headers(cache[2]);
293
+ }
294
+ return cache[2];
295
+ }
296
+ return this[getResponseCache]().headers;
297
+ }
298
+ get status() {
299
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
300
+ }
301
+ get ok() {
302
+ const status = this.status;
303
+ return status >= 200 && status < 300;
304
+ }
305
+ };
306
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
307
+ Object.defineProperty(Response2.prototype, k, {
308
+ get() {
309
+ return this[getResponseCache]()[k];
310
+ }
311
+ });
312
+ });
313
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
314
+ Object.defineProperty(Response2.prototype, k, {
315
+ value: function() {
316
+ return this[getResponseCache]()[k]();
317
+ }
318
+ });
319
+ });
320
+ Object.setPrototypeOf(Response2, GlobalResponse);
321
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
322
+ buildOutgoingHttpHeaders = (headers) => {
323
+ const res = {};
324
+ if (!(headers instanceof Headers)) {
325
+ headers = new Headers(headers ?? void 0);
326
+ }
327
+ const cookies = [];
328
+ for (const [k, v] of headers) {
329
+ if (k === "set-cookie") {
330
+ cookies.push(v);
331
+ } else {
332
+ res[k] = v;
333
+ }
334
+ }
335
+ if (cookies.length > 0) {
336
+ res["set-cookie"] = cookies;
337
+ }
338
+ res["content-type"] ??= "text/plain; charset=UTF-8";
339
+ return res;
340
+ };
341
+ X_ALREADY_SENT = "x-hono-already-sent";
342
+ webFetch = global.fetch;
343
+ if (typeof global.crypto === "undefined") {
344
+ global.crypto = crypto;
345
+ }
346
+ global.fetch = (info, init) => {
347
+ init = {
348
+ // Disable compression handling so people can return the result of a fetch
349
+ // directly in the loader without messing with the Content-Encoding header.
350
+ compress: false,
351
+ ...init
352
+ };
353
+ return webFetch(info, init);
354
+ };
355
+ outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
356
+ handleRequestError = () => new Response(null, {
357
+ status: 400
358
+ });
359
+ handleFetchError = (e) => new Response(null, {
360
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
361
+ });
362
+ handleResponseError = (e, outgoing) => {
363
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
364
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
365
+ console.info("The user aborted a request.");
366
+ } else {
367
+ console.error(e);
368
+ if (!outgoing.headersSent) {
369
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
370
+ }
371
+ outgoing.end(`Error: ${err.message}`);
372
+ outgoing.destroy(err);
373
+ }
374
+ };
375
+ flushHeaders = (outgoing) => {
376
+ if ("flushHeaders" in outgoing && outgoing.writable) {
377
+ outgoing.flushHeaders();
378
+ }
379
+ };
380
+ responseViaCache = async (res, outgoing) => {
381
+ let [status, body, header] = res[cacheKey];
382
+ if (header instanceof Headers) {
383
+ header = buildOutgoingHttpHeaders(header);
384
+ }
385
+ if (typeof body === "string") {
386
+ header["Content-Length"] = Buffer.byteLength(body);
387
+ } else if (body instanceof Uint8Array) {
388
+ header["Content-Length"] = body.byteLength;
389
+ } else if (body instanceof Blob) {
390
+ header["Content-Length"] = body.size;
391
+ }
392
+ outgoing.writeHead(status, header);
393
+ if (typeof body === "string" || body instanceof Uint8Array) {
394
+ outgoing.end(body);
395
+ } else if (body instanceof Blob) {
396
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
397
+ } else {
398
+ flushHeaders(outgoing);
399
+ await writeFromReadableStream(body, outgoing)?.catch(
400
+ (e) => handleResponseError(e, outgoing)
401
+ );
402
+ }
403
+ ;
404
+ outgoing[outgoingEnded]?.();
405
+ };
406
+ isPromise = (res) => typeof res.then === "function";
407
+ responseViaResponseObject = async (res, outgoing, options = {}) => {
408
+ if (isPromise(res)) {
409
+ if (options.errorHandler) {
410
+ try {
411
+ res = await res;
412
+ } catch (err) {
413
+ const errRes = await options.errorHandler(err);
414
+ if (!errRes) {
415
+ return;
416
+ }
417
+ res = errRes;
418
+ }
419
+ } else {
420
+ res = await res.catch(handleFetchError);
421
+ }
422
+ }
423
+ if (cacheKey in res) {
424
+ return responseViaCache(res, outgoing);
425
+ }
426
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
427
+ if (res.body) {
428
+ const reader = res.body.getReader();
429
+ const values = [];
430
+ let done = false;
431
+ let currentReadPromise = void 0;
432
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
433
+ let maxReadCount = 2;
434
+ for (let i = 0; i < maxReadCount; i++) {
435
+ currentReadPromise ||= reader.read();
436
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
437
+ console.error(e);
438
+ done = true;
74
439
  });
440
+ if (!chunk) {
441
+ if (i === 1) {
442
+ await new Promise((resolve) => setTimeout(resolve));
443
+ maxReadCount = 3;
444
+ continue;
445
+ }
446
+ break;
447
+ }
448
+ currentReadPromise = void 0;
449
+ if (chunk.value) {
450
+ values.push(chunk.value);
451
+ }
452
+ if (chunk.done) {
453
+ done = true;
454
+ break;
455
+ }
456
+ }
457
+ if (done && !("content-length" in resHeaderRecord)) {
458
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
459
+ }
460
+ }
461
+ outgoing.writeHead(res.status, resHeaderRecord);
462
+ values.forEach((value) => {
463
+ ;
464
+ outgoing.write(value);
465
+ });
466
+ if (done) {
467
+ outgoing.end();
468
+ } else {
469
+ if (values.length === 0) {
470
+ flushHeaders(outgoing);
471
+ }
472
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
75
473
  }
76
- catch (error) {
77
- return {
78
- content: [
79
- {
80
- type: "text",
81
- text: `Error: ${error instanceof Error ? error.message : String(error)}`,
82
- },
83
- ],
84
- isError: true,
85
- };
86
- }
87
- });
88
- return server;
89
- }
90
- function parseArgs() {
91
- const args = process.argv.slice(2);
92
- let transport = "http"; // Default transport
93
- let port = 3000;
94
- for (let i = 0; i < args.length; i++) {
95
- const arg = args[i];
96
- if (arg === "--transport" || arg === "-t") {
97
- const value = args[i + 1];
98
- if (value && !value.startsWith("-")) {
99
- transport = value.toLowerCase();
100
- i++;
101
- }
102
- }
103
- else if (arg === "--port" || arg === "-p") {
104
- const value = args[i + 1];
105
- if (value && !value.startsWith("-")) {
106
- const parsed = Number.parseInt(value, 10);
107
- if (Number.isFinite(parsed)) {
108
- port = parsed;
474
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
475
+ } else {
476
+ outgoing.writeHead(res.status, resHeaderRecord);
477
+ outgoing.end();
478
+ }
479
+ ;
480
+ outgoing[outgoingEnded]?.();
481
+ };
482
+ getRequestListener = (fetchCallback, options = {}) => {
483
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
484
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
485
+ Object.defineProperty(global, "Request", {
486
+ value: Request2
487
+ });
488
+ Object.defineProperty(global, "Response", {
489
+ value: Response2
490
+ });
491
+ }
492
+ return async (incoming, outgoing) => {
493
+ let res, req;
494
+ try {
495
+ req = newRequest(incoming, options.hostname);
496
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
497
+ if (!incomingEnded) {
498
+ ;
499
+ incoming[wrapBodyStream] = true;
500
+ incoming.on("end", () => {
501
+ incomingEnded = true;
502
+ });
503
+ if (incoming instanceof Http2ServerRequest2) {
504
+ ;
505
+ outgoing[outgoingEnded] = () => {
506
+ if (!incomingEnded) {
507
+ setTimeout(() => {
508
+ if (!incomingEnded) {
509
+ setTimeout(() => {
510
+ incoming.destroy();
511
+ outgoing.destroy();
512
+ });
513
+ }
514
+ });
515
+ }
516
+ };
517
+ }
518
+ }
519
+ outgoing.on("close", () => {
520
+ const abortController = req[abortControllerKey];
521
+ if (abortController) {
522
+ if (incoming.errored) {
523
+ req[abortControllerKey].abort(incoming.errored.toString());
524
+ } else if (!outgoing.writableFinished) {
525
+ req[abortControllerKey].abort("Client connection prematurely closed.");
526
+ }
527
+ }
528
+ if (!incomingEnded) {
529
+ setTimeout(() => {
530
+ if (!incomingEnded) {
531
+ setTimeout(() => {
532
+ incoming.destroy();
533
+ });
109
534
  }
110
- i++;
535
+ });
536
+ }
537
+ });
538
+ res = fetchCallback(req, { incoming, outgoing });
539
+ if (cacheKey in res) {
540
+ return responseViaCache(res, outgoing);
541
+ }
542
+ } catch (e) {
543
+ if (!res) {
544
+ if (options.errorHandler) {
545
+ res = await options.errorHandler(req ? e : toRequestError(e));
546
+ if (!res) {
547
+ return;
548
+ }
549
+ } else if (!req) {
550
+ res = handleRequestError();
551
+ } else {
552
+ res = handleFetchError(e);
111
553
  }
554
+ } else {
555
+ return handleResponseError(e, outgoing);
556
+ }
557
+ }
558
+ try {
559
+ return await responseViaResponseObject(res, outgoing, options);
560
+ } catch (e) {
561
+ return handleResponseError(e, outgoing);
562
+ }
563
+ };
564
+ };
565
+ createAdaptorServer = (options) => {
566
+ const fetchCallback = options.fetch;
567
+ const requestListener = getRequestListener(fetchCallback, {
568
+ hostname: options.hostname,
569
+ overrideGlobalObjects: options.overrideGlobalObjects,
570
+ autoCleanupIncoming: options.autoCleanupIncoming
571
+ });
572
+ const createServer2 = options.createServer || createServerHTTP;
573
+ const server2 = createServer2(options.serverOptions || {}, requestListener);
574
+ return server2;
575
+ };
576
+ serve = (options, listeningListener) => {
577
+ const server2 = createAdaptorServer(options);
578
+ server2.listen(options?.port ?? 3e3, options.hostname, () => {
579
+ const serverInfo = server2.address();
580
+ listeningListener && listeningListener(serverInfo);
581
+ });
582
+ return server2;
583
+ };
584
+ }
585
+ });
586
+
587
+ // ../../packages/mcp-core/dist/config-schema.js
588
+ function parseCliFromDefs(defs, argv) {
589
+ const config2 = {};
590
+ const flagMap = /* @__PURE__ */ new Map();
591
+ const negationMap = /* @__PURE__ */ new Map();
592
+ for (const [key, def] of Object.entries(defs)) {
593
+ flagMap.set(def.cli, { key, def });
594
+ if (def.type === "boolean") {
595
+ const baseName = def.cli.replace(/^--/, "");
596
+ negationMap.set(`--no-${baseName}`, key);
597
+ }
598
+ }
599
+ for (let i = 0; i < argv.length; i++) {
600
+ const arg = argv[i];
601
+ const nextArg = argv[i + 1];
602
+ const negKey = negationMap.get(arg);
603
+ if (negKey !== void 0) {
604
+ config2[negKey] = false;
605
+ continue;
606
+ }
607
+ const entry = flagMap.get(arg);
608
+ if (!entry)
609
+ continue;
610
+ const { key, def } = entry;
611
+ switch (def.type) {
612
+ case "boolean":
613
+ config2[key] = true;
614
+ break;
615
+ case "string":
616
+ if (nextArg && !nextArg.startsWith("-")) {
617
+ config2[key] = nextArg;
618
+ i++;
619
+ }
620
+ break;
621
+ case "number":
622
+ if (nextArg && !nextArg.startsWith("-")) {
623
+ const num = Number(nextArg);
624
+ if (Number.isFinite(num)) {
625
+ config2[key] = num;
626
+ }
627
+ i++;
628
+ }
629
+ break;
630
+ case "string[]":
631
+ if (nextArg && !nextArg.startsWith("-")) {
632
+ config2[key] = nextArg.split(",").map((s) => s.trim());
633
+ i++;
634
+ }
635
+ break;
636
+ }
637
+ }
638
+ return config2;
639
+ }
640
+ function parseEnvFromDefs(defs, env) {
641
+ const config2 = {};
642
+ for (const [key, def] of Object.entries(defs)) {
643
+ if (!def.env)
644
+ continue;
645
+ const val = env[def.env];
646
+ if (val === void 0)
647
+ continue;
648
+ switch (def.type) {
649
+ case "boolean":
650
+ if (val === "true")
651
+ config2[key] = true;
652
+ else if (val === "false")
653
+ config2[key] = false;
654
+ break;
655
+ case "number": {
656
+ if (val === "")
657
+ break;
658
+ const num = Number(val);
659
+ if (Number.isFinite(num))
660
+ config2[key] = num;
661
+ break;
662
+ }
663
+ case "string":
664
+ if (val)
665
+ config2[key] = val;
666
+ break;
667
+ case "string[]":
668
+ if (val)
669
+ config2[key] = val.split(",").map((s) => s.trim());
670
+ break;
671
+ }
672
+ }
673
+ return config2;
674
+ }
675
+ function getDefaultsFromDefs(defs) {
676
+ const defaults = {};
677
+ for (const [key, def] of Object.entries(defs)) {
678
+ if (def.default !== void 0) {
679
+ defaults[key] = def.default;
680
+ }
681
+ }
682
+ return defaults;
683
+ }
684
+ function generateHelp(defs, opts) {
685
+ const lines = [];
686
+ if (opts?.usage) {
687
+ lines.push(`Usage: ${opts.usage}`);
688
+ lines.push("");
689
+ }
690
+ lines.push("Options:");
691
+ lines.push(" --help, -h Show this help message");
692
+ lines.push(" --version, -v Show version number");
693
+ lines.push(" --init Generate .voicevoxrc.json with default settings");
694
+ lines.push("");
695
+ const groups = /* @__PURE__ */ new Map();
696
+ for (const [key, def] of Object.entries(defs)) {
697
+ const group = def.group;
698
+ if (!groups.has(group))
699
+ groups.set(group, []);
700
+ groups.get(group).push({ key, def });
701
+ }
702
+ for (const [groupName, entries] of groups) {
703
+ lines.push(` ${groupName}:`);
704
+ for (const { def } of entries) {
705
+ const flag = def.type === "boolean" ? def.cli : `${def.cli} ${def.valueName || "<value>"}`;
706
+ const defaultStr = def.default !== void 0 ? ` (default: ${Array.isArray(def.default) ? def.default.join(",") : def.default})` : "";
707
+ const line = ` ${flag.padEnd(28)}${def.description}${defaultStr}`;
708
+ lines.push(line);
709
+ if (def.type === "boolean") {
710
+ const baseName = def.cli.replace(/^--/, "");
711
+ const negFlag = `--no-${baseName}`;
712
+ lines.push(` ${negFlag.padEnd(28)}Disable ${def.description.toLowerCase().replace(/^enable /, "")}`);
713
+ }
714
+ }
715
+ lines.push("");
716
+ }
717
+ if (opts?.examples?.length) {
718
+ lines.push("Examples:");
719
+ for (const ex of opts.examples) {
720
+ lines.push(` ${ex}`);
721
+ }
722
+ lines.push("");
723
+ }
724
+ return lines.join("\n");
725
+ }
726
+ function filterUndefined(obj) {
727
+ return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== void 0));
728
+ }
729
+
730
+ // ../../packages/mcp-core/dist/config.js
731
+ var baseConfigDefs = {
732
+ httpMode: {
733
+ cli: "--http",
734
+ env: "MCP_HTTP_MODE",
735
+ description: "Enable HTTP server mode",
736
+ group: "Server Options",
737
+ type: "boolean",
738
+ default: false
739
+ },
740
+ httpPort: {
741
+ cli: "--port",
742
+ env: "MCP_HTTP_PORT",
743
+ description: "HTTP server port",
744
+ group: "Server Options",
745
+ type: "number",
746
+ default: 3e3,
747
+ valueName: "<port>"
748
+ },
749
+ httpHost: {
750
+ cli: "--host",
751
+ env: "MCP_HTTP_HOST",
752
+ description: "HTTP server host",
753
+ group: "Server Options",
754
+ type: "string",
755
+ default: "0.0.0.0",
756
+ valueName: "<host>"
757
+ },
758
+ allowedHosts: {
759
+ cli: "--allowed-hosts",
760
+ env: "MCP_ALLOWED_HOSTS",
761
+ description: "Comma-separated list of allowed hosts",
762
+ group: "Server Options",
763
+ type: "string[]",
764
+ default: ["localhost", "127.0.0.1", "[::1]"],
765
+ valueName: "<hosts>"
766
+ },
767
+ allowedOrigins: {
768
+ cli: "--allowed-origins",
769
+ env: "MCP_ALLOWED_ORIGINS",
770
+ description: "Comma-separated list of allowed origins",
771
+ group: "Server Options",
772
+ type: "string[]",
773
+ default: [
774
+ "http://localhost",
775
+ "http://127.0.0.1",
776
+ "https://localhost",
777
+ "https://127.0.0.1"
778
+ ],
779
+ valueName: "<origins>"
780
+ },
781
+ apiKey: {
782
+ cli: "--api-key",
783
+ env: "MCP_API_KEY",
784
+ description: "Require matching API key via X-API-Key or Authorization: Bearer",
785
+ group: "Server Options",
786
+ type: "string",
787
+ valueName: "<key>"
788
+ }
789
+ };
790
+ var defaultBaseConfig = getDefaultsFromDefs(baseConfigDefs);
791
+
792
+ // ../../packages/mcp-core/dist/session.js
793
+ var sessionConfigs = /* @__PURE__ */ new Map();
794
+ function deleteSessionConfig(sessionId) {
795
+ sessionConfigs.delete(sessionId);
796
+ }
797
+
798
+ // ../../packages/mcp-core/dist/http.js
799
+ import { randomUUID } from "crypto";
800
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
801
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
802
+
803
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/compose.js
804
+ var compose = (middleware, onError, onNotFound) => {
805
+ return (context, next) => {
806
+ let index = -1;
807
+ return dispatch(0);
808
+ async function dispatch(i) {
809
+ if (i <= index) {
810
+ throw new Error("next() called multiple times");
811
+ }
812
+ index = i;
813
+ let res;
814
+ let isError = false;
815
+ let handler;
816
+ if (middleware[i]) {
817
+ handler = middleware[i][0][0];
818
+ context.req.routeIndex = i;
819
+ } else {
820
+ handler = i === middleware.length && next || void 0;
821
+ }
822
+ if (handler) {
823
+ try {
824
+ res = await handler(context, () => dispatch(i + 1));
825
+ } catch (err) {
826
+ if (err instanceof Error && onError) {
827
+ context.error = err;
828
+ res = await onError(err, context);
829
+ isError = true;
830
+ } else {
831
+ throw err;
832
+ }
833
+ }
834
+ } else {
835
+ if (context.finalized === false && onNotFound) {
836
+ res = await onNotFound(context);
837
+ }
838
+ }
839
+ if (res && (context.finalized === false || isError)) {
840
+ context.res = res;
841
+ }
842
+ return context;
843
+ }
844
+ };
845
+ };
846
+
847
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/request/constants.js
848
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
849
+
850
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/body.js
851
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
852
+ const { all = false, dot = false } = options;
853
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
854
+ const contentType = headers.get("Content-Type");
855
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
856
+ return parseFormData(request, { all, dot });
857
+ }
858
+ return {};
859
+ };
860
+ async function parseFormData(request, options) {
861
+ const formData = await request.formData();
862
+ if (formData) {
863
+ return convertFormDataToBodyData(formData, options);
864
+ }
865
+ return {};
866
+ }
867
+ function convertFormDataToBodyData(formData, options) {
868
+ const form = /* @__PURE__ */ Object.create(null);
869
+ formData.forEach((value, key) => {
870
+ const shouldParseAllValues = options.all || key.endsWith("[]");
871
+ if (!shouldParseAllValues) {
872
+ form[key] = value;
873
+ } else {
874
+ handleParsingAllValues(form, key, value);
875
+ }
876
+ });
877
+ if (options.dot) {
878
+ Object.entries(form).forEach(([key, value]) => {
879
+ const shouldParseDotValues = key.includes(".");
880
+ if (shouldParseDotValues) {
881
+ handleParsingNestedValues(form, key, value);
882
+ delete form[key];
883
+ }
884
+ });
885
+ }
886
+ return form;
887
+ }
888
+ var handleParsingAllValues = (form, key, value) => {
889
+ if (form[key] !== void 0) {
890
+ if (Array.isArray(form[key])) {
891
+ ;
892
+ form[key].push(value);
893
+ } else {
894
+ form[key] = [form[key], value];
895
+ }
896
+ } else {
897
+ if (!key.endsWith("[]")) {
898
+ form[key] = value;
899
+ } else {
900
+ form[key] = [value];
901
+ }
902
+ }
903
+ };
904
+ var handleParsingNestedValues = (form, key, value) => {
905
+ let nestedForm = form;
906
+ const keys = key.split(".");
907
+ keys.forEach((key2, index) => {
908
+ if (index === keys.length - 1) {
909
+ nestedForm[key2] = value;
910
+ } else {
911
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
912
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
913
+ }
914
+ nestedForm = nestedForm[key2];
915
+ }
916
+ });
917
+ };
918
+
919
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/url.js
920
+ var splitPath = (path) => {
921
+ const paths = path.split("/");
922
+ if (paths[0] === "") {
923
+ paths.shift();
924
+ }
925
+ return paths;
926
+ };
927
+ var splitRoutingPath = (routePath) => {
928
+ const { groups, path } = extractGroupsFromPath(routePath);
929
+ const paths = splitPath(path);
930
+ return replaceGroupMarks(paths, groups);
931
+ };
932
+ var extractGroupsFromPath = (path) => {
933
+ const groups = [];
934
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
935
+ const mark = `@${index}`;
936
+ groups.push([mark, match2]);
937
+ return mark;
938
+ });
939
+ return { groups, path };
940
+ };
941
+ var replaceGroupMarks = (paths, groups) => {
942
+ for (let i = groups.length - 1; i >= 0; i--) {
943
+ const [mark] = groups[i];
944
+ for (let j = paths.length - 1; j >= 0; j--) {
945
+ if (paths[j].includes(mark)) {
946
+ paths[j] = paths[j].replace(mark, groups[i][1]);
947
+ break;
948
+ }
949
+ }
950
+ }
951
+ return paths;
952
+ };
953
+ var patternCache = {};
954
+ var getPattern = (label, next) => {
955
+ if (label === "*") {
956
+ return "*";
957
+ }
958
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
959
+ if (match2) {
960
+ const cacheKey2 = `${label}#${next}`;
961
+ if (!patternCache[cacheKey2]) {
962
+ if (match2[2]) {
963
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
964
+ } else {
965
+ patternCache[cacheKey2] = [label, match2[1], true];
966
+ }
967
+ }
968
+ return patternCache[cacheKey2];
969
+ }
970
+ return null;
971
+ };
972
+ var tryDecode = (str, decoder) => {
973
+ try {
974
+ return decoder(str);
975
+ } catch {
976
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
977
+ try {
978
+ return decoder(match2);
979
+ } catch {
980
+ return match2;
981
+ }
982
+ });
983
+ }
984
+ };
985
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
986
+ var getPath = (request) => {
987
+ const url = request.url;
988
+ const start = url.indexOf("/", url.indexOf(":") + 4);
989
+ let i = start;
990
+ for (; i < url.length; i++) {
991
+ const charCode = url.charCodeAt(i);
992
+ if (charCode === 37) {
993
+ const queryIndex = url.indexOf("?", i);
994
+ const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
995
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
996
+ } else if (charCode === 63) {
997
+ break;
998
+ }
999
+ }
1000
+ return url.slice(start, i);
1001
+ };
1002
+ var getPathNoStrict = (request) => {
1003
+ const result = getPath(request);
1004
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
1005
+ };
1006
+ var mergePath = (base, sub, ...rest) => {
1007
+ if (rest.length) {
1008
+ sub = mergePath(sub, ...rest);
1009
+ }
1010
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
1011
+ };
1012
+ var checkOptionalParameter = (path) => {
1013
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
1014
+ return null;
1015
+ }
1016
+ const segments = path.split("/");
1017
+ const results = [];
1018
+ let basePath = "";
1019
+ segments.forEach((segment) => {
1020
+ if (segment !== "" && !/\:/.test(segment)) {
1021
+ basePath += "/" + segment;
1022
+ } else if (/\:/.test(segment)) {
1023
+ if (/\?/.test(segment)) {
1024
+ if (results.length === 0 && basePath === "") {
1025
+ results.push("/");
1026
+ } else {
1027
+ results.push(basePath);
1028
+ }
1029
+ const optionalSegment = segment.replace("?", "");
1030
+ basePath += "/" + optionalSegment;
1031
+ results.push(basePath);
1032
+ } else {
1033
+ basePath += "/" + segment;
1034
+ }
1035
+ }
1036
+ });
1037
+ return results.filter((v, i, a) => a.indexOf(v) === i);
1038
+ };
1039
+ var _decodeURI = (value) => {
1040
+ if (!/[%+]/.test(value)) {
1041
+ return value;
1042
+ }
1043
+ if (value.indexOf("+") !== -1) {
1044
+ value = value.replace(/\+/g, " ");
1045
+ }
1046
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
1047
+ };
1048
+ var _getQueryParam = (url, key, multiple) => {
1049
+ let encoded;
1050
+ if (!multiple && key && !/[%+]/.test(key)) {
1051
+ let keyIndex2 = url.indexOf("?", 8);
1052
+ if (keyIndex2 === -1) {
1053
+ return void 0;
1054
+ }
1055
+ if (!url.startsWith(key, keyIndex2 + 1)) {
1056
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1057
+ }
1058
+ while (keyIndex2 !== -1) {
1059
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
1060
+ if (trailingKeyCode === 61) {
1061
+ const valueIndex = keyIndex2 + key.length + 2;
1062
+ const endIndex = url.indexOf("&", valueIndex);
1063
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
1064
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
1065
+ return "";
1066
+ }
1067
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
1068
+ }
1069
+ encoded = /[%+]/.test(url);
1070
+ if (!encoded) {
1071
+ return void 0;
1072
+ }
1073
+ }
1074
+ const results = {};
1075
+ encoded ??= /[%+]/.test(url);
1076
+ let keyIndex = url.indexOf("?", 8);
1077
+ while (keyIndex !== -1) {
1078
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
1079
+ let valueIndex = url.indexOf("=", keyIndex);
1080
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
1081
+ valueIndex = -1;
1082
+ }
1083
+ let name = url.slice(
1084
+ keyIndex + 1,
1085
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
1086
+ );
1087
+ if (encoded) {
1088
+ name = _decodeURI(name);
1089
+ }
1090
+ keyIndex = nextKeyIndex;
1091
+ if (name === "") {
1092
+ continue;
1093
+ }
1094
+ let value;
1095
+ if (valueIndex === -1) {
1096
+ value = "";
1097
+ } else {
1098
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
1099
+ if (encoded) {
1100
+ value = _decodeURI(value);
1101
+ }
1102
+ }
1103
+ if (multiple) {
1104
+ if (!(results[name] && Array.isArray(results[name]))) {
1105
+ results[name] = [];
1106
+ }
1107
+ ;
1108
+ results[name].push(value);
1109
+ } else {
1110
+ results[name] ??= value;
1111
+ }
1112
+ }
1113
+ return key ? results[key] : results;
1114
+ };
1115
+ var getQueryParam = _getQueryParam;
1116
+ var getQueryParams = (url, key) => {
1117
+ return _getQueryParam(url, key, true);
1118
+ };
1119
+ var decodeURIComponent_ = decodeURIComponent;
1120
+
1121
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/request.js
1122
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
1123
+ var HonoRequest = class {
1124
+ /**
1125
+ * `.raw` can get the raw Request object.
1126
+ *
1127
+ * @see {@link https://hono.dev/docs/api/request#raw}
1128
+ *
1129
+ * @example
1130
+ * ```ts
1131
+ * // For Cloudflare Workers
1132
+ * app.post('/', async (c) => {
1133
+ * const metadata = c.req.raw.cf?.hostMetadata?
1134
+ * ...
1135
+ * })
1136
+ * ```
1137
+ */
1138
+ raw;
1139
+ #validatedData;
1140
+ // Short name of validatedData
1141
+ #matchResult;
1142
+ routeIndex = 0;
1143
+ /**
1144
+ * `.path` can get the pathname of the request.
1145
+ *
1146
+ * @see {@link https://hono.dev/docs/api/request#path}
1147
+ *
1148
+ * @example
1149
+ * ```ts
1150
+ * app.get('/about/me', (c) => {
1151
+ * const pathname = c.req.path // `/about/me`
1152
+ * })
1153
+ * ```
1154
+ */
1155
+ path;
1156
+ bodyCache = {};
1157
+ constructor(request, path = "/", matchResult = [[]]) {
1158
+ this.raw = request;
1159
+ this.path = path;
1160
+ this.#matchResult = matchResult;
1161
+ this.#validatedData = {};
1162
+ }
1163
+ param(key) {
1164
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1165
+ }
1166
+ #getDecodedParam(key) {
1167
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1168
+ const param = this.#getParamValue(paramKey);
1169
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1170
+ }
1171
+ #getAllDecodedParams() {
1172
+ const decoded = {};
1173
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1174
+ for (const key of keys) {
1175
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1176
+ if (value !== void 0) {
1177
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1178
+ }
1179
+ }
1180
+ return decoded;
1181
+ }
1182
+ #getParamValue(paramKey) {
1183
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1184
+ }
1185
+ query(key) {
1186
+ return getQueryParam(this.url, key);
1187
+ }
1188
+ queries(key) {
1189
+ return getQueryParams(this.url, key);
1190
+ }
1191
+ header(name) {
1192
+ if (name) {
1193
+ return this.raw.headers.get(name) ?? void 0;
1194
+ }
1195
+ const headerData = {};
1196
+ this.raw.headers.forEach((value, key) => {
1197
+ headerData[key] = value;
1198
+ });
1199
+ return headerData;
1200
+ }
1201
+ async parseBody(options) {
1202
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
1203
+ }
1204
+ #cachedBody = (key) => {
1205
+ const { bodyCache, raw: raw2 } = this;
1206
+ const cachedBody = bodyCache[key];
1207
+ if (cachedBody) {
1208
+ return cachedBody;
1209
+ }
1210
+ const anyCachedKey = Object.keys(bodyCache)[0];
1211
+ if (anyCachedKey) {
1212
+ return bodyCache[anyCachedKey].then((body) => {
1213
+ if (anyCachedKey === "json") {
1214
+ body = JSON.stringify(body);
1215
+ }
1216
+ return new Response(body)[key]();
1217
+ });
1218
+ }
1219
+ return bodyCache[key] = raw2[key]();
1220
+ };
1221
+ /**
1222
+ * `.json()` can parse Request body of type `application/json`
1223
+ *
1224
+ * @see {@link https://hono.dev/docs/api/request#json}
1225
+ *
1226
+ * @example
1227
+ * ```ts
1228
+ * app.post('/entry', async (c) => {
1229
+ * const body = await c.req.json()
1230
+ * })
1231
+ * ```
1232
+ */
1233
+ json() {
1234
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
1235
+ }
1236
+ /**
1237
+ * `.text()` can parse Request body of type `text/plain`
1238
+ *
1239
+ * @see {@link https://hono.dev/docs/api/request#text}
1240
+ *
1241
+ * @example
1242
+ * ```ts
1243
+ * app.post('/entry', async (c) => {
1244
+ * const body = await c.req.text()
1245
+ * })
1246
+ * ```
1247
+ */
1248
+ text() {
1249
+ return this.#cachedBody("text");
1250
+ }
1251
+ /**
1252
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1253
+ *
1254
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1255
+ *
1256
+ * @example
1257
+ * ```ts
1258
+ * app.post('/entry', async (c) => {
1259
+ * const body = await c.req.arrayBuffer()
1260
+ * })
1261
+ * ```
1262
+ */
1263
+ arrayBuffer() {
1264
+ return this.#cachedBody("arrayBuffer");
1265
+ }
1266
+ /**
1267
+ * Parses the request body as a `Blob`.
1268
+ * @example
1269
+ * ```ts
1270
+ * app.post('/entry', async (c) => {
1271
+ * const body = await c.req.blob();
1272
+ * });
1273
+ * ```
1274
+ * @see https://hono.dev/docs/api/request#blob
1275
+ */
1276
+ blob() {
1277
+ return this.#cachedBody("blob");
1278
+ }
1279
+ /**
1280
+ * Parses the request body as `FormData`.
1281
+ * @example
1282
+ * ```ts
1283
+ * app.post('/entry', async (c) => {
1284
+ * const body = await c.req.formData();
1285
+ * });
1286
+ * ```
1287
+ * @see https://hono.dev/docs/api/request#formdata
1288
+ */
1289
+ formData() {
1290
+ return this.#cachedBody("formData");
1291
+ }
1292
+ /**
1293
+ * Adds validated data to the request.
1294
+ *
1295
+ * @param target - The target of the validation.
1296
+ * @param data - The validated data to add.
1297
+ */
1298
+ addValidatedData(target, data) {
1299
+ this.#validatedData[target] = data;
1300
+ }
1301
+ valid(target) {
1302
+ return this.#validatedData[target];
1303
+ }
1304
+ /**
1305
+ * `.url()` can get the request url strings.
1306
+ *
1307
+ * @see {@link https://hono.dev/docs/api/request#url}
1308
+ *
1309
+ * @example
1310
+ * ```ts
1311
+ * app.get('/about/me', (c) => {
1312
+ * const url = c.req.url // `http://localhost:8787/about/me`
1313
+ * ...
1314
+ * })
1315
+ * ```
1316
+ */
1317
+ get url() {
1318
+ return this.raw.url;
1319
+ }
1320
+ /**
1321
+ * `.method()` can get the method name of the request.
1322
+ *
1323
+ * @see {@link https://hono.dev/docs/api/request#method}
1324
+ *
1325
+ * @example
1326
+ * ```ts
1327
+ * app.get('/about/me', (c) => {
1328
+ * const method = c.req.method // `GET`
1329
+ * })
1330
+ * ```
1331
+ */
1332
+ get method() {
1333
+ return this.raw.method;
1334
+ }
1335
+ get [GET_MATCH_RESULT]() {
1336
+ return this.#matchResult;
1337
+ }
1338
+ /**
1339
+ * `.matchedRoutes()` can return a matched route in the handler
1340
+ *
1341
+ * @deprecated
1342
+ *
1343
+ * Use matchedRoutes helper defined in "hono/route" instead.
1344
+ *
1345
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1346
+ *
1347
+ * @example
1348
+ * ```ts
1349
+ * app.use('*', async function logger(c, next) {
1350
+ * await next()
1351
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1352
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1353
+ * console.log(
1354
+ * method,
1355
+ * ' ',
1356
+ * path,
1357
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1358
+ * name,
1359
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1360
+ * )
1361
+ * })
1362
+ * })
1363
+ * ```
1364
+ */
1365
+ get matchedRoutes() {
1366
+ return this.#matchResult[0].map(([[, route]]) => route);
1367
+ }
1368
+ /**
1369
+ * `routePath()` can retrieve the path registered within the handler
1370
+ *
1371
+ * @deprecated
1372
+ *
1373
+ * Use routePath helper defined in "hono/route" instead.
1374
+ *
1375
+ * @see {@link https://hono.dev/docs/api/request#routepath}
1376
+ *
1377
+ * @example
1378
+ * ```ts
1379
+ * app.get('/posts/:id', (c) => {
1380
+ * return c.json({ path: c.req.routePath })
1381
+ * })
1382
+ * ```
1383
+ */
1384
+ get routePath() {
1385
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1386
+ }
1387
+ };
1388
+
1389
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/html.js
1390
+ var HtmlEscapedCallbackPhase = {
1391
+ Stringify: 1,
1392
+ BeforeStream: 2,
1393
+ Stream: 3
1394
+ };
1395
+ var raw = (value, callbacks) => {
1396
+ const escapedString = new String(value);
1397
+ escapedString.isEscaped = true;
1398
+ escapedString.callbacks = callbacks;
1399
+ return escapedString;
1400
+ };
1401
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1402
+ if (typeof str === "object" && !(str instanceof String)) {
1403
+ if (!(str instanceof Promise)) {
1404
+ str = str.toString();
1405
+ }
1406
+ if (str instanceof Promise) {
1407
+ str = await str;
1408
+ }
1409
+ }
1410
+ const callbacks = str.callbacks;
1411
+ if (!callbacks?.length) {
1412
+ return Promise.resolve(str);
1413
+ }
1414
+ if (buffer) {
1415
+ buffer[0] += str;
1416
+ } else {
1417
+ buffer = [str];
1418
+ }
1419
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1420
+ (res) => Promise.all(
1421
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1422
+ ).then(() => buffer[0])
1423
+ );
1424
+ if (preserveCallbacks) {
1425
+ return raw(await resStr, callbacks);
1426
+ } else {
1427
+ return resStr;
1428
+ }
1429
+ };
1430
+
1431
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/context.js
1432
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
1433
+ var setDefaultContentType = (contentType, headers) => {
1434
+ return {
1435
+ "Content-Type": contentType,
1436
+ ...headers
1437
+ };
1438
+ };
1439
+ var Context = class {
1440
+ #rawRequest;
1441
+ #req;
1442
+ /**
1443
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1444
+ *
1445
+ * @see {@link https://hono.dev/docs/api/context#env}
1446
+ *
1447
+ * @example
1448
+ * ```ts
1449
+ * // Environment object for Cloudflare Workers
1450
+ * app.get('*', async c => {
1451
+ * const counter = c.env.COUNTER
1452
+ * })
1453
+ * ```
1454
+ */
1455
+ env = {};
1456
+ #var;
1457
+ finalized = false;
1458
+ /**
1459
+ * `.error` can get the error object from the middleware if the Handler throws an error.
1460
+ *
1461
+ * @see {@link https://hono.dev/docs/api/context#error}
1462
+ *
1463
+ * @example
1464
+ * ```ts
1465
+ * app.use('*', async (c, next) => {
1466
+ * await next()
1467
+ * if (c.error) {
1468
+ * // do something...
1469
+ * }
1470
+ * })
1471
+ * ```
1472
+ */
1473
+ error;
1474
+ #status;
1475
+ #executionCtx;
1476
+ #res;
1477
+ #layout;
1478
+ #renderer;
1479
+ #notFoundHandler;
1480
+ #preparedHeaders;
1481
+ #matchResult;
1482
+ #path;
1483
+ /**
1484
+ * Creates an instance of the Context class.
1485
+ *
1486
+ * @param req - The Request object.
1487
+ * @param options - Optional configuration options for the context.
1488
+ */
1489
+ constructor(req, options) {
1490
+ this.#rawRequest = req;
1491
+ if (options) {
1492
+ this.#executionCtx = options.executionCtx;
1493
+ this.env = options.env;
1494
+ this.#notFoundHandler = options.notFoundHandler;
1495
+ this.#path = options.path;
1496
+ this.#matchResult = options.matchResult;
1497
+ }
1498
+ }
1499
+ /**
1500
+ * `.req` is the instance of {@link HonoRequest}.
1501
+ */
1502
+ get req() {
1503
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1504
+ return this.#req;
1505
+ }
1506
+ /**
1507
+ * @see {@link https://hono.dev/docs/api/context#event}
1508
+ * The FetchEvent associated with the current request.
1509
+ *
1510
+ * @throws Will throw an error if the context does not have a FetchEvent.
1511
+ */
1512
+ get event() {
1513
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1514
+ return this.#executionCtx;
1515
+ } else {
1516
+ throw Error("This context has no FetchEvent");
1517
+ }
1518
+ }
1519
+ /**
1520
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
1521
+ * The ExecutionContext associated with the current request.
1522
+ *
1523
+ * @throws Will throw an error if the context does not have an ExecutionContext.
1524
+ */
1525
+ get executionCtx() {
1526
+ if (this.#executionCtx) {
1527
+ return this.#executionCtx;
1528
+ } else {
1529
+ throw Error("This context has no ExecutionContext");
1530
+ }
1531
+ }
1532
+ /**
1533
+ * @see {@link https://hono.dev/docs/api/context#res}
1534
+ * The Response object for the current request.
1535
+ */
1536
+ get res() {
1537
+ return this.#res ||= new Response(null, {
1538
+ headers: this.#preparedHeaders ??= new Headers()
1539
+ });
1540
+ }
1541
+ /**
1542
+ * Sets the Response object for the current request.
1543
+ *
1544
+ * @param _res - The Response object to set.
1545
+ */
1546
+ set res(_res) {
1547
+ if (this.#res && _res) {
1548
+ _res = new Response(_res.body, _res);
1549
+ for (const [k, v] of this.#res.headers.entries()) {
1550
+ if (k === "content-type") {
1551
+ continue;
1552
+ }
1553
+ if (k === "set-cookie") {
1554
+ const cookies = this.#res.headers.getSetCookie();
1555
+ _res.headers.delete("set-cookie");
1556
+ for (const cookie of cookies) {
1557
+ _res.headers.append("set-cookie", cookie);
1558
+ }
1559
+ } else {
1560
+ _res.headers.set(k, v);
1561
+ }
1562
+ }
1563
+ }
1564
+ this.#res = _res;
1565
+ this.finalized = true;
1566
+ }
1567
+ /**
1568
+ * `.render()` can create a response within a layout.
1569
+ *
1570
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1571
+ *
1572
+ * @example
1573
+ * ```ts
1574
+ * app.get('/', (c) => {
1575
+ * return c.render('Hello!')
1576
+ * })
1577
+ * ```
1578
+ */
1579
+ render = (...args) => {
1580
+ this.#renderer ??= (content) => this.html(content);
1581
+ return this.#renderer(...args);
1582
+ };
1583
+ /**
1584
+ * Sets the layout for the response.
1585
+ *
1586
+ * @param layout - The layout to set.
1587
+ * @returns The layout function.
1588
+ */
1589
+ setLayout = (layout) => this.#layout = layout;
1590
+ /**
1591
+ * Gets the current layout for the response.
1592
+ *
1593
+ * @returns The current layout function.
1594
+ */
1595
+ getLayout = () => this.#layout;
1596
+ /**
1597
+ * `.setRenderer()` can set the layout in the custom middleware.
1598
+ *
1599
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1600
+ *
1601
+ * @example
1602
+ * ```tsx
1603
+ * app.use('*', async (c, next) => {
1604
+ * c.setRenderer((content) => {
1605
+ * return c.html(
1606
+ * <html>
1607
+ * <body>
1608
+ * <p>{content}</p>
1609
+ * </body>
1610
+ * </html>
1611
+ * )
1612
+ * })
1613
+ * await next()
1614
+ * })
1615
+ * ```
1616
+ */
1617
+ setRenderer = (renderer) => {
1618
+ this.#renderer = renderer;
1619
+ };
1620
+ /**
1621
+ * `.header()` can set headers.
1622
+ *
1623
+ * @see {@link https://hono.dev/docs/api/context#header}
1624
+ *
1625
+ * @example
1626
+ * ```ts
1627
+ * app.get('/welcome', (c) => {
1628
+ * // Set headers
1629
+ * c.header('X-Message', 'Hello!')
1630
+ * c.header('Content-Type', 'text/plain')
1631
+ *
1632
+ * return c.body('Thank you for coming')
1633
+ * })
1634
+ * ```
1635
+ */
1636
+ header = (name, value, options) => {
1637
+ if (this.finalized) {
1638
+ this.#res = new Response(this.#res.body, this.#res);
1639
+ }
1640
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1641
+ if (value === void 0) {
1642
+ headers.delete(name);
1643
+ } else if (options?.append) {
1644
+ headers.append(name, value);
1645
+ } else {
1646
+ headers.set(name, value);
1647
+ }
1648
+ };
1649
+ status = (status) => {
1650
+ this.#status = status;
1651
+ };
1652
+ /**
1653
+ * `.set()` can set the value specified by the key.
1654
+ *
1655
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1656
+ *
1657
+ * @example
1658
+ * ```ts
1659
+ * app.use('*', async (c, next) => {
1660
+ * c.set('message', 'Hono is hot!!')
1661
+ * await next()
1662
+ * })
1663
+ * ```
1664
+ */
1665
+ set = (key, value) => {
1666
+ this.#var ??= /* @__PURE__ */ new Map();
1667
+ this.#var.set(key, value);
1668
+ };
1669
+ /**
1670
+ * `.get()` can use the value specified by the key.
1671
+ *
1672
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1673
+ *
1674
+ * @example
1675
+ * ```ts
1676
+ * app.get('/', (c) => {
1677
+ * const message = c.get('message')
1678
+ * return c.text(`The message is "${message}"`)
1679
+ * })
1680
+ * ```
1681
+ */
1682
+ get = (key) => {
1683
+ return this.#var ? this.#var.get(key) : void 0;
1684
+ };
1685
+ /**
1686
+ * `.var` can access the value of a variable.
1687
+ *
1688
+ * @see {@link https://hono.dev/docs/api/context#var}
1689
+ *
1690
+ * @example
1691
+ * ```ts
1692
+ * const result = c.var.client.oneMethod()
1693
+ * ```
1694
+ */
1695
+ // c.var.propName is a read-only
1696
+ get var() {
1697
+ if (!this.#var) {
1698
+ return {};
1699
+ }
1700
+ return Object.fromEntries(this.#var);
1701
+ }
1702
+ #newResponse(data, arg, headers) {
1703
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1704
+ if (typeof arg === "object" && "headers" in arg) {
1705
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1706
+ for (const [key, value] of argHeaders) {
1707
+ if (key.toLowerCase() === "set-cookie") {
1708
+ responseHeaders.append(key, value);
1709
+ } else {
1710
+ responseHeaders.set(key, value);
1711
+ }
1712
+ }
1713
+ }
1714
+ if (headers) {
1715
+ for (const [k, v] of Object.entries(headers)) {
1716
+ if (typeof v === "string") {
1717
+ responseHeaders.set(k, v);
1718
+ } else {
1719
+ responseHeaders.delete(k);
1720
+ for (const v2 of v) {
1721
+ responseHeaders.append(k, v2);
1722
+ }
1723
+ }
1724
+ }
1725
+ }
1726
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1727
+ return new Response(data, { status, headers: responseHeaders });
1728
+ }
1729
+ newResponse = (...args) => this.#newResponse(...args);
1730
+ /**
1731
+ * `.body()` can return the HTTP response.
1732
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1733
+ * This can also be set in `.text()`, `.json()` and so on.
1734
+ *
1735
+ * @see {@link https://hono.dev/docs/api/context#body}
1736
+ *
1737
+ * @example
1738
+ * ```ts
1739
+ * app.get('/welcome', (c) => {
1740
+ * // Set headers
1741
+ * c.header('X-Message', 'Hello!')
1742
+ * c.header('Content-Type', 'text/plain')
1743
+ * // Set HTTP status code
1744
+ * c.status(201)
1745
+ *
1746
+ * // Return the response body
1747
+ * return c.body('Thank you for coming')
1748
+ * })
1749
+ * ```
1750
+ */
1751
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1752
+ /**
1753
+ * `.text()` can render text as `Content-Type:text/plain`.
1754
+ *
1755
+ * @see {@link https://hono.dev/docs/api/context#text}
1756
+ *
1757
+ * @example
1758
+ * ```ts
1759
+ * app.get('/say', (c) => {
1760
+ * return c.text('Hello!')
1761
+ * })
1762
+ * ```
1763
+ */
1764
+ text = (text, arg, headers) => {
1765
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1766
+ text,
1767
+ arg,
1768
+ setDefaultContentType(TEXT_PLAIN, headers)
1769
+ );
1770
+ };
1771
+ /**
1772
+ * `.json()` can render JSON as `Content-Type:application/json`.
1773
+ *
1774
+ * @see {@link https://hono.dev/docs/api/context#json}
1775
+ *
1776
+ * @example
1777
+ * ```ts
1778
+ * app.get('/api', (c) => {
1779
+ * return c.json({ message: 'Hello!' })
1780
+ * })
1781
+ * ```
1782
+ */
1783
+ json = (object, arg, headers) => {
1784
+ return this.#newResponse(
1785
+ JSON.stringify(object),
1786
+ arg,
1787
+ setDefaultContentType("application/json", headers)
1788
+ );
1789
+ };
1790
+ html = (html, arg, headers) => {
1791
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1792
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1793
+ };
1794
+ /**
1795
+ * `.redirect()` can Redirect, default status code is 302.
1796
+ *
1797
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1798
+ *
1799
+ * @example
1800
+ * ```ts
1801
+ * app.get('/redirect', (c) => {
1802
+ * return c.redirect('/')
1803
+ * })
1804
+ * app.get('/redirect-permanently', (c) => {
1805
+ * return c.redirect('/', 301)
1806
+ * })
1807
+ * ```
1808
+ */
1809
+ redirect = (location, status) => {
1810
+ const locationString = String(location);
1811
+ this.header(
1812
+ "Location",
1813
+ // Multibyes should be encoded
1814
+ // eslint-disable-next-line no-control-regex
1815
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1816
+ );
1817
+ return this.newResponse(null, status ?? 302);
1818
+ };
1819
+ /**
1820
+ * `.notFound()` can return the Not Found Response.
1821
+ *
1822
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1823
+ *
1824
+ * @example
1825
+ * ```ts
1826
+ * app.get('/notfound', (c) => {
1827
+ * return c.notFound()
1828
+ * })
1829
+ * ```
1830
+ */
1831
+ notFound = () => {
1832
+ this.#notFoundHandler ??= () => new Response();
1833
+ return this.#notFoundHandler(this);
1834
+ };
1835
+ };
1836
+
1837
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router.js
1838
+ var METHOD_NAME_ALL = "ALL";
1839
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1840
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1841
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1842
+ var UnsupportedPathError = class extends Error {
1843
+ };
1844
+
1845
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/constants.js
1846
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1847
+
1848
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/hono-base.js
1849
+ var notFoundHandler = (c) => {
1850
+ return c.text("404 Not Found", 404);
1851
+ };
1852
+ var errorHandler = (err, c) => {
1853
+ if ("getResponse" in err) {
1854
+ const res = err.getResponse();
1855
+ return c.newResponse(res.body, res);
1856
+ }
1857
+ console.error(err);
1858
+ return c.text("Internal Server Error", 500);
1859
+ };
1860
+ var Hono = class _Hono {
1861
+ get;
1862
+ post;
1863
+ put;
1864
+ delete;
1865
+ options;
1866
+ patch;
1867
+ all;
1868
+ on;
1869
+ use;
1870
+ /*
1871
+ This class is like an abstract class and does not have a router.
1872
+ To use it, inherit the class and implement router in the constructor.
1873
+ */
1874
+ router;
1875
+ getPath;
1876
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1877
+ _basePath = "/";
1878
+ #path = "/";
1879
+ routes = [];
1880
+ constructor(options = {}) {
1881
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1882
+ allMethods.forEach((method) => {
1883
+ this[method] = (args1, ...args) => {
1884
+ if (typeof args1 === "string") {
1885
+ this.#path = args1;
1886
+ } else {
1887
+ this.#addRoute(method, this.#path, args1);
1888
+ }
1889
+ args.forEach((handler) => {
1890
+ this.#addRoute(method, this.#path, handler);
1891
+ });
1892
+ return this;
1893
+ };
1894
+ });
1895
+ this.on = (method, path, ...handlers) => {
1896
+ for (const p of [path].flat()) {
1897
+ this.#path = p;
1898
+ for (const m of [method].flat()) {
1899
+ handlers.map((handler) => {
1900
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1901
+ });
1902
+ }
1903
+ }
1904
+ return this;
1905
+ };
1906
+ this.use = (arg1, ...handlers) => {
1907
+ if (typeof arg1 === "string") {
1908
+ this.#path = arg1;
1909
+ } else {
1910
+ this.#path = "*";
1911
+ handlers.unshift(arg1);
1912
+ }
1913
+ handlers.forEach((handler) => {
1914
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1915
+ });
1916
+ return this;
1917
+ };
1918
+ const { strict, ...optionsWithoutStrict } = options;
1919
+ Object.assign(this, optionsWithoutStrict);
1920
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1921
+ }
1922
+ #clone() {
1923
+ const clone = new _Hono({
1924
+ router: this.router,
1925
+ getPath: this.getPath
1926
+ });
1927
+ clone.errorHandler = this.errorHandler;
1928
+ clone.#notFoundHandler = this.#notFoundHandler;
1929
+ clone.routes = this.routes;
1930
+ return clone;
1931
+ }
1932
+ #notFoundHandler = notFoundHandler;
1933
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1934
+ errorHandler = errorHandler;
1935
+ /**
1936
+ * `.route()` allows grouping other Hono instance in routes.
1937
+ *
1938
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1939
+ *
1940
+ * @param {string} path - base Path
1941
+ * @param {Hono} app - other Hono instance
1942
+ * @returns {Hono} routed Hono instance
1943
+ *
1944
+ * @example
1945
+ * ```ts
1946
+ * const app = new Hono()
1947
+ * const app2 = new Hono()
1948
+ *
1949
+ * app2.get("/user", (c) => c.text("user"))
1950
+ * app.route("/api", app2) // GET /api/user
1951
+ * ```
1952
+ */
1953
+ route(path, app) {
1954
+ const subApp = this.basePath(path);
1955
+ app.routes.map((r) => {
1956
+ let handler;
1957
+ if (app.errorHandler === errorHandler) {
1958
+ handler = r.handler;
1959
+ } else {
1960
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1961
+ handler[COMPOSED_HANDLER] = r.handler;
1962
+ }
1963
+ subApp.#addRoute(r.method, r.path, handler);
1964
+ });
1965
+ return this;
1966
+ }
1967
+ /**
1968
+ * `.basePath()` allows base paths to be specified.
1969
+ *
1970
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1971
+ *
1972
+ * @param {string} path - base Path
1973
+ * @returns {Hono} changed Hono instance
1974
+ *
1975
+ * @example
1976
+ * ```ts
1977
+ * const api = new Hono().basePath('/api')
1978
+ * ```
1979
+ */
1980
+ basePath(path) {
1981
+ const subApp = this.#clone();
1982
+ subApp._basePath = mergePath(this._basePath, path);
1983
+ return subApp;
1984
+ }
1985
+ /**
1986
+ * `.onError()` handles an error and returns a customized Response.
1987
+ *
1988
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1989
+ *
1990
+ * @param {ErrorHandler} handler - request Handler for error
1991
+ * @returns {Hono} changed Hono instance
1992
+ *
1993
+ * @example
1994
+ * ```ts
1995
+ * app.onError((err, c) => {
1996
+ * console.error(`${err}`)
1997
+ * return c.text('Custom Error Message', 500)
1998
+ * })
1999
+ * ```
2000
+ */
2001
+ onError = (handler) => {
2002
+ this.errorHandler = handler;
2003
+ return this;
2004
+ };
2005
+ /**
2006
+ * `.notFound()` allows you to customize a Not Found Response.
2007
+ *
2008
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
2009
+ *
2010
+ * @param {NotFoundHandler} handler - request handler for not-found
2011
+ * @returns {Hono} changed Hono instance
2012
+ *
2013
+ * @example
2014
+ * ```ts
2015
+ * app.notFound((c) => {
2016
+ * return c.text('Custom 404 Message', 404)
2017
+ * })
2018
+ * ```
2019
+ */
2020
+ notFound = (handler) => {
2021
+ this.#notFoundHandler = handler;
2022
+ return this;
2023
+ };
2024
+ /**
2025
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
2026
+ *
2027
+ * @see {@link https://hono.dev/docs/api/hono#mount}
2028
+ *
2029
+ * @param {string} path - base Path
2030
+ * @param {Function} applicationHandler - other Request Handler
2031
+ * @param {MountOptions} [options] - options of `.mount()`
2032
+ * @returns {Hono} mounted Hono instance
2033
+ *
2034
+ * @example
2035
+ * ```ts
2036
+ * import { Router as IttyRouter } from 'itty-router'
2037
+ * import { Hono } from 'hono'
2038
+ * // Create itty-router application
2039
+ * const ittyRouter = IttyRouter()
2040
+ * // GET /itty-router/hello
2041
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
2042
+ *
2043
+ * const app = new Hono()
2044
+ * app.mount('/itty-router', ittyRouter.handle)
2045
+ * ```
2046
+ *
2047
+ * @example
2048
+ * ```ts
2049
+ * const app = new Hono()
2050
+ * // Send the request to another application without modification.
2051
+ * app.mount('/app', anotherApp, {
2052
+ * replaceRequest: (req) => req,
2053
+ * })
2054
+ * ```
2055
+ */
2056
+ mount(path, applicationHandler, options) {
2057
+ let replaceRequest;
2058
+ let optionHandler;
2059
+ if (options) {
2060
+ if (typeof options === "function") {
2061
+ optionHandler = options;
2062
+ } else {
2063
+ optionHandler = options.optionHandler;
2064
+ if (options.replaceRequest === false) {
2065
+ replaceRequest = (request) => request;
2066
+ } else {
2067
+ replaceRequest = options.replaceRequest;
2068
+ }
2069
+ }
2070
+ }
2071
+ const getOptions = optionHandler ? (c) => {
2072
+ const options2 = optionHandler(c);
2073
+ return Array.isArray(options2) ? options2 : [options2];
2074
+ } : (c) => {
2075
+ let executionContext = void 0;
2076
+ try {
2077
+ executionContext = c.executionCtx;
2078
+ } catch {
2079
+ }
2080
+ return [c.env, executionContext];
2081
+ };
2082
+ replaceRequest ||= (() => {
2083
+ const mergedPath = mergePath(this._basePath, path);
2084
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2085
+ return (request) => {
2086
+ const url = new URL(request.url);
2087
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2088
+ return new Request(url, request);
2089
+ };
2090
+ })();
2091
+ const handler = async (c, next) => {
2092
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2093
+ if (res) {
2094
+ return res;
2095
+ }
2096
+ await next();
2097
+ };
2098
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2099
+ return this;
2100
+ }
2101
+ #addRoute(method, path, handler) {
2102
+ method = method.toUpperCase();
2103
+ path = mergePath(this._basePath, path);
2104
+ const r = { basePath: this._basePath, path, method, handler };
2105
+ this.router.add(method, path, [handler, r]);
2106
+ this.routes.push(r);
2107
+ }
2108
+ #handleError(err, c) {
2109
+ if (err instanceof Error) {
2110
+ return this.errorHandler(err, c);
2111
+ }
2112
+ throw err;
2113
+ }
2114
+ #dispatch(request, executionCtx, env, method) {
2115
+ if (method === "HEAD") {
2116
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
2117
+ }
2118
+ const path = this.getPath(request, { env });
2119
+ const matchResult = this.router.match(method, path);
2120
+ const c = new Context(request, {
2121
+ path,
2122
+ matchResult,
2123
+ env,
2124
+ executionCtx,
2125
+ notFoundHandler: this.#notFoundHandler
2126
+ });
2127
+ if (matchResult[0].length === 1) {
2128
+ let res;
2129
+ try {
2130
+ res = matchResult[0][0][0][0](c, async () => {
2131
+ c.res = await this.#notFoundHandler(c);
2132
+ });
2133
+ } catch (err) {
2134
+ return this.#handleError(err, c);
2135
+ }
2136
+ return res instanceof Promise ? res.then(
2137
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2138
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2139
+ }
2140
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2141
+ return (async () => {
2142
+ try {
2143
+ const context = await composed(c);
2144
+ if (!context.finalized) {
2145
+ throw new Error(
2146
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2147
+ );
2148
+ }
2149
+ return context.res;
2150
+ } catch (err) {
2151
+ return this.#handleError(err, c);
2152
+ }
2153
+ })();
2154
+ }
2155
+ /**
2156
+ * `.fetch()` will be entry point of your app.
2157
+ *
2158
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
2159
+ *
2160
+ * @param {Request} request - request Object of request
2161
+ * @param {Env} Env - env Object
2162
+ * @param {ExecutionContext} - context of execution
2163
+ * @returns {Response | Promise<Response>} response of request
2164
+ *
2165
+ */
2166
+ fetch = (request, ...rest) => {
2167
+ return this.#dispatch(request, rest[1], rest[0], request.method);
2168
+ };
2169
+ /**
2170
+ * `.request()` is a useful method for testing.
2171
+ * You can pass a URL or pathname to send a GET request.
2172
+ * app will return a Response object.
2173
+ * ```ts
2174
+ * test('GET /hello is ok', async () => {
2175
+ * const res = await app.request('/hello')
2176
+ * expect(res.status).toBe(200)
2177
+ * })
2178
+ * ```
2179
+ * @see https://hono.dev/docs/api/hono#request
2180
+ */
2181
+ request = (input, requestInit, Env, executionCtx) => {
2182
+ if (input instanceof Request) {
2183
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2184
+ }
2185
+ input = input.toString();
2186
+ return this.fetch(
2187
+ new Request(
2188
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2189
+ requestInit
2190
+ ),
2191
+ Env,
2192
+ executionCtx
2193
+ );
2194
+ };
2195
+ /**
2196
+ * `.fire()` automatically adds a global fetch event listener.
2197
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2198
+ * @deprecated
2199
+ * Use `fire` from `hono/service-worker` instead.
2200
+ * ```ts
2201
+ * import { Hono } from 'hono'
2202
+ * import { fire } from 'hono/service-worker'
2203
+ *
2204
+ * const app = new Hono()
2205
+ * // ...
2206
+ * fire(app)
2207
+ * ```
2208
+ * @see https://hono.dev/docs/api/hono#fire
2209
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2210
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2211
+ */
2212
+ fire = () => {
2213
+ addEventListener("fetch", (event) => {
2214
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2215
+ });
2216
+ };
2217
+ };
2218
+
2219
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/matcher.js
2220
+ var emptyParam = [];
2221
+ function match(method, path) {
2222
+ const matchers = this.buildAllMatchers();
2223
+ const match2 = ((method2, path2) => {
2224
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2225
+ const staticMatch = matcher[2][path2];
2226
+ if (staticMatch) {
2227
+ return staticMatch;
2228
+ }
2229
+ const match3 = path2.match(matcher[0]);
2230
+ if (!match3) {
2231
+ return [[], emptyParam];
2232
+ }
2233
+ const index = match3.indexOf("", 1);
2234
+ return [matcher[1][index], match3];
2235
+ });
2236
+ this.match = match2;
2237
+ return match2(method, path);
2238
+ }
2239
+
2240
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/node.js
2241
+ var LABEL_REG_EXP_STR = "[^/]+";
2242
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2243
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2244
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2245
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2246
+ function compareKey(a, b) {
2247
+ if (a.length === 1) {
2248
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2249
+ }
2250
+ if (b.length === 1) {
2251
+ return 1;
2252
+ }
2253
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2254
+ return 1;
2255
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2256
+ return -1;
2257
+ }
2258
+ if (a === LABEL_REG_EXP_STR) {
2259
+ return 1;
2260
+ } else if (b === LABEL_REG_EXP_STR) {
2261
+ return -1;
2262
+ }
2263
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2264
+ }
2265
+ var Node = class _Node {
2266
+ #index;
2267
+ #varIndex;
2268
+ #children = /* @__PURE__ */ Object.create(null);
2269
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2270
+ if (tokens.length === 0) {
2271
+ if (this.#index !== void 0) {
2272
+ throw PATH_ERROR;
2273
+ }
2274
+ if (pathErrorCheckOnly) {
2275
+ return;
2276
+ }
2277
+ this.#index = index;
2278
+ return;
2279
+ }
2280
+ const [token, ...restTokens] = tokens;
2281
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2282
+ let node;
2283
+ if (pattern) {
2284
+ const name = pattern[1];
2285
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2286
+ if (name && pattern[2]) {
2287
+ if (regexpStr === ".*") {
2288
+ throw PATH_ERROR;
2289
+ }
2290
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2291
+ if (/\((?!\?:)/.test(regexpStr)) {
2292
+ throw PATH_ERROR;
2293
+ }
2294
+ }
2295
+ node = this.#children[regexpStr];
2296
+ if (!node) {
2297
+ if (Object.keys(this.#children).some(
2298
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2299
+ )) {
2300
+ throw PATH_ERROR;
2301
+ }
2302
+ if (pathErrorCheckOnly) {
2303
+ return;
2304
+ }
2305
+ node = this.#children[regexpStr] = new _Node();
2306
+ if (name !== "") {
2307
+ node.#varIndex = context.varIndex++;
2308
+ }
2309
+ }
2310
+ if (!pathErrorCheckOnly && name !== "") {
2311
+ paramMap.push([name, node.#varIndex]);
2312
+ }
2313
+ } else {
2314
+ node = this.#children[token];
2315
+ if (!node) {
2316
+ if (Object.keys(this.#children).some(
2317
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2318
+ )) {
2319
+ throw PATH_ERROR;
2320
+ }
2321
+ if (pathErrorCheckOnly) {
2322
+ return;
2323
+ }
2324
+ node = this.#children[token] = new _Node();
2325
+ }
2326
+ }
2327
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2328
+ }
2329
+ buildRegExpStr() {
2330
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2331
+ const strList = childKeys.map((k) => {
2332
+ const c = this.#children[k];
2333
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2334
+ });
2335
+ if (typeof this.#index === "number") {
2336
+ strList.unshift(`#${this.#index}`);
2337
+ }
2338
+ if (strList.length === 0) {
2339
+ return "";
2340
+ }
2341
+ if (strList.length === 1) {
2342
+ return strList[0];
2343
+ }
2344
+ return "(?:" + strList.join("|") + ")";
2345
+ }
2346
+ };
2347
+
2348
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/trie.js
2349
+ var Trie = class {
2350
+ #context = { varIndex: 0 };
2351
+ #root = new Node();
2352
+ insert(path, index, pathErrorCheckOnly) {
2353
+ const paramAssoc = [];
2354
+ const groups = [];
2355
+ for (let i = 0; ; ) {
2356
+ let replaced = false;
2357
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2358
+ const mark = `@\\${i}`;
2359
+ groups[i] = [mark, m];
2360
+ i++;
2361
+ replaced = true;
2362
+ return mark;
2363
+ });
2364
+ if (!replaced) {
2365
+ break;
2366
+ }
2367
+ }
2368
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2369
+ for (let i = groups.length - 1; i >= 0; i--) {
2370
+ const [mark] = groups[i];
2371
+ for (let j = tokens.length - 1; j >= 0; j--) {
2372
+ if (tokens[j].indexOf(mark) !== -1) {
2373
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2374
+ break;
2375
+ }
2376
+ }
2377
+ }
2378
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2379
+ return paramAssoc;
2380
+ }
2381
+ buildRegExp() {
2382
+ let regexp = this.#root.buildRegExpStr();
2383
+ if (regexp === "") {
2384
+ return [/^$/, [], []];
2385
+ }
2386
+ let captureIndex = 0;
2387
+ const indexReplacementMap = [];
2388
+ const paramReplacementMap = [];
2389
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2390
+ if (handlerIndex !== void 0) {
2391
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2392
+ return "$()";
2393
+ }
2394
+ if (paramIndex !== void 0) {
2395
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2396
+ return "";
2397
+ }
2398
+ return "";
2399
+ });
2400
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2401
+ }
2402
+ };
2403
+
2404
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/reg-exp-router/router.js
2405
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2406
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2407
+ function buildWildcardRegExp(path) {
2408
+ return wildcardRegExpCache[path] ??= new RegExp(
2409
+ path === "*" ? "" : `^${path.replace(
2410
+ /\/\*$|([.\\+*[^\]$()])/g,
2411
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2412
+ )}$`
2413
+ );
2414
+ }
2415
+ function clearWildcardRegExpCache() {
2416
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2417
+ }
2418
+ function buildMatcherFromPreprocessedRoutes(routes) {
2419
+ const trie = new Trie();
2420
+ const handlerData = [];
2421
+ if (routes.length === 0) {
2422
+ return nullMatcher;
2423
+ }
2424
+ const routesWithStaticPathFlag = routes.map(
2425
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
2426
+ ).sort(
2427
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2428
+ );
2429
+ const staticMap = /* @__PURE__ */ Object.create(null);
2430
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2431
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2432
+ if (pathErrorCheckOnly) {
2433
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2434
+ } else {
2435
+ j++;
2436
+ }
2437
+ let paramAssoc;
2438
+ try {
2439
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2440
+ } catch (e) {
2441
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2442
+ }
2443
+ if (pathErrorCheckOnly) {
2444
+ continue;
2445
+ }
2446
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2447
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2448
+ paramCount -= 1;
2449
+ for (; paramCount >= 0; paramCount--) {
2450
+ const [key, value] = paramAssoc[paramCount];
2451
+ paramIndexMap[key] = value;
2452
+ }
2453
+ return [h, paramIndexMap];
2454
+ });
2455
+ }
2456
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2457
+ for (let i = 0, len = handlerData.length; i < len; i++) {
2458
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2459
+ const map = handlerData[i][j]?.[1];
2460
+ if (!map) {
2461
+ continue;
2462
+ }
2463
+ const keys = Object.keys(map);
2464
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
2465
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2466
+ }
2467
+ }
2468
+ }
2469
+ const handlerMap = [];
2470
+ for (const i in indexReplacementMap) {
2471
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2472
+ }
2473
+ return [regexp, handlerMap, staticMap];
2474
+ }
2475
+ function findMiddleware(middleware, path) {
2476
+ if (!middleware) {
2477
+ return void 0;
2478
+ }
2479
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2480
+ if (buildWildcardRegExp(k).test(path)) {
2481
+ return [...middleware[k]];
2482
+ }
2483
+ }
2484
+ return void 0;
2485
+ }
2486
+ var RegExpRouter = class {
2487
+ name = "RegExpRouter";
2488
+ #middleware;
2489
+ #routes;
2490
+ constructor() {
2491
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2492
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2493
+ }
2494
+ add(method, path, handler) {
2495
+ const middleware = this.#middleware;
2496
+ const routes = this.#routes;
2497
+ if (!middleware || !routes) {
2498
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2499
+ }
2500
+ if (!middleware[method]) {
2501
+ ;
2502
+ [middleware, routes].forEach((handlerMap) => {
2503
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
2504
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2505
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2506
+ });
2507
+ });
2508
+ }
2509
+ if (path === "/*") {
2510
+ path = "*";
2511
+ }
2512
+ const paramCount = (path.match(/\/:/g) || []).length;
2513
+ if (/\*$/.test(path)) {
2514
+ const re = buildWildcardRegExp(path);
2515
+ if (method === METHOD_NAME_ALL) {
2516
+ Object.keys(middleware).forEach((m) => {
2517
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2518
+ });
2519
+ } else {
2520
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2521
+ }
2522
+ Object.keys(middleware).forEach((m) => {
2523
+ if (method === METHOD_NAME_ALL || method === m) {
2524
+ Object.keys(middleware[m]).forEach((p) => {
2525
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
2526
+ });
2527
+ }
2528
+ });
2529
+ Object.keys(routes).forEach((m) => {
2530
+ if (method === METHOD_NAME_ALL || method === m) {
2531
+ Object.keys(routes[m]).forEach(
2532
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2533
+ );
2534
+ }
2535
+ });
2536
+ return;
2537
+ }
2538
+ const paths = checkOptionalParameter(path) || [path];
2539
+ for (let i = 0, len = paths.length; i < len; i++) {
2540
+ const path2 = paths[i];
2541
+ Object.keys(routes).forEach((m) => {
2542
+ if (method === METHOD_NAME_ALL || method === m) {
2543
+ routes[m][path2] ||= [
2544
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2545
+ ];
2546
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
2547
+ }
2548
+ });
2549
+ }
2550
+ }
2551
+ match = match;
2552
+ buildAllMatchers() {
2553
+ const matchers = /* @__PURE__ */ Object.create(null);
2554
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2555
+ matchers[method] ||= this.#buildMatcher(method);
2556
+ });
2557
+ this.#middleware = this.#routes = void 0;
2558
+ clearWildcardRegExpCache();
2559
+ return matchers;
2560
+ }
2561
+ #buildMatcher(method) {
2562
+ const routes = [];
2563
+ let hasOwnRoute = method === METHOD_NAME_ALL;
2564
+ [this.#middleware, this.#routes].forEach((r) => {
2565
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2566
+ if (ownRoute.length !== 0) {
2567
+ hasOwnRoute ||= true;
2568
+ routes.push(...ownRoute);
2569
+ } else if (method !== METHOD_NAME_ALL) {
2570
+ routes.push(
2571
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2572
+ );
2573
+ }
2574
+ });
2575
+ if (!hasOwnRoute) {
2576
+ return null;
2577
+ } else {
2578
+ return buildMatcherFromPreprocessedRoutes(routes);
2579
+ }
2580
+ }
2581
+ };
2582
+
2583
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/smart-router/router.js
2584
+ var SmartRouter = class {
2585
+ name = "SmartRouter";
2586
+ #routers = [];
2587
+ #routes = [];
2588
+ constructor(init) {
2589
+ this.#routers = init.routers;
2590
+ }
2591
+ add(method, path, handler) {
2592
+ if (!this.#routes) {
2593
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2594
+ }
2595
+ this.#routes.push([method, path, handler]);
2596
+ }
2597
+ match(method, path) {
2598
+ if (!this.#routes) {
2599
+ throw new Error("Fatal error");
2600
+ }
2601
+ const routers = this.#routers;
2602
+ const routes = this.#routes;
2603
+ const len = routers.length;
2604
+ let i = 0;
2605
+ let res;
2606
+ for (; i < len; i++) {
2607
+ const router = routers[i];
2608
+ try {
2609
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2610
+ router.add(...routes[i2]);
2611
+ }
2612
+ res = router.match(method, path);
2613
+ } catch (e) {
2614
+ if (e instanceof UnsupportedPathError) {
2615
+ continue;
2616
+ }
2617
+ throw e;
2618
+ }
2619
+ this.match = router.match.bind(router);
2620
+ this.#routers = [router];
2621
+ this.#routes = void 0;
2622
+ break;
2623
+ }
2624
+ if (i === len) {
2625
+ throw new Error("Fatal error");
2626
+ }
2627
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2628
+ return res;
2629
+ }
2630
+ get activeRouter() {
2631
+ if (this.#routes || this.#routers.length !== 1) {
2632
+ throw new Error("No active router has been determined yet.");
2633
+ }
2634
+ return this.#routers[0];
2635
+ }
2636
+ };
2637
+
2638
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/trie-router/node.js
2639
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2640
+ var Node2 = class _Node2 {
2641
+ #methods;
2642
+ #children;
2643
+ #patterns;
2644
+ #order = 0;
2645
+ #params = emptyParams;
2646
+ constructor(method, handler, children) {
2647
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2648
+ this.#methods = [];
2649
+ if (method && handler) {
2650
+ const m = /* @__PURE__ */ Object.create(null);
2651
+ m[method] = { handler, possibleKeys: [], score: 0 };
2652
+ this.#methods = [m];
2653
+ }
2654
+ this.#patterns = [];
2655
+ }
2656
+ insert(method, path, handler) {
2657
+ this.#order = ++this.#order;
2658
+ let curNode = this;
2659
+ const parts = splitRoutingPath(path);
2660
+ const possibleKeys = [];
2661
+ for (let i = 0, len = parts.length; i < len; i++) {
2662
+ const p = parts[i];
2663
+ const nextP = parts[i + 1];
2664
+ const pattern = getPattern(p, nextP);
2665
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2666
+ if (key in curNode.#children) {
2667
+ curNode = curNode.#children[key];
2668
+ if (pattern) {
2669
+ possibleKeys.push(pattern[1]);
2670
+ }
2671
+ continue;
2672
+ }
2673
+ curNode.#children[key] = new _Node2();
2674
+ if (pattern) {
2675
+ curNode.#patterns.push(pattern);
2676
+ possibleKeys.push(pattern[1]);
2677
+ }
2678
+ curNode = curNode.#children[key];
2679
+ }
2680
+ curNode.#methods.push({
2681
+ [method]: {
2682
+ handler,
2683
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2684
+ score: this.#order
2685
+ }
2686
+ });
2687
+ return curNode;
2688
+ }
2689
+ #getHandlerSets(node, method, nodeParams, params) {
2690
+ const handlerSets = [];
2691
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2692
+ const m = node.#methods[i];
2693
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2694
+ const processedSet = {};
2695
+ if (handlerSet !== void 0) {
2696
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2697
+ handlerSets.push(handlerSet);
2698
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2699
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2700
+ const key = handlerSet.possibleKeys[i2];
2701
+ const processed = processedSet[handlerSet.score];
2702
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2703
+ processedSet[handlerSet.score] = true;
2704
+ }
112
2705
  }
113
- else if (arg.startsWith("--transport=")) {
114
- transport = arg.split("=")[1].toLowerCase();
2706
+ }
2707
+ }
2708
+ return handlerSets;
2709
+ }
2710
+ search(method, path) {
2711
+ const handlerSets = [];
2712
+ this.#params = emptyParams;
2713
+ const curNode = this;
2714
+ let curNodes = [curNode];
2715
+ const parts = splitPath(path);
2716
+ const curNodesQueue = [];
2717
+ for (let i = 0, len = parts.length; i < len; i++) {
2718
+ const part = parts[i];
2719
+ const isLast = i === len - 1;
2720
+ const tempNodes = [];
2721
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2722
+ const node = curNodes[j];
2723
+ const nextNode = node.#children[part];
2724
+ if (nextNode) {
2725
+ nextNode.#params = node.#params;
2726
+ if (isLast) {
2727
+ if (nextNode.#children["*"]) {
2728
+ handlerSets.push(
2729
+ ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
2730
+ );
2731
+ }
2732
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
2733
+ } else {
2734
+ tempNodes.push(nextNode);
2735
+ }
115
2736
  }
116
- else if (arg.startsWith("--port=")) {
117
- const parsed = Number.parseInt(arg.split("=")[1], 10);
118
- if (Number.isFinite(parsed)) {
119
- port = parsed;
2737
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2738
+ const pattern = node.#patterns[k];
2739
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2740
+ if (pattern === "*") {
2741
+ const astNode = node.#children["*"];
2742
+ if (astNode) {
2743
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
2744
+ astNode.#params = params;
2745
+ tempNodes.push(astNode);
120
2746
  }
2747
+ continue;
2748
+ }
2749
+ const [key, name, matcher] = pattern;
2750
+ if (!part && !(matcher instanceof RegExp)) {
2751
+ continue;
2752
+ }
2753
+ const child = node.#children[key];
2754
+ const restPathString = parts.slice(i).join("/");
2755
+ if (matcher instanceof RegExp) {
2756
+ const m = matcher.exec(restPathString);
2757
+ if (m) {
2758
+ params[name] = m[0];
2759
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
2760
+ if (Object.keys(child.#children).length) {
2761
+ child.#params = params;
2762
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2763
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2764
+ targetCurNodes.push(child);
2765
+ }
2766
+ continue;
2767
+ }
2768
+ }
2769
+ if (matcher === true || matcher.test(part)) {
2770
+ params[name] = part;
2771
+ if (isLast) {
2772
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
2773
+ if (child.#children["*"]) {
2774
+ handlerSets.push(
2775
+ ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
2776
+ );
2777
+ }
2778
+ } else {
2779
+ child.#params = params;
2780
+ tempNodes.push(child);
2781
+ }
2782
+ }
121
2783
  }
122
- else if (arg === "--help" || arg === "-h") {
123
- console.log(`
124
- Connpass MCP Server
2784
+ }
2785
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
2786
+ }
2787
+ if (handlerSets.length > 1) {
2788
+ handlerSets.sort((a, b) => {
2789
+ return a.score - b.score;
2790
+ });
2791
+ }
2792
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2793
+ }
2794
+ };
125
2795
 
126
- Usage: connpass-mcp-server [options]
2796
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/router/trie-router/router.js
2797
+ var TrieRouter = class {
2798
+ name = "TrieRouter";
2799
+ #node;
2800
+ constructor() {
2801
+ this.#node = new Node2();
2802
+ }
2803
+ add(method, path, handler) {
2804
+ const results = checkOptionalParameter(path);
2805
+ if (results) {
2806
+ for (let i = 0, len = results.length; i < len; i++) {
2807
+ this.#node.insert(method, results[i], handler);
2808
+ }
2809
+ return;
2810
+ }
2811
+ this.#node.insert(method, path, handler);
2812
+ }
2813
+ match(method, path) {
2814
+ return this.#node.search(method, path);
2815
+ }
2816
+ };
127
2817
 
128
- Options:
129
- -t, --transport <type> Transport type: http or sse (default: http)
130
- -p, --port <number> Port number for http/sse transports (default: 3000)
131
- -h, --help Show this help message
2818
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/hono.js
2819
+ var Hono2 = class extends Hono {
2820
+ /**
2821
+ * Creates an instance of the Hono class.
2822
+ *
2823
+ * @param options - Optional configuration options for the Hono instance.
2824
+ */
2825
+ constructor(options = {}) {
2826
+ super(options);
2827
+ this.router = options.router ?? new SmartRouter({
2828
+ routers: [new RegExpRouter(), new TrieRouter()]
2829
+ });
2830
+ }
2831
+ };
132
2832
 
133
- Examples:
134
- connpass-mcp-server # Start with HTTP transport on port 3000
135
- connpass-mcp-server --transport sse --port 8080 # Start with SSE transport on port 8080
136
- connpass-mcp-server -t http -p 5000 # Start with HTTP transport on port 5000
2833
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/middleware/cors/index.js
2834
+ var cors = (options) => {
2835
+ const defaults = {
2836
+ origin: "*",
2837
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
2838
+ allowHeaders: [],
2839
+ exposeHeaders: []
2840
+ };
2841
+ const opts = {
2842
+ ...defaults,
2843
+ ...options
2844
+ };
2845
+ const findAllowOrigin = ((optsOrigin) => {
2846
+ if (typeof optsOrigin === "string") {
2847
+ if (optsOrigin === "*") {
2848
+ return () => optsOrigin;
2849
+ } else {
2850
+ return (origin) => optsOrigin === origin ? origin : null;
2851
+ }
2852
+ } else if (typeof optsOrigin === "function") {
2853
+ return optsOrigin;
2854
+ } else {
2855
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2856
+ }
2857
+ })(opts.origin);
2858
+ const findAllowMethods = ((optsAllowMethods) => {
2859
+ if (typeof optsAllowMethods === "function") {
2860
+ return optsAllowMethods;
2861
+ } else if (Array.isArray(optsAllowMethods)) {
2862
+ return () => optsAllowMethods;
2863
+ } else {
2864
+ return () => [];
2865
+ }
2866
+ })(opts.allowMethods);
2867
+ return async function cors2(c, next) {
2868
+ function set(key, value) {
2869
+ c.res.headers.set(key, value);
2870
+ }
2871
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2872
+ if (allowOrigin) {
2873
+ set("Access-Control-Allow-Origin", allowOrigin);
2874
+ }
2875
+ if (opts.credentials) {
2876
+ set("Access-Control-Allow-Credentials", "true");
2877
+ }
2878
+ if (opts.exposeHeaders?.length) {
2879
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2880
+ }
2881
+ if (c.req.method === "OPTIONS") {
2882
+ if (opts.origin !== "*") {
2883
+ set("Vary", "Origin");
2884
+ }
2885
+ if (opts.maxAge != null) {
2886
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2887
+ }
2888
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2889
+ if (allowMethods.length) {
2890
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2891
+ }
2892
+ let headers = opts.allowHeaders;
2893
+ if (!headers?.length) {
2894
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2895
+ if (requestHeaders) {
2896
+ headers = requestHeaders.split(/\s*,\s*/);
2897
+ }
2898
+ }
2899
+ if (headers?.length) {
2900
+ set("Access-Control-Allow-Headers", headers.join(","));
2901
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2902
+ }
2903
+ c.res.headers.delete("Content-Length");
2904
+ c.res.headers.delete("Content-Type");
2905
+ return new Response(null, {
2906
+ headers: c.res.headers,
2907
+ status: 204,
2908
+ statusText: "No Content"
2909
+ });
2910
+ }
2911
+ await next();
2912
+ if (opts.origin !== "*") {
2913
+ c.header("Vary", "Origin", { append: true });
2914
+ }
2915
+ };
2916
+ };
137
2917
 
138
- Environment Variables:
139
- CONNPASS_API_KEY Connpass API Key
140
- CONNPASS_DEFAULT_USER_ID Default user ID
141
- CONNPASS_INCLUDE_PRESENTATIONS_DEFAULT Include presentations by default
142
- CONNPASS_ENABLE_APPS_SDK_OUTPUT Enable Apps SDK output
143
- MCP_BASE_PATH MCP base path (for SSE transport)
144
- `);
145
- process.exit(0);
2918
+ // ../../packages/mcp-core/dist/http.js
2919
+ function badRequestError(message = "Bad Request: No valid session ID provided") {
2920
+ return {
2921
+ jsonrpc: "2.0",
2922
+ error: { code: -32e3, message },
2923
+ id: null
2924
+ };
2925
+ }
2926
+ function internalServerError() {
2927
+ return {
2928
+ jsonrpc: "2.0",
2929
+ error: { code: -32603, message: "Internal server error" },
2930
+ id: null
2931
+ };
2932
+ }
2933
+ function forbiddenError(message) {
2934
+ return {
2935
+ jsonrpc: "2.0",
2936
+ error: { code: -32e3, message },
2937
+ id: null
2938
+ };
2939
+ }
2940
+ function unauthorizedError(message) {
2941
+ return {
2942
+ jsonrpc: "2.0",
2943
+ error: { code: -32001, message },
2944
+ id: null
2945
+ };
2946
+ }
2947
+ function extractHostnameFromHostHeader(host) {
2948
+ const trimmedHost = host.trim();
2949
+ if (trimmedHost.startsWith("[")) {
2950
+ const bracketEnd = trimmedHost.indexOf("]");
2951
+ if (bracketEnd !== -1) {
2952
+ return trimmedHost.slice(0, bracketEnd + 1);
2953
+ }
2954
+ }
2955
+ const colonIndex = trimmedHost.indexOf(":");
2956
+ if (colonIndex === -1) {
2957
+ return trimmedHost;
2958
+ }
2959
+ return trimmedHost.slice(0, colonIndex);
2960
+ }
2961
+ function validateOrigin(config2) {
2962
+ return async (c, next) => {
2963
+ const origin = c.req.header("Origin");
2964
+ if (!origin) {
2965
+ return next();
2966
+ }
2967
+ try {
2968
+ const originUrl = new URL(origin);
2969
+ const originWithoutPort = `${originUrl.protocol}//${originUrl.hostname}`;
2970
+ const isAllowed = config2.allowedOrigins.some((allowed) => {
2971
+ try {
2972
+ const allowedUrl = new URL(allowed);
2973
+ return originWithoutPort === `${allowedUrl.protocol}//${allowedUrl.hostname}`;
2974
+ } catch {
2975
+ return false;
146
2976
  }
2977
+ });
2978
+ if (!isAllowed) {
2979
+ console.log(`Rejected request with invalid Origin: ${origin} (allowed: ${config2.allowedOrigins.join(", ")})`);
2980
+ return c.json(forbiddenError("Forbidden: Invalid Origin header"), {
2981
+ status: 403
2982
+ });
2983
+ }
2984
+ } catch {
2985
+ console.log(`Rejected request with malformed Origin: ${origin}`);
2986
+ return c.json(forbiddenError("Forbidden: Malformed Origin header"), {
2987
+ status: 403
2988
+ });
147
2989
  }
148
- // Allow environment variable override for port
149
- const envPort = Number.parseInt(process.env.PORT ?? "", 10);
150
- if (Number.isFinite(envPort)) {
151
- port = envPort;
2990
+ return next();
2991
+ };
2992
+ }
2993
+ function validateHost(config2) {
2994
+ return async (c, next) => {
2995
+ const host = c.req.header("Host");
2996
+ if (!host) {
2997
+ return next();
152
2998
  }
153
- // Allow environment variable override for transport
154
- const envTransport = process.env.MCP_TRANSPORT?.toLowerCase();
155
- if (envTransport) {
156
- transport = envTransport;
2999
+ const hostname = extractHostnameFromHostHeader(host);
3000
+ if (!config2.allowedHosts.includes(hostname)) {
3001
+ console.log(`Rejected request with invalid Host: ${host} (allowed: ${config2.allowedHosts.join(", ")})`);
3002
+ return c.json(forbiddenError("Forbidden: Invalid Host header"), {
3003
+ status: 403
3004
+ });
157
3005
  }
158
- return { transport, port };
3006
+ return next();
3007
+ };
159
3008
  }
160
- async function main() {
161
- const { transport, port } = parseArgs();
162
- switch (transport) {
163
- case "http": {
164
- await (0, http_js_1.startHttpServer)({
165
- createMcpServer: createConnpassServer,
166
- port,
167
- });
168
- break;
169
- }
170
- case "sse": {
171
- const basePath = (0, config_js_1.getMcpBasePath)();
172
- const messagePath = basePath === "/" ? "/messages" : `${basePath}/messages`;
173
- await (0, sse_js_1.startSseServer)({
174
- createMcpServer: createConnpassServer,
175
- ssePath: basePath,
176
- messagePath,
177
- port,
178
- });
179
- break;
3009
+ function validateApiKey(config2) {
3010
+ return async (c, next) => {
3011
+ if (!config2.apiKey || c.req.method === "OPTIONS") {
3012
+ return next();
3013
+ }
3014
+ const xApiKey = c.req.header("X-API-Key");
3015
+ const authorization = c.req.header("Authorization");
3016
+ const bearerToken = authorization?.startsWith("Bearer ") ? authorization.slice(7).trim() : void 0;
3017
+ const providedKey = xApiKey ?? bearerToken;
3018
+ if (providedKey !== config2.apiKey) {
3019
+ console.log("Rejected request with invalid API key");
3020
+ return c.json(unauthorizedError("Unauthorized: Invalid API key"), {
3021
+ status: 401
3022
+ });
3023
+ }
3024
+ return next();
3025
+ };
3026
+ }
3027
+ function createHttpApp(options) {
3028
+ const { server: server2, config: config2, serverFactory, extraCorsHeaders = [], onSessionInitialized, onSessionClosed } = options;
3029
+ const transports = /* @__PURE__ */ new Map();
3030
+ async function handleMCP(c) {
3031
+ console.log(`Received ${c.req.method} request for MCP`);
3032
+ const sessionId = c.req.header("mcp-session-id");
3033
+ try {
3034
+ if (sessionId && transports.has(sessionId)) {
3035
+ console.log(`Reusing existing session: ${sessionId}`);
3036
+ const transport = transports.get(sessionId);
3037
+ return transport.handleRequest(c.req.raw);
3038
+ }
3039
+ if (c.req.method === "POST") {
3040
+ let body;
3041
+ try {
3042
+ body = await c.req.json();
3043
+ } catch {
3044
+ return c.json(badRequestError("Invalid JSON"), { status: 400 });
3045
+ }
3046
+ if (isInitializeRequest(body)) {
3047
+ console.log("Creating new WebStandard session");
3048
+ const rawRequest = c.req.raw;
3049
+ const transport = new WebStandardStreamableHTTPServerTransport({
3050
+ sessionIdGenerator: () => randomUUID(),
3051
+ onsessioninitialized: (newSessionId) => {
3052
+ console.log(`Session initialized: ${newSessionId}`);
3053
+ transports.set(newSessionId, transport);
3054
+ onSessionInitialized?.(newSessionId, rawRequest);
3055
+ }
3056
+ });
3057
+ transport.onclose = () => {
3058
+ const sid = transport.sessionId;
3059
+ if (sid) {
3060
+ console.log(`Transport closed for session: ${sid}`);
3061
+ transports.delete(sid);
3062
+ deleteSessionConfig(sid);
3063
+ onSessionClosed?.(sid);
3064
+ }
3065
+ };
3066
+ const sessionServer = serverFactory ? serverFactory() : server2;
3067
+ await sessionServer.connect(transport);
3068
+ return transport.handleRequest(c.req.raw, { parsedBody: body });
180
3069
  }
181
- default:
182
- throw new Error(`Unsupported MCP transport: ${transport}. Use 'http' or 'sse'.`);
3070
+ }
3071
+ console.log("Invalid request - no session ID and not an initialize request");
3072
+ return c.json(badRequestError(), { status: 400 });
3073
+ } catch (e) {
3074
+ console.error("MCP connection error:", e);
3075
+ return c.json(internalServerError(), { status: 500 });
183
3076
  }
3077
+ }
3078
+ function handleHealth(c) {
3079
+ const response = {
3080
+ status: "ok",
3081
+ transports: transports.size,
3082
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3083
+ };
3084
+ return c.json(response);
3085
+ }
3086
+ const app = new Hono2();
3087
+ const allowHeaders = [
3088
+ "Content-Type",
3089
+ "mcp-session-id",
3090
+ "Last-Event-ID",
3091
+ "mcp-protocol-version",
3092
+ "X-API-Key",
3093
+ "Authorization",
3094
+ ...extraCorsHeaders
3095
+ ];
3096
+ app.use("/mcp", cors({
3097
+ origin: "*",
3098
+ allowMethods: ["GET", "POST", "DELETE", "OPTIONS"],
3099
+ allowHeaders,
3100
+ exposeHeaders: ["mcp-session-id", "mcp-protocol-version"]
3101
+ }));
3102
+ app.use("/mcp", validateOrigin(config2));
3103
+ app.use("/mcp", validateHost(config2));
3104
+ app.use("/mcp", validateApiKey(config2));
3105
+ app.all("/mcp", handleMCP);
3106
+ app.get("/health", handleHealth);
3107
+ return app;
184
3108
  }
185
- main().catch((error) => {
186
- console.error("Server error:", error);
3109
+
3110
+ // ../../packages/mcp-core/dist/stdio.js
3111
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3112
+ async function connectStdio(server2) {
3113
+ await server2.connect(new StdioServerTransport());
3114
+ }
3115
+
3116
+ // ../../packages/mcp-core/dist/launcher.js
3117
+ function isNodejs() {
3118
+ return typeof process !== "undefined" && !!process.versions?.node;
3119
+ }
3120
+ function isBun() {
3121
+ return "Bun" in globalThis;
3122
+ }
3123
+ async function startHttpServer(options) {
3124
+ const { server: server2, config: config2, serverName, serverFactory, httpOptions = {} } = options;
3125
+ try {
3126
+ console.error(`Starting ${serverName} HTTP server...`);
3127
+ const app = createHttpApp({
3128
+ server: server2,
3129
+ config: config2,
3130
+ serverFactory,
3131
+ ...httpOptions
3132
+ });
3133
+ if (isBun()) {
3134
+ const bunServer = Bun.serve({
3135
+ fetch: app.fetch,
3136
+ port: config2.httpPort,
3137
+ hostname: config2.httpHost
3138
+ });
3139
+ console.error(`${serverName} HTTP server running at http://${bunServer.hostname}:${bunServer.port}/mcp`);
3140
+ console.error(`Health check: http://${bunServer.hostname}:${bunServer.port}/health`);
3141
+ } else {
3142
+ const { serve: serve2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
3143
+ serve2({
3144
+ fetch: app.fetch,
3145
+ port: config2.httpPort,
3146
+ hostname: config2.httpHost
3147
+ }, (info) => {
3148
+ console.error(`${serverName} HTTP server running at http://${info.address}:${info.port}/mcp`);
3149
+ console.error(`Health check: http://${info.address}:${info.port}/health`);
3150
+ });
3151
+ }
3152
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
3153
+ console.error("HTTP server startup completed");
3154
+ } catch (error) {
3155
+ console.error("HTTP server startup failed:", error);
3156
+ if (error instanceof Error) {
3157
+ console.error("Error details:", {
3158
+ message: error.message,
3159
+ stack: error.stack,
3160
+ name: error.name
3161
+ });
3162
+ }
3163
+ throw new Error(`Failed to start HTTP server: ${error}`);
3164
+ }
3165
+ }
3166
+ async function startStdioServer(options) {
3167
+ try {
3168
+ await connectStdio(options.server);
3169
+ process.on("SIGINT", () => {
3170
+ process.exit(0);
3171
+ });
3172
+ } catch (error) {
3173
+ console.error("Stdio server startup failed:", error);
3174
+ if (error instanceof Error) {
3175
+ console.error("Error details:", {
3176
+ message: error.message,
3177
+ stack: error.stack,
3178
+ name: error.name
3179
+ });
3180
+ }
3181
+ throw new Error(`Failed to start stdio server: ${error}`);
3182
+ }
3183
+ }
3184
+ async function launchServer(options) {
3185
+ const { config: config2 } = options;
3186
+ try {
3187
+ if (config2.httpMode) {
3188
+ await startHttpServer(options);
3189
+ } else {
3190
+ await startStdioServer(options);
3191
+ }
3192
+ } catch (error) {
3193
+ console.error("Server startup failed:", error);
187
3194
  process.exit(1);
3195
+ }
3196
+ }
3197
+
3198
+ // src/config.ts
3199
+ var connpassConfigDefs = {
3200
+ connpassApiKey: {
3201
+ cli: "--connpass-api-key",
3202
+ env: "CONNPASS_API_KEY",
3203
+ description: "Connpass API key",
3204
+ group: "Connpass Configuration",
3205
+ type: "string",
3206
+ valueName: "<key>"
3207
+ },
3208
+ defaultUserId: {
3209
+ cli: "--default-user-id",
3210
+ env: "CONNPASS_DEFAULT_USER_ID",
3211
+ description: "Default Connpass user ID for schedule search",
3212
+ group: "Connpass Configuration",
3213
+ type: "number",
3214
+ valueName: "<id>"
3215
+ },
3216
+ rateLimitEnabled: {
3217
+ cli: "--rate-limit",
3218
+ env: "CONNPASS_RATE_LIMIT_ENABLED",
3219
+ description: "Enable API rate limiting",
3220
+ group: "Connpass Configuration",
3221
+ type: "boolean",
3222
+ default: true
3223
+ },
3224
+ rateLimitDelayMs: {
3225
+ cli: "--rate-limit-delay",
3226
+ env: "CONNPASS_RATE_LIMIT_DELAY_MS",
3227
+ description: "Rate limit delay in milliseconds",
3228
+ group: "Connpass Configuration",
3229
+ type: "number",
3230
+ default: 1e3,
3231
+ valueName: "<ms>"
3232
+ }
3233
+ };
3234
+ var allConfigDefs = {
3235
+ ...connpassConfigDefs,
3236
+ ...baseConfigDefs
3237
+ };
3238
+ function createDefaultConfig() {
3239
+ const schemaDefs = getDefaultsFromDefs(allConfigDefs);
3240
+ return schemaDefs;
3241
+ }
3242
+ function getConfig(argv, env) {
3243
+ const cliConfig = parseCliFromDefs(
3244
+ allConfigDefs,
3245
+ argv ?? process.argv.slice(2)
3246
+ );
3247
+ const envConfig = parseEnvFromDefs(
3248
+ allConfigDefs,
3249
+ env ?? process.env
3250
+ );
3251
+ const defaultConfig = createDefaultConfig();
3252
+ const merged = {
3253
+ ...defaultConfig,
3254
+ ...filterUndefined(envConfig),
3255
+ ...filterUndefined(cliConfig)
3256
+ };
3257
+ return merged;
3258
+ }
3259
+ function getHelpText() {
3260
+ return generateHelp(allConfigDefs, {
3261
+ usage: "connpass-mcp-apps [options]",
3262
+ examples: [
3263
+ "CONNPASS_API_KEY=xxx connpass-mcp-apps",
3264
+ "connpass-mcp-apps --http --port 8080",
3265
+ "connpass-mcp-apps --connpass-api-key xxx --default-user-id 12345"
3266
+ ]
3267
+ });
3268
+ }
3269
+
3270
+ // src/server.ts
3271
+ import { ConnpassClient } from "@kajidog/connpass-api-client";
3272
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3273
+
3274
+ // src/tools/events.ts
3275
+ import { z as z2 } from "zod";
3276
+
3277
+ // src/tools/prefectures.ts
3278
+ import {
3279
+ getAllPrefectures,
3280
+ normalizePrefecture
3281
+ } from "@kajidog/connpass-api-client";
3282
+ import { z } from "zod";
3283
+
3284
+ // src/tools/utils/registration.ts
3285
+ import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
3286
+ function registerAppToolIfEnabled(server2, name, ...args) {
3287
+ const [config2, cb] = args;
3288
+ const normalizedConfig = {
3289
+ ...config2,
3290
+ _meta: config2._meta && typeof config2._meta === "object" ? config2._meta : {}
3291
+ };
3292
+ registerAppTool(server2, name, normalizedConfig, cb);
3293
+ }
3294
+
3295
+ // src/tools/prefectures.ts
3296
+ var EmptyInputSchema = z.object({});
3297
+ function buildPrefectureListResult(invalid = []) {
3298
+ const prefectures = getAllPrefectures();
3299
+ const payload = {
3300
+ invalid,
3301
+ prefectures
3302
+ };
3303
+ const invalidText = invalid.length > 0 ? `\u6307\u5B9A\u3055\u308C\u305F\u90FD\u9053\u5E9C\u770C\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${invalid.join(", ")}
3304
+ ` : "";
3305
+ return {
3306
+ content: [
3307
+ {
3308
+ type: "text",
3309
+ text: `${invalidText}\u5229\u7528\u53EF\u80FD\u306A\u90FD\u9053\u5E9C\u770C\u4E00\u89A7: ${prefectures.map((item) => `${item.name} (${item.code})`).join(", ")}`
3310
+ }
3311
+ ],
3312
+ structuredContent: {
3313
+ kind: "prefectures",
3314
+ data: payload
3315
+ }
3316
+ };
3317
+ }
3318
+ function resolvePrefectureInputs(values) {
3319
+ if (!values) return {};
3320
+ const inputs = Array.isArray(values) ? values : [values];
3321
+ const prefectures = [];
3322
+ const invalid = [];
3323
+ for (const value of inputs) {
3324
+ const normalized = normalizePrefecture(value);
3325
+ if (!normalized) {
3326
+ invalid.push(value);
3327
+ continue;
3328
+ }
3329
+ prefectures.push(normalized);
3330
+ }
3331
+ if (invalid.length > 0) {
3332
+ return { response: buildPrefectureListResult(invalid) };
3333
+ }
3334
+ return { prefectures };
3335
+ }
3336
+ function registerPrefectureTools(deps) {
3337
+ const { server: server2 } = deps;
3338
+ registerAppToolIfEnabled(
3339
+ server2,
3340
+ "list_prefectures",
3341
+ {
3342
+ title: "List Prefectures",
3343
+ description: "List supported prefectures and region codes for filtering",
3344
+ inputSchema: EmptyInputSchema
3345
+ },
3346
+ async () => buildPrefectureListResult()
3347
+ );
3348
+ registerAppToolIfEnabled(
3349
+ server2,
3350
+ "_get_prefectures",
3351
+ {
3352
+ title: "Get Prefectures (UI)",
3353
+ description: "Internal: list supported prefectures for the UI",
3354
+ inputSchema: EmptyInputSchema,
3355
+ _meta: {
3356
+ ui: {
3357
+ visibility: ["app"]
3358
+ }
3359
+ }
3360
+ },
3361
+ async () => buildPrefectureListResult()
3362
+ );
3363
+ }
3364
+
3365
+ // src/tools/utils/formatting.ts
3366
+ var HTML_ENTITY_MAP = {
3367
+ "&nbsp;": " ",
3368
+ "&amp;": "&",
3369
+ "&lt;": "<",
3370
+ "&gt;": ">",
3371
+ "&quot;": '"',
3372
+ "&#34;": '"',
3373
+ "&#39;": "'",
3374
+ "&#x27;": "'",
3375
+ "&#x60;": "`"
3376
+ };
3377
+ var FORMAT_PRESETS = {
3378
+ default: {
3379
+ descriptionLimit: 0,
3380
+ catchPhraseLimit: void 0
3381
+ },
3382
+ detailed: {
3383
+ descriptionLimit: 200,
3384
+ catchPhraseLimit: void 0
3385
+ },
3386
+ full: {
3387
+ descriptionLimit: void 0,
3388
+ catchPhraseLimit: void 0
3389
+ }
3390
+ };
3391
+ function compactDateLabel(isoString) {
3392
+ if (!isoString) return void 0;
3393
+ const date = new Date(isoString);
3394
+ if (Number.isNaN(date.getTime())) return void 0;
3395
+ const year = date.getFullYear();
3396
+ const month = String(date.getMonth() + 1).padStart(2, "0");
3397
+ const day = String(date.getDate()).padStart(2, "0");
3398
+ return `${year}-${month}-${day}`;
3399
+ }
3400
+ function summarizeEventLine(event) {
3401
+ const date = compactDateLabel(event.schedule.start);
3402
+ const place = event.location?.place || event.location?.address;
3403
+ const fragments = [
3404
+ date,
3405
+ event.title,
3406
+ place ? `@ ${place}` : void 0
3407
+ ].filter(Boolean);
3408
+ return `- ${fragments.join(" ")}`;
3409
+ }
3410
+ function summarizeGroupLine(group) {
3411
+ const place = [group.prefecture, group.place].filter(Boolean).join(" ");
3412
+ const fragments = [
3413
+ group.title?.trim(),
3414
+ typeof group.id === "number" ? `id:${group.id}` : void 0,
3415
+ place || void 0
3416
+ ].filter(Boolean);
3417
+ return `- ${fragments.join(" / ")}`;
3418
+ }
3419
+ function summarizeUserLine(user) {
3420
+ const fragments = [
3421
+ user.nickname?.trim(),
3422
+ typeof user.id === "number" ? `id:${user.id}` : void 0,
3423
+ user.displayName?.trim() ? `name:${user.displayName.trim()}` : void 0
3424
+ ].filter(Boolean);
3425
+ return `- ${fragments.join(" / ")}`;
3426
+ }
3427
+ function truncateText(text, limit) {
3428
+ if (!text) return "";
3429
+ if (text.length <= limit) return text;
3430
+ if (limit <= 3) return text.slice(0, limit);
3431
+ return `${text.slice(0, limit - 3).trimEnd()}...`;
3432
+ }
3433
+ function decodeHtmlEntities(input) {
3434
+ return input.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (entity) => {
3435
+ const mapped = HTML_ENTITY_MAP[entity];
3436
+ if (mapped) return mapped;
3437
+ const numericMatch = entity.match(/^&#(x?[0-9a-fA-F]+);$/);
3438
+ if (!numericMatch) return entity;
3439
+ const value = numericMatch[1];
3440
+ const codePoint = value.startsWith("x") || value.startsWith("X") ? Number.parseInt(value.slice(1), 16) : Number.parseInt(value, 10);
3441
+ if (!Number.isFinite(codePoint)) return entity;
3442
+ try {
3443
+ return String.fromCodePoint(codePoint);
3444
+ } catch {
3445
+ return entity;
3446
+ }
3447
+ }).replace(/\u00a0/gi, " ");
3448
+ }
3449
+ function stripHtml(input) {
3450
+ if (!input) return "";
3451
+ const withoutScripts = input.replace(/<script[\s\S]*?<\/script>/gi, "");
3452
+ const withoutStyles = withoutScripts.replace(/<style[\s\S]*?<\/style>/gi, "");
3453
+ const withCellBrNormalized = withoutStyles.replace(
3454
+ /(<(?:td|th)\b[^>]*>)([\s\S]*?)(<\/(?:td|th)>)/gi,
3455
+ (_, open, content, close) => `${open}${content.replace(/<br\s*\/?\s*>/gi, " ")}${close}`
3456
+ );
3457
+ const normalizedTableCells = withCellBrNormalized.replace(/<\/(td|th)>\s*<(td|th)/gi, "</$1> <$2").replace(/<\/(tr)>\s*<tr/gi, "</$1>\n<tr");
3458
+ const withLineBreaks = normalizedTableCells.replace(/<br\s*\/?\s*>/gi, "\n").replace(/<\/(p|div|section|article|header|footer|li)>/gi, "\n").replace(/<\/(td|th)>/gi, " ").replace(/<li[^>]*>/gi, "- ").replace(/<h[1-6]\b[^>]*>/gi, "\n## ").replace(/<\/(h[1-6]|tr)>/gi, "\n");
3459
+ const withoutTags = withLineBreaks.replace(/<[^>]+>/g, "");
3460
+ return decodeHtmlEntities(withoutTags);
3461
+ }
3462
+ function sanitizeRichText(input) {
3463
+ if (!input) return "";
3464
+ const stripped = stripHtml(input);
3465
+ const normalizedWhitespace = stripped.replace(/\r/g, "\n").split(/\n+/).map(
3466
+ (line) => line.split(/\t+/).map((cell) => cell.trim()).filter(Boolean).join(" ")
3467
+ ).filter(Boolean).join("\n");
3468
+ return normalizedWhitespace.replace(/ {2,}/g, " ").replace(/ *\t */g, " ").trim();
3469
+ }
3470
+ function formatPresentation(presentation, descriptionLimit) {
3471
+ const summary = sanitizeRichText(presentation.description);
3472
+ const title = String(presentation.title ?? "").trim();
3473
+ const speaker = String(presentation.speakerName ?? "").trim();
3474
+ const formatted = {
3475
+ id: presentation.id,
3476
+ title: title || "Untitled presentation",
3477
+ speaker: speaker || "Speaker unknown",
3478
+ order: presentation.order,
3479
+ updatedAt: presentation.updatedAt
3480
+ };
3481
+ const processedSummary = typeof descriptionLimit === "number" && descriptionLimit > 0 ? truncateText(summary, descriptionLimit) : summary;
3482
+ if (processedSummary) {
3483
+ formatted.summary = processedSummary;
3484
+ }
3485
+ const links = {
3486
+ url: presentation.url,
3487
+ slideshare: presentation.slideshareUrl,
3488
+ youtube: presentation.youtubeUrl,
3489
+ twitter: presentation.twitterUrl
3490
+ };
3491
+ if (links.url || links.slideshare || links.youtube || links.twitter) {
3492
+ formatted.links = links;
3493
+ }
3494
+ return formatted;
3495
+ }
3496
+ function formatPresentationsResponse(response, options) {
3497
+ const descriptionLimit = options?.presentationDescriptionLimit;
3498
+ return {
3499
+ returned: response.presentationsReturned,
3500
+ presentations: response.presentations.map(
3501
+ (presentation) => formatPresentation(presentation, descriptionLimit)
3502
+ )
3503
+ };
3504
+ }
3505
+ function formatEvent(event, options) {
3506
+ const descriptionLimit = options?.descriptionLimit;
3507
+ const catchPhraseLimit = options?.catchPhraseLimit;
3508
+ const presentationDescriptionLimit = options?.presentationDescriptionLimit;
3509
+ const catchPhrase = sanitizeRichText(event.catchPhrase);
3510
+ const description = sanitizeRichText(event.description);
3511
+ const participants = {
3512
+ accepted: event.participantCount,
3513
+ waiting: event.waitingCount
3514
+ };
3515
+ if (typeof event.limit === "number") {
3516
+ participants.limit = event.limit;
3517
+ }
3518
+ const formatted = {
3519
+ id: event.id,
3520
+ title: event.title.trim(),
3521
+ url: event.url,
3522
+ schedule: {
3523
+ start: event.startedAt,
3524
+ end: event.endedAt
3525
+ },
3526
+ owner: {
3527
+ nickname: event.ownerNickname,
3528
+ displayName: event.ownerDisplayName
3529
+ },
3530
+ participants,
3531
+ updatedAt: event.updatedAt
3532
+ };
3533
+ if (event.hashTag) formatted.hashTag = event.hashTag;
3534
+ if (event.imageUrl) formatted.imageUrl = event.imageUrl;
3535
+ const processedCatchPhrase = typeof catchPhraseLimit === "number" && catchPhraseLimit > 0 ? truncateText(catchPhrase, catchPhraseLimit) : catchPhrase;
3536
+ if (processedCatchPhrase) formatted.catchPhrase = processedCatchPhrase;
3537
+ const processedDescription = typeof descriptionLimit === "number" ? descriptionLimit > 0 ? truncateText(description, descriptionLimit) : "" : description;
3538
+ if (processedDescription) formatted.summary = processedDescription;
3539
+ if (event.place || event.address) {
3540
+ const location = {};
3541
+ if (event.place) location.place = event.place;
3542
+ if (event.address) location.address = event.address;
3543
+ if (Object.keys(location).length > 0) formatted.location = location;
3544
+ }
3545
+ if (event.groupId || event.groupTitle || event.groupUrl) {
3546
+ const group = {};
3547
+ if (typeof event.groupId === "number") group.id = event.groupId;
3548
+ if (event.groupTitle) group.title = event.groupTitle;
3549
+ if (event.groupUrl) group.url = event.groupUrl;
3550
+ if (Object.keys(group).length > 0) formatted.group = group;
3551
+ }
3552
+ const eventWithPresentations = event;
3553
+ if (eventWithPresentations.presentations?.length) {
3554
+ formatted.presentations = eventWithPresentations.presentations.map(
3555
+ (presentation) => formatPresentation(presentation, presentationDescriptionLimit)
3556
+ );
3557
+ }
3558
+ return formatted;
3559
+ }
3560
+ function formatEventsResponse(response, options) {
3561
+ return {
3562
+ returned: response.eventsReturned,
3563
+ available: response.eventsAvailable,
3564
+ start: response.eventsStart,
3565
+ events: response.events.map((event) => formatEvent(event, options))
3566
+ };
3567
+ }
3568
+ function summarizeEventsResponse(response, label = "events") {
3569
+ const lines = [
3570
+ `${label}: ${response.returned} returned / ${response.available} available`,
3571
+ ...response.events.slice(0, 5).map(summarizeEventLine)
3572
+ ];
3573
+ if (response.events.length > 5) {
3574
+ lines.push(`- ...and ${response.events.length - 5} more`);
3575
+ }
3576
+ return lines.join("\n");
3577
+ }
3578
+ function summarizeGroupsResponse(response) {
3579
+ const lines = [
3580
+ `groups: ${response.groupsReturned} returned / ${response.groupsAvailable} available`,
3581
+ ...response.groups.slice(0, 5).map(summarizeGroupLine)
3582
+ ];
3583
+ if (response.groups.length > 5) {
3584
+ lines.push(`- ...and ${response.groups.length - 5} more`);
3585
+ }
3586
+ return lines.join("\n");
3587
+ }
3588
+ function summarizeUsersResponse(response) {
3589
+ const lines = [
3590
+ `users: ${response.usersReturned} returned / ${response.usersAvailable} available`,
3591
+ ...response.users.slice(0, 5).map(summarizeUserLine)
3592
+ ];
3593
+ if (response.users.length > 5) {
3594
+ lines.push(`- ...and ${response.users.length - 5} more`);
3595
+ }
3596
+ return lines.join("\n");
3597
+ }
3598
+ function formatEventList(events, options) {
3599
+ return events.map((event) => formatEvent(event, options));
3600
+ }
3601
+
3602
+ // src/tools/utils/resource.ts
3603
+ import { readFileSync } from "fs";
3604
+ import { dirname, join } from "path";
3605
+ import { fileURLToPath } from "url";
3606
+ import {
3607
+ RESOURCE_MIME_TYPE,
3608
+ registerAppResource
3609
+ } from "@modelcontextprotocol/ext-apps/server";
3610
+ var __dirname = typeof import.meta.dirname === "string" ? import.meta.dirname : dirname(fileURLToPath(import.meta.url));
3611
+ var connpassResourceUri = "ui://connpass/app.html";
3612
+ function loadConnpassHtml() {
3613
+ try {
3614
+ const htmlPath = join(__dirname, "mcp-app.html");
3615
+ return readFileSync(htmlPath, "utf-8");
3616
+ } catch {
3617
+ try {
3618
+ const htmlPath = join(
3619
+ __dirname,
3620
+ "..",
3621
+ "..",
3622
+ "node_modules",
3623
+ "@kajidog",
3624
+ "connpass-ui",
3625
+ "dist",
3626
+ "mcp-app.html"
3627
+ );
3628
+ return readFileSync(htmlPath, "utf-8");
3629
+ } catch {
3630
+ console.error(
3631
+ "Warning: connpass-ui HTML not found. Please build @kajidog/connpass-ui first."
3632
+ );
3633
+ return "<html><body><p>Connpass UI not available. Please build @kajidog/connpass-ui.</p></body></html>";
3634
+ }
3635
+ }
3636
+ }
3637
+ var connpassHtml = loadConnpassHtml();
3638
+ function registerConnpassResource(deps) {
3639
+ const { server: server2 } = deps;
3640
+ registerAppResource(
3641
+ server2,
3642
+ "Connpass App",
3643
+ connpassResourceUri,
3644
+ {
3645
+ description: "Interactive Connpass event browser",
3646
+ mimeType: RESOURCE_MIME_TYPE
3647
+ },
3648
+ async () => ({
3649
+ contents: [
3650
+ {
3651
+ uri: connpassResourceUri,
3652
+ mimeType: RESOURCE_MIME_TYPE,
3653
+ text: connpassHtml,
3654
+ _meta: {
3655
+ ui: {
3656
+ csp: {
3657
+ resourceDomains: [
3658
+ "https://connpass.com",
3659
+ "https://media.connpass.com"
3660
+ ]
3661
+ }
3662
+ }
3663
+ }
3664
+ }
3665
+ ]
3666
+ })
3667
+ );
3668
+ }
3669
+
3670
+ // src/tools/utils/shared.ts
3671
+ var DEFAULT_PAGE_SIZE = 20;
3672
+ var EVENT_SORT_KEYS = [
3673
+ "start-date-asc",
3674
+ "start-date-desc",
3675
+ "newly-added"
3676
+ ];
3677
+ var EVENT_SORT_MAP = {
3678
+ "start-date-asc": 1,
3679
+ "start-date-desc": 2,
3680
+ "newly-added": 3
3681
+ };
3682
+ var GROUP_SORT_KEYS = [
3683
+ "most-events",
3684
+ "most-members",
3685
+ "newly-added"
3686
+ ];
3687
+ var GROUP_SORT_MAP = {
3688
+ "most-events": 1,
3689
+ "most-members": 2,
3690
+ "newly-added": 3
3691
+ };
3692
+ var USER_SORT_KEYS = [
3693
+ "most-events",
3694
+ "most-followers",
3695
+ "newly-added"
3696
+ ];
3697
+ var USER_SORT_MAP = {
3698
+ "most-events": 1,
3699
+ "most-followers": 2,
3700
+ "newly-added": 3
3701
+ };
3702
+ function formatAsCompactYmd(date) {
3703
+ const year = date.getFullYear();
3704
+ const month = String(date.getMonth() + 1).padStart(2, "0");
3705
+ const day = String(date.getDate()).padStart(2, "0");
3706
+ return `${year}${month}${day}`;
3707
+ }
3708
+ function formatAsHyphenatedYmd(date) {
3709
+ const year = date.getFullYear();
3710
+ const month = String(date.getMonth() + 1).padStart(2, "0");
3711
+ const day = String(date.getDate()).padStart(2, "0");
3712
+ return `${year}-${month}-${day}`;
3713
+ }
3714
+ function parseDateInput(input, options) {
3715
+ const normalized = input.trim();
3716
+ const hyphenFree = normalized.replace(/[-/.]/g, "");
3717
+ if (/^\d{8}$/.test(hyphenFree)) {
3718
+ const year = Number(hyphenFree.slice(0, 4));
3719
+ const month = Number(hyphenFree.slice(4, 6)) - 1;
3720
+ const day = Number(hyphenFree.slice(6, 8));
3721
+ const candidate = new Date(Date.UTC(year, month, day));
3722
+ if (!Number.isNaN(candidate.getTime())) {
3723
+ return options?.style === "hyphenated" ? formatAsHyphenatedYmd(candidate) : formatAsCompactYmd(candidate);
3724
+ }
3725
+ }
3726
+ throw new Error(
3727
+ `Invalid date format: ${input}. Expected YYYY-MM-DD or YYYYMMDD format.`
3728
+ );
3729
+ }
3730
+ function toYmdArray(value) {
3731
+ if (!value) return void 0;
3732
+ const inputs = Array.isArray(value) ? value : [value];
3733
+ return inputs.map((item) => parseDateInput(item));
3734
+ }
3735
+ function parseHyphenatedDate(input) {
3736
+ const parsed = parseDateInput(input, { style: "hyphenated" });
3737
+ if (/^\d{4}-\d{2}-\d{2}$/.test(parsed)) return parsed;
3738
+ const digitsOnly = parsed.replace(/[^0-9]/g, "");
3739
+ if (digitsOnly.length === 8) {
3740
+ return `${digitsOnly.slice(0, 4)}-${digitsOnly.slice(4, 6)}-${digitsOnly.slice(6, 8)}`;
3741
+ }
3742
+ throw new Error(`Could not convert date input to YYYY-MM-DD: ${input}`);
3743
+ }
3744
+ function normalizeStringArray(value) {
3745
+ if (!value) return void 0;
3746
+ return Array.isArray(value) ? value : [value];
3747
+ }
3748
+ function normalizeKeywordOr(value) {
3749
+ if (!value) return void 0;
3750
+ const tokens = value.split(/[、,]+/).map((item) => item.trim()).filter(Boolean);
3751
+ if (tokens.length === 0) return void 0;
3752
+ return tokens.join(",");
3753
+ }
3754
+ function applyPagination(page, pageSize, options) {
3755
+ const includePagination = options?.includePagination ?? true;
3756
+ if (!includePagination) return {};
3757
+ const effectivePageSize = pageSize ?? DEFAULT_PAGE_SIZE;
3758
+ const pagination = {};
3759
+ if (page) {
3760
+ pagination.start = 1 + (page - 1) * effectivePageSize;
3761
+ pagination.count = effectivePageSize;
3762
+ } else if (pageSize) {
3763
+ pagination.count = effectivePageSize;
3764
+ }
3765
+ return pagination;
3766
+ }
3767
+
3768
+ // src/tools/events.ts
3769
+ var EventSearchInputSchema = z2.object({
3770
+ anyQuery: z2.string().min(1).describe("Search keywords (comma-separated, matches ANY keyword)").optional(),
3771
+ on: z2.union([z2.string().min(1), z2.array(z2.string().min(1))]).describe("Specific date(s) in YYYY-MM-DD or YYYYMMDD format").optional(),
3772
+ from: z2.string().min(1).describe("Start of date range (inclusive). Format: YYYY-MM-DD").optional(),
3773
+ to: z2.string().min(1).describe("End of date range (inclusive). Format: YYYY-MM-DD").optional(),
3774
+ participantNickname: z2.string().min(1).describe("Filter by participant nickname").optional(),
3775
+ hostNickname: z2.string().min(1).describe("Filter by host/owner nickname").optional(),
3776
+ groupIds: z2.array(z2.number()).describe("Limit results to specific group IDs").optional(),
3777
+ prefectures: z2.union([z2.string().min(1), z2.array(z2.string().min(1))]).describe("Prefecture name(s) to filter by").optional(),
3778
+ page: z2.number().int().min(1).describe("1-based page number").optional(),
3779
+ pageSize: z2.number().int().min(1).max(100).describe("Events per page (default 20, max 100)").optional(),
3780
+ sort: z2.enum(EVENT_SORT_KEYS).describe("Sort order").optional(),
3781
+ includeDetails: z2.boolean().describe(
3782
+ "Include event description (up to 200 chars). Use when you need content details for recommendations."
3783
+ ).default(false).optional()
3784
+ });
3785
+ var EventPresentationsInputSchema = z2.object({
3786
+ eventId: z2.union([z2.number().int().positive(), z2.string().min(1)]).describe("Connpass event ID").transform((value) => Number(value)).refine((value) => Number.isFinite(value), "eventId must be a number")
3787
+ });
3788
+ function buildEventSearchParams(input) {
3789
+ const pagination = applyPagination(input.page, input.pageSize);
3790
+ const resolved = resolvePrefectureInputs(input.prefectures);
3791
+ if ("response" in resolved) {
3792
+ return resolved;
3793
+ }
3794
+ return {
3795
+ keywordOr: normalizeKeywordOr(input.anyQuery),
3796
+ ymd: toYmdArray(input.on),
3797
+ ymdFrom: input.from ? parseHyphenatedDate(input.from) : void 0,
3798
+ ymdTo: input.to ? parseHyphenatedDate(input.to) : void 0,
3799
+ nickname: input.participantNickname,
3800
+ ownerNickname: input.hostNickname,
3801
+ groupId: input.groupIds,
3802
+ prefecture: resolved.prefectures ?? normalizeStringArray(input.prefectures),
3803
+ order: input.sort ? EVENT_SORT_MAP[input.sort] : void 0,
3804
+ ...pagination
3805
+ };
3806
+ }
3807
+ var LIST_FORMAT_OPTIONS = {
3808
+ descriptionLimit: 0,
3809
+ catchPhraseLimit: 100
3810
+ };
3811
+ function registerEventTools(deps) {
3812
+ const { server: server2, connpassClient, searchSessionStore } = deps;
3813
+ const searchEventsHandler = async (args) => {
3814
+ const params = EventSearchInputSchema.parse(args ?? {});
3815
+ const searchParams = buildEventSearchParams(params);
3816
+ if ("response" in searchParams) {
3817
+ return {
3818
+ ...searchParams.response,
3819
+ isError: true
3820
+ };
3821
+ }
3822
+ const response = await connpassClient.searchEvents(searchParams);
3823
+ const formatOptions = params.includeDetails ? FORMAT_PRESETS.detailed : FORMAT_PRESETS.default;
3824
+ const formatted = formatEventsResponse(response, formatOptions);
3825
+ const browseFormatted = formatEventsResponse(response, LIST_FORMAT_OPTIONS);
3826
+ const searchSessionId = searchSessionStore.save(browseFormatted);
3827
+ return {
3828
+ content: [
3829
+ {
3830
+ type: "text",
3831
+ text: summarizeEventsResponse(formatted)
3832
+ }
3833
+ ],
3834
+ structuredContent: {
3835
+ kind: "events",
3836
+ searchSessionId,
3837
+ data: formatted
3838
+ }
3839
+ };
3840
+ };
3841
+ registerAppToolIfEnabled(
3842
+ server2,
3843
+ "search_events",
3844
+ {
3845
+ title: "Search Events",
3846
+ description: "Search Connpass events and return results as text for reasoning and recommendations. Use this whenever the user asks about events.",
3847
+ inputSchema: EventSearchInputSchema
3848
+ },
3849
+ searchEventsHandler
3850
+ );
3851
+ registerAppToolIfEnabled(
3852
+ server2,
3853
+ "browse_events",
3854
+ {
3855
+ title: "Browse Events",
3856
+ description: "Display previously searched events in the interactive event browser UI. Use this proactively when the user wants to browse event options, scan many candidates, compare events, or inspect results visually. The UI lets the user refine and re-run searches directly, so prefer this for event exploration. Call this ONCE with the searchSessionId returned by search_events. Do not use this to search again.",
3857
+ inputSchema: z2.object({
3858
+ searchSessionId: z2.uuid().describe("Session ID returned by search_events")
3859
+ }),
3860
+ _meta: {
3861
+ ui: { resourceUri: connpassResourceUri }
3862
+ }
3863
+ },
3864
+ async (args) => {
3865
+ const { searchSessionId } = z2.object({
3866
+ searchSessionId: z2.uuid()
3867
+ }).parse(args ?? {});
3868
+ const formatted = searchSessionStore.get(searchSessionId);
3869
+ if (!formatted) {
3870
+ return {
3871
+ content: [
3872
+ {
3873
+ type: "text",
3874
+ text: "Search session not found or expired. Run search_events again, then call browse_events once with the returned searchSessionId."
3875
+ }
3876
+ ],
3877
+ isError: true
3878
+ };
3879
+ }
3880
+ return {
3881
+ content: [
3882
+ { type: "text", text: summarizeEventsResponse(formatted) }
3883
+ ],
3884
+ structuredContent: {
3885
+ kind: "events",
3886
+ searchSessionId,
3887
+ data: formatted
3888
+ }
3889
+ };
3890
+ }
3891
+ );
3892
+ registerAppToolIfEnabled(
3893
+ server2,
3894
+ "get_event_presentations",
3895
+ {
3896
+ title: "Get Event Presentations",
3897
+ description: "Look up presentation details for a specific event",
3898
+ inputSchema: EventPresentationsInputSchema
3899
+ },
3900
+ async (args) => {
3901
+ const { eventId } = EventPresentationsInputSchema.parse(args ?? {});
3902
+ const response = await connpassClient.getEventPresentations(eventId);
3903
+ const formatted = formatPresentationsResponse(response);
3904
+ return {
3905
+ content: [{ type: "text", text: JSON.stringify(formatted) }]
3906
+ };
3907
+ }
3908
+ );
3909
+ registerAppToolIfEnabled(
3910
+ server2,
3911
+ "get_event_detail",
3912
+ {
3913
+ title: "Get Event Detail",
3914
+ description: "Get full details of a specific event by ID, including complete description and presentations",
3915
+ inputSchema: EventPresentationsInputSchema
3916
+ },
3917
+ async (args) => {
3918
+ const { eventId } = EventPresentationsInputSchema.parse(args ?? {});
3919
+ const [eventsResponse, presentationsResponse] = await Promise.all([
3920
+ connpassClient.searchEvents({ eventId: [eventId], count: 1 }),
3921
+ connpassClient.getEventPresentations(eventId).catch(() => void 0)
3922
+ ]);
3923
+ const event = eventsResponse.events[0];
3924
+ if (!event) {
3925
+ throw new Error(`Event with ID ${eventId} not found.`);
3926
+ }
3927
+ const formatted = formatEvent(event, FORMAT_PRESETS.full);
3928
+ const presentations = presentationsResponse ? formatPresentationsResponse(presentationsResponse) : void 0;
3929
+ return {
3930
+ content: [
3931
+ {
3932
+ type: "text",
3933
+ text: JSON.stringify({ event: formatted, presentations })
3934
+ }
3935
+ ]
3936
+ };
3937
+ }
3938
+ );
3939
+ }
3940
+
3941
+ // src/tools/groups.ts
3942
+ import { z as z3 } from "zod";
3943
+ var GroupSearchInputSchema = z3.object({
3944
+ query: z3.string().min(1).describe("Keywords matching group title or description").optional(),
3945
+ groupIds: z3.array(z3.number()).describe("Limit to specific group IDs").optional(),
3946
+ country: z3.string().min(1).describe("ISO country code, e.g. 'JP'").optional(),
3947
+ prefecture: z3.string().min(1).describe("Prefecture name to filter by").optional(),
3948
+ page: z3.number().int().min(1).describe("1-based page number").optional(),
3949
+ pageSize: z3.number().int().min(1).max(100).describe("Groups per page (default 20)").optional(),
3950
+ sort: z3.enum(GROUP_SORT_KEYS).describe("Ranking by activity, members, or recency").optional()
3951
+ });
3952
+ function buildGroupSearchParams(input) {
3953
+ const pagination = applyPagination(input.page, input.pageSize);
3954
+ const resolved = resolvePrefectureInputs(input.prefecture);
3955
+ if ("response" in resolved) {
3956
+ return resolved;
3957
+ }
3958
+ return {
3959
+ keyword: input.query,
3960
+ groupId: input.groupIds,
3961
+ countryCode: input.country,
3962
+ prefecture: resolved.prefectures?.[0] ?? input.prefecture,
3963
+ order: input.sort ? GROUP_SORT_MAP[input.sort] : void 0,
3964
+ ...pagination
3965
+ };
3966
+ }
3967
+ function registerGroupTools(deps) {
3968
+ const { server: server2, connpassClient } = deps;
3969
+ registerAppToolIfEnabled(
3970
+ server2,
3971
+ "search_groups",
3972
+ {
3973
+ title: "Search Groups",
3974
+ description: "Find Connpass groups with simple filters",
3975
+ inputSchema: GroupSearchInputSchema
3976
+ },
3977
+ async (args) => {
3978
+ const params = GroupSearchInputSchema.parse(args ?? {});
3979
+ const searchParams = buildGroupSearchParams(params);
3980
+ if ("response" in searchParams) {
3981
+ return {
3982
+ ...searchParams.response,
3983
+ isError: true
3984
+ };
3985
+ }
3986
+ const response = await connpassClient.searchGroups(searchParams);
3987
+ return {
3988
+ content: [
3989
+ { type: "text", text: summarizeGroupsResponse(response) }
3990
+ ]
3991
+ };
3992
+ }
3993
+ );
3994
+ }
3995
+
3996
+ // src/tools/schedule.ts
3997
+ import { z as z4 } from "zod";
3998
+ var ScheduleInputSchema = z4.object({
3999
+ userId: z4.number().int().positive().describe("Connpass user ID").optional(),
4000
+ nickname: z4.string().min(1).describe("Connpass user nickname").optional(),
4001
+ fromDate: z4.string().min(1).describe("Start date (YYYY-MM-DD). Defaults to today.").optional(),
4002
+ toDate: z4.string().min(1).describe("End date (YYYY-MM-DD). Defaults to +7 days.").optional(),
4003
+ maxEvents: z4.number().int().min(1).max(100).describe("Maximum events to check (default 30)").optional(),
4004
+ includeDetails: z4.boolean().describe("Include event description (up to 200 chars)").default(false).optional()
4005
+ });
4006
+ function startOfDay(date) {
4007
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
4008
+ }
4009
+ function formatDateLabel(date) {
4010
+ const year = date.getFullYear();
4011
+ const month = String(date.getMonth() + 1).padStart(2, "0");
4012
+ const day = String(date.getDate()).padStart(2, "0");
4013
+ return `${year}-${month}-${day}`;
4014
+ }
4015
+ function registerScheduleTools(deps) {
4016
+ const { server: server2, connpassClient, config: config2 } = deps;
4017
+ registerAppToolIfEnabled(
4018
+ server2,
4019
+ "search_schedule",
4020
+ {
4021
+ title: "Search Schedule",
4022
+ description: "Search user's schedule - events within a date range",
4023
+ inputSchema: ScheduleInputSchema,
4024
+ _meta: {
4025
+ ui: { resourceUri: connpassResourceUri }
4026
+ }
4027
+ },
4028
+ async (args) => {
4029
+ const parsed = ScheduleInputSchema.parse(args ?? {});
4030
+ let resolvedUserId = parsed.userId ?? config2.defaultUserId;
4031
+ let userNickname;
4032
+ if (parsed.nickname) {
4033
+ const userSearchResponse = await connpassClient.searchUsers({
4034
+ nickname: parsed.nickname
4035
+ });
4036
+ if (userSearchResponse.users.length === 0) {
4037
+ throw new Error(`User with nickname "${parsed.nickname}" not found.`);
4038
+ }
4039
+ resolvedUserId = userSearchResponse.users[0].id;
4040
+ userNickname = userSearchResponse.users[0].nickname;
4041
+ }
4042
+ if (!resolvedUserId) {
4043
+ throw new Error(
4044
+ "User ID or nickname is required. Pass userId, nickname, or set CONNPASS_DEFAULT_USER_ID."
4045
+ );
4046
+ }
4047
+ const maxEventsToFetch = parsed.maxEvents ?? 30;
4048
+ const today = startOfDay(/* @__PURE__ */ new Date());
4049
+ const rangeStart = parsed.fromDate ? startOfDay(new Date(parseHyphenatedDate(parsed.fromDate))) : today;
4050
+ const rangeEnd = parsed.toDate ? startOfDay(new Date(parseHyphenatedDate(parsed.toDate))) : (() => {
4051
+ const defaultEnd = new Date(rangeStart);
4052
+ defaultEnd.setDate(defaultEnd.getDate() + 7);
4053
+ return defaultEnd;
4054
+ })();
4055
+ rangeEnd.setHours(23, 59, 59, 999);
4056
+ if (!userNickname) {
4057
+ const userResponse = await connpassClient.searchUsers({
4058
+ userId: [resolvedUserId]
4059
+ });
4060
+ if (userResponse.users.length === 0) {
4061
+ throw new Error(`User with ID ${resolvedUserId} not found.`);
4062
+ }
4063
+ userNickname = userResponse.users.find(
4064
+ (u) => u.id === resolvedUserId
4065
+ )?.nickname;
4066
+ if (!userNickname)
4067
+ throw new Error(`User with ID ${resolvedUserId} not found.`);
4068
+ }
4069
+ const searchResponse = await connpassClient.searchEvents({
4070
+ nickname: userNickname,
4071
+ ymdFrom: formatDateLabel(rangeStart),
4072
+ ymdTo: formatDateLabel(rangeEnd),
4073
+ order: EVENT_SORT_MAP["start-date-asc"],
4074
+ count: maxEventsToFetch
4075
+ });
4076
+ const eventsByDate = /* @__PURE__ */ new Map();
4077
+ for (const event of searchResponse.events) {
4078
+ const eventDate = formatDateLabel(
4079
+ startOfDay(new Date(event.startedAt))
4080
+ );
4081
+ if (!eventsByDate.has(eventDate)) {
4082
+ eventsByDate.set(eventDate, []);
4083
+ }
4084
+ eventsByDate.get(eventDate).push(event);
4085
+ }
4086
+ const sortedDates = Array.from(eventsByDate.keys()).sort();
4087
+ const sections = sortedDates.map((date) => ({
4088
+ date,
4089
+ events: formatEventList(
4090
+ eventsByDate.get(date),
4091
+ parsed.includeDetails ? FORMAT_PRESETS.detailed : FORMAT_PRESETS.default
4092
+ )
4093
+ }));
4094
+ const result = {
4095
+ userId: resolvedUserId,
4096
+ sections,
4097
+ metadata: {
4098
+ fromDate: formatDateLabel(rangeStart),
4099
+ toDate: formatDateLabel(rangeEnd),
4100
+ inspected: searchResponse.eventsReturned,
4101
+ limit: maxEventsToFetch
4102
+ }
4103
+ };
4104
+ return {
4105
+ content: [
4106
+ {
4107
+ type: "text",
4108
+ text: summarizeEventsResponse(
4109
+ {
4110
+ returned: sections.reduce(
4111
+ (count, section) => count + section.events.length,
4112
+ 0
4113
+ ),
4114
+ available: sections.reduce(
4115
+ (count, section) => count + section.events.length,
4116
+ 0
4117
+ ),
4118
+ start: 1,
4119
+ events: sections.flatMap((section) => section.events)
4120
+ },
4121
+ "schedule"
4122
+ )
4123
+ }
4124
+ ],
4125
+ structuredContent: {
4126
+ kind: "schedule",
4127
+ data: result
4128
+ }
4129
+ };
4130
+ }
4131
+ );
4132
+ }
4133
+
4134
+ // src/tools/ui-tools/detail.ts
4135
+ import { z as z5 } from "zod";
4136
+ var UIEventDetailInputSchema = z5.object({
4137
+ eventId: z5.number().int().positive()
4138
+ });
4139
+ function registerUIEventDetailTool(deps) {
4140
+ const { server: server2, connpassClient } = deps;
4141
+ registerAppToolIfEnabled(
4142
+ server2,
4143
+ "_get_event_detail",
4144
+ {
4145
+ title: "Get Event Detail (UI)",
4146
+ description: "Internal: fetch full event details for the detail view",
4147
+ inputSchema: UIEventDetailInputSchema,
4148
+ _meta: {
4149
+ ui: {
4150
+ resourceUri: connpassResourceUri,
4151
+ visibility: ["app"]
4152
+ }
4153
+ }
4154
+ },
4155
+ async (args) => {
4156
+ const { eventId } = UIEventDetailInputSchema.parse(args ?? {});
4157
+ const [eventsResponse, presentationsResponse] = await Promise.all([
4158
+ connpassClient.searchEvents({
4159
+ eventId: [eventId],
4160
+ count: 1
4161
+ }),
4162
+ connpassClient.getEventPresentations(eventId).catch(() => void 0)
4163
+ ]);
4164
+ const event = eventsResponse.events[0];
4165
+ if (!event) {
4166
+ throw new Error(`Event with ID ${eventId} not found.`);
4167
+ }
4168
+ const formatted = formatEvent(event);
4169
+ const presentations = presentationsResponse ? formatPresentationsResponse(presentationsResponse) : void 0;
4170
+ const detailEvent = presentations?.presentations?.length ? { ...formatted, presentations: presentations.presentations } : formatted;
4171
+ return {
4172
+ content: [{ type: "text", text: JSON.stringify(detailEvent) }],
4173
+ structuredContent: {
4174
+ kind: "event-detail",
4175
+ data: {
4176
+ event: detailEvent,
4177
+ presentations
4178
+ }
4179
+ }
4180
+ };
4181
+ }
4182
+ );
4183
+ }
4184
+
4185
+ // src/tools/ui-tools/schedule.ts
4186
+ import { z as z6 } from "zod";
4187
+ var UIScheduleInputSchema = z6.object({
4188
+ userId: z6.number().int().positive().optional(),
4189
+ nickname: z6.string().min(1).optional(),
4190
+ fromDate: z6.string().min(1).optional(),
4191
+ toDate: z6.string().min(1).optional(),
4192
+ maxEvents: z6.number().int().min(1).max(100).optional()
4193
+ });
4194
+ function startOfDay2(date) {
4195
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate());
4196
+ }
4197
+ function formatDateLabel2(date) {
4198
+ const year = date.getFullYear();
4199
+ const month = String(date.getMonth() + 1).padStart(2, "0");
4200
+ const day = String(date.getDate()).padStart(2, "0");
4201
+ return `${year}-${month}-${day}`;
4202
+ }
4203
+ var SCHEDULE_FORMAT_OPTIONS = {
4204
+ descriptionLimit: 0,
4205
+ catchPhraseLimit: 100
4206
+ };
4207
+ var userNicknameCache = /* @__PURE__ */ new Map();
4208
+ function registerUIScheduleTool(deps) {
4209
+ const { server: server2, connpassClient, config: config2 } = deps;
4210
+ registerAppToolIfEnabled(
4211
+ server2,
4212
+ "_search_schedule",
4213
+ {
4214
+ title: "Search Schedule (UI)",
4215
+ description: "Internal: re-search schedule from UI",
4216
+ inputSchema: UIScheduleInputSchema,
4217
+ _meta: {
4218
+ ui: {
4219
+ resourceUri: connpassResourceUri,
4220
+ visibility: ["app"]
4221
+ }
4222
+ }
4223
+ },
4224
+ async (args) => {
4225
+ const parsed = UIScheduleInputSchema.parse(args ?? {});
4226
+ let resolvedUserId = parsed.userId ?? config2.defaultUserId;
4227
+ let userNickname;
4228
+ if (parsed.nickname) {
4229
+ const userSearchResponse = await connpassClient.searchUsers({
4230
+ nickname: parsed.nickname
4231
+ });
4232
+ if (userSearchResponse.users.length === 0) {
4233
+ throw new Error(`User with nickname "${parsed.nickname}" not found.`);
4234
+ }
4235
+ resolvedUserId = userSearchResponse.users[0].id;
4236
+ userNickname = userSearchResponse.users[0].nickname;
4237
+ userNicknameCache.set(resolvedUserId, userNickname);
4238
+ }
4239
+ if (!resolvedUserId) {
4240
+ throw new Error("User ID or nickname is required.");
4241
+ }
4242
+ const maxEventsToFetch = parsed.maxEvents ?? 30;
4243
+ const today = startOfDay2(/* @__PURE__ */ new Date());
4244
+ const rangeStart = parsed.fromDate ? startOfDay2(new Date(parseHyphenatedDate(parsed.fromDate))) : today;
4245
+ const rangeEnd = parsed.toDate ? startOfDay2(new Date(parseHyphenatedDate(parsed.toDate))) : (() => {
4246
+ const defaultEnd = new Date(rangeStart);
4247
+ defaultEnd.setDate(defaultEnd.getDate() + 7);
4248
+ return defaultEnd;
4249
+ })();
4250
+ rangeEnd.setHours(23, 59, 59, 999);
4251
+ if (!userNickname) {
4252
+ userNickname = userNicknameCache.get(resolvedUserId);
4253
+ if (!userNickname) {
4254
+ const userResponse = await connpassClient.searchUsers({
4255
+ userId: [resolvedUserId]
4256
+ });
4257
+ if (userResponse.users.length === 0)
4258
+ throw new Error(`User with ID ${resolvedUserId} not found.`);
4259
+ userNickname = userResponse.users.find(
4260
+ (u) => u.id === resolvedUserId
4261
+ )?.nickname;
4262
+ if (!userNickname)
4263
+ throw new Error(`User with ID ${resolvedUserId} not found.`);
4264
+ userNicknameCache.set(resolvedUserId, userNickname);
4265
+ }
4266
+ }
4267
+ const searchResponse = await connpassClient.searchEvents({
4268
+ nickname: userNickname,
4269
+ ymdFrom: formatDateLabel2(rangeStart),
4270
+ ymdTo: formatDateLabel2(rangeEnd),
4271
+ order: EVENT_SORT_MAP["start-date-asc"],
4272
+ count: maxEventsToFetch
4273
+ });
4274
+ const eventsByDate = /* @__PURE__ */ new Map();
4275
+ for (const event of searchResponse.events) {
4276
+ const eventDate = formatDateLabel2(
4277
+ startOfDay2(new Date(event.startedAt))
4278
+ );
4279
+ if (!eventsByDate.has(eventDate)) eventsByDate.set(eventDate, []);
4280
+ eventsByDate.get(eventDate).push(event);
4281
+ }
4282
+ const sortedDates = Array.from(eventsByDate.keys()).sort();
4283
+ const sections = sortedDates.map((date) => ({
4284
+ date,
4285
+ events: formatEventList(
4286
+ eventsByDate.get(date),
4287
+ SCHEDULE_FORMAT_OPTIONS
4288
+ )
4289
+ }));
4290
+ const result = {
4291
+ userId: resolvedUserId,
4292
+ sections,
4293
+ metadata: {
4294
+ fromDate: formatDateLabel2(rangeStart),
4295
+ toDate: formatDateLabel2(rangeEnd),
4296
+ inspected: searchResponse.eventsReturned,
4297
+ limit: maxEventsToFetch
4298
+ }
4299
+ };
4300
+ return {
4301
+ content: [{ type: "text", text: JSON.stringify(result) }],
4302
+ structuredContent: {
4303
+ kind: "schedule",
4304
+ data: result
4305
+ }
4306
+ };
4307
+ }
4308
+ );
4309
+ }
4310
+
4311
+ // src/tools/ui-tools/search.ts
4312
+ import { z as z7 } from "zod";
4313
+ var UI_LIST_FORMAT_OPTIONS = {
4314
+ descriptionLimit: 0,
4315
+ catchPhraseLimit: 100
4316
+ };
4317
+ var UIEventSearchInputSchema = z7.object({
4318
+ query: z7.string().min(1).optional(),
4319
+ anyQuery: z7.string().min(1).optional(),
4320
+ on: z7.union([z7.string().min(1), z7.array(z7.string().min(1))]).optional(),
4321
+ from: z7.string().min(1).optional(),
4322
+ to: z7.string().min(1).optional(),
4323
+ participantNickname: z7.string().min(1).optional(),
4324
+ hostNickname: z7.string().min(1).optional(),
4325
+ groupIds: z7.array(z7.number()).optional(),
4326
+ prefectures: z7.union([z7.string().min(1), z7.array(z7.string().min(1))]).optional(),
4327
+ companyQuery: z7.string().min(1).optional(),
4328
+ minAccepted: z7.number().int().min(0).optional(),
4329
+ maxAccepted: z7.number().int().min(0).optional(),
4330
+ minCapacity: z7.number().int().min(0).optional(),
4331
+ maxCapacity: z7.number().int().min(0).optional(),
4332
+ page: z7.number().int().min(1).optional(),
4333
+ pageSize: z7.number().int().min(1).max(100).optional(),
4334
+ sort: z7.enum(["start-date-asc", "participant-count-desc", "title-asc"]).optional()
4335
+ });
4336
+ function includesNormalized(targets, query) {
4337
+ if (!query) return true;
4338
+ const normalizedQuery = query.trim().toLowerCase();
4339
+ if (!normalizedQuery) return true;
4340
+ return targets.some(
4341
+ (value) => value?.toLowerCase().includes(normalizedQuery)
4342
+ );
4343
+ }
4344
+ function applyLocalFilters(events, params) {
4345
+ return events.filter((event) => {
4346
+ if (!includesNormalized(
4347
+ [event.ownerDisplayName, event.groupTitle],
4348
+ params.companyQuery
4349
+ )) {
4350
+ return false;
4351
+ }
4352
+ if (typeof params.minAccepted === "number" && event.participantCount < params.minAccepted) {
4353
+ return false;
4354
+ }
4355
+ if (typeof params.maxAccepted === "number" && event.participantCount > params.maxAccepted) {
4356
+ return false;
4357
+ }
4358
+ if (typeof params.minCapacity === "number") {
4359
+ const limit = typeof event.limit === "number" ? event.limit : 0;
4360
+ if (limit < params.minCapacity) return false;
4361
+ }
4362
+ if (typeof params.maxCapacity === "number") {
4363
+ const limit = typeof event.limit === "number" ? event.limit : 0;
4364
+ if (limit > params.maxCapacity) return false;
4365
+ }
4366
+ return true;
4367
+ });
4368
+ }
4369
+ function sortEvents(events, sort) {
4370
+ const copied = [...events];
4371
+ copied.sort((a, b) => {
4372
+ if (sort === "participant-count-desc") {
4373
+ return b.participantCount - a.participantCount || a.startedAt.localeCompare(b.startedAt);
4374
+ }
4375
+ if (sort === "title-asc") {
4376
+ return a.title.localeCompare(b.title, "ja") || a.startedAt.localeCompare(b.startedAt);
4377
+ }
4378
+ return a.startedAt.localeCompare(b.startedAt);
4379
+ });
4380
+ return copied;
4381
+ }
4382
+ function registerUISearchTool(deps) {
4383
+ const { server: server2, connpassClient } = deps;
4384
+ registerAppToolIfEnabled(
4385
+ server2,
4386
+ "_search_events",
4387
+ {
4388
+ title: "Search Events (UI)",
4389
+ description: "Internal: re-search events from UI",
4390
+ inputSchema: UIEventSearchInputSchema,
4391
+ _meta: {
4392
+ ui: {
4393
+ resourceUri: connpassResourceUri,
4394
+ visibility: ["app"]
4395
+ }
4396
+ }
4397
+ },
4398
+ async (args) => {
4399
+ const params = UIEventSearchInputSchema.parse(args ?? {});
4400
+ const useLocalFiltering = Boolean(params.companyQuery) || typeof params.minAccepted === "number" || typeof params.maxAccepted === "number" || typeof params.minCapacity === "number" || typeof params.maxCapacity === "number" || params.sort === "participant-count-desc" || params.sort === "title-asc";
4401
+ const pagination = useLocalFiltering ? {} : applyPagination(params.page, params.pageSize);
4402
+ const resolved = resolvePrefectureInputs(params.prefectures);
4403
+ if ("response" in resolved) {
4404
+ return {
4405
+ ...resolved.response,
4406
+ isError: true
4407
+ };
4408
+ }
4409
+ const searchParams = {
4410
+ keyword: params.query,
4411
+ keywordOr: normalizeKeywordOr(params.anyQuery),
4412
+ ymd: toYmdArray(params.on),
4413
+ ymdFrom: params.from ? parseHyphenatedDate(params.from) : void 0,
4414
+ ymdTo: params.to ? parseHyphenatedDate(params.to) : void 0,
4415
+ nickname: params.participantNickname,
4416
+ ownerNickname: params.hostNickname,
4417
+ groupId: params.groupIds,
4418
+ prefecture: resolved.prefectures ?? normalizeStringArray(params.prefectures),
4419
+ order: EVENT_SORT_MAP["start-date-asc"],
4420
+ ...pagination
4421
+ };
4422
+ if (!useLocalFiltering) {
4423
+ const response2 = await connpassClient.searchEvents(searchParams);
4424
+ const formatted2 = formatEventsResponse(
4425
+ response2,
4426
+ UI_LIST_FORMAT_OPTIONS
4427
+ );
4428
+ return {
4429
+ content: [{ type: "text", text: JSON.stringify(formatted2) }],
4430
+ structuredContent: {
4431
+ kind: "events",
4432
+ data: formatted2
4433
+ }
4434
+ };
4435
+ }
4436
+ const response = await connpassClient.getAllEvents(searchParams);
4437
+ const filtered = sortEvents(
4438
+ applyLocalFilters(response.events, params),
4439
+ params.sort
4440
+ );
4441
+ const pageSize = params.pageSize ?? 20;
4442
+ const page = params.page ?? 1;
4443
+ const sliceStart = (page - 1) * pageSize;
4444
+ const paged = filtered.slice(sliceStart, sliceStart + pageSize);
4445
+ const formatted = {
4446
+ returned: paged.length,
4447
+ available: filtered.length,
4448
+ start: filtered.length === 0 ? 0 : sliceStart + 1,
4449
+ events: paged.map(
4450
+ (event) => formatEvent(event, UI_LIST_FORMAT_OPTIONS)
4451
+ )
4452
+ };
4453
+ return {
4454
+ content: [{ type: "text", text: JSON.stringify(formatted) }],
4455
+ structuredContent: {
4456
+ kind: "events",
4457
+ data: formatted
4458
+ }
4459
+ };
4460
+ }
4461
+ );
4462
+ }
4463
+
4464
+ // src/tools/ui-tools/index.ts
4465
+ function registerUITools(deps) {
4466
+ registerUIEventDetailTool(deps);
4467
+ registerUISearchTool(deps);
4468
+ registerUIScheduleTool(deps);
4469
+ }
4470
+
4471
+ // src/tools/users.ts
4472
+ import { z as z8 } from "zod";
4473
+ var UserSearchInputSchema = z8.object({
4474
+ nickname: z8.string().min(1).describe("Match users by nickname (substring search)").optional(),
4475
+ userIds: z8.array(z8.number()).describe("Limit to specific user IDs").optional(),
4476
+ page: z8.number().int().min(1).describe("1-based page number").optional(),
4477
+ pageSize: z8.number().int().min(1).max(100).describe("Users per page (default 20)").optional(),
4478
+ sort: z8.enum(USER_SORT_KEYS).describe("Ranking by activity, followers, or recency").optional()
4479
+ });
4480
+ var UserGroupsInputSchema = z8.object({
4481
+ userId: z8.number().int().positive().describe("Connpass user ID"),
4482
+ limit: z8.number().int().min(1).max(100).describe("How many to return (default 20)").optional(),
4483
+ page: z8.number().int().min(1).describe("1-based page number").optional()
4484
+ });
4485
+ var UserRelationshipInputSchema = z8.object({
4486
+ userId: z8.number().int().positive().describe("Connpass user ID"),
4487
+ limit: z8.number().int().min(1).max(100).describe("How many to return (default 20)").optional(),
4488
+ page: z8.number().int().min(1).describe("1-based page number").optional(),
4489
+ sort: z8.enum(EVENT_SORT_KEYS).describe("Sort events by schedule or recency").optional(),
4490
+ includeDetails: z8.boolean().describe(
4491
+ "Include event description (up to 200 chars). Use when you need content details for recommendations."
4492
+ ).default(false).optional()
188
4493
  });
4494
+ function buildUserRelationshipParams(input) {
4495
+ const pagination = applyPagination(input.page, input.limit, {
4496
+ includePagination: true
4497
+ });
4498
+ return {
4499
+ pagination,
4500
+ order: input.sort ? EVENT_SORT_MAP[input.sort] : void 0
4501
+ };
4502
+ }
4503
+ function registerUserTools(deps) {
4504
+ const { server: server2, connpassClient } = deps;
4505
+ registerAppToolIfEnabled(
4506
+ server2,
4507
+ "search_users",
4508
+ {
4509
+ title: "Search Users",
4510
+ description: "Discover Connpass users",
4511
+ inputSchema: UserSearchInputSchema
4512
+ },
4513
+ async (args) => {
4514
+ const params = UserSearchInputSchema.parse(args ?? {});
4515
+ const pagination = applyPagination(params.page, params.pageSize);
4516
+ const response = await connpassClient.searchUsers({
4517
+ nickname: params.nickname,
4518
+ userId: params.userIds,
4519
+ order: params.sort ? USER_SORT_MAP[params.sort] : void 0,
4520
+ ...pagination
4521
+ });
4522
+ return {
4523
+ content: [
4524
+ { type: "text", text: summarizeUsersResponse(response) }
4525
+ ]
4526
+ };
4527
+ }
4528
+ );
4529
+ registerAppToolIfEnabled(
4530
+ server2,
4531
+ "get_user_groups",
4532
+ {
4533
+ title: "Get User Groups",
4534
+ description: "List the groups a user belongs to",
4535
+ inputSchema: UserGroupsInputSchema
4536
+ },
4537
+ async (args) => {
4538
+ const { userId, limit, page } = UserGroupsInputSchema.parse(args ?? {});
4539
+ const pagination = applyPagination(page, limit);
4540
+ const response = await connpassClient.getUserGroups(userId, pagination);
4541
+ return {
4542
+ content: [
4543
+ { type: "text", text: summarizeGroupsResponse(response) }
4544
+ ]
4545
+ };
4546
+ }
4547
+ );
4548
+ registerAppToolIfEnabled(
4549
+ server2,
4550
+ "get_user_attended_events",
4551
+ {
4552
+ title: "Get User Attended Events",
4553
+ description: "List events that a user has attended",
4554
+ inputSchema: UserRelationshipInputSchema
4555
+ },
4556
+ async (args) => {
4557
+ const parsed = UserRelationshipInputSchema.parse(args ?? {});
4558
+ const { pagination, order } = buildUserRelationshipParams(parsed);
4559
+ const response = await connpassClient.getUserAttendedEvents(
4560
+ parsed.userId,
4561
+ { ...pagination, order }
4562
+ );
4563
+ const formatOptions = parsed.includeDetails ? FORMAT_PRESETS.detailed : FORMAT_PRESETS.default;
4564
+ const formatted = formatEventsResponse(response, formatOptions);
4565
+ return {
4566
+ content: [
4567
+ {
4568
+ type: "text",
4569
+ text: summarizeEventsResponse(formatted, "attended events")
4570
+ }
4571
+ ]
4572
+ };
4573
+ }
4574
+ );
4575
+ registerAppToolIfEnabled(
4576
+ server2,
4577
+ "get_user_presenter_events",
4578
+ {
4579
+ title: "Get User Presenter Events",
4580
+ description: "List events where the user presented",
4581
+ inputSchema: UserRelationshipInputSchema
4582
+ },
4583
+ async (args) => {
4584
+ const parsed = UserRelationshipInputSchema.parse(args ?? {});
4585
+ const { pagination, order } = buildUserRelationshipParams(parsed);
4586
+ const response = await connpassClient.getUserPresenterEvents(
4587
+ parsed.userId,
4588
+ { ...pagination, order }
4589
+ );
4590
+ const formatOptions = parsed.includeDetails ? FORMAT_PRESETS.detailed : FORMAT_PRESETS.default;
4591
+ const formatted = formatEventsResponse(response, formatOptions);
4592
+ return {
4593
+ content: [
4594
+ {
4595
+ type: "text",
4596
+ text: summarizeEventsResponse(formatted, "presenter events")
4597
+ }
4598
+ ]
4599
+ };
4600
+ }
4601
+ );
4602
+ }
4603
+
4604
+ // src/tools/index.ts
4605
+ function registerAllTools(deps) {
4606
+ registerConnpassResource(deps);
4607
+ registerEventTools(deps);
4608
+ registerScheduleTools(deps);
4609
+ registerGroupTools(deps);
4610
+ registerPrefectureTools(deps);
4611
+ registerUserTools(deps);
4612
+ registerUITools(deps);
4613
+ }
4614
+
4615
+ // src/tools/utils/searchSessionStore.ts
4616
+ import { randomUUID as randomUUID2 } from "crypto";
4617
+ var SearchSessionStore = class {
4618
+ ttlMs;
4619
+ sessions = /* @__PURE__ */ new Map();
4620
+ constructor(options = {}) {
4621
+ this.ttlMs = options.ttlMs ?? 10 * 60 * 1e3;
4622
+ }
4623
+ save(result) {
4624
+ this.cleanup();
4625
+ const sessionId = randomUUID2();
4626
+ this.sessions.set(sessionId, {
4627
+ expiresAt: Date.now() + this.ttlMs,
4628
+ result
4629
+ });
4630
+ return sessionId;
4631
+ }
4632
+ get(sessionId) {
4633
+ this.cleanup();
4634
+ const entry = this.sessions.get(sessionId);
4635
+ if (!entry) {
4636
+ return void 0;
4637
+ }
4638
+ if (entry.expiresAt <= Date.now()) {
4639
+ this.sessions.delete(sessionId);
4640
+ return void 0;
4641
+ }
4642
+ return entry.result;
4643
+ }
4644
+ cleanup() {
4645
+ const now = Date.now();
4646
+ for (const [sessionId, entry] of this.sessions.entries()) {
4647
+ if (entry.expiresAt <= now) {
4648
+ this.sessions.delete(sessionId);
4649
+ }
4650
+ }
4651
+ }
4652
+ };
4653
+
4654
+ // src/server.ts
4655
+ var config = getConfig();
4656
+ var cachedServer = null;
4657
+ function createUnavailableConnpassClient() {
4658
+ const message = "CONNPASS_API_KEY is required to use Connpass API tools. Set the environment variable or pass --connpass-api-key.";
4659
+ return new Proxy({}, {
4660
+ get(_target, property) {
4661
+ if (property === "then") {
4662
+ return void 0;
4663
+ }
4664
+ if (typeof property === "symbol") {
4665
+ return void 0;
4666
+ }
4667
+ return async () => {
4668
+ throw new Error(message);
4669
+ };
4670
+ }
4671
+ });
4672
+ }
4673
+ function createConnpassClient() {
4674
+ if (!config.connpassApiKey?.trim()) {
4675
+ return createUnavailableConnpassClient();
4676
+ }
4677
+ return new ConnpassClient({
4678
+ apiKey: config.connpassApiKey,
4679
+ rateLimitEnabled: config.rateLimitEnabled,
4680
+ rateLimitDelay: config.rateLimitDelayMs
4681
+ });
4682
+ }
4683
+ function createServer() {
4684
+ const server2 = new McpServer({
4685
+ name: "connpass-mcp-server",
4686
+ version: "0.3.0",
4687
+ description: "Connpass event search and browsing MCP server with Apps UI"
4688
+ });
4689
+ const connpassClient = createConnpassClient();
4690
+ const searchSessionStore = new SearchSessionStore();
4691
+ const deps = {
4692
+ server: server2,
4693
+ connpassClient,
4694
+ config,
4695
+ searchSessionStore
4696
+ };
4697
+ registerAllTools(deps);
4698
+ return server2;
4699
+ }
4700
+ function getServer() {
4701
+ if (!cachedServer) {
4702
+ cachedServer = createServer();
4703
+ }
4704
+ return cachedServer;
4705
+ }
4706
+ var server = getServer();
4707
+
4708
+ // src/index.ts
4709
+ function isCLI() {
4710
+ if (!isNodejs() || !process.argv) return false;
4711
+ const isNpmStart = process.env?.npm_lifecycle_event === "start";
4712
+ const argv1 = process.argv[1] || "";
4713
+ const isDirectExecution = argv1.includes("connpass-mcp-apps") || argv1.endsWith("dist/index.js") || argv1.endsWith("src/index.ts") || argv1.includes("index.js") || argv1.includes("npx");
4714
+ const config2 = getConfig();
4715
+ const isForceMode = config2.httpMode;
4716
+ const isMainModule = process.argv0?.includes("node") || process.argv0?.includes("bun");
4717
+ return isNpmStart || isDirectExecution || isForceMode || isMainModule;
4718
+ }
4719
+ function printHelp() {
4720
+ console.log(`
4721
+ ${getHelpText()}`);
4722
+ }
4723
+ async function startMCPServer() {
4724
+ if (!isNodejs()) {
4725
+ throw new Error("Node.js environment required");
4726
+ }
4727
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
4728
+ printHelp();
4729
+ process.exit(0);
4730
+ }
4731
+ const shouldStart = isCLI();
4732
+ const config2 = getConfig();
4733
+ if (config2.httpMode) {
4734
+ console.error("Server configuration:", {
4735
+ port: config2.httpPort,
4736
+ host: config2.httpHost,
4737
+ isDevelopment: process.env.NODE_ENV === "development",
4738
+ isHttpMode: config2.httpMode
4739
+ });
4740
+ }
4741
+ if (!shouldStart) {
4742
+ return;
4743
+ }
4744
+ await launchServer({
4745
+ server: getServer(),
4746
+ config: config2,
4747
+ serverName: "Connpass MCP Apps",
4748
+ serverFactory: createServer
4749
+ });
4750
+ }
4751
+ if (isNodejs()) {
4752
+ startMCPServer().catch((error) => {
4753
+ console.error("Initialization error:", error);
4754
+ });
4755
+ }
189
4756
  //# sourceMappingURL=index.js.map