@caplets/core 0.15.0 → 0.17.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.
- package/dist/auth.d.ts +14 -0
- package/dist/cli/auth.d.ts +24 -0
- package/dist/cli.d.ts +4 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4136 -180
- package/dist/native/options.d.ts +33 -0
- package/dist/native/remote.d.ts +46 -0
- package/dist/native/service.d.ts +7 -1
- package/dist/native.d.ts +2 -0
- package/dist/native.js +233 -2
- package/dist/{engine-Bh55p8Lm.js → options-CJEOqS87.js} +26545 -26325
- package/dist/remote-control/auth-flow.d.ts +22 -0
- package/dist/remote-control/client.d.ts +11 -0
- package/dist/remote-control/dispatch.d.ts +9 -0
- package/dist/remote-control/types.d.ts +17 -0
- package/dist/runtime.d.ts +3 -8
- package/dist/serve/http.d.ts +23 -0
- package/dist/serve/index.d.ts +14 -0
- package/dist/serve/options.d.ts +36 -0
- package/dist/serve/session.d.ts +21 -0
- package/dist/serve/stdio.d.ts +5 -0
- package/dist/server/options.d.ts +41 -0
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as CompleteRequestSchema, At as string, B as InitializedNotificationSchema, C as assertToolsCallTaskCapability, Ct as resolveProjectConfigPath, D as toJsonSchemaCompat, Dt as ZodOptional, E as mergeCapabilities, Et as SERVER_ID_PATTERN, F as ElicitResultSchema, Ft as toSafeError, G as ListResourcesRequestSchema, H as LATEST_PROTOCOL_VERSION, I as EmptyResultSchema, It as __commonJSMin, J as LoggingLevelSchema, K as ListRootsResultSchema, L as ErrorCode, Lt as __require, M as CreateMessageResultWithToolsSchema, Mt as CAPLETS_ERROR_CODES, N as CreateTaskResultSchema, Nt as CapletsError, O as CallToolRequestSchema, Ot as literal, Pt as redactSecrets, Q as SetLevelRequestSchema, R as GetPromptRequestSchema, Rt as __toESM, S as assertClientRequestTaskCapability, St as resolveProjectCapletsRoot, T as Protocol, Tt as validateCapletFile, U as ListPromptsRequestSchema, V as JSONRPCMessageSchema, W as ListResourceTemplatesRequestSchema, X as ReadResourceRequestSchema, Y as McpError, Z as SUPPORTED_PROTOCOL_VERSIONS, _ as readTokenBundle, _t as loadConfigWithSources, a as resolveCapletsServer, at as isJSONRPCResultResponse, b as serializeMessage, bt as resolveCapletsRoot, c as handleServerTool, ct as getParseErrorMessage, d as runGenericOAuthFlow, dt as isZ4Schema, et as assertCompleteRequestPrompt, f as runOAuthFlow, ft as normalizeObjectSchema, g as isTokenBundleExpired, gt as loadConfig, h as deleteTokenBundle, ht as safeParseAsync, i as resolveCapletsMode, it as isJSONRPCRequest, j as CreateMessageResultSchema, jt as url, k as CallToolResultSchema, kt as object, l as ServerRegistry, lt as getSchemaDescription, m as startOAuthFlow, mt as safeParse, nt as isInitializeRequest, o as CapletsEngine, ot as getLiteralValue, p as startGenericOAuthFlow, pt as objectFromShape, q as ListToolsRequestSchema, r as parseServerBaseUrl, rt as isJSONRPCErrorResponse, s as generatedToolInputSchema, st as getObjectShape, t as controlUrlForBase, tt as assertCompleteRequestResourceTemplate, u as capabilityDescription, ut as isSchemaOptional, vt as parseConfig, w as AjvJsonSchemaValidator, wt as discoverCapletFiles, xt as resolveConfigPath, y as ReadBuffer, yt as DEFAULT_AUTH_DIR, z as InitializeRequestSchema } from "./options-CJEOqS87.js";
|
|
2
2
|
import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, join, parse, relative, resolve } from "node:path";
|
|
4
|
-
import { stdin, stdout } from "node:process";
|
|
5
|
-
import { tmpdir } from "node:os";
|
|
6
4
|
import { execFileSync } from "node:child_process";
|
|
5
|
+
import process$1, { stdin, stdout } from "node:process";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
7
8
|
import { createInterface } from "node:readline/promises";
|
|
9
|
+
import { createServer } from "http";
|
|
10
|
+
import { Http2ServerRequest, constants as constants$1 } from "http2";
|
|
11
|
+
import { Readable } from "stream";
|
|
12
|
+
import crypto$1 from "crypto";
|
|
8
13
|
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
|
|
9
14
|
/**
|
|
10
15
|
* Experimental server task features for MCP SDK.
|
|
@@ -1314,16 +1319,17 @@ const EMPTY_COMPLETION_RESULT = { completion: {
|
|
|
1314
1319
|
} };
|
|
1315
1320
|
//#endregion
|
|
1316
1321
|
//#region package.json
|
|
1317
|
-
var version = "0.
|
|
1322
|
+
var version = "0.17.0";
|
|
1318
1323
|
//#endregion
|
|
1319
|
-
//#region src/
|
|
1320
|
-
var
|
|
1321
|
-
server;
|
|
1324
|
+
//#region src/serve/session.ts
|
|
1325
|
+
var CapletsMcpSession = class {
|
|
1322
1326
|
engine;
|
|
1327
|
+
server;
|
|
1323
1328
|
tools = /* @__PURE__ */ new Map();
|
|
1324
1329
|
unsubscribeReload;
|
|
1325
|
-
|
|
1326
|
-
|
|
1330
|
+
closed = false;
|
|
1331
|
+
constructor(engine, options = {}) {
|
|
1332
|
+
this.engine = engine;
|
|
1327
1333
|
this.server = options.server ?? new McpServer({
|
|
1328
1334
|
name: "caplets",
|
|
1329
1335
|
version
|
|
@@ -1334,28 +1340,15 @@ var CapletsRuntime = class {
|
|
|
1334
1340
|
async connect(transport) {
|
|
1335
1341
|
await this.server.connect(transport);
|
|
1336
1342
|
}
|
|
1337
|
-
scheduleReload() {
|
|
1338
|
-
this.engine.scheduleReload();
|
|
1339
|
-
}
|
|
1340
|
-
async reload() {
|
|
1341
|
-
return await this.engine.reload();
|
|
1342
|
-
}
|
|
1343
|
-
async close() {
|
|
1344
|
-
this.unsubscribeReload();
|
|
1345
|
-
try {
|
|
1346
|
-
await this.engine.close();
|
|
1347
|
-
} finally {
|
|
1348
|
-
await this.server.close();
|
|
1349
|
-
}
|
|
1350
|
-
}
|
|
1351
|
-
currentConfig() {
|
|
1352
|
-
return this.engine.currentConfig();
|
|
1353
|
-
}
|
|
1354
1343
|
registeredToolIds() {
|
|
1355
1344
|
return [...this.tools.keys()].sort();
|
|
1356
1345
|
}
|
|
1357
|
-
|
|
1358
|
-
|
|
1346
|
+
async close() {
|
|
1347
|
+
if (this.closed) return;
|
|
1348
|
+
this.closed = true;
|
|
1349
|
+
this.unsubscribeReload();
|
|
1350
|
+
this.tools.clear();
|
|
1351
|
+
await this.server.close();
|
|
1359
1352
|
}
|
|
1360
1353
|
reconcileTools(previous, next) {
|
|
1361
1354
|
const enabled = new Map(nextEnabledServers(next).map((server) => [server.server, server]));
|
|
@@ -1406,6 +1399,46 @@ function capletById(config, serverId) {
|
|
|
1406
1399
|
function serializeCaplet(caplet) {
|
|
1407
1400
|
return JSON.stringify(caplet ?? null);
|
|
1408
1401
|
}
|
|
1402
|
+
//#endregion
|
|
1403
|
+
//#region src/runtime.ts
|
|
1404
|
+
var CapletsRuntime = class {
|
|
1405
|
+
server;
|
|
1406
|
+
engine;
|
|
1407
|
+
session;
|
|
1408
|
+
constructor(options = {}) {
|
|
1409
|
+
this.engine = new CapletsEngine(engineOptions(options));
|
|
1410
|
+
this.session = new CapletsMcpSession(this.engine, selectSessionOptions(options));
|
|
1411
|
+
this.server = this.session.server;
|
|
1412
|
+
}
|
|
1413
|
+
async connect(transport) {
|
|
1414
|
+
await this.session.connect(transport);
|
|
1415
|
+
}
|
|
1416
|
+
scheduleReload() {
|
|
1417
|
+
this.engine.scheduleReload();
|
|
1418
|
+
}
|
|
1419
|
+
async reload() {
|
|
1420
|
+
return await this.engine.reload();
|
|
1421
|
+
}
|
|
1422
|
+
async close() {
|
|
1423
|
+
try {
|
|
1424
|
+
await this.session.close();
|
|
1425
|
+
} finally {
|
|
1426
|
+
await this.engine.close();
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
currentConfig() {
|
|
1430
|
+
return this.engine.currentConfig();
|
|
1431
|
+
}
|
|
1432
|
+
registeredToolIds() {
|
|
1433
|
+
return this.session.registeredToolIds();
|
|
1434
|
+
}
|
|
1435
|
+
watchedPaths() {
|
|
1436
|
+
return this.engine.watchedPaths();
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
function selectSessionOptions(options) {
|
|
1440
|
+
return options.server === void 0 ? {} : { server: options.server };
|
|
1441
|
+
}
|
|
1409
1442
|
function engineOptions(options) {
|
|
1410
1443
|
const engineOptions = {};
|
|
1411
1444
|
if (options.configPath !== void 0) engineOptions.configPath = options.configPath;
|
|
@@ -4888,49 +4921,56 @@ async function loginAuth(serverId, options) {
|
|
|
4888
4921
|
}
|
|
4889
4922
|
}
|
|
4890
4923
|
function logoutAuth(serverId, options) {
|
|
4891
|
-
|
|
4892
|
-
if (deleteTokenBundle(serverId, options.authDir)) options.writeOut(`Deleted OAuth credentials for \`${serverId}\`.\n`);
|
|
4924
|
+
if (logoutAuthResult(serverId, options).deleted) options.writeOut(`Deleted OAuth credentials for \`${serverId}\`.\n`);
|
|
4893
4925
|
else options.writeOut(`No OAuth credentials found for \`${serverId}\`.\n`);
|
|
4894
4926
|
}
|
|
4927
|
+
function logoutAuthResult(serverId, options) {
|
|
4928
|
+
assertLoginTarget(findAuthTarget(serverId, loadConfig(options.configPath)), serverId);
|
|
4929
|
+
return {
|
|
4930
|
+
server: serverId,
|
|
4931
|
+
deleted: deleteTokenBundle(serverId, options.authDir)
|
|
4932
|
+
};
|
|
4933
|
+
}
|
|
4895
4934
|
function listAuth(options) {
|
|
4896
|
-
const
|
|
4935
|
+
const rows = listAuthRows(options);
|
|
4897
4936
|
const format = options.format ?? "plain";
|
|
4898
4937
|
if (format === "json") {
|
|
4899
|
-
const rows = servers.map((server) => {
|
|
4900
|
-
const bundle = readTokenBundle(server.server, options.authDir);
|
|
4901
|
-
const status = !bundle ? "missing" : isTokenBundleExpired(bundle) ? "expired" : "authenticated";
|
|
4902
|
-
return {
|
|
4903
|
-
server: server.server,
|
|
4904
|
-
status,
|
|
4905
|
-
...bundle?.expiresAt ? { expiresAt: bundle.expiresAt } : {},
|
|
4906
|
-
...bundle?.scope ? { scope: bundle.scope } : {}
|
|
4907
|
-
};
|
|
4908
|
-
});
|
|
4909
4938
|
options.writeOut(`${JSON.stringify(rows, null, 2)}\n`);
|
|
4910
4939
|
return;
|
|
4911
4940
|
}
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
if (format === "markdown") options.writeOut("## OAuth credentials\n\n");
|
|
4917
|
-
else options.writeOut("OAuth credentials\n\n");
|
|
4918
|
-
for (const server of servers) {
|
|
4941
|
+
options.writeOut(formatAuthRows(rows, format));
|
|
4942
|
+
}
|
|
4943
|
+
function listAuthRows(options) {
|
|
4944
|
+
return authTargets(loadConfig(options.configPath)).sort((left, right) => left.server.localeCompare(right.server)).map((server) => {
|
|
4919
4945
|
const bundle = readTokenBundle(server.server, options.authDir);
|
|
4920
4946
|
const status = !bundle ? "missing" : isTokenBundleExpired(bundle) ? "expired" : "authenticated";
|
|
4921
|
-
|
|
4947
|
+
return {
|
|
4948
|
+
server: server.server,
|
|
4949
|
+
status,
|
|
4950
|
+
...bundle?.expiresAt ? { expiresAt: bundle.expiresAt } : {},
|
|
4951
|
+
...bundle?.scope ? { scope: bundle.scope } : {}
|
|
4952
|
+
};
|
|
4953
|
+
});
|
|
4954
|
+
}
|
|
4955
|
+
function formatAuthRows(rows, format) {
|
|
4956
|
+
if (rows.length === 0) return format === "markdown" ? "## OAuth credentials\n\nNo configured remote OAuth servers found.\n" : "No configured remote OAuth servers found.\n";
|
|
4957
|
+
let output = "";
|
|
4958
|
+
if (format === "markdown") output += "## OAuth credentials\n\n";
|
|
4959
|
+
else output += "OAuth credentials\n\n";
|
|
4960
|
+
for (const row of rows) {
|
|
4961
|
+
const details = [row.expiresAt ? `expires ${row.expiresAt}` : void 0, row.scope ? `scope ${row.scope}` : void 0].filter(Boolean).join("; ");
|
|
4922
4962
|
if (format === "markdown") {
|
|
4923
|
-
|
|
4963
|
+
output += `- \`${row.server}\` — ${row.status}${details ? ` (${details})` : ""}\n`;
|
|
4924
4964
|
continue;
|
|
4925
4965
|
}
|
|
4926
|
-
|
|
4927
|
-
|
|
4928
|
-
` Status: ${status}`,
|
|
4929
|
-
...
|
|
4930
|
-
...
|
|
4931
|
-
].join("\n")
|
|
4932
|
-
options.writeOut("\n\n");
|
|
4966
|
+
output += [
|
|
4967
|
+
row.server,
|
|
4968
|
+
` Status: ${row.status}`,
|
|
4969
|
+
...row.expiresAt ? [` Expires: ${row.expiresAt}`] : [],
|
|
4970
|
+
...row.scope ? [` Scope: ${row.scope}`] : []
|
|
4971
|
+
].join("\n") + "\n\n";
|
|
4933
4972
|
}
|
|
4973
|
+
return output;
|
|
4934
4974
|
}
|
|
4935
4975
|
function findAuthTarget(serverId, config = loadConfig()) {
|
|
4936
4976
|
return authTargets(config).find((server) => server.server === serverId);
|
|
@@ -5357,134 +5397,3969 @@ function nearestExistingParent(path) {
|
|
|
5357
5397
|
return nearestExistingParent(parent);
|
|
5358
5398
|
}
|
|
5359
5399
|
//#endregion
|
|
5360
|
-
//#region src/
|
|
5361
|
-
|
|
5362
|
-
|
|
5400
|
+
//#region src/remote-control/client.ts
|
|
5401
|
+
var RemoteControlClient = class {
|
|
5402
|
+
#baseUrl;
|
|
5403
|
+
#requestInit;
|
|
5404
|
+
#fetch;
|
|
5405
|
+
constructor(options) {
|
|
5406
|
+
this.#baseUrl = options.baseUrl;
|
|
5407
|
+
this.#requestInit = options.requestInit;
|
|
5408
|
+
this.#fetch = options.fetch ?? fetch;
|
|
5409
|
+
}
|
|
5410
|
+
async request(command, args) {
|
|
5411
|
+
const controlUrl = controlUrlForBase(this.#baseUrl);
|
|
5412
|
+
let response;
|
|
5413
|
+
try {
|
|
5414
|
+
response = await this.#fetch(controlUrl, {
|
|
5415
|
+
...this.#requestInit,
|
|
5416
|
+
method: "POST",
|
|
5417
|
+
headers: mergeJsonHeaders(this.#requestInit.headers),
|
|
5418
|
+
body: JSON.stringify({
|
|
5419
|
+
command,
|
|
5420
|
+
arguments: args
|
|
5421
|
+
})
|
|
5422
|
+
});
|
|
5423
|
+
} catch (error) {
|
|
5424
|
+
throw new CapletsError("SERVER_UNAVAILABLE", `Could not connect to Caplets server at ${safeBaseUrl(this.#baseUrl)}.`, toSafeError(error, "SERVER_UNAVAILABLE"));
|
|
5425
|
+
}
|
|
5426
|
+
if (response.status === 401 || response.status === 403) throw new CapletsError("AUTH_FAILED", "Caplets server authentication failed. Check CAPLETS_SERVER_USER and CAPLETS_SERVER_PASSWORD.");
|
|
5427
|
+
if (!response.ok) throw new CapletsError("SERVER_UNAVAILABLE", `Caplets server at ${safeBaseUrl(this.#baseUrl)} returned HTTP ${response.status}.`);
|
|
5428
|
+
const payload = await parseRemoteCliResponse(response);
|
|
5429
|
+
if (!payload.ok) throw new CapletsError(payload.error.code, redactRemoteMessage(payload.error.message), payload.error.nextAction === void 0 ? void 0 : { nextAction: payload.error.nextAction });
|
|
5430
|
+
return payload.result;
|
|
5431
|
+
}
|
|
5432
|
+
};
|
|
5433
|
+
function mergeJsonHeaders(headers) {
|
|
5434
|
+
const merged = new Headers(headers);
|
|
5435
|
+
merged.set("content-type", "application/json");
|
|
5436
|
+
return merged;
|
|
5437
|
+
}
|
|
5438
|
+
function safeBaseUrl(baseUrl) {
|
|
5439
|
+
const safe = new URL(baseUrl.href);
|
|
5440
|
+
safe.username = "";
|
|
5441
|
+
safe.password = "";
|
|
5442
|
+
safe.search = "";
|
|
5443
|
+
safe.hash = "";
|
|
5444
|
+
return safe.toString();
|
|
5445
|
+
}
|
|
5446
|
+
async function parseRemoteCliResponse(response) {
|
|
5447
|
+
let payload;
|
|
5363
5448
|
try {
|
|
5364
|
-
await
|
|
5365
|
-
"node",
|
|
5366
|
-
"caplets",
|
|
5367
|
-
...args
|
|
5368
|
-
]);
|
|
5449
|
+
payload = await response.json();
|
|
5369
5450
|
} catch (error) {
|
|
5370
|
-
|
|
5371
|
-
if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.message === "(outputHelp)") return;
|
|
5372
|
-
throw new CapletsError("REQUEST_INVALID", error.message);
|
|
5373
|
-
}
|
|
5374
|
-
throw error;
|
|
5451
|
+
throw invalidRemoteControlResponse(error);
|
|
5375
5452
|
}
|
|
5453
|
+
if (!isRecord(payload)) throw invalidRemoteControlResponse();
|
|
5454
|
+
if (payload.ok === true) {
|
|
5455
|
+
if (!("result" in payload)) throw invalidRemoteControlResponse();
|
|
5456
|
+
return {
|
|
5457
|
+
ok: true,
|
|
5458
|
+
result: payload.result
|
|
5459
|
+
};
|
|
5460
|
+
}
|
|
5461
|
+
if (payload.ok === false) {
|
|
5462
|
+
const error = payload.error;
|
|
5463
|
+
if (!isRecord(error) || typeof error.code !== "string" || typeof error.message !== "string") throw invalidRemoteControlResponse();
|
|
5464
|
+
if ("nextAction" in error && error.nextAction !== void 0 && typeof error.nextAction !== "string") throw invalidRemoteControlResponse();
|
|
5465
|
+
const errorResponse = {
|
|
5466
|
+
ok: false,
|
|
5467
|
+
error: {
|
|
5468
|
+
code: isCapletsErrorCode(error.code) ? error.code : "DOWNSTREAM_TOOL_ERROR",
|
|
5469
|
+
message: error.message
|
|
5470
|
+
}
|
|
5471
|
+
};
|
|
5472
|
+
if (typeof error.nextAction === "string") errorResponse.error.nextAction = error.nextAction;
|
|
5473
|
+
return errorResponse;
|
|
5474
|
+
}
|
|
5475
|
+
throw invalidRemoteControlResponse();
|
|
5376
5476
|
}
|
|
5377
|
-
function
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5390
|
-
|
|
5391
|
-
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
5477
|
+
function invalidRemoteControlResponse(cause) {
|
|
5478
|
+
return new CapletsError("DOWNSTREAM_PROTOCOL_ERROR", "Caplets server returned an invalid remote control response.", cause === void 0 ? void 0 : toSafeError(cause, "DOWNSTREAM_PROTOCOL_ERROR"));
|
|
5479
|
+
}
|
|
5480
|
+
function isRecord(value) {
|
|
5481
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5482
|
+
}
|
|
5483
|
+
function isCapletsErrorCode(value) {
|
|
5484
|
+
return CAPLETS_ERROR_CODES.includes(value);
|
|
5485
|
+
}
|
|
5486
|
+
function redactRemoteMessage(message) {
|
|
5487
|
+
return String(redactSecrets(message)).replace(/\b(authorization\s*:\s*(?:basic|bearer)\s+)[^\s,;]+/giu, "$1[REDACTED]").replace(/\b((?:access_)?token=)[^\s,;]+/giu, "$1[REDACTED]").replace(/\b((?:token|secret|authorization|auth|api[-_]?key|password|credential|clientsecret|client_secret|code|refresh(?:_token)?)\s*[=:]\s*)[^\s,;]+/giu, "$1[REDACTED]");
|
|
5488
|
+
}
|
|
5489
|
+
//#endregion
|
|
5490
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/compose.js
|
|
5491
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
5492
|
+
return (context, next) => {
|
|
5493
|
+
let index = -1;
|
|
5494
|
+
return dispatch(0);
|
|
5495
|
+
async function dispatch(i) {
|
|
5496
|
+
if (i <= index) throw new Error("next() called multiple times");
|
|
5497
|
+
index = i;
|
|
5498
|
+
let res;
|
|
5499
|
+
let isError = false;
|
|
5500
|
+
let handler;
|
|
5501
|
+
if (middleware[i]) {
|
|
5502
|
+
handler = middleware[i][0][0];
|
|
5503
|
+
context.req.routeIndex = i;
|
|
5504
|
+
} else handler = i === middleware.length && next || void 0;
|
|
5505
|
+
if (handler) try {
|
|
5506
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
5507
|
+
} catch (err) {
|
|
5508
|
+
if (err instanceof Error && onError) {
|
|
5509
|
+
context.error = err;
|
|
5510
|
+
res = await onError(err, context);
|
|
5511
|
+
isError = true;
|
|
5512
|
+
} else throw err;
|
|
5513
|
+
}
|
|
5514
|
+
else if (context.finalized === false && onNotFound) res = await onNotFound(context);
|
|
5515
|
+
if (res && (context.finalized === false || isError)) context.res = res;
|
|
5516
|
+
return context;
|
|
5401
5517
|
}
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5409
|
-
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
5518
|
+
};
|
|
5519
|
+
};
|
|
5520
|
+
//#endregion
|
|
5521
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/http-exception.js
|
|
5522
|
+
var HTTPException = class extends Error {
|
|
5523
|
+
res;
|
|
5524
|
+
status;
|
|
5525
|
+
/**
|
|
5526
|
+
* Creates an instance of `HTTPException`.
|
|
5527
|
+
* @param status - HTTP status code for the exception. Defaults to 500.
|
|
5528
|
+
* @param options - Additional options for the exception.
|
|
5529
|
+
*/
|
|
5530
|
+
constructor(status = 500, options) {
|
|
5531
|
+
super(options?.message, { cause: options?.cause });
|
|
5532
|
+
this.res = options?.res;
|
|
5533
|
+
this.status = status;
|
|
5534
|
+
}
|
|
5535
|
+
/**
|
|
5536
|
+
* Returns the response object associated with the exception.
|
|
5537
|
+
* If a response object is not provided, a new response is created with the error message and status code.
|
|
5538
|
+
* @returns The response object.
|
|
5539
|
+
*/
|
|
5540
|
+
getResponse() {
|
|
5541
|
+
if (this.res) return new Response(this.res.body, {
|
|
5542
|
+
status: this.status,
|
|
5543
|
+
headers: this.res.headers
|
|
5417
5544
|
});
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5545
|
+
return new Response(this.message, { status: this.status });
|
|
5546
|
+
}
|
|
5547
|
+
};
|
|
5548
|
+
//#endregion
|
|
5549
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/request/constants.js
|
|
5550
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
5551
|
+
//#endregion
|
|
5552
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/body.js
|
|
5553
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
5554
|
+
const { all = false, dot = false } = options;
|
|
5555
|
+
const contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
|
|
5556
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) return parseFormData(request, {
|
|
5557
|
+
all,
|
|
5558
|
+
dot
|
|
5423
5559
|
});
|
|
5424
|
-
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5560
|
+
return {};
|
|
5561
|
+
};
|
|
5562
|
+
async function parseFormData(request, options) {
|
|
5563
|
+
const formData = await request.formData();
|
|
5564
|
+
if (formData) return convertFormDataToBodyData(formData, options);
|
|
5565
|
+
return {};
|
|
5566
|
+
}
|
|
5567
|
+
function convertFormDataToBodyData(formData, options) {
|
|
5568
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
5569
|
+
formData.forEach((value, key) => {
|
|
5570
|
+
if (!(options.all || key.endsWith("[]"))) form[key] = value;
|
|
5571
|
+
else handleParsingAllValues(form, key, value);
|
|
5429
5572
|
});
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
5434
|
-
}
|
|
5573
|
+
if (options.dot) Object.entries(form).forEach(([key, value]) => {
|
|
5574
|
+
if (key.includes(".")) {
|
|
5575
|
+
handleParsingNestedValues(form, key, value);
|
|
5576
|
+
delete form[key];
|
|
5577
|
+
}
|
|
5435
5578
|
});
|
|
5436
|
-
|
|
5437
|
-
|
|
5438
|
-
|
|
5439
|
-
|
|
5440
|
-
|
|
5579
|
+
return form;
|
|
5580
|
+
}
|
|
5581
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
5582
|
+
if (form[key] !== void 0) if (Array.isArray(form[key])) form[key].push(value);
|
|
5583
|
+
else form[key] = [form[key], value];
|
|
5584
|
+
else if (!key.endsWith("[]")) form[key] = value;
|
|
5585
|
+
else form[key] = [value];
|
|
5586
|
+
};
|
|
5587
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
5588
|
+
if (/(?:^|\.)__proto__\./.test(key)) return;
|
|
5589
|
+
let nestedForm = form;
|
|
5590
|
+
const keys = key.split(".");
|
|
5591
|
+
keys.forEach((key2, index) => {
|
|
5592
|
+
if (index === keys.length - 1) nestedForm[key2] = value;
|
|
5593
|
+
else {
|
|
5594
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
5595
|
+
nestedForm = nestedForm[key2];
|
|
5596
|
+
}
|
|
5441
5597
|
});
|
|
5442
|
-
|
|
5443
|
-
|
|
5444
|
-
|
|
5445
|
-
|
|
5446
|
-
|
|
5598
|
+
};
|
|
5599
|
+
//#endregion
|
|
5600
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/url.js
|
|
5601
|
+
var splitPath = (path) => {
|
|
5602
|
+
const paths = path.split("/");
|
|
5603
|
+
if (paths[0] === "") paths.shift();
|
|
5604
|
+
return paths;
|
|
5605
|
+
};
|
|
5606
|
+
var splitRoutingPath = (routePath) => {
|
|
5607
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
5608
|
+
return replaceGroupMarks(splitPath(path), groups);
|
|
5609
|
+
};
|
|
5610
|
+
var extractGroupsFromPath = (path) => {
|
|
5611
|
+
const groups = [];
|
|
5612
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
5613
|
+
const mark = `@${index}`;
|
|
5614
|
+
groups.push([mark, match]);
|
|
5615
|
+
return mark;
|
|
5447
5616
|
});
|
|
5448
|
-
|
|
5449
|
-
|
|
5450
|
-
|
|
5451
|
-
|
|
5452
|
-
|
|
5453
|
-
|
|
5454
|
-
|
|
5617
|
+
return {
|
|
5618
|
+
groups,
|
|
5619
|
+
path
|
|
5620
|
+
};
|
|
5621
|
+
};
|
|
5622
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
5623
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
5624
|
+
const [mark] = groups[i];
|
|
5625
|
+
for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
|
|
5626
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
5627
|
+
break;
|
|
5628
|
+
}
|
|
5629
|
+
}
|
|
5630
|
+
return paths;
|
|
5631
|
+
};
|
|
5632
|
+
var patternCache = {};
|
|
5633
|
+
var getPattern = (label, next) => {
|
|
5634
|
+
if (label === "*") return "*";
|
|
5635
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
5636
|
+
if (match) {
|
|
5637
|
+
const cacheKey = `${label}#${next}`;
|
|
5638
|
+
if (!patternCache[cacheKey]) if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
|
|
5639
|
+
cacheKey,
|
|
5640
|
+
match[1],
|
|
5641
|
+
new RegExp(`^${match[2]}(?=/${next})`)
|
|
5642
|
+
] : [
|
|
5643
|
+
label,
|
|
5644
|
+
match[1],
|
|
5645
|
+
new RegExp(`^${match[2]}$`)
|
|
5646
|
+
];
|
|
5647
|
+
else patternCache[cacheKey] = [
|
|
5648
|
+
label,
|
|
5649
|
+
match[1],
|
|
5650
|
+
true
|
|
5651
|
+
];
|
|
5652
|
+
return patternCache[cacheKey];
|
|
5653
|
+
}
|
|
5654
|
+
return null;
|
|
5655
|
+
};
|
|
5656
|
+
var tryDecode = (str, decoder) => {
|
|
5657
|
+
try {
|
|
5658
|
+
return decoder(str);
|
|
5659
|
+
} catch {
|
|
5660
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
5661
|
+
try {
|
|
5662
|
+
return decoder(match);
|
|
5663
|
+
} catch {
|
|
5664
|
+
return match;
|
|
5665
|
+
}
|
|
5455
5666
|
});
|
|
5667
|
+
}
|
|
5668
|
+
};
|
|
5669
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
5670
|
+
var getPath = (request) => {
|
|
5671
|
+
const url = request.url;
|
|
5672
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
5673
|
+
let i = start;
|
|
5674
|
+
for (; i < url.length; i++) {
|
|
5675
|
+
const charCode = url.charCodeAt(i);
|
|
5676
|
+
if (charCode === 37) {
|
|
5677
|
+
const queryIndex = url.indexOf("?", i);
|
|
5678
|
+
const hashIndex = url.indexOf("#", i);
|
|
5679
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
5680
|
+
const path = url.slice(start, end);
|
|
5681
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
5682
|
+
} else if (charCode === 63 || charCode === 35) break;
|
|
5683
|
+
}
|
|
5684
|
+
return url.slice(start, i);
|
|
5685
|
+
};
|
|
5686
|
+
var getPathNoStrict = (request) => {
|
|
5687
|
+
const result = getPath(request);
|
|
5688
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
5689
|
+
};
|
|
5690
|
+
var mergePath = (base, sub, ...rest) => {
|
|
5691
|
+
if (rest.length) sub = mergePath(sub, ...rest);
|
|
5692
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
5693
|
+
};
|
|
5694
|
+
var checkOptionalParameter = (path) => {
|
|
5695
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
|
|
5696
|
+
const segments = path.split("/");
|
|
5697
|
+
const results = [];
|
|
5698
|
+
let basePath = "";
|
|
5699
|
+
segments.forEach((segment) => {
|
|
5700
|
+
if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
|
|
5701
|
+
else if (/\:/.test(segment)) if (/\?/.test(segment)) {
|
|
5702
|
+
if (results.length === 0 && basePath === "") results.push("/");
|
|
5703
|
+
else results.push(basePath);
|
|
5704
|
+
const optionalSegment = segment.replace("?", "");
|
|
5705
|
+
basePath += "/" + optionalSegment;
|
|
5706
|
+
results.push(basePath);
|
|
5707
|
+
} else basePath += "/" + segment;
|
|
5456
5708
|
});
|
|
5457
|
-
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
|
|
5463
|
-
|
|
5709
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
5710
|
+
};
|
|
5711
|
+
var _decodeURI = (value) => {
|
|
5712
|
+
if (!/[%+]/.test(value)) return value;
|
|
5713
|
+
if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
|
|
5714
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
5715
|
+
};
|
|
5716
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
5717
|
+
let encoded;
|
|
5718
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
5719
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
5720
|
+
if (keyIndex2 === -1) return;
|
|
5721
|
+
if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
5722
|
+
while (keyIndex2 !== -1) {
|
|
5723
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
5724
|
+
if (trailingKeyCode === 61) {
|
|
5725
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
5726
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
5727
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
5728
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
|
|
5729
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
5730
|
+
}
|
|
5731
|
+
encoded = /[%+]/.test(url);
|
|
5732
|
+
if (!encoded) return;
|
|
5733
|
+
}
|
|
5734
|
+
const results = {};
|
|
5735
|
+
encoded ??= /[%+]/.test(url);
|
|
5736
|
+
let keyIndex = url.indexOf("?", 8);
|
|
5737
|
+
while (keyIndex !== -1) {
|
|
5738
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
5739
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
5740
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
|
|
5741
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
|
|
5742
|
+
if (encoded) name = _decodeURI(name);
|
|
5743
|
+
keyIndex = nextKeyIndex;
|
|
5744
|
+
if (name === "") continue;
|
|
5745
|
+
let value;
|
|
5746
|
+
if (valueIndex === -1) value = "";
|
|
5747
|
+
else {
|
|
5748
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
5749
|
+
if (encoded) value = _decodeURI(value);
|
|
5750
|
+
}
|
|
5751
|
+
if (multiple) {
|
|
5752
|
+
if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
|
|
5753
|
+
results[name].push(value);
|
|
5754
|
+
} else results[name] ??= value;
|
|
5755
|
+
}
|
|
5756
|
+
return key ? results[key] : results;
|
|
5757
|
+
};
|
|
5758
|
+
var getQueryParam = _getQueryParam;
|
|
5759
|
+
var getQueryParams = (url, key) => {
|
|
5760
|
+
return _getQueryParam(url, key, true);
|
|
5761
|
+
};
|
|
5762
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
5763
|
+
//#endregion
|
|
5764
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/request.js
|
|
5765
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
5766
|
+
var HonoRequest = class {
|
|
5767
|
+
/**
|
|
5768
|
+
* `.raw` can get the raw Request object.
|
|
5769
|
+
*
|
|
5770
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
5771
|
+
*
|
|
5772
|
+
* @example
|
|
5773
|
+
* ```ts
|
|
5774
|
+
* // For Cloudflare Workers
|
|
5775
|
+
* app.post('/', async (c) => {
|
|
5776
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
5777
|
+
* ...
|
|
5778
|
+
* })
|
|
5779
|
+
* ```
|
|
5780
|
+
*/
|
|
5781
|
+
raw;
|
|
5782
|
+
#validatedData;
|
|
5783
|
+
#matchResult;
|
|
5784
|
+
routeIndex = 0;
|
|
5785
|
+
/**
|
|
5786
|
+
* `.path` can get the pathname of the request.
|
|
5787
|
+
*
|
|
5788
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
5789
|
+
*
|
|
5790
|
+
* @example
|
|
5791
|
+
* ```ts
|
|
5792
|
+
* app.get('/about/me', (c) => {
|
|
5793
|
+
* const pathname = c.req.path // `/about/me`
|
|
5794
|
+
* })
|
|
5795
|
+
* ```
|
|
5796
|
+
*/
|
|
5797
|
+
path;
|
|
5798
|
+
bodyCache = {};
|
|
5799
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
5800
|
+
this.raw = request;
|
|
5801
|
+
this.path = path;
|
|
5802
|
+
this.#matchResult = matchResult;
|
|
5803
|
+
this.#validatedData = {};
|
|
5804
|
+
}
|
|
5805
|
+
param(key) {
|
|
5806
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
5807
|
+
}
|
|
5808
|
+
#getDecodedParam(key) {
|
|
5809
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
5810
|
+
const param = this.#getParamValue(paramKey);
|
|
5811
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
5812
|
+
}
|
|
5813
|
+
#getAllDecodedParams() {
|
|
5814
|
+
const decoded = {};
|
|
5815
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
5816
|
+
for (const key of keys) {
|
|
5817
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
5818
|
+
if (value !== void 0) decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
5819
|
+
}
|
|
5820
|
+
return decoded;
|
|
5821
|
+
}
|
|
5822
|
+
#getParamValue(paramKey) {
|
|
5823
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
5824
|
+
}
|
|
5825
|
+
query(key) {
|
|
5826
|
+
return getQueryParam(this.url, key);
|
|
5827
|
+
}
|
|
5828
|
+
queries(key) {
|
|
5829
|
+
return getQueryParams(this.url, key);
|
|
5830
|
+
}
|
|
5831
|
+
header(name) {
|
|
5832
|
+
if (name) return this.raw.headers.get(name) ?? void 0;
|
|
5833
|
+
const headerData = {};
|
|
5834
|
+
this.raw.headers.forEach((value, key) => {
|
|
5835
|
+
headerData[key] = value;
|
|
5464
5836
|
});
|
|
5465
|
-
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5837
|
+
return headerData;
|
|
5838
|
+
}
|
|
5839
|
+
async parseBody(options) {
|
|
5840
|
+
return parseBody(this, options);
|
|
5841
|
+
}
|
|
5842
|
+
#cachedBody = (key) => {
|
|
5843
|
+
const { bodyCache, raw } = this;
|
|
5844
|
+
const cachedBody = bodyCache[key];
|
|
5845
|
+
if (cachedBody) return cachedBody;
|
|
5846
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
5847
|
+
if (anyCachedKey) return bodyCache[anyCachedKey].then((body) => {
|
|
5848
|
+
if (anyCachedKey === "json") body = JSON.stringify(body);
|
|
5849
|
+
return new Response(body)[key]();
|
|
5473
5850
|
});
|
|
5474
|
-
|
|
5475
|
-
|
|
5476
|
-
|
|
5477
|
-
|
|
5478
|
-
|
|
5479
|
-
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5851
|
+
return bodyCache[key] = raw[key]();
|
|
5852
|
+
};
|
|
5853
|
+
/**
|
|
5854
|
+
* `.json()` can parse Request body of type `application/json`
|
|
5855
|
+
*
|
|
5856
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
5857
|
+
*
|
|
5858
|
+
* @example
|
|
5859
|
+
* ```ts
|
|
5860
|
+
* app.post('/entry', async (c) => {
|
|
5861
|
+
* const body = await c.req.json()
|
|
5862
|
+
* })
|
|
5863
|
+
* ```
|
|
5864
|
+
*/
|
|
5865
|
+
json() {
|
|
5866
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
5867
|
+
}
|
|
5868
|
+
/**
|
|
5869
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
5870
|
+
*
|
|
5871
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
5872
|
+
*
|
|
5873
|
+
* @example
|
|
5874
|
+
* ```ts
|
|
5875
|
+
* app.post('/entry', async (c) => {
|
|
5876
|
+
* const body = await c.req.text()
|
|
5877
|
+
* })
|
|
5878
|
+
* ```
|
|
5879
|
+
*/
|
|
5880
|
+
text() {
|
|
5881
|
+
return this.#cachedBody("text");
|
|
5882
|
+
}
|
|
5883
|
+
/**
|
|
5884
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
5885
|
+
*
|
|
5886
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
5887
|
+
*
|
|
5888
|
+
* @example
|
|
5889
|
+
* ```ts
|
|
5890
|
+
* app.post('/entry', async (c) => {
|
|
5891
|
+
* const body = await c.req.arrayBuffer()
|
|
5892
|
+
* })
|
|
5893
|
+
* ```
|
|
5894
|
+
*/
|
|
5895
|
+
arrayBuffer() {
|
|
5896
|
+
return this.#cachedBody("arrayBuffer");
|
|
5897
|
+
}
|
|
5898
|
+
/**
|
|
5899
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
5900
|
+
*
|
|
5901
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
5902
|
+
*
|
|
5903
|
+
* @example
|
|
5904
|
+
* ```ts
|
|
5905
|
+
* app.post('/entry', async (c) => {
|
|
5906
|
+
* const body = await c.req.bytes()
|
|
5907
|
+
* })
|
|
5908
|
+
* ```
|
|
5909
|
+
*/
|
|
5910
|
+
bytes() {
|
|
5911
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
5912
|
+
}
|
|
5913
|
+
/**
|
|
5914
|
+
* Parses the request body as a `Blob`.
|
|
5915
|
+
* @example
|
|
5916
|
+
* ```ts
|
|
5917
|
+
* app.post('/entry', async (c) => {
|
|
5918
|
+
* const body = await c.req.blob();
|
|
5919
|
+
* });
|
|
5920
|
+
* ```
|
|
5921
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
5922
|
+
*/
|
|
5923
|
+
blob() {
|
|
5924
|
+
return this.#cachedBody("blob");
|
|
5925
|
+
}
|
|
5926
|
+
/**
|
|
5927
|
+
* Parses the request body as `FormData`.
|
|
5928
|
+
* @example
|
|
5929
|
+
* ```ts
|
|
5930
|
+
* app.post('/entry', async (c) => {
|
|
5931
|
+
* const body = await c.req.formData();
|
|
5932
|
+
* });
|
|
5933
|
+
* ```
|
|
5934
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
5935
|
+
*/
|
|
5936
|
+
formData() {
|
|
5937
|
+
return this.#cachedBody("formData");
|
|
5938
|
+
}
|
|
5939
|
+
/**
|
|
5940
|
+
* Adds validated data to the request.
|
|
5941
|
+
*
|
|
5942
|
+
* @param target - The target of the validation.
|
|
5943
|
+
* @param data - The validated data to add.
|
|
5944
|
+
*/
|
|
5945
|
+
addValidatedData(target, data) {
|
|
5946
|
+
this.#validatedData[target] = data;
|
|
5947
|
+
}
|
|
5948
|
+
valid(target) {
|
|
5949
|
+
return this.#validatedData[target];
|
|
5950
|
+
}
|
|
5951
|
+
/**
|
|
5952
|
+
* `.url()` can get the request url strings.
|
|
5953
|
+
*
|
|
5954
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
5955
|
+
*
|
|
5956
|
+
* @example
|
|
5957
|
+
* ```ts
|
|
5958
|
+
* app.get('/about/me', (c) => {
|
|
5959
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
5960
|
+
* ...
|
|
5961
|
+
* })
|
|
5962
|
+
* ```
|
|
5963
|
+
*/
|
|
5964
|
+
get url() {
|
|
5965
|
+
return this.raw.url;
|
|
5966
|
+
}
|
|
5967
|
+
/**
|
|
5968
|
+
* `.method()` can get the method name of the request.
|
|
5969
|
+
*
|
|
5970
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
5971
|
+
*
|
|
5972
|
+
* @example
|
|
5973
|
+
* ```ts
|
|
5974
|
+
* app.get('/about/me', (c) => {
|
|
5975
|
+
* const method = c.req.method // `GET`
|
|
5976
|
+
* })
|
|
5977
|
+
* ```
|
|
5978
|
+
*/
|
|
5979
|
+
get method() {
|
|
5980
|
+
return this.raw.method;
|
|
5981
|
+
}
|
|
5982
|
+
get [GET_MATCH_RESULT]() {
|
|
5983
|
+
return this.#matchResult;
|
|
5984
|
+
}
|
|
5985
|
+
/**
|
|
5986
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
5987
|
+
*
|
|
5988
|
+
* @deprecated
|
|
5989
|
+
*
|
|
5990
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
5991
|
+
*
|
|
5992
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
5993
|
+
*
|
|
5994
|
+
* @example
|
|
5995
|
+
* ```ts
|
|
5996
|
+
* app.use('*', async function logger(c, next) {
|
|
5997
|
+
* await next()
|
|
5998
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
5999
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
6000
|
+
* console.log(
|
|
6001
|
+
* method,
|
|
6002
|
+
* ' ',
|
|
6003
|
+
* path,
|
|
6004
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
6005
|
+
* name,
|
|
6006
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
6007
|
+
* )
|
|
6008
|
+
* })
|
|
6009
|
+
* })
|
|
6010
|
+
* ```
|
|
6011
|
+
*/
|
|
6012
|
+
get matchedRoutes() {
|
|
6013
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
6014
|
+
}
|
|
6015
|
+
/**
|
|
6016
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
6017
|
+
*
|
|
6018
|
+
* @deprecated
|
|
6019
|
+
*
|
|
6020
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
6021
|
+
*
|
|
6022
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
6023
|
+
*
|
|
6024
|
+
* @example
|
|
6025
|
+
* ```ts
|
|
6026
|
+
* app.get('/posts/:id', (c) => {
|
|
6027
|
+
* return c.json({ path: c.req.routePath })
|
|
6028
|
+
* })
|
|
6029
|
+
* ```
|
|
6030
|
+
*/
|
|
6031
|
+
get routePath() {
|
|
6032
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
6033
|
+
}
|
|
6034
|
+
};
|
|
6035
|
+
//#endregion
|
|
6036
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/html.js
|
|
6037
|
+
var HtmlEscapedCallbackPhase = {
|
|
6038
|
+
Stringify: 1,
|
|
6039
|
+
BeforeStream: 2,
|
|
6040
|
+
Stream: 3
|
|
6041
|
+
};
|
|
6042
|
+
var raw = (value, callbacks) => {
|
|
6043
|
+
const escapedString = new String(value);
|
|
6044
|
+
escapedString.isEscaped = true;
|
|
6045
|
+
escapedString.callbacks = callbacks;
|
|
6046
|
+
return escapedString;
|
|
6047
|
+
};
|
|
6048
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
6049
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
6050
|
+
if (!(str instanceof Promise)) str = str.toString();
|
|
6051
|
+
if (str instanceof Promise) str = await str;
|
|
6052
|
+
}
|
|
6053
|
+
const callbacks = str.callbacks;
|
|
6054
|
+
if (!callbacks?.length) return Promise.resolve(str);
|
|
6055
|
+
if (buffer) buffer[0] += str;
|
|
6056
|
+
else buffer = [str];
|
|
6057
|
+
const resStr = Promise.all(callbacks.map((c) => c({
|
|
6058
|
+
phase,
|
|
6059
|
+
buffer,
|
|
6060
|
+
context
|
|
6061
|
+
}))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
6062
|
+
if (preserveCallbacks) return raw(await resStr, callbacks);
|
|
6063
|
+
else return resStr;
|
|
6064
|
+
};
|
|
6065
|
+
//#endregion
|
|
6066
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/context.js
|
|
6067
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
6068
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
6069
|
+
return {
|
|
6070
|
+
"Content-Type": contentType,
|
|
6071
|
+
...headers
|
|
6072
|
+
};
|
|
6073
|
+
};
|
|
6074
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
6075
|
+
var Context = class {
|
|
6076
|
+
#rawRequest;
|
|
6077
|
+
#req;
|
|
6078
|
+
/**
|
|
6079
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
6080
|
+
*
|
|
6081
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
6082
|
+
*
|
|
6083
|
+
* @example
|
|
6084
|
+
* ```ts
|
|
6085
|
+
* // Environment object for Cloudflare Workers
|
|
6086
|
+
* app.get('*', async c => {
|
|
6087
|
+
* const counter = c.env.COUNTER
|
|
6088
|
+
* })
|
|
6089
|
+
* ```
|
|
6090
|
+
*/
|
|
6091
|
+
env = {};
|
|
6092
|
+
#var;
|
|
6093
|
+
finalized = false;
|
|
6094
|
+
/**
|
|
6095
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
6096
|
+
*
|
|
6097
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
6098
|
+
*
|
|
6099
|
+
* @example
|
|
6100
|
+
* ```ts
|
|
6101
|
+
* app.use('*', async (c, next) => {
|
|
6102
|
+
* await next()
|
|
6103
|
+
* if (c.error) {
|
|
6104
|
+
* // do something...
|
|
6105
|
+
* }
|
|
6106
|
+
* })
|
|
6107
|
+
* ```
|
|
6108
|
+
*/
|
|
6109
|
+
error;
|
|
6110
|
+
#status;
|
|
6111
|
+
#executionCtx;
|
|
6112
|
+
#res;
|
|
6113
|
+
#layout;
|
|
6114
|
+
#renderer;
|
|
6115
|
+
#notFoundHandler;
|
|
6116
|
+
#preparedHeaders;
|
|
6117
|
+
#matchResult;
|
|
6118
|
+
#path;
|
|
6119
|
+
/**
|
|
6120
|
+
* Creates an instance of the Context class.
|
|
6121
|
+
*
|
|
6122
|
+
* @param req - The Request object.
|
|
6123
|
+
* @param options - Optional configuration options for the context.
|
|
6124
|
+
*/
|
|
6125
|
+
constructor(req, options) {
|
|
6126
|
+
this.#rawRequest = req;
|
|
6127
|
+
if (options) {
|
|
6128
|
+
this.#executionCtx = options.executionCtx;
|
|
6129
|
+
this.env = options.env;
|
|
6130
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
6131
|
+
this.#path = options.path;
|
|
6132
|
+
this.#matchResult = options.matchResult;
|
|
6133
|
+
}
|
|
6134
|
+
}
|
|
6135
|
+
/**
|
|
6136
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
6137
|
+
*/
|
|
6138
|
+
get req() {
|
|
6139
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
6140
|
+
return this.#req;
|
|
6141
|
+
}
|
|
6142
|
+
/**
|
|
6143
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
6144
|
+
* The FetchEvent associated with the current request.
|
|
6145
|
+
*
|
|
6146
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
6147
|
+
*/
|
|
6148
|
+
get event() {
|
|
6149
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) return this.#executionCtx;
|
|
6150
|
+
else throw Error("This context has no FetchEvent");
|
|
6151
|
+
}
|
|
6152
|
+
/**
|
|
6153
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
6154
|
+
* The ExecutionContext associated with the current request.
|
|
6155
|
+
*
|
|
6156
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
6157
|
+
*/
|
|
6158
|
+
get executionCtx() {
|
|
6159
|
+
if (this.#executionCtx) return this.#executionCtx;
|
|
6160
|
+
else throw Error("This context has no ExecutionContext");
|
|
6161
|
+
}
|
|
6162
|
+
/**
|
|
6163
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
6164
|
+
* The Response object for the current request.
|
|
6165
|
+
*/
|
|
6166
|
+
get res() {
|
|
6167
|
+
return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });
|
|
6168
|
+
}
|
|
6169
|
+
/**
|
|
6170
|
+
* Sets the Response object for the current request.
|
|
6171
|
+
*
|
|
6172
|
+
* @param _res - The Response object to set.
|
|
6173
|
+
*/
|
|
6174
|
+
set res(_res) {
|
|
6175
|
+
if (this.#res && _res) {
|
|
6176
|
+
_res = createResponseInstance(_res.body, _res);
|
|
6177
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
6178
|
+
if (k === "content-type") continue;
|
|
6179
|
+
if (k === "set-cookie") {
|
|
6180
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
6181
|
+
_res.headers.delete("set-cookie");
|
|
6182
|
+
for (const cookie of cookies) _res.headers.append("set-cookie", cookie);
|
|
6183
|
+
} else _res.headers.set(k, v);
|
|
6184
|
+
}
|
|
6185
|
+
}
|
|
6186
|
+
this.#res = _res;
|
|
6187
|
+
this.finalized = true;
|
|
6188
|
+
}
|
|
6189
|
+
/**
|
|
6190
|
+
* `.render()` can create a response within a layout.
|
|
6191
|
+
*
|
|
6192
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
6193
|
+
*
|
|
6194
|
+
* @example
|
|
6195
|
+
* ```ts
|
|
6196
|
+
* app.get('/', (c) => {
|
|
6197
|
+
* return c.render('Hello!')
|
|
6198
|
+
* })
|
|
6199
|
+
* ```
|
|
6200
|
+
*/
|
|
6201
|
+
render = (...args) => {
|
|
6202
|
+
this.#renderer ??= (content) => this.html(content);
|
|
6203
|
+
return this.#renderer(...args);
|
|
6204
|
+
};
|
|
6205
|
+
/**
|
|
6206
|
+
* Sets the layout for the response.
|
|
6207
|
+
*
|
|
6208
|
+
* @param layout - The layout to set.
|
|
6209
|
+
* @returns The layout function.
|
|
6210
|
+
*/
|
|
6211
|
+
setLayout = (layout) => this.#layout = layout;
|
|
6212
|
+
/**
|
|
6213
|
+
* Gets the current layout for the response.
|
|
6214
|
+
*
|
|
6215
|
+
* @returns The current layout function.
|
|
6216
|
+
*/
|
|
6217
|
+
getLayout = () => this.#layout;
|
|
6218
|
+
/**
|
|
6219
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
6220
|
+
*
|
|
6221
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
6222
|
+
*
|
|
6223
|
+
* @example
|
|
6224
|
+
* ```tsx
|
|
6225
|
+
* app.use('*', async (c, next) => {
|
|
6226
|
+
* c.setRenderer((content) => {
|
|
6227
|
+
* return c.html(
|
|
6228
|
+
* <html>
|
|
6229
|
+
* <body>
|
|
6230
|
+
* <p>{content}</p>
|
|
6231
|
+
* </body>
|
|
6232
|
+
* </html>
|
|
6233
|
+
* )
|
|
6234
|
+
* })
|
|
6235
|
+
* await next()
|
|
6236
|
+
* })
|
|
6237
|
+
* ```
|
|
6238
|
+
*/
|
|
6239
|
+
setRenderer = (renderer) => {
|
|
6240
|
+
this.#renderer = renderer;
|
|
6241
|
+
};
|
|
6242
|
+
/**
|
|
6243
|
+
* `.header()` can set headers.
|
|
6244
|
+
*
|
|
6245
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
6246
|
+
*
|
|
6247
|
+
* @example
|
|
6248
|
+
* ```ts
|
|
6249
|
+
* app.get('/welcome', (c) => {
|
|
6250
|
+
* // Set headers
|
|
6251
|
+
* c.header('X-Message', 'Hello!')
|
|
6252
|
+
* c.header('Content-Type', 'text/plain')
|
|
6253
|
+
*
|
|
6254
|
+
* return c.body('Thank you for coming')
|
|
6255
|
+
* })
|
|
6256
|
+
* ```
|
|
6257
|
+
*/
|
|
6258
|
+
header = (name, value, options) => {
|
|
6259
|
+
if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
6260
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
6261
|
+
if (value === void 0) headers.delete(name);
|
|
6262
|
+
else if (options?.append) headers.append(name, value);
|
|
6263
|
+
else headers.set(name, value);
|
|
6264
|
+
};
|
|
6265
|
+
status = (status) => {
|
|
6266
|
+
this.#status = status;
|
|
6267
|
+
};
|
|
6268
|
+
/**
|
|
6269
|
+
* `.set()` can set the value specified by the key.
|
|
6270
|
+
*
|
|
6271
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
6272
|
+
*
|
|
6273
|
+
* @example
|
|
6274
|
+
* ```ts
|
|
6275
|
+
* app.use('*', async (c, next) => {
|
|
6276
|
+
* c.set('message', 'Hono is hot!!')
|
|
6277
|
+
* await next()
|
|
6278
|
+
* })
|
|
6279
|
+
* ```
|
|
6280
|
+
*/
|
|
6281
|
+
set = (key, value) => {
|
|
6282
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
6283
|
+
this.#var.set(key, value);
|
|
6284
|
+
};
|
|
6285
|
+
/**
|
|
6286
|
+
* `.get()` can use the value specified by the key.
|
|
6287
|
+
*
|
|
6288
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
6289
|
+
*
|
|
6290
|
+
* @example
|
|
6291
|
+
* ```ts
|
|
6292
|
+
* app.get('/', (c) => {
|
|
6293
|
+
* const message = c.get('message')
|
|
6294
|
+
* return c.text(`The message is "${message}"`)
|
|
6295
|
+
* })
|
|
6296
|
+
* ```
|
|
6297
|
+
*/
|
|
6298
|
+
get = (key) => {
|
|
6299
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
6300
|
+
};
|
|
6301
|
+
/**
|
|
6302
|
+
* `.var` can access the value of a variable.
|
|
6303
|
+
*
|
|
6304
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
6305
|
+
*
|
|
6306
|
+
* @example
|
|
6307
|
+
* ```ts
|
|
6308
|
+
* const result = c.var.client.oneMethod()
|
|
6309
|
+
* ```
|
|
6310
|
+
*/
|
|
6311
|
+
get var() {
|
|
6312
|
+
if (!this.#var) return {};
|
|
6313
|
+
return Object.fromEntries(this.#var);
|
|
6314
|
+
}
|
|
6315
|
+
#newResponse(data, arg, headers) {
|
|
6316
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
6317
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
6318
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
6319
|
+
for (const [key, value] of argHeaders) if (key.toLowerCase() === "set-cookie") responseHeaders.append(key, value);
|
|
6320
|
+
else responseHeaders.set(key, value);
|
|
6321
|
+
}
|
|
6322
|
+
if (headers) for (const [k, v] of Object.entries(headers)) if (typeof v === "string") responseHeaders.set(k, v);
|
|
6323
|
+
else {
|
|
6324
|
+
responseHeaders.delete(k);
|
|
6325
|
+
for (const v2 of v) responseHeaders.append(k, v2);
|
|
6326
|
+
}
|
|
6327
|
+
return createResponseInstance(data, {
|
|
6328
|
+
status: typeof arg === "number" ? arg : arg?.status ?? this.#status,
|
|
6329
|
+
headers: responseHeaders
|
|
6330
|
+
});
|
|
6331
|
+
}
|
|
6332
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
6333
|
+
/**
|
|
6334
|
+
* `.body()` can return the HTTP response.
|
|
6335
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
6336
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
6337
|
+
*
|
|
6338
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
6339
|
+
*
|
|
6340
|
+
* @example
|
|
6341
|
+
* ```ts
|
|
6342
|
+
* app.get('/welcome', (c) => {
|
|
6343
|
+
* // Set headers
|
|
6344
|
+
* c.header('X-Message', 'Hello!')
|
|
6345
|
+
* c.header('Content-Type', 'text/plain')
|
|
6346
|
+
* // Set HTTP status code
|
|
6347
|
+
* c.status(201)
|
|
6348
|
+
*
|
|
6349
|
+
* // Return the response body
|
|
6350
|
+
* return c.body('Thank you for coming')
|
|
6351
|
+
* })
|
|
6352
|
+
* ```
|
|
6353
|
+
*/
|
|
6354
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
6355
|
+
/**
|
|
6356
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
6357
|
+
*
|
|
6358
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
6359
|
+
*
|
|
6360
|
+
* @example
|
|
6361
|
+
* ```ts
|
|
6362
|
+
* app.get('/say', (c) => {
|
|
6363
|
+
* return c.text('Hello!')
|
|
6364
|
+
* })
|
|
6365
|
+
* ```
|
|
6366
|
+
*/
|
|
6367
|
+
text = (text, arg, headers) => {
|
|
6368
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
6369
|
+
};
|
|
6370
|
+
/**
|
|
6371
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
6372
|
+
*
|
|
6373
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
6374
|
+
*
|
|
6375
|
+
* @example
|
|
6376
|
+
* ```ts
|
|
6377
|
+
* app.get('/api', (c) => {
|
|
6378
|
+
* return c.json({ message: 'Hello!' })
|
|
6379
|
+
* })
|
|
6380
|
+
* ```
|
|
6381
|
+
*/
|
|
6382
|
+
json = (object, arg, headers) => {
|
|
6383
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
6384
|
+
};
|
|
6385
|
+
html = (html, arg, headers) => {
|
|
6386
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
6387
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
6388
|
+
};
|
|
6389
|
+
/**
|
|
6390
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
6391
|
+
*
|
|
6392
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
6393
|
+
*
|
|
6394
|
+
* @example
|
|
6395
|
+
* ```ts
|
|
6396
|
+
* app.get('/redirect', (c) => {
|
|
6397
|
+
* return c.redirect('/')
|
|
6398
|
+
* })
|
|
6399
|
+
* app.get('/redirect-permanently', (c) => {
|
|
6400
|
+
* return c.redirect('/', 301)
|
|
6401
|
+
* })
|
|
6402
|
+
* ```
|
|
6403
|
+
*/
|
|
6404
|
+
redirect = (location, status) => {
|
|
6405
|
+
const locationString = String(location);
|
|
6406
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
6407
|
+
return this.newResponse(null, status ?? 302);
|
|
6408
|
+
};
|
|
6409
|
+
/**
|
|
6410
|
+
* `.notFound()` can return the Not Found Response.
|
|
6411
|
+
*
|
|
6412
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
6413
|
+
*
|
|
6414
|
+
* @example
|
|
6415
|
+
* ```ts
|
|
6416
|
+
* app.get('/notfound', (c) => {
|
|
6417
|
+
* return c.notFound()
|
|
6418
|
+
* })
|
|
6419
|
+
* ```
|
|
6420
|
+
*/
|
|
6421
|
+
notFound = () => {
|
|
6422
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
6423
|
+
return this.#notFoundHandler(this);
|
|
6424
|
+
};
|
|
6425
|
+
};
|
|
6426
|
+
//#endregion
|
|
6427
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router.js
|
|
6428
|
+
var METHODS = [
|
|
6429
|
+
"get",
|
|
6430
|
+
"post",
|
|
6431
|
+
"put",
|
|
6432
|
+
"delete",
|
|
6433
|
+
"options",
|
|
6434
|
+
"patch"
|
|
6435
|
+
];
|
|
6436
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
6437
|
+
var UnsupportedPathError = class extends Error {};
|
|
6438
|
+
//#endregion
|
|
6439
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/constants.js
|
|
6440
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
6441
|
+
//#endregion
|
|
6442
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/hono-base.js
|
|
6443
|
+
var notFoundHandler = (c) => {
|
|
6444
|
+
return c.text("404 Not Found", 404);
|
|
6445
|
+
};
|
|
6446
|
+
var errorHandler = (err, c) => {
|
|
6447
|
+
if ("getResponse" in err) {
|
|
6448
|
+
const res = err.getResponse();
|
|
6449
|
+
return c.newResponse(res.body, res);
|
|
6450
|
+
}
|
|
6451
|
+
console.error(err);
|
|
6452
|
+
return c.text("Internal Server Error", 500);
|
|
6453
|
+
};
|
|
6454
|
+
var Hono$1 = class _Hono {
|
|
6455
|
+
get;
|
|
6456
|
+
post;
|
|
6457
|
+
put;
|
|
6458
|
+
delete;
|
|
6459
|
+
options;
|
|
6460
|
+
patch;
|
|
6461
|
+
all;
|
|
6462
|
+
on;
|
|
6463
|
+
use;
|
|
6464
|
+
router;
|
|
6465
|
+
getPath;
|
|
6466
|
+
_basePath = "/";
|
|
6467
|
+
#path = "/";
|
|
6468
|
+
routes = [];
|
|
6469
|
+
constructor(options = {}) {
|
|
6470
|
+
[...METHODS, "all"].forEach((method) => {
|
|
6471
|
+
this[method] = (args1, ...args) => {
|
|
6472
|
+
if (typeof args1 === "string") this.#path = args1;
|
|
6473
|
+
else this.#addRoute(method, this.#path, args1);
|
|
6474
|
+
args.forEach((handler) => {
|
|
6475
|
+
this.#addRoute(method, this.#path, handler);
|
|
6476
|
+
});
|
|
6477
|
+
return this;
|
|
6478
|
+
};
|
|
6479
|
+
});
|
|
6480
|
+
this.on = (method, path, ...handlers) => {
|
|
6481
|
+
for (const p of [path].flat()) {
|
|
6482
|
+
this.#path = p;
|
|
6483
|
+
for (const m of [method].flat()) handlers.map((handler) => {
|
|
6484
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
6485
|
+
});
|
|
6486
|
+
}
|
|
6487
|
+
return this;
|
|
6488
|
+
};
|
|
6489
|
+
this.use = (arg1, ...handlers) => {
|
|
6490
|
+
if (typeof arg1 === "string") this.#path = arg1;
|
|
6491
|
+
else {
|
|
6492
|
+
this.#path = "*";
|
|
6493
|
+
handlers.unshift(arg1);
|
|
6494
|
+
}
|
|
6495
|
+
handlers.forEach((handler) => {
|
|
6496
|
+
this.#addRoute("ALL", this.#path, handler);
|
|
6497
|
+
});
|
|
6498
|
+
return this;
|
|
6499
|
+
};
|
|
6500
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
6501
|
+
Object.assign(this, optionsWithoutStrict);
|
|
6502
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
6503
|
+
}
|
|
6504
|
+
#clone() {
|
|
6505
|
+
const clone = new _Hono({
|
|
6506
|
+
router: this.router,
|
|
6507
|
+
getPath: this.getPath
|
|
6508
|
+
});
|
|
6509
|
+
clone.errorHandler = this.errorHandler;
|
|
6510
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
6511
|
+
clone.routes = this.routes;
|
|
6512
|
+
return clone;
|
|
6513
|
+
}
|
|
6514
|
+
#notFoundHandler = notFoundHandler;
|
|
6515
|
+
errorHandler = errorHandler;
|
|
6516
|
+
/**
|
|
6517
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
6518
|
+
*
|
|
6519
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
6520
|
+
*
|
|
6521
|
+
* @param {string} path - base Path
|
|
6522
|
+
* @param {Hono} app - other Hono instance
|
|
6523
|
+
* @returns {Hono} routed Hono instance
|
|
6524
|
+
*
|
|
6525
|
+
* @example
|
|
6526
|
+
* ```ts
|
|
6527
|
+
* const app = new Hono()
|
|
6528
|
+
* const app2 = new Hono()
|
|
6529
|
+
*
|
|
6530
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
6531
|
+
* app.route("/api", app2) // GET /api/user
|
|
6532
|
+
* ```
|
|
6533
|
+
*/
|
|
6534
|
+
route(path, app) {
|
|
6535
|
+
const subApp = this.basePath(path);
|
|
6536
|
+
app.routes.map((r) => {
|
|
6537
|
+
let handler;
|
|
6538
|
+
if (app.errorHandler === errorHandler) handler = r.handler;
|
|
6539
|
+
else {
|
|
6540
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
6541
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
6542
|
+
}
|
|
6543
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
6544
|
+
});
|
|
6545
|
+
return this;
|
|
6546
|
+
}
|
|
6547
|
+
/**
|
|
6548
|
+
* `.basePath()` allows base paths to be specified.
|
|
6549
|
+
*
|
|
6550
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
6551
|
+
*
|
|
6552
|
+
* @param {string} path - base Path
|
|
6553
|
+
* @returns {Hono} changed Hono instance
|
|
6554
|
+
*
|
|
6555
|
+
* @example
|
|
6556
|
+
* ```ts
|
|
6557
|
+
* const api = new Hono().basePath('/api')
|
|
6558
|
+
* ```
|
|
6559
|
+
*/
|
|
6560
|
+
basePath(path) {
|
|
6561
|
+
const subApp = this.#clone();
|
|
6562
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
6563
|
+
return subApp;
|
|
6564
|
+
}
|
|
6565
|
+
/**
|
|
6566
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
6567
|
+
*
|
|
6568
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
6569
|
+
*
|
|
6570
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
6571
|
+
* @returns {Hono} changed Hono instance
|
|
6572
|
+
*
|
|
6573
|
+
* @example
|
|
6574
|
+
* ```ts
|
|
6575
|
+
* app.onError((err, c) => {
|
|
6576
|
+
* console.error(`${err}`)
|
|
6577
|
+
* return c.text('Custom Error Message', 500)
|
|
6578
|
+
* })
|
|
6579
|
+
* ```
|
|
6580
|
+
*/
|
|
6581
|
+
onError = (handler) => {
|
|
6582
|
+
this.errorHandler = handler;
|
|
6583
|
+
return this;
|
|
6584
|
+
};
|
|
6585
|
+
/**
|
|
6586
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
6587
|
+
*
|
|
6588
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
6589
|
+
*
|
|
6590
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
6591
|
+
* @returns {Hono} changed Hono instance
|
|
6592
|
+
*
|
|
6593
|
+
* @example
|
|
6594
|
+
* ```ts
|
|
6595
|
+
* app.notFound((c) => {
|
|
6596
|
+
* return c.text('Custom 404 Message', 404)
|
|
6597
|
+
* })
|
|
6598
|
+
* ```
|
|
6599
|
+
*/
|
|
6600
|
+
notFound = (handler) => {
|
|
6601
|
+
this.#notFoundHandler = handler;
|
|
6602
|
+
return this;
|
|
6603
|
+
};
|
|
6604
|
+
/**
|
|
6605
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
6606
|
+
*
|
|
6607
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
6608
|
+
*
|
|
6609
|
+
* @param {string} path - base Path
|
|
6610
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
6611
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
6612
|
+
* @returns {Hono} mounted Hono instance
|
|
6613
|
+
*
|
|
6614
|
+
* @example
|
|
6615
|
+
* ```ts
|
|
6616
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
6617
|
+
* import { Hono } from 'hono'
|
|
6618
|
+
* // Create itty-router application
|
|
6619
|
+
* const ittyRouter = IttyRouter()
|
|
6620
|
+
* // GET /itty-router/hello
|
|
6621
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
6622
|
+
*
|
|
6623
|
+
* const app = new Hono()
|
|
6624
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
6625
|
+
* ```
|
|
6626
|
+
*
|
|
6627
|
+
* @example
|
|
6628
|
+
* ```ts
|
|
6629
|
+
* const app = new Hono()
|
|
6630
|
+
* // Send the request to another application without modification.
|
|
6631
|
+
* app.mount('/app', anotherApp, {
|
|
6632
|
+
* replaceRequest: (req) => req,
|
|
6633
|
+
* })
|
|
6634
|
+
* ```
|
|
6635
|
+
*/
|
|
6636
|
+
mount(path, applicationHandler, options) {
|
|
6637
|
+
let replaceRequest;
|
|
6638
|
+
let optionHandler;
|
|
6639
|
+
if (options) if (typeof options === "function") optionHandler = options;
|
|
6640
|
+
else {
|
|
6641
|
+
optionHandler = options.optionHandler;
|
|
6642
|
+
if (options.replaceRequest === false) replaceRequest = (request) => request;
|
|
6643
|
+
else replaceRequest = options.replaceRequest;
|
|
6644
|
+
}
|
|
6645
|
+
const getOptions = optionHandler ? (c) => {
|
|
6646
|
+
const options2 = optionHandler(c);
|
|
6647
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
6648
|
+
} : (c) => {
|
|
6649
|
+
let executionContext = void 0;
|
|
6650
|
+
try {
|
|
6651
|
+
executionContext = c.executionCtx;
|
|
6652
|
+
} catch {}
|
|
6653
|
+
return [c.env, executionContext];
|
|
6654
|
+
};
|
|
6655
|
+
replaceRequest ||= (() => {
|
|
6656
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
6657
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
6658
|
+
return (request) => {
|
|
6659
|
+
const url = new URL(request.url);
|
|
6660
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
6661
|
+
return new Request(url, request);
|
|
6662
|
+
};
|
|
6663
|
+
})();
|
|
6664
|
+
const handler = async (c, next) => {
|
|
6665
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
6666
|
+
if (res) return res;
|
|
6667
|
+
await next();
|
|
6668
|
+
};
|
|
6669
|
+
this.#addRoute("ALL", mergePath(path, "*"), handler);
|
|
6670
|
+
return this;
|
|
6671
|
+
}
|
|
6672
|
+
#addRoute(method, path, handler) {
|
|
6673
|
+
method = method.toUpperCase();
|
|
6674
|
+
path = mergePath(this._basePath, path);
|
|
6675
|
+
const r = {
|
|
6676
|
+
basePath: this._basePath,
|
|
6677
|
+
path,
|
|
6678
|
+
method,
|
|
6679
|
+
handler
|
|
6680
|
+
};
|
|
6681
|
+
this.router.add(method, path, [handler, r]);
|
|
6682
|
+
this.routes.push(r);
|
|
6683
|
+
}
|
|
6684
|
+
#handleError(err, c) {
|
|
6685
|
+
if (err instanceof Error) return this.errorHandler(err, c);
|
|
6686
|
+
throw err;
|
|
6687
|
+
}
|
|
6688
|
+
#dispatch(request, executionCtx, env, method) {
|
|
6689
|
+
if (method === "HEAD") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
6690
|
+
const path = this.getPath(request, { env });
|
|
6691
|
+
const matchResult = this.router.match(method, path);
|
|
6692
|
+
const c = new Context(request, {
|
|
6693
|
+
path,
|
|
6694
|
+
matchResult,
|
|
6695
|
+
env,
|
|
6696
|
+
executionCtx,
|
|
6697
|
+
notFoundHandler: this.#notFoundHandler
|
|
6698
|
+
});
|
|
6699
|
+
if (matchResult[0].length === 1) {
|
|
6700
|
+
let res;
|
|
6701
|
+
try {
|
|
6702
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
6703
|
+
c.res = await this.#notFoundHandler(c);
|
|
6704
|
+
});
|
|
6705
|
+
} catch (err) {
|
|
6706
|
+
return this.#handleError(err, c);
|
|
6707
|
+
}
|
|
6708
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
6709
|
+
}
|
|
6710
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
6711
|
+
return (async () => {
|
|
6712
|
+
try {
|
|
6713
|
+
const context = await composed(c);
|
|
6714
|
+
if (!context.finalized) throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
6715
|
+
return context.res;
|
|
6716
|
+
} catch (err) {
|
|
6717
|
+
return this.#handleError(err, c);
|
|
6718
|
+
}
|
|
6719
|
+
})();
|
|
6720
|
+
}
|
|
6721
|
+
/**
|
|
6722
|
+
* `.fetch()` will be entry point of your app.
|
|
6723
|
+
*
|
|
6724
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
6725
|
+
*
|
|
6726
|
+
* @param {Request} request - request Object of request
|
|
6727
|
+
* @param {Env} Env - env Object
|
|
6728
|
+
* @param {ExecutionContext} - context of execution
|
|
6729
|
+
* @returns {Response | Promise<Response>} response of request
|
|
6730
|
+
*
|
|
6731
|
+
*/
|
|
6732
|
+
fetch = (request, ...rest) => {
|
|
6733
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
6734
|
+
};
|
|
6735
|
+
/**
|
|
6736
|
+
* `.request()` is a useful method for testing.
|
|
6737
|
+
* You can pass a URL or pathname to send a GET request.
|
|
6738
|
+
* app will return a Response object.
|
|
6739
|
+
* ```ts
|
|
6740
|
+
* test('GET /hello is ok', async () => {
|
|
6741
|
+
* const res = await app.request('/hello')
|
|
6742
|
+
* expect(res.status).toBe(200)
|
|
6743
|
+
* })
|
|
6744
|
+
* ```
|
|
6745
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
6746
|
+
*/
|
|
6747
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
6748
|
+
if (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
6749
|
+
input = input.toString();
|
|
6750
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
6751
|
+
};
|
|
6752
|
+
/**
|
|
6753
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
6754
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
6755
|
+
* @deprecated
|
|
6756
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
6757
|
+
* ```ts
|
|
6758
|
+
* import { Hono } from 'hono'
|
|
6759
|
+
* import { fire } from 'hono/service-worker'
|
|
6760
|
+
*
|
|
6761
|
+
* const app = new Hono()
|
|
6762
|
+
* // ...
|
|
6763
|
+
* fire(app)
|
|
6764
|
+
* ```
|
|
6765
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
6766
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
6767
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
6768
|
+
*/
|
|
6769
|
+
fire = () => {
|
|
6770
|
+
addEventListener("fetch", (event) => {
|
|
6771
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
6772
|
+
});
|
|
6773
|
+
};
|
|
6774
|
+
};
|
|
6775
|
+
//#endregion
|
|
6776
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
6777
|
+
var emptyParam = [];
|
|
6778
|
+
function match(method, path) {
|
|
6779
|
+
const matchers = this.buildAllMatchers();
|
|
6780
|
+
const match2 = ((method2, path2) => {
|
|
6781
|
+
const matcher = matchers[method2] || matchers["ALL"];
|
|
6782
|
+
const staticMatch = matcher[2][path2];
|
|
6783
|
+
if (staticMatch) return staticMatch;
|
|
6784
|
+
const match3 = path2.match(matcher[0]);
|
|
6785
|
+
if (!match3) return [[], emptyParam];
|
|
6786
|
+
const index = match3.indexOf("", 1);
|
|
6787
|
+
return [matcher[1][index], match3];
|
|
6788
|
+
});
|
|
6789
|
+
this.match = match2;
|
|
6790
|
+
return match2(method, path);
|
|
6791
|
+
}
|
|
6792
|
+
//#endregion
|
|
6793
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/node.js
|
|
6794
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
6795
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
6796
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
6797
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
6798
|
+
var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
|
|
6799
|
+
function compareKey(a, b) {
|
|
6800
|
+
if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
6801
|
+
if (b.length === 1) return 1;
|
|
6802
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) return 1;
|
|
6803
|
+
else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) return -1;
|
|
6804
|
+
if (a === LABEL_REG_EXP_STR) return 1;
|
|
6805
|
+
else if (b === LABEL_REG_EXP_STR) return -1;
|
|
6806
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
6807
|
+
}
|
|
6808
|
+
var Node$1 = class _Node {
|
|
6809
|
+
#index;
|
|
6810
|
+
#varIndex;
|
|
6811
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
6812
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
6813
|
+
if (tokens.length === 0) {
|
|
6814
|
+
if (this.#index !== void 0) throw PATH_ERROR;
|
|
6815
|
+
if (pathErrorCheckOnly) return;
|
|
6816
|
+
this.#index = index;
|
|
6817
|
+
return;
|
|
6818
|
+
}
|
|
6819
|
+
const [token, ...restTokens] = tokens;
|
|
6820
|
+
const pattern = token === "*" ? restTokens.length === 0 ? [
|
|
6821
|
+
"",
|
|
6822
|
+
"",
|
|
6823
|
+
ONLY_WILDCARD_REG_EXP_STR
|
|
6824
|
+
] : [
|
|
6825
|
+
"",
|
|
6826
|
+
"",
|
|
6827
|
+
LABEL_REG_EXP_STR
|
|
6828
|
+
] : token === "/*" ? [
|
|
6829
|
+
"",
|
|
6830
|
+
"",
|
|
6831
|
+
TAIL_WILDCARD_REG_EXP_STR
|
|
6832
|
+
] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
6833
|
+
let node;
|
|
6834
|
+
if (pattern) {
|
|
6835
|
+
const name = pattern[1];
|
|
6836
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
6837
|
+
if (name && pattern[2]) {
|
|
6838
|
+
if (regexpStr === ".*") throw PATH_ERROR;
|
|
6839
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
6840
|
+
if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
|
|
6841
|
+
}
|
|
6842
|
+
node = this.#children[regexpStr];
|
|
6843
|
+
if (!node) {
|
|
6844
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
|
|
6845
|
+
if (pathErrorCheckOnly) return;
|
|
6846
|
+
node = this.#children[regexpStr] = new _Node();
|
|
6847
|
+
if (name !== "") node.#varIndex = context.varIndex++;
|
|
6848
|
+
}
|
|
6849
|
+
if (!pathErrorCheckOnly && name !== "") paramMap.push([name, node.#varIndex]);
|
|
6850
|
+
} else {
|
|
6851
|
+
node = this.#children[token];
|
|
6852
|
+
if (!node) {
|
|
6853
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) throw PATH_ERROR;
|
|
6854
|
+
if (pathErrorCheckOnly) return;
|
|
6855
|
+
node = this.#children[token] = new _Node();
|
|
6856
|
+
}
|
|
6857
|
+
}
|
|
6858
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
6859
|
+
}
|
|
6860
|
+
buildRegExpStr() {
|
|
6861
|
+
const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
|
|
6862
|
+
const c = this.#children[k];
|
|
6863
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
6864
|
+
});
|
|
6865
|
+
if (typeof this.#index === "number") strList.unshift(`#${this.#index}`);
|
|
6866
|
+
if (strList.length === 0) return "";
|
|
6867
|
+
if (strList.length === 1) return strList[0];
|
|
6868
|
+
return "(?:" + strList.join("|") + ")";
|
|
6869
|
+
}
|
|
6870
|
+
};
|
|
6871
|
+
//#endregion
|
|
6872
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
6873
|
+
var Trie = class {
|
|
6874
|
+
#context = { varIndex: 0 };
|
|
6875
|
+
#root = new Node$1();
|
|
6876
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
6877
|
+
const paramAssoc = [];
|
|
6878
|
+
const groups = [];
|
|
6879
|
+
for (let i = 0;;) {
|
|
6880
|
+
let replaced = false;
|
|
6881
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
6882
|
+
const mark = `@\\${i}`;
|
|
6883
|
+
groups[i] = [mark, m];
|
|
6884
|
+
i++;
|
|
6885
|
+
replaced = true;
|
|
6886
|
+
return mark;
|
|
6887
|
+
});
|
|
6888
|
+
if (!replaced) break;
|
|
6889
|
+
}
|
|
6890
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
6891
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
6892
|
+
const [mark] = groups[i];
|
|
6893
|
+
for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
|
|
6894
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
6895
|
+
break;
|
|
6896
|
+
}
|
|
6897
|
+
}
|
|
6898
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
6899
|
+
return paramAssoc;
|
|
6900
|
+
}
|
|
6901
|
+
buildRegExp() {
|
|
6902
|
+
let regexp = this.#root.buildRegExpStr();
|
|
6903
|
+
if (regexp === "") return [
|
|
6904
|
+
/^$/,
|
|
6905
|
+
[],
|
|
6906
|
+
[]
|
|
6907
|
+
];
|
|
6908
|
+
let captureIndex = 0;
|
|
6909
|
+
const indexReplacementMap = [];
|
|
6910
|
+
const paramReplacementMap = [];
|
|
6911
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
6912
|
+
if (handlerIndex !== void 0) {
|
|
6913
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
6914
|
+
return "$()";
|
|
6915
|
+
}
|
|
6916
|
+
if (paramIndex !== void 0) {
|
|
6917
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
6918
|
+
return "";
|
|
6919
|
+
}
|
|
6920
|
+
return "";
|
|
6921
|
+
});
|
|
6922
|
+
return [
|
|
6923
|
+
new RegExp(`^${regexp}`),
|
|
6924
|
+
indexReplacementMap,
|
|
6925
|
+
paramReplacementMap
|
|
6926
|
+
];
|
|
6927
|
+
}
|
|
6928
|
+
};
|
|
6929
|
+
//#endregion
|
|
6930
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/reg-exp-router/router.js
|
|
6931
|
+
var nullMatcher = [
|
|
6932
|
+
/^$/,
|
|
6933
|
+
[],
|
|
6934
|
+
/* @__PURE__ */ Object.create(null)
|
|
6935
|
+
];
|
|
6936
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
6937
|
+
function buildWildcardRegExp(path) {
|
|
6938
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
6939
|
+
}
|
|
6940
|
+
function clearWildcardRegExpCache() {
|
|
6941
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
6942
|
+
}
|
|
6943
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
6944
|
+
const trie = new Trie();
|
|
6945
|
+
const handlerData = [];
|
|
6946
|
+
if (routes.length === 0) return nullMatcher;
|
|
6947
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
6948
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
6949
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
6950
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
6951
|
+
if (pathErrorCheckOnly) staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
6952
|
+
else j++;
|
|
6953
|
+
let paramAssoc;
|
|
6954
|
+
try {
|
|
6955
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
6956
|
+
} catch (e) {
|
|
6957
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
6958
|
+
}
|
|
6959
|
+
if (pathErrorCheckOnly) continue;
|
|
6960
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
6961
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
6962
|
+
paramCount -= 1;
|
|
6963
|
+
for (; paramCount >= 0; paramCount--) {
|
|
6964
|
+
const [key, value] = paramAssoc[paramCount];
|
|
6965
|
+
paramIndexMap[key] = value;
|
|
6966
|
+
}
|
|
6967
|
+
return [h, paramIndexMap];
|
|
6968
|
+
});
|
|
6969
|
+
}
|
|
6970
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
6971
|
+
for (let i = 0, len = handlerData.length; i < len; i++) for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
6972
|
+
const map = handlerData[i][j]?.[1];
|
|
6973
|
+
if (!map) continue;
|
|
6974
|
+
const keys = Object.keys(map);
|
|
6975
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
6976
|
+
}
|
|
6977
|
+
const handlerMap = [];
|
|
6978
|
+
for (const i in indexReplacementMap) handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
6979
|
+
return [
|
|
6980
|
+
regexp,
|
|
6981
|
+
handlerMap,
|
|
6982
|
+
staticMap
|
|
6983
|
+
];
|
|
6984
|
+
}
|
|
6985
|
+
function findMiddleware(middleware, path) {
|
|
6986
|
+
if (!middleware) return;
|
|
6987
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
|
|
6988
|
+
}
|
|
6989
|
+
var RegExpRouter = class {
|
|
6990
|
+
name = "RegExpRouter";
|
|
6991
|
+
#middleware;
|
|
6992
|
+
#routes;
|
|
6993
|
+
constructor() {
|
|
6994
|
+
this.#middleware = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
|
|
6995
|
+
this.#routes = { ["ALL"]: /* @__PURE__ */ Object.create(null) };
|
|
6996
|
+
}
|
|
6997
|
+
add(method, path, handler) {
|
|
6998
|
+
const middleware = this.#middleware;
|
|
6999
|
+
const routes = this.#routes;
|
|
7000
|
+
if (!middleware || !routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
7001
|
+
if (!middleware[method]) [middleware, routes].forEach((handlerMap) => {
|
|
7002
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
7003
|
+
Object.keys(handlerMap["ALL"]).forEach((p) => {
|
|
7004
|
+
handlerMap[method][p] = [...handlerMap["ALL"][p]];
|
|
7005
|
+
});
|
|
7006
|
+
});
|
|
7007
|
+
if (path === "/*") path = "*";
|
|
7008
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
7009
|
+
if (/\*$/.test(path)) {
|
|
7010
|
+
const re = buildWildcardRegExp(path);
|
|
7011
|
+
if (method === "ALL") Object.keys(middleware).forEach((m) => {
|
|
7012
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
|
|
7013
|
+
});
|
|
7014
|
+
else middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware["ALL"], path) || [];
|
|
7015
|
+
Object.keys(middleware).forEach((m) => {
|
|
7016
|
+
if (method === "ALL" || method === m) Object.keys(middleware[m]).forEach((p) => {
|
|
7017
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
7018
|
+
});
|
|
7019
|
+
});
|
|
7020
|
+
Object.keys(routes).forEach((m) => {
|
|
7021
|
+
if (method === "ALL" || method === m) Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
7022
|
+
});
|
|
7023
|
+
return;
|
|
7024
|
+
}
|
|
7025
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
7026
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
7027
|
+
const path2 = paths[i];
|
|
7028
|
+
Object.keys(routes).forEach((m) => {
|
|
7029
|
+
if (method === "ALL" || method === m) {
|
|
7030
|
+
routes[m][path2] ||= [...findMiddleware(middleware[m], path2) || findMiddleware(middleware["ALL"], path2) || []];
|
|
7031
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
7032
|
+
}
|
|
7033
|
+
});
|
|
7034
|
+
}
|
|
7035
|
+
}
|
|
7036
|
+
match = match;
|
|
7037
|
+
buildAllMatchers() {
|
|
7038
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
7039
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
7040
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
7041
|
+
});
|
|
7042
|
+
this.#middleware = this.#routes = void 0;
|
|
7043
|
+
clearWildcardRegExpCache();
|
|
7044
|
+
return matchers;
|
|
7045
|
+
}
|
|
7046
|
+
#buildMatcher(method) {
|
|
7047
|
+
const routes = [];
|
|
7048
|
+
let hasOwnRoute = method === "ALL";
|
|
7049
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
7050
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
7051
|
+
if (ownRoute.length !== 0) {
|
|
7052
|
+
hasOwnRoute ||= true;
|
|
7053
|
+
routes.push(...ownRoute);
|
|
7054
|
+
} else if (method !== "ALL") routes.push(...Object.keys(r["ALL"]).map((path) => [path, r["ALL"][path]]));
|
|
7055
|
+
});
|
|
7056
|
+
if (!hasOwnRoute) return null;
|
|
7057
|
+
else return buildMatcherFromPreprocessedRoutes(routes);
|
|
7058
|
+
}
|
|
7059
|
+
};
|
|
7060
|
+
//#endregion
|
|
7061
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/smart-router/router.js
|
|
7062
|
+
var SmartRouter = class {
|
|
7063
|
+
name = "SmartRouter";
|
|
7064
|
+
#routers = [];
|
|
7065
|
+
#routes = [];
|
|
7066
|
+
constructor(init) {
|
|
7067
|
+
this.#routers = init.routers;
|
|
7068
|
+
}
|
|
7069
|
+
add(method, path, handler) {
|
|
7070
|
+
if (!this.#routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
7071
|
+
this.#routes.push([
|
|
7072
|
+
method,
|
|
7073
|
+
path,
|
|
7074
|
+
handler
|
|
7075
|
+
]);
|
|
7076
|
+
}
|
|
7077
|
+
match(method, path) {
|
|
7078
|
+
if (!this.#routes) throw new Error("Fatal error");
|
|
7079
|
+
const routers = this.#routers;
|
|
7080
|
+
const routes = this.#routes;
|
|
7081
|
+
const len = routers.length;
|
|
7082
|
+
let i = 0;
|
|
7083
|
+
let res;
|
|
7084
|
+
for (; i < len; i++) {
|
|
7085
|
+
const router = routers[i];
|
|
7086
|
+
try {
|
|
7087
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) router.add(...routes[i2]);
|
|
7088
|
+
res = router.match(method, path);
|
|
7089
|
+
} catch (e) {
|
|
7090
|
+
if (e instanceof UnsupportedPathError) continue;
|
|
7091
|
+
throw e;
|
|
7092
|
+
}
|
|
7093
|
+
this.match = router.match.bind(router);
|
|
7094
|
+
this.#routers = [router];
|
|
7095
|
+
this.#routes = void 0;
|
|
7096
|
+
break;
|
|
7097
|
+
}
|
|
7098
|
+
if (i === len) throw new Error("Fatal error");
|
|
7099
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
7100
|
+
return res;
|
|
7101
|
+
}
|
|
7102
|
+
get activeRouter() {
|
|
7103
|
+
if (this.#routes || this.#routers.length !== 1) throw new Error("No active router has been determined yet.");
|
|
7104
|
+
return this.#routers[0];
|
|
7105
|
+
}
|
|
7106
|
+
};
|
|
7107
|
+
//#endregion
|
|
7108
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/trie-router/node.js
|
|
7109
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
7110
|
+
var hasChildren = (children) => {
|
|
7111
|
+
for (const _ in children) return true;
|
|
7112
|
+
return false;
|
|
7113
|
+
};
|
|
7114
|
+
var Node = class _Node {
|
|
7115
|
+
#methods;
|
|
7116
|
+
#children;
|
|
7117
|
+
#patterns;
|
|
7118
|
+
#order = 0;
|
|
7119
|
+
#params = emptyParams;
|
|
7120
|
+
constructor(method, handler, children) {
|
|
7121
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
7122
|
+
this.#methods = [];
|
|
7123
|
+
if (method && handler) {
|
|
7124
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
7125
|
+
m[method] = {
|
|
7126
|
+
handler,
|
|
7127
|
+
possibleKeys: [],
|
|
7128
|
+
score: 0
|
|
7129
|
+
};
|
|
7130
|
+
this.#methods = [m];
|
|
7131
|
+
}
|
|
7132
|
+
this.#patterns = [];
|
|
7133
|
+
}
|
|
7134
|
+
insert(method, path, handler) {
|
|
7135
|
+
this.#order = ++this.#order;
|
|
7136
|
+
let curNode = this;
|
|
7137
|
+
const parts = splitRoutingPath(path);
|
|
7138
|
+
const possibleKeys = [];
|
|
7139
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
7140
|
+
const p = parts[i];
|
|
7141
|
+
const nextP = parts[i + 1];
|
|
7142
|
+
const pattern = getPattern(p, nextP);
|
|
7143
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
7144
|
+
if (key in curNode.#children) {
|
|
7145
|
+
curNode = curNode.#children[key];
|
|
7146
|
+
if (pattern) possibleKeys.push(pattern[1]);
|
|
7147
|
+
continue;
|
|
7148
|
+
}
|
|
7149
|
+
curNode.#children[key] = new _Node();
|
|
7150
|
+
if (pattern) {
|
|
7151
|
+
curNode.#patterns.push(pattern);
|
|
7152
|
+
possibleKeys.push(pattern[1]);
|
|
7153
|
+
}
|
|
7154
|
+
curNode = curNode.#children[key];
|
|
7155
|
+
}
|
|
7156
|
+
curNode.#methods.push({ [method]: {
|
|
7157
|
+
handler,
|
|
7158
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
7159
|
+
score: this.#order
|
|
7160
|
+
} });
|
|
7161
|
+
return curNode;
|
|
7162
|
+
}
|
|
7163
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
7164
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
7165
|
+
const m = node.#methods[i];
|
|
7166
|
+
const handlerSet = m[method] || m["ALL"];
|
|
7167
|
+
const processedSet = {};
|
|
7168
|
+
if (handlerSet !== void 0) {
|
|
7169
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
7170
|
+
handlerSets.push(handlerSet);
|
|
7171
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
7172
|
+
const key = handlerSet.possibleKeys[i2];
|
|
7173
|
+
const processed = processedSet[handlerSet.score];
|
|
7174
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
7175
|
+
processedSet[handlerSet.score] = true;
|
|
7176
|
+
}
|
|
7177
|
+
}
|
|
7178
|
+
}
|
|
7179
|
+
}
|
|
7180
|
+
search(method, path) {
|
|
7181
|
+
const handlerSets = [];
|
|
7182
|
+
this.#params = emptyParams;
|
|
7183
|
+
let curNodes = [this];
|
|
7184
|
+
const parts = splitPath(path);
|
|
7185
|
+
const curNodesQueue = [];
|
|
7186
|
+
const len = parts.length;
|
|
7187
|
+
let partOffsets = null;
|
|
7188
|
+
for (let i = 0; i < len; i++) {
|
|
7189
|
+
const part = parts[i];
|
|
7190
|
+
const isLast = i === len - 1;
|
|
7191
|
+
const tempNodes = [];
|
|
7192
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
7193
|
+
const node = curNodes[j];
|
|
7194
|
+
const nextNode = node.#children[part];
|
|
7195
|
+
if (nextNode) {
|
|
7196
|
+
nextNode.#params = node.#params;
|
|
7197
|
+
if (isLast) {
|
|
7198
|
+
if (nextNode.#children["*"]) this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
7199
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
7200
|
+
} else tempNodes.push(nextNode);
|
|
7201
|
+
}
|
|
7202
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
7203
|
+
const pattern = node.#patterns[k];
|
|
7204
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
7205
|
+
if (pattern === "*") {
|
|
7206
|
+
const astNode = node.#children["*"];
|
|
7207
|
+
if (astNode) {
|
|
7208
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
7209
|
+
astNode.#params = params;
|
|
7210
|
+
tempNodes.push(astNode);
|
|
7211
|
+
}
|
|
7212
|
+
continue;
|
|
7213
|
+
}
|
|
7214
|
+
const [key, name, matcher] = pattern;
|
|
7215
|
+
if (!part && !(matcher instanceof RegExp)) continue;
|
|
7216
|
+
const child = node.#children[key];
|
|
7217
|
+
if (matcher instanceof RegExp) {
|
|
7218
|
+
if (partOffsets === null) {
|
|
7219
|
+
partOffsets = new Array(len);
|
|
7220
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
7221
|
+
for (let p = 0; p < len; p++) {
|
|
7222
|
+
partOffsets[p] = offset;
|
|
7223
|
+
offset += parts[p].length + 1;
|
|
7224
|
+
}
|
|
7225
|
+
}
|
|
7226
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
7227
|
+
const m = matcher.exec(restPathString);
|
|
7228
|
+
if (m) {
|
|
7229
|
+
params[name] = m[0];
|
|
7230
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
7231
|
+
if (hasChildren(child.#children)) {
|
|
7232
|
+
child.#params = params;
|
|
7233
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
7234
|
+
(curNodesQueue[componentCount] ||= []).push(child);
|
|
7235
|
+
}
|
|
7236
|
+
continue;
|
|
7237
|
+
}
|
|
7238
|
+
}
|
|
7239
|
+
if (matcher === true || matcher.test(part)) {
|
|
7240
|
+
params[name] = part;
|
|
7241
|
+
if (isLast) {
|
|
7242
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
7243
|
+
if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
|
|
7244
|
+
} else {
|
|
7245
|
+
child.#params = params;
|
|
7246
|
+
tempNodes.push(child);
|
|
7247
|
+
}
|
|
7248
|
+
}
|
|
7249
|
+
}
|
|
7250
|
+
}
|
|
7251
|
+
const shifted = curNodesQueue.shift();
|
|
7252
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
7253
|
+
}
|
|
7254
|
+
if (handlerSets.length > 1) handlerSets.sort((a, b) => {
|
|
7255
|
+
return a.score - b.score;
|
|
7256
|
+
});
|
|
7257
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
7258
|
+
}
|
|
7259
|
+
};
|
|
7260
|
+
//#endregion
|
|
7261
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/router/trie-router/router.js
|
|
7262
|
+
var TrieRouter = class {
|
|
7263
|
+
name = "TrieRouter";
|
|
7264
|
+
#node;
|
|
7265
|
+
constructor() {
|
|
7266
|
+
this.#node = new Node();
|
|
7267
|
+
}
|
|
7268
|
+
add(method, path, handler) {
|
|
7269
|
+
const results = checkOptionalParameter(path);
|
|
7270
|
+
if (results) {
|
|
7271
|
+
for (let i = 0, len = results.length; i < len; i++) this.#node.insert(method, results[i], handler);
|
|
7272
|
+
return;
|
|
7273
|
+
}
|
|
7274
|
+
this.#node.insert(method, path, handler);
|
|
7275
|
+
}
|
|
7276
|
+
match(method, path) {
|
|
7277
|
+
return this.#node.search(method, path);
|
|
7278
|
+
}
|
|
7279
|
+
};
|
|
7280
|
+
//#endregion
|
|
7281
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/hono.js
|
|
7282
|
+
var Hono = class extends Hono$1 {
|
|
7283
|
+
/**
|
|
7284
|
+
* Creates an instance of the Hono class.
|
|
7285
|
+
*
|
|
7286
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
7287
|
+
*/
|
|
7288
|
+
constructor(options = {}) {
|
|
7289
|
+
super(options);
|
|
7290
|
+
this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
|
|
7291
|
+
}
|
|
7292
|
+
};
|
|
7293
|
+
object({
|
|
7294
|
+
client_id: string(),
|
|
7295
|
+
redirect_uri: string().optional().refine((value) => value === void 0 || URL.canParse(value), { message: "redirect_uri must be a valid URL" })
|
|
7296
|
+
});
|
|
7297
|
+
object({
|
|
7298
|
+
response_type: literal("code"),
|
|
7299
|
+
code_challenge: string(),
|
|
7300
|
+
code_challenge_method: literal("S256"),
|
|
7301
|
+
scope: string().optional(),
|
|
7302
|
+
state: string().optional(),
|
|
7303
|
+
resource: url().optional()
|
|
7304
|
+
});
|
|
7305
|
+
object({ grant_type: string() });
|
|
7306
|
+
object({
|
|
7307
|
+
code: string(),
|
|
7308
|
+
code_verifier: string(),
|
|
7309
|
+
redirect_uri: string().optional(),
|
|
7310
|
+
resource: url().optional()
|
|
7311
|
+
});
|
|
7312
|
+
object({
|
|
7313
|
+
refresh_token: string(),
|
|
7314
|
+
scope: string().optional(),
|
|
7315
|
+
resource: url().optional()
|
|
7316
|
+
});
|
|
7317
|
+
object({
|
|
7318
|
+
client_id: string(),
|
|
7319
|
+
client_secret: string().optional()
|
|
7320
|
+
});
|
|
7321
|
+
//#endregion
|
|
7322
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/stream.js
|
|
7323
|
+
var StreamingApi = class {
|
|
7324
|
+
writer;
|
|
7325
|
+
encoder;
|
|
7326
|
+
writable;
|
|
7327
|
+
abortSubscribers = [];
|
|
7328
|
+
responseReadable;
|
|
7329
|
+
/**
|
|
7330
|
+
* Whether the stream has been aborted.
|
|
7331
|
+
*/
|
|
7332
|
+
aborted = false;
|
|
7333
|
+
/**
|
|
7334
|
+
* Whether the stream has been closed normally.
|
|
7335
|
+
*/
|
|
7336
|
+
closed = false;
|
|
7337
|
+
constructor(writable, _readable) {
|
|
7338
|
+
this.writable = writable;
|
|
7339
|
+
this.writer = writable.getWriter();
|
|
7340
|
+
this.encoder = new TextEncoder();
|
|
7341
|
+
const reader = _readable.getReader();
|
|
7342
|
+
this.abortSubscribers.push(async () => {
|
|
7343
|
+
await reader.cancel();
|
|
7344
|
+
});
|
|
7345
|
+
this.responseReadable = new ReadableStream({
|
|
7346
|
+
async pull(controller) {
|
|
7347
|
+
const { done, value } = await reader.read();
|
|
7348
|
+
done ? controller.close() : controller.enqueue(value);
|
|
7349
|
+
},
|
|
7350
|
+
cancel: () => {
|
|
7351
|
+
if (!this.closed) this.abort();
|
|
7352
|
+
}
|
|
7353
|
+
});
|
|
7354
|
+
}
|
|
7355
|
+
async write(input) {
|
|
7356
|
+
try {
|
|
7357
|
+
if (typeof input === "string") input = this.encoder.encode(input);
|
|
7358
|
+
await this.writer.write(input);
|
|
7359
|
+
} catch {}
|
|
7360
|
+
return this;
|
|
7361
|
+
}
|
|
7362
|
+
async writeln(input) {
|
|
7363
|
+
await this.write(input + "\n");
|
|
7364
|
+
return this;
|
|
7365
|
+
}
|
|
7366
|
+
sleep(ms) {
|
|
7367
|
+
return new Promise((res) => setTimeout(res, ms));
|
|
7368
|
+
}
|
|
7369
|
+
async close() {
|
|
7370
|
+
this.closed = true;
|
|
7371
|
+
try {
|
|
7372
|
+
await this.writer.close();
|
|
7373
|
+
} catch {}
|
|
7374
|
+
}
|
|
7375
|
+
async pipe(body) {
|
|
7376
|
+
this.writer.releaseLock();
|
|
7377
|
+
await body.pipeTo(this.writable, { preventClose: true });
|
|
7378
|
+
this.writer = this.writable.getWriter();
|
|
7379
|
+
}
|
|
7380
|
+
onAbort(listener) {
|
|
7381
|
+
this.abortSubscribers.push(listener);
|
|
7382
|
+
}
|
|
7383
|
+
/**
|
|
7384
|
+
* Abort the stream.
|
|
7385
|
+
* You can call this method when stream is aborted by external event.
|
|
7386
|
+
*/
|
|
7387
|
+
abort() {
|
|
7388
|
+
if (!this.aborted) {
|
|
7389
|
+
this.aborted = true;
|
|
7390
|
+
this.abortSubscribers.forEach((subscriber) => subscriber());
|
|
7391
|
+
}
|
|
7392
|
+
}
|
|
7393
|
+
};
|
|
7394
|
+
//#endregion
|
|
7395
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/helper/streaming/sse.js
|
|
7396
|
+
var SSEStreamingApi = class extends StreamingApi {
|
|
7397
|
+
constructor(writable, readable) {
|
|
7398
|
+
super(writable, readable);
|
|
7399
|
+
}
|
|
7400
|
+
async writeSSE(message) {
|
|
7401
|
+
const dataLines = (await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {})).split(/\r\n|\r|\n/).map((line) => {
|
|
7402
|
+
return `data: ${line}`;
|
|
7403
|
+
}).join("\n");
|
|
7404
|
+
for (const key of [
|
|
7405
|
+
"event",
|
|
7406
|
+
"id",
|
|
7407
|
+
"retry"
|
|
7408
|
+
]) if (message[key] && /[\r\n]/.test(message[key])) throw new Error(`${key} must not contain "\\r" or "\\n"`);
|
|
7409
|
+
const sseData = [
|
|
7410
|
+
message.event && `event: ${message.event}`,
|
|
7411
|
+
dataLines,
|
|
7412
|
+
message.id && `id: ${message.id}`,
|
|
7413
|
+
message.retry && `retry: ${message.retry}`
|
|
7414
|
+
].filter(Boolean).join("\n") + "\n\n";
|
|
7415
|
+
await this.write(sseData);
|
|
7416
|
+
}
|
|
7417
|
+
};
|
|
7418
|
+
//#endregion
|
|
7419
|
+
//#region ../../node_modules/.pnpm/@hono+mcp@0.3.0_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__hono-rate-limiter@0.5.3_hono@4.12.19__hono@4.12.19_zod@4.4.3/node_modules/@hono/mcp/dist/index.js
|
|
7420
|
+
let isOldBunVersion = () => {
|
|
7421
|
+
const version = typeof Bun !== "undefined" ? Bun.version : void 0;
|
|
7422
|
+
if (version === void 0) return false;
|
|
7423
|
+
const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0.");
|
|
7424
|
+
isOldBunVersion = () => result;
|
|
7425
|
+
return result;
|
|
7426
|
+
};
|
|
7427
|
+
const run = async (stream, cb, onError) => {
|
|
7428
|
+
try {
|
|
7429
|
+
await cb(stream);
|
|
7430
|
+
} catch (e) {
|
|
7431
|
+
if (e instanceof Error && onError) {
|
|
7432
|
+
await onError(e, stream);
|
|
7433
|
+
await stream.writeSSE({
|
|
7434
|
+
event: "error",
|
|
7435
|
+
data: e.message
|
|
7436
|
+
});
|
|
7437
|
+
} else console.error(e);
|
|
7438
|
+
}
|
|
7439
|
+
};
|
|
7440
|
+
const contextStash = /* @__PURE__ */ new WeakMap();
|
|
7441
|
+
const streamSSE = (c, cb, onError) => {
|
|
7442
|
+
const { readable, writable } = new TransformStream();
|
|
7443
|
+
const stream = new SSEStreamingApi(writable, readable);
|
|
7444
|
+
if (isOldBunVersion()) c.req.raw.signal.addEventListener("abort", () => {
|
|
7445
|
+
if (!stream.closed) stream.abort();
|
|
7446
|
+
});
|
|
7447
|
+
contextStash.set(stream.responseReadable, c);
|
|
7448
|
+
c.header("Transfer-Encoding", "chunked");
|
|
7449
|
+
c.header("Content-Type", "text/event-stream");
|
|
7450
|
+
c.header("Cache-Control", "no-cache");
|
|
7451
|
+
c.header("Connection", "keep-alive");
|
|
7452
|
+
run(stream, cb, onError);
|
|
7453
|
+
return c.newResponse(stream.responseReadable);
|
|
7454
|
+
};
|
|
7455
|
+
var StreamableHTTPTransport = class {
|
|
7456
|
+
#started = false;
|
|
7457
|
+
#initialized = false;
|
|
7458
|
+
#onSessionInitialized;
|
|
7459
|
+
#onSessionClosed;
|
|
7460
|
+
#sessionIdGenerator;
|
|
7461
|
+
#eventStore;
|
|
7462
|
+
#enableJsonResponse = false;
|
|
7463
|
+
#standaloneSseStreamId = "_GET_stream";
|
|
7464
|
+
#streamMapping = /* @__PURE__ */ new Map();
|
|
7465
|
+
#requestToStreamMapping = /* @__PURE__ */ new Map();
|
|
7466
|
+
#requestResponseMap = /* @__PURE__ */ new Map();
|
|
7467
|
+
#allowedHosts;
|
|
7468
|
+
#allowedOrigins;
|
|
7469
|
+
#enableDnsRebindingProtection;
|
|
7470
|
+
#strictAcceptHeader;
|
|
7471
|
+
sessionId;
|
|
7472
|
+
onclose;
|
|
7473
|
+
onerror;
|
|
7474
|
+
onmessage;
|
|
7475
|
+
constructor(options) {
|
|
7476
|
+
this.#sessionIdGenerator = options?.sessionIdGenerator;
|
|
7477
|
+
this.#enableJsonResponse = options?.enableJsonResponse ?? false;
|
|
7478
|
+
this.#eventStore = options?.eventStore;
|
|
7479
|
+
this.#onSessionInitialized = options?.onsessioninitialized;
|
|
7480
|
+
this.#onSessionClosed = options?.onsessionclosed;
|
|
7481
|
+
this.#allowedHosts = options?.allowedHosts;
|
|
7482
|
+
this.#allowedOrigins = options?.allowedOrigins;
|
|
7483
|
+
this.#enableDnsRebindingProtection = options?.enableDnsRebindingProtection ?? false;
|
|
7484
|
+
this.#strictAcceptHeader = options?.strictAcceptHeader ?? false;
|
|
7485
|
+
}
|
|
7486
|
+
/**
|
|
7487
|
+
* Starts the transport. This is required by the Transport interface but is a no-op
|
|
7488
|
+
* for the Streamable HTTP transport as connections are managed per-request.
|
|
7489
|
+
*/
|
|
7490
|
+
async start() {
|
|
7491
|
+
if (this.#started) throw new Error("Transport already started");
|
|
7492
|
+
this.#started = true;
|
|
7493
|
+
}
|
|
7494
|
+
/**
|
|
7495
|
+
* Validates request headers for DNS rebinding protection.
|
|
7496
|
+
* @returns Error message if validation fails, undefined if validation passes.
|
|
7497
|
+
*/
|
|
7498
|
+
#validateRequestHeaders(ctx) {
|
|
7499
|
+
if (!this.#enableDnsRebindingProtection) return;
|
|
7500
|
+
if (this.#allowedHosts && this.#allowedHosts.length > 0) {
|
|
7501
|
+
const hostHeader = ctx.req.header("Host");
|
|
7502
|
+
if (!hostHeader || !this.#allowedHosts.includes(hostHeader)) return `Invalid Host header: ${hostHeader}`;
|
|
7503
|
+
}
|
|
7504
|
+
if (this.#allowedOrigins && this.#allowedOrigins.length > 0) {
|
|
7505
|
+
const originHeader = ctx.req.header("Origin");
|
|
7506
|
+
if (!originHeader || !this.#allowedOrigins.includes(originHeader)) return `Invalid Origin header: ${originHeader}`;
|
|
7507
|
+
}
|
|
7508
|
+
}
|
|
7509
|
+
/**
|
|
7510
|
+
* Handles an incoming HTTP request, whether GET or POST
|
|
7511
|
+
*/
|
|
7512
|
+
async handleRequest(ctx, parsedBody) {
|
|
7513
|
+
const validationError = this.#validateRequestHeaders(ctx);
|
|
7514
|
+
if (validationError) throw new HTTPException(403, { res: Response.json({
|
|
7515
|
+
jsonrpc: "2.0",
|
|
7516
|
+
error: {
|
|
7517
|
+
code: -32e3,
|
|
7518
|
+
message: validationError
|
|
7519
|
+
},
|
|
7520
|
+
id: null
|
|
7521
|
+
}) });
|
|
7522
|
+
switch (ctx.req.method) {
|
|
7523
|
+
case "GET": return this.handleGetRequest(ctx);
|
|
7524
|
+
case "POST": return this.handlePostRequest(ctx, parsedBody);
|
|
7525
|
+
case "DELETE": return this.handleDeleteRequest(ctx);
|
|
7526
|
+
default: return this.handleUnsupportedRequest(ctx);
|
|
7527
|
+
}
|
|
7528
|
+
}
|
|
7529
|
+
/**
|
|
7530
|
+
* Handles GET requests for SSE stream
|
|
7531
|
+
*/
|
|
7532
|
+
async handleGetRequest(ctx) {
|
|
7533
|
+
try {
|
|
7534
|
+
const getAcceptHeader = ctx.req.header("Accept") ?? "*/*";
|
|
7535
|
+
if (!getAcceptHeader.includes("text/event-stream") && !getAcceptHeader.includes("*/*")) throw new HTTPException(406, { res: Response.json({
|
|
7536
|
+
jsonrpc: "2.0",
|
|
7537
|
+
error: {
|
|
7538
|
+
code: -32e3,
|
|
7539
|
+
message: "Not Acceptable: Client must accept text/event-stream"
|
|
7540
|
+
},
|
|
7541
|
+
id: null
|
|
7542
|
+
}) });
|
|
7543
|
+
this.#validateSession(ctx);
|
|
7544
|
+
this.#validateProtocolVersion(ctx);
|
|
7545
|
+
if (this.sessionId !== void 0) ctx.header("mcp-session-id", this.sessionId);
|
|
7546
|
+
let streamId = this.#standaloneSseStreamId;
|
|
7547
|
+
if (this.#eventStore) {
|
|
7548
|
+
const lastEventId = ctx.req.header("last-event-id");
|
|
7549
|
+
if (lastEventId) streamId = (stream) => this.#eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => {
|
|
7550
|
+
try {
|
|
7551
|
+
await stream.writeSSE({
|
|
7552
|
+
id: eventId,
|
|
7553
|
+
event: "message",
|
|
7554
|
+
data: JSON.stringify(message)
|
|
7555
|
+
});
|
|
7556
|
+
} catch {
|
|
7557
|
+
this.onerror?.(/* @__PURE__ */ new Error("Failed replay events"));
|
|
7558
|
+
throw new HTTPException(500, { message: "Failed replay events" });
|
|
7559
|
+
}
|
|
7560
|
+
} });
|
|
7561
|
+
}
|
|
7562
|
+
if (typeof streamId === "string" && this.#streamMapping.get(streamId) !== void 0) throw new HTTPException(409, { res: Response.json({
|
|
7563
|
+
jsonrpc: "2.0",
|
|
7564
|
+
error: {
|
|
7565
|
+
code: -32e3,
|
|
7566
|
+
message: "Conflict: Only one SSE stream is allowed per session"
|
|
7567
|
+
},
|
|
7568
|
+
id: null
|
|
7569
|
+
}) });
|
|
7570
|
+
return streamSSE(ctx, async (stream) => {
|
|
7571
|
+
const resolvedStreamId = typeof streamId === "string" ? streamId : await streamId(stream);
|
|
7572
|
+
const keepAlive = setInterval(() => {
|
|
7573
|
+
if (!stream.closed) stream.writeSSE({
|
|
7574
|
+
data: "",
|
|
7575
|
+
event: "ping"
|
|
7576
|
+
}).catch(() => {
|
|
7577
|
+
stream.abort();
|
|
7578
|
+
});
|
|
7579
|
+
}, 3e4);
|
|
7580
|
+
if (typeof keepAlive === "object" && "unref" in keepAlive) keepAlive.unref();
|
|
7581
|
+
this.#streamMapping.set(resolvedStreamId, {
|
|
7582
|
+
ctx: { header: ctx.header },
|
|
7583
|
+
stream,
|
|
7584
|
+
cleanup: () => {
|
|
7585
|
+
clearInterval(keepAlive);
|
|
7586
|
+
this.#streamMapping.delete(resolvedStreamId);
|
|
7587
|
+
}
|
|
7588
|
+
});
|
|
7589
|
+
stream.onAbort(() => {
|
|
7590
|
+
this.#streamMapping.get(resolvedStreamId)?.cleanup();
|
|
7591
|
+
});
|
|
7592
|
+
});
|
|
7593
|
+
} catch (error) {
|
|
7594
|
+
if (error instanceof HTTPException) throw error;
|
|
7595
|
+
this.onerror?.(error);
|
|
7596
|
+
throw new HTTPException(400, { res: Response.json({
|
|
7597
|
+
jsonrpc: "2.0",
|
|
7598
|
+
error: {
|
|
7599
|
+
code: ErrorCode.ParseError,
|
|
7600
|
+
message: "Parse error",
|
|
7601
|
+
data: String(error)
|
|
7602
|
+
},
|
|
7603
|
+
id: null
|
|
7604
|
+
}) });
|
|
7605
|
+
}
|
|
7606
|
+
}
|
|
7607
|
+
/**
|
|
7608
|
+
* Handles POST requests containing JSON-RPC messages
|
|
7609
|
+
*/
|
|
7610
|
+
async handlePostRequest(ctx, parsedBody) {
|
|
7611
|
+
try {
|
|
7612
|
+
const acceptHeader = ctx.req.header("Accept") ?? "*/*";
|
|
7613
|
+
if (!(this.#strictAcceptHeader ? acceptHeader.includes("application/json") && acceptHeader.includes("text/event-stream") : acceptHeader.includes("application/json") || acceptHeader.includes("text/event-stream") || acceptHeader.includes("*/*"))) throw new HTTPException(406, { res: Response.json({
|
|
7614
|
+
jsonrpc: "2.0",
|
|
7615
|
+
error: {
|
|
7616
|
+
code: ErrorCode.ConnectionClosed,
|
|
7617
|
+
message: this.#strictAcceptHeader ? "Not Acceptable: Client must accept both application/json and text/event-stream" : "Not Acceptable: Client must accept application/json or text/event-stream"
|
|
7618
|
+
},
|
|
7619
|
+
id: null
|
|
7620
|
+
}) });
|
|
7621
|
+
if (!ctx.req.header("Content-Type")?.includes("application/json")) throw new HTTPException(415, { res: Response.json({
|
|
7622
|
+
jsonrpc: "2.0",
|
|
7623
|
+
error: {
|
|
7624
|
+
code: ErrorCode.ConnectionClosed,
|
|
7625
|
+
message: "Unsupported Media Type: Content-Type must be application/json"
|
|
7626
|
+
},
|
|
7627
|
+
id: null
|
|
7628
|
+
}) });
|
|
7629
|
+
const authInfo = ctx.get("auth");
|
|
7630
|
+
const requestInfo = { headers: ctx.req.header() };
|
|
7631
|
+
let rawMessage = parsedBody;
|
|
7632
|
+
if (rawMessage === void 0) rawMessage = await ctx.req.json();
|
|
7633
|
+
let messages;
|
|
7634
|
+
if (Array.isArray(rawMessage)) messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg));
|
|
7635
|
+
else messages = [JSONRPCMessageSchema.parse(rawMessage)];
|
|
7636
|
+
const isInitializationRequest = messages.some(isInitializeRequest);
|
|
7637
|
+
if (isInitializationRequest) {
|
|
7638
|
+
if (this.#initialized && this.sessionId !== void 0) throw new HTTPException(400, { res: Response.json({
|
|
7639
|
+
jsonrpc: "2.0",
|
|
7640
|
+
error: {
|
|
7641
|
+
code: ErrorCode.InvalidRequest,
|
|
7642
|
+
message: "Invalid Request: Server already initialized"
|
|
7643
|
+
},
|
|
7644
|
+
id: null
|
|
7645
|
+
}) });
|
|
7646
|
+
if (messages.length > 1) throw new HTTPException(400, { res: Response.json({
|
|
7647
|
+
jsonrpc: "2.0",
|
|
7648
|
+
error: {
|
|
7649
|
+
code: ErrorCode.InvalidRequest,
|
|
7650
|
+
message: "Invalid Request: Only one initialization request is allowed"
|
|
7651
|
+
},
|
|
7652
|
+
id: null
|
|
7653
|
+
}) });
|
|
7654
|
+
this.sessionId = this.#sessionIdGenerator?.();
|
|
7655
|
+
this.#initialized = true;
|
|
7656
|
+
if (this.sessionId && this.#onSessionInitialized) await this.#onSessionInitialized(this.sessionId);
|
|
7657
|
+
}
|
|
7658
|
+
if (!isInitializationRequest) {
|
|
7659
|
+
this.#validateSession(ctx);
|
|
7660
|
+
this.#validateProtocolVersion(ctx);
|
|
7661
|
+
}
|
|
7662
|
+
const hasRequests = messages.some(isJSONRPCRequest);
|
|
7663
|
+
if (!hasRequests) {
|
|
7664
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7665
|
+
authInfo,
|
|
7666
|
+
requestInfo
|
|
7667
|
+
});
|
|
7668
|
+
return ctx.json(null, { status: 202 });
|
|
7669
|
+
}
|
|
7670
|
+
if (hasRequests) {
|
|
7671
|
+
const streamId = crypto.randomUUID();
|
|
7672
|
+
if (!this.#enableJsonResponse && this.sessionId !== void 0) ctx.header("mcp-session-id", this.sessionId);
|
|
7673
|
+
if (this.#enableJsonResponse) return await new Promise((resolve) => {
|
|
7674
|
+
for (const message of messages) if (isJSONRPCRequest(message)) {
|
|
7675
|
+
this.#streamMapping.set(streamId, {
|
|
7676
|
+
ctx: {
|
|
7677
|
+
header: ctx.header,
|
|
7678
|
+
json: (data) => {
|
|
7679
|
+
resolve(ctx.json(data));
|
|
7680
|
+
}
|
|
7681
|
+
},
|
|
7682
|
+
cleanup: () => {
|
|
7683
|
+
this.#streamMapping.delete(streamId);
|
|
7684
|
+
}
|
|
7685
|
+
});
|
|
7686
|
+
this.#requestToStreamMapping.set(message.id, streamId);
|
|
7687
|
+
}
|
|
7688
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7689
|
+
authInfo,
|
|
7690
|
+
requestInfo
|
|
7691
|
+
});
|
|
7692
|
+
});
|
|
7693
|
+
return streamSSE(ctx, async (stream) => {
|
|
7694
|
+
for (const message of messages) if (isJSONRPCRequest(message)) {
|
|
7695
|
+
this.#streamMapping.set(streamId, {
|
|
7696
|
+
ctx: { header: ctx.header },
|
|
7697
|
+
stream,
|
|
7698
|
+
cleanup: () => {
|
|
7699
|
+
this.#streamMapping.delete(streamId);
|
|
7700
|
+
}
|
|
7701
|
+
});
|
|
7702
|
+
this.#requestToStreamMapping.set(message.id, streamId);
|
|
7703
|
+
}
|
|
7704
|
+
for (const message of messages) this.onmessage?.(message, {
|
|
7705
|
+
authInfo,
|
|
7706
|
+
requestInfo
|
|
7707
|
+
});
|
|
7708
|
+
stream.onAbort(() => {
|
|
7709
|
+
this.#streamMapping.get(streamId)?.cleanup();
|
|
7710
|
+
});
|
|
7711
|
+
});
|
|
7712
|
+
}
|
|
7713
|
+
} catch (error) {
|
|
7714
|
+
if (error instanceof HTTPException) throw error;
|
|
7715
|
+
this.onerror?.(error);
|
|
7716
|
+
throw new HTTPException(400, { res: Response.json({
|
|
7717
|
+
jsonrpc: "2.0",
|
|
7718
|
+
error: {
|
|
7719
|
+
code: ErrorCode.ParseError,
|
|
7720
|
+
message: "Parse error",
|
|
7721
|
+
data: String(error)
|
|
7722
|
+
},
|
|
7723
|
+
id: null
|
|
7724
|
+
}) });
|
|
7725
|
+
}
|
|
7726
|
+
}
|
|
7727
|
+
/**
|
|
7728
|
+
* Handles DELETE requests to terminate sessions
|
|
7729
|
+
*/
|
|
7730
|
+
async handleDeleteRequest(ctx) {
|
|
7731
|
+
this.#validateSession(ctx);
|
|
7732
|
+
this.#validateProtocolVersion(ctx);
|
|
7733
|
+
if (this.#onSessionClosed && this.sessionId) await Promise.resolve(this.#onSessionClosed(this.sessionId));
|
|
7734
|
+
await this.close();
|
|
7735
|
+
return ctx.body(null, 200);
|
|
7736
|
+
}
|
|
7737
|
+
/**
|
|
7738
|
+
* Handles unsupported requests (PUT, PATCH, etc.)
|
|
7739
|
+
*/
|
|
7740
|
+
handleUnsupportedRequest(ctx) {
|
|
7741
|
+
return ctx.json({
|
|
7742
|
+
jsonrpc: "2.0",
|
|
7743
|
+
error: {
|
|
7744
|
+
code: ErrorCode.ConnectionClosed,
|
|
7745
|
+
message: "Method not allowed."
|
|
7746
|
+
},
|
|
7747
|
+
id: null
|
|
7748
|
+
}, {
|
|
7749
|
+
status: 405,
|
|
7750
|
+
headers: { Allow: "GET, POST, DELETE" }
|
|
7751
|
+
});
|
|
7752
|
+
}
|
|
7753
|
+
/**
|
|
7754
|
+
* Validates session ID for non-initialization requests
|
|
7755
|
+
* Returns true if the session is valid, false otherwise
|
|
7756
|
+
*/
|
|
7757
|
+
#validateSession(ctx) {
|
|
7758
|
+
if (this.#sessionIdGenerator === void 0) return true;
|
|
7759
|
+
if (!this.#initialized) throw new HTTPException(400, { res: Response.json({
|
|
7760
|
+
jsonrpc: "2.0",
|
|
7761
|
+
error: {
|
|
7762
|
+
code: ErrorCode.ConnectionClosed,
|
|
7763
|
+
message: "Bad Request: Server not initialized"
|
|
7764
|
+
},
|
|
7765
|
+
id: null
|
|
7766
|
+
}) });
|
|
7767
|
+
const sessionId = ctx.req.header("mcp-session-id");
|
|
7768
|
+
if (!sessionId) throw new HTTPException(400, { res: Response.json({
|
|
7769
|
+
jsonrpc: "2.0",
|
|
7770
|
+
error: {
|
|
7771
|
+
code: ErrorCode.ConnectionClosed,
|
|
7772
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
7773
|
+
},
|
|
7774
|
+
id: null
|
|
7775
|
+
}) });
|
|
7776
|
+
if (Array.isArray(sessionId)) throw new HTTPException(400, { res: Response.json({
|
|
7777
|
+
jsonrpc: "2.0",
|
|
7778
|
+
error: {
|
|
7779
|
+
code: ErrorCode.ConnectionClosed,
|
|
7780
|
+
message: "Bad Request: Mcp-Session-Id header must be a single value"
|
|
7781
|
+
},
|
|
7782
|
+
id: null
|
|
7783
|
+
}) });
|
|
7784
|
+
if (sessionId !== this.sessionId) throw new HTTPException(404, { res: Response.json({
|
|
7785
|
+
jsonrpc: "2.0",
|
|
7786
|
+
error: {
|
|
7787
|
+
code: ErrorCode.RequestTimeout,
|
|
7788
|
+
message: "Session not found"
|
|
7789
|
+
},
|
|
7790
|
+
id: null
|
|
7791
|
+
}) });
|
|
7792
|
+
return true;
|
|
7793
|
+
}
|
|
7794
|
+
#validateProtocolVersion(ctx) {
|
|
7795
|
+
let protocolVersion = ctx.req.header("mcp-protocol-version") ?? "2025-03-26";
|
|
7796
|
+
if (Array.isArray(protocolVersion)) protocolVersion = protocolVersion[protocolVersion.length - 1];
|
|
7797
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) throw new HTTPException(404, { res: Response.json({
|
|
7798
|
+
jsonrpc: "2.0",
|
|
7799
|
+
error: {
|
|
7800
|
+
code: ErrorCode.ConnectionClosed,
|
|
7801
|
+
message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`
|
|
7802
|
+
},
|
|
7803
|
+
id: null
|
|
7804
|
+
}) });
|
|
7805
|
+
return true;
|
|
7806
|
+
}
|
|
7807
|
+
async close() {
|
|
7808
|
+
for (const { stream } of this.#streamMapping.values()) stream?.abort();
|
|
7809
|
+
this.#streamMapping.clear();
|
|
7810
|
+
this.#requestResponseMap.clear();
|
|
7811
|
+
this.onclose?.();
|
|
7812
|
+
}
|
|
7813
|
+
async send(message, options) {
|
|
7814
|
+
let requestId = options?.relatedRequestId;
|
|
7815
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id;
|
|
7816
|
+
if (requestId === void 0) {
|
|
7817
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");
|
|
7818
|
+
const standaloneSse = this.#streamMapping.get(this.#standaloneSseStreamId);
|
|
7819
|
+
if (standaloneSse === void 0) return;
|
|
7820
|
+
let eventId;
|
|
7821
|
+
if (this.#eventStore) eventId = await this.#eventStore.storeEvent(this.#standaloneSseStreamId, message);
|
|
7822
|
+
return standaloneSse.stream?.writeSSE({
|
|
7823
|
+
id: eventId,
|
|
7824
|
+
event: "message",
|
|
7825
|
+
data: JSON.stringify(message)
|
|
7826
|
+
});
|
|
7827
|
+
}
|
|
7828
|
+
const streamId = this.#requestToStreamMapping.get(requestId);
|
|
7829
|
+
const response = this.#streamMapping.get(streamId);
|
|
7830
|
+
if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
7831
|
+
if (!this.#enableJsonResponse) {
|
|
7832
|
+
let eventId;
|
|
7833
|
+
if (this.#eventStore) eventId = await this.#eventStore.storeEvent(streamId, message);
|
|
7834
|
+
if (response) await response.stream?.writeSSE({
|
|
7835
|
+
id: eventId,
|
|
7836
|
+
event: "message",
|
|
7837
|
+
data: JSON.stringify(message)
|
|
7838
|
+
});
|
|
7839
|
+
}
|
|
7840
|
+
if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
|
|
7841
|
+
this.#requestResponseMap.set(requestId, message);
|
|
7842
|
+
const relatedIds = Array.from(this.#requestToStreamMapping.entries()).filter(([, streamId$1]) => this.#streamMapping.get(streamId$1) === response).map(([id]) => id);
|
|
7843
|
+
if (relatedIds.every((id) => this.#requestResponseMap.has(id))) {
|
|
7844
|
+
if (!response) throw new Error(`No connection established for request ID: ${String(requestId)}`);
|
|
7845
|
+
if (this.#enableJsonResponse) {
|
|
7846
|
+
if (this.sessionId !== void 0) response.ctx.header("mcp-session-id", this.sessionId);
|
|
7847
|
+
const responses = relatedIds.map((id) => this.#requestResponseMap.get(id));
|
|
7848
|
+
response.ctx.json?.(responses.length === 1 ? responses[0] : responses);
|
|
7849
|
+
return;
|
|
7850
|
+
} else response.stream?.abort();
|
|
7851
|
+
for (const id of relatedIds) {
|
|
7852
|
+
this.#requestResponseMap.delete(id);
|
|
7853
|
+
this.#requestToStreamMapping.delete(id);
|
|
7854
|
+
}
|
|
7855
|
+
}
|
|
7856
|
+
}
|
|
7857
|
+
}
|
|
7858
|
+
};
|
|
7859
|
+
//#endregion
|
|
7860
|
+
//#region ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.19/node_modules/@hono/node-server/dist/index.mjs
|
|
7861
|
+
var RequestError = class extends Error {
|
|
7862
|
+
constructor(message, options) {
|
|
7863
|
+
super(message, options);
|
|
7864
|
+
this.name = "RequestError";
|
|
7865
|
+
}
|
|
7866
|
+
};
|
|
7867
|
+
var toRequestError = (e) => {
|
|
7868
|
+
if (e instanceof RequestError) return e;
|
|
7869
|
+
return new RequestError(e.message, { cause: e });
|
|
7870
|
+
};
|
|
7871
|
+
var GlobalRequest = global.Request;
|
|
7872
|
+
var Request$1 = class extends GlobalRequest {
|
|
7873
|
+
constructor(input, options) {
|
|
7874
|
+
if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
|
|
7875
|
+
if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
|
|
7876
|
+
super(input, options);
|
|
7877
|
+
}
|
|
7878
|
+
};
|
|
7879
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
7880
|
+
const headerRecord = [];
|
|
7881
|
+
const rawHeaders = incoming.rawHeaders;
|
|
7882
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
7883
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
7884
|
+
if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
|
|
7885
|
+
}
|
|
7886
|
+
return new Headers(headerRecord);
|
|
7887
|
+
};
|
|
7888
|
+
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
7889
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
7890
|
+
const init = {
|
|
7891
|
+
method,
|
|
7892
|
+
headers,
|
|
7893
|
+
signal: abortController.signal
|
|
7894
|
+
};
|
|
7895
|
+
if (method === "TRACE") {
|
|
7896
|
+
init.method = "GET";
|
|
7897
|
+
const req = new Request$1(url, init);
|
|
7898
|
+
Object.defineProperty(req, "method", { get() {
|
|
7899
|
+
return "TRACE";
|
|
7900
|
+
} });
|
|
7901
|
+
return req;
|
|
7902
|
+
}
|
|
7903
|
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
|
7904
|
+
controller.enqueue(incoming.rawBody);
|
|
7905
|
+
controller.close();
|
|
7906
|
+
} });
|
|
7907
|
+
else if (incoming[wrapBodyStream]) {
|
|
7908
|
+
let reader;
|
|
7909
|
+
init.body = new ReadableStream({ async pull(controller) {
|
|
7910
|
+
try {
|
|
7911
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
7912
|
+
const { done, value } = await reader.read();
|
|
7913
|
+
if (done) controller.close();
|
|
7914
|
+
else controller.enqueue(value);
|
|
7915
|
+
} catch (error) {
|
|
7916
|
+
controller.error(error);
|
|
7917
|
+
}
|
|
7918
|
+
} });
|
|
7919
|
+
} else init.body = Readable.toWeb(incoming);
|
|
7920
|
+
return new Request$1(url, init);
|
|
7921
|
+
};
|
|
7922
|
+
var getRequestCache = Symbol("getRequestCache");
|
|
7923
|
+
var requestCache = Symbol("requestCache");
|
|
7924
|
+
var incomingKey = Symbol("incomingKey");
|
|
7925
|
+
var urlKey = Symbol("urlKey");
|
|
7926
|
+
var headersKey = Symbol("headersKey");
|
|
7927
|
+
var abortControllerKey = Symbol("abortControllerKey");
|
|
7928
|
+
var requestPrototype = {
|
|
7929
|
+
get method() {
|
|
7930
|
+
return this[incomingKey].method || "GET";
|
|
7931
|
+
},
|
|
7932
|
+
get url() {
|
|
7933
|
+
return this[urlKey];
|
|
7934
|
+
},
|
|
7935
|
+
get headers() {
|
|
7936
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
7937
|
+
},
|
|
7938
|
+
[Symbol("getAbortController")]() {
|
|
7939
|
+
this[getRequestCache]();
|
|
7940
|
+
return this[abortControllerKey];
|
|
7941
|
+
},
|
|
7942
|
+
[getRequestCache]() {
|
|
7943
|
+
this[abortControllerKey] ||= new AbortController();
|
|
7944
|
+
return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
|
|
7945
|
+
}
|
|
7946
|
+
};
|
|
7947
|
+
[
|
|
7948
|
+
"body",
|
|
7949
|
+
"bodyUsed",
|
|
7950
|
+
"cache",
|
|
7951
|
+
"credentials",
|
|
7952
|
+
"destination",
|
|
7953
|
+
"integrity",
|
|
7954
|
+
"mode",
|
|
7955
|
+
"redirect",
|
|
7956
|
+
"referrer",
|
|
7957
|
+
"referrerPolicy",
|
|
7958
|
+
"signal",
|
|
7959
|
+
"keepalive"
|
|
7960
|
+
].forEach((k) => {
|
|
7961
|
+
Object.defineProperty(requestPrototype, k, { get() {
|
|
7962
|
+
return this[getRequestCache]()[k];
|
|
7963
|
+
} });
|
|
7964
|
+
});
|
|
7965
|
+
[
|
|
7966
|
+
"arrayBuffer",
|
|
7967
|
+
"blob",
|
|
7968
|
+
"clone",
|
|
7969
|
+
"formData",
|
|
7970
|
+
"json",
|
|
7971
|
+
"text"
|
|
7972
|
+
].forEach((k) => {
|
|
7973
|
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
|
7974
|
+
return this[getRequestCache]()[k]();
|
|
7975
|
+
} });
|
|
7976
|
+
});
|
|
7977
|
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
7978
|
+
return `Request (lightweight) ${inspectFn({
|
|
7979
|
+
method: this.method,
|
|
7980
|
+
url: this.url,
|
|
7981
|
+
headers: this.headers,
|
|
7982
|
+
nativeRequest: this[requestCache]
|
|
7983
|
+
}, {
|
|
7984
|
+
...options,
|
|
7985
|
+
depth: depth == null ? null : depth - 1
|
|
7986
|
+
})}`;
|
|
7987
|
+
} });
|
|
7988
|
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
|
7989
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
7990
|
+
const req = Object.create(requestPrototype);
|
|
7991
|
+
req[incomingKey] = incoming;
|
|
7992
|
+
const incomingUrl = incoming.url || "";
|
|
7993
|
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
7994
|
+
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
7995
|
+
try {
|
|
7996
|
+
req[urlKey] = new URL(incomingUrl).href;
|
|
7997
|
+
} catch (e) {
|
|
7998
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
7999
|
+
}
|
|
8000
|
+
return req;
|
|
8001
|
+
}
|
|
8002
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
8003
|
+
if (!host) throw new RequestError("Missing host header");
|
|
8004
|
+
let scheme;
|
|
8005
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
8006
|
+
scheme = incoming.scheme;
|
|
8007
|
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
|
8008
|
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
8009
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
8010
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
|
|
8011
|
+
req[urlKey] = url.href;
|
|
8012
|
+
return req;
|
|
8013
|
+
};
|
|
8014
|
+
var responseCache = Symbol("responseCache");
|
|
8015
|
+
var getResponseCache = Symbol("getResponseCache");
|
|
8016
|
+
var cacheKey = Symbol("cache");
|
|
8017
|
+
var GlobalResponse = global.Response;
|
|
8018
|
+
var Response2 = class _Response {
|
|
8019
|
+
#body;
|
|
8020
|
+
#init;
|
|
8021
|
+
[getResponseCache]() {
|
|
8022
|
+
delete this[cacheKey];
|
|
8023
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
8024
|
+
}
|
|
8025
|
+
constructor(body, init) {
|
|
8026
|
+
let headers;
|
|
8027
|
+
this.#body = body;
|
|
8028
|
+
if (init instanceof _Response) {
|
|
8029
|
+
const cachedGlobalResponse = init[responseCache];
|
|
8030
|
+
if (cachedGlobalResponse) {
|
|
8031
|
+
this.#init = cachedGlobalResponse;
|
|
8032
|
+
this[getResponseCache]();
|
|
8033
|
+
return;
|
|
8034
|
+
} else {
|
|
8035
|
+
this.#init = init.#init;
|
|
8036
|
+
headers = new Headers(init.#init.headers);
|
|
8037
|
+
}
|
|
8038
|
+
} else this.#init = init;
|
|
8039
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
|
8040
|
+
init?.status || 200,
|
|
8041
|
+
body,
|
|
8042
|
+
headers || init?.headers
|
|
8043
|
+
];
|
|
8044
|
+
}
|
|
8045
|
+
get headers() {
|
|
8046
|
+
const cache = this[cacheKey];
|
|
8047
|
+
if (cache) {
|
|
8048
|
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
|
|
8049
|
+
return cache[2];
|
|
8050
|
+
}
|
|
8051
|
+
return this[getResponseCache]().headers;
|
|
8052
|
+
}
|
|
8053
|
+
get status() {
|
|
8054
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
8055
|
+
}
|
|
8056
|
+
get ok() {
|
|
8057
|
+
const status = this.status;
|
|
8058
|
+
return status >= 200 && status < 300;
|
|
8059
|
+
}
|
|
8060
|
+
};
|
|
8061
|
+
[
|
|
8062
|
+
"body",
|
|
8063
|
+
"bodyUsed",
|
|
8064
|
+
"redirected",
|
|
8065
|
+
"statusText",
|
|
8066
|
+
"trailers",
|
|
8067
|
+
"type",
|
|
8068
|
+
"url"
|
|
8069
|
+
].forEach((k) => {
|
|
8070
|
+
Object.defineProperty(Response2.prototype, k, { get() {
|
|
8071
|
+
return this[getResponseCache]()[k];
|
|
8072
|
+
} });
|
|
8073
|
+
});
|
|
8074
|
+
[
|
|
8075
|
+
"arrayBuffer",
|
|
8076
|
+
"blob",
|
|
8077
|
+
"clone",
|
|
8078
|
+
"formData",
|
|
8079
|
+
"json",
|
|
8080
|
+
"text"
|
|
8081
|
+
].forEach((k) => {
|
|
8082
|
+
Object.defineProperty(Response2.prototype, k, { value: function() {
|
|
8083
|
+
return this[getResponseCache]()[k]();
|
|
8084
|
+
} });
|
|
8085
|
+
});
|
|
8086
|
+
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
8087
|
+
return `Response (lightweight) ${inspectFn({
|
|
8088
|
+
status: this.status,
|
|
8089
|
+
headers: this.headers,
|
|
8090
|
+
ok: this.ok,
|
|
8091
|
+
nativeResponse: this[responseCache]
|
|
8092
|
+
}, {
|
|
8093
|
+
...options,
|
|
8094
|
+
depth: depth == null ? null : depth - 1
|
|
8095
|
+
})}`;
|
|
8096
|
+
} });
|
|
8097
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
8098
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
8099
|
+
async function readWithoutBlocking(readPromise) {
|
|
8100
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
8101
|
+
}
|
|
8102
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
8103
|
+
const cancel = (error) => {
|
|
8104
|
+
reader.cancel(error).catch(() => {});
|
|
8105
|
+
};
|
|
8106
|
+
writable.on("close", cancel);
|
|
8107
|
+
writable.on("error", cancel);
|
|
8108
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
8109
|
+
return reader.closed.finally(() => {
|
|
8110
|
+
writable.off("close", cancel);
|
|
8111
|
+
writable.off("error", cancel);
|
|
8112
|
+
});
|
|
8113
|
+
function handleStreamError(error) {
|
|
8114
|
+
if (error) writable.destroy(error);
|
|
8115
|
+
}
|
|
8116
|
+
function onDrain() {
|
|
8117
|
+
reader.read().then(flow, handleStreamError);
|
|
8118
|
+
}
|
|
8119
|
+
function flow({ done, value }) {
|
|
8120
|
+
try {
|
|
8121
|
+
if (done) writable.end();
|
|
8122
|
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
|
8123
|
+
else return reader.read().then(flow, handleStreamError);
|
|
8124
|
+
} catch (e) {
|
|
8125
|
+
handleStreamError(e);
|
|
8126
|
+
}
|
|
8127
|
+
}
|
|
8128
|
+
}
|
|
8129
|
+
function writeFromReadableStream(stream, writable) {
|
|
8130
|
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
|
8131
|
+
else if (writable.destroyed) return;
|
|
8132
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
8133
|
+
}
|
|
8134
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
8135
|
+
const res = {};
|
|
8136
|
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
|
8137
|
+
const cookies = [];
|
|
8138
|
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
|
8139
|
+
else res[k] = v;
|
|
8140
|
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
|
8141
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
8142
|
+
return res;
|
|
8143
|
+
};
|
|
8144
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
8145
|
+
if (typeof global.crypto === "undefined") global.crypto = crypto$1;
|
|
8146
|
+
var outgoingEnded = Symbol("outgoingEnded");
|
|
8147
|
+
var incomingDraining = Symbol("incomingDraining");
|
|
8148
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
8149
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
8150
|
+
var drainIncoming = (incoming) => {
|
|
8151
|
+
const incomingWithDrainState = incoming;
|
|
8152
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
|
8153
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
8154
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
8155
|
+
try {
|
|
8156
|
+
incoming.stream?.close?.(constants$1.NGHTTP2_NO_ERROR);
|
|
8157
|
+
} catch {}
|
|
8158
|
+
return;
|
|
8159
|
+
}
|
|
8160
|
+
let bytesRead = 0;
|
|
8161
|
+
const cleanup = () => {
|
|
8162
|
+
clearTimeout(timer);
|
|
8163
|
+
incoming.off("data", onData);
|
|
8164
|
+
incoming.off("end", cleanup);
|
|
8165
|
+
incoming.off("error", cleanup);
|
|
8166
|
+
};
|
|
8167
|
+
const forceClose = () => {
|
|
8168
|
+
cleanup();
|
|
8169
|
+
const socket = incoming.socket;
|
|
8170
|
+
if (socket && !socket.destroyed) socket.destroySoon();
|
|
8171
|
+
};
|
|
8172
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
8173
|
+
timer.unref?.();
|
|
8174
|
+
const onData = (chunk) => {
|
|
8175
|
+
bytesRead += chunk.length;
|
|
8176
|
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
|
8177
|
+
};
|
|
8178
|
+
incoming.on("data", onData);
|
|
8179
|
+
incoming.on("end", cleanup);
|
|
8180
|
+
incoming.on("error", cleanup);
|
|
8181
|
+
incoming.resume();
|
|
8182
|
+
};
|
|
8183
|
+
var handleRequestError = () => new Response(null, { status: 400 });
|
|
8184
|
+
var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
|
8185
|
+
var handleResponseError = (e, outgoing) => {
|
|
8186
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
8187
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
|
8188
|
+
else {
|
|
8189
|
+
console.error(e);
|
|
8190
|
+
if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
8191
|
+
outgoing.end(`Error: ${err.message}`);
|
|
8192
|
+
outgoing.destroy(err);
|
|
8193
|
+
}
|
|
8194
|
+
};
|
|
8195
|
+
var flushHeaders = (outgoing) => {
|
|
8196
|
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
|
8197
|
+
};
|
|
8198
|
+
var responseViaCache = async (res, outgoing) => {
|
|
8199
|
+
let [status, body, header] = res[cacheKey];
|
|
8200
|
+
let hasContentLength = false;
|
|
8201
|
+
if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
|
|
8202
|
+
else if (header instanceof Headers) {
|
|
8203
|
+
hasContentLength = header.has("content-length");
|
|
8204
|
+
header = buildOutgoingHttpHeaders(header);
|
|
8205
|
+
} else if (Array.isArray(header)) {
|
|
8206
|
+
const headerObj = new Headers(header);
|
|
8207
|
+
hasContentLength = headerObj.has("content-length");
|
|
8208
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
8209
|
+
} else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
8210
|
+
hasContentLength = true;
|
|
8211
|
+
break;
|
|
8212
|
+
}
|
|
8213
|
+
if (!hasContentLength) {
|
|
8214
|
+
if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
|
|
8215
|
+
else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
|
|
8216
|
+
else if (body instanceof Blob) header["Content-Length"] = body.size;
|
|
8217
|
+
}
|
|
8218
|
+
outgoing.writeHead(status, header);
|
|
8219
|
+
if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
|
8220
|
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
8221
|
+
else {
|
|
8222
|
+
flushHeaders(outgoing);
|
|
8223
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
8224
|
+
}
|
|
8225
|
+
outgoing[outgoingEnded]?.();
|
|
8226
|
+
};
|
|
8227
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
8228
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
8229
|
+
if (isPromise(res)) if (options.errorHandler) try {
|
|
8230
|
+
res = await res;
|
|
8231
|
+
} catch (err) {
|
|
8232
|
+
const errRes = await options.errorHandler(err);
|
|
8233
|
+
if (!errRes) return;
|
|
8234
|
+
res = errRes;
|
|
8235
|
+
}
|
|
8236
|
+
else res = await res.catch(handleFetchError);
|
|
8237
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
8238
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
8239
|
+
if (res.body) {
|
|
8240
|
+
const reader = res.body.getReader();
|
|
8241
|
+
const values = [];
|
|
8242
|
+
let done = false;
|
|
8243
|
+
let currentReadPromise = void 0;
|
|
8244
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
8245
|
+
let maxReadCount = 2;
|
|
8246
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
8247
|
+
currentReadPromise ||= reader.read();
|
|
8248
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
8249
|
+
console.error(e);
|
|
8250
|
+
done = true;
|
|
8251
|
+
});
|
|
8252
|
+
if (!chunk) {
|
|
8253
|
+
if (i === 1) {
|
|
8254
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
8255
|
+
maxReadCount = 3;
|
|
8256
|
+
continue;
|
|
8257
|
+
}
|
|
8258
|
+
break;
|
|
8259
|
+
}
|
|
8260
|
+
currentReadPromise = void 0;
|
|
8261
|
+
if (chunk.value) values.push(chunk.value);
|
|
8262
|
+
if (chunk.done) {
|
|
8263
|
+
done = true;
|
|
8264
|
+
break;
|
|
8265
|
+
}
|
|
8266
|
+
}
|
|
8267
|
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
8268
|
+
}
|
|
8269
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
8270
|
+
values.forEach((value) => {
|
|
8271
|
+
outgoing.write(value);
|
|
8272
|
+
});
|
|
8273
|
+
if (done) outgoing.end();
|
|
8274
|
+
else {
|
|
8275
|
+
if (values.length === 0) flushHeaders(outgoing);
|
|
8276
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
8277
|
+
}
|
|
8278
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
|
|
8279
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
8280
|
+
outgoing.end();
|
|
8281
|
+
}
|
|
8282
|
+
outgoing[outgoingEnded]?.();
|
|
8283
|
+
};
|
|
8284
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
8285
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
8286
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
|
8287
|
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
|
8288
|
+
Object.defineProperty(global, "Response", { value: Response2 });
|
|
8289
|
+
}
|
|
8290
|
+
return async (incoming, outgoing) => {
|
|
8291
|
+
let res, req;
|
|
8292
|
+
try {
|
|
8293
|
+
req = newRequest(incoming, options.hostname);
|
|
8294
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
8295
|
+
if (!incomingEnded) {
|
|
8296
|
+
incoming[wrapBodyStream] = true;
|
|
8297
|
+
incoming.on("end", () => {
|
|
8298
|
+
incomingEnded = true;
|
|
8299
|
+
});
|
|
8300
|
+
if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
|
8301
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8302
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8303
|
+
drainIncoming(incoming);
|
|
8304
|
+
});
|
|
8305
|
+
});
|
|
8306
|
+
};
|
|
8307
|
+
outgoing.on("finish", () => {
|
|
8308
|
+
if (!incomingEnded) drainIncoming(incoming);
|
|
8309
|
+
});
|
|
8310
|
+
}
|
|
8311
|
+
outgoing.on("close", () => {
|
|
8312
|
+
if (req[abortControllerKey]) {
|
|
8313
|
+
if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
|
|
8314
|
+
else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
8315
|
+
}
|
|
8316
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8317
|
+
if (!incomingEnded) setTimeout(() => {
|
|
8318
|
+
drainIncoming(incoming);
|
|
8319
|
+
});
|
|
8320
|
+
});
|
|
8321
|
+
});
|
|
8322
|
+
res = fetchCallback(req, {
|
|
8323
|
+
incoming,
|
|
8324
|
+
outgoing
|
|
8325
|
+
});
|
|
8326
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
8327
|
+
} catch (e) {
|
|
8328
|
+
if (!res) if (options.errorHandler) {
|
|
8329
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
8330
|
+
if (!res) return;
|
|
8331
|
+
} else if (!req) res = handleRequestError();
|
|
8332
|
+
else res = handleFetchError(e);
|
|
8333
|
+
else return handleResponseError(e, outgoing);
|
|
8334
|
+
}
|
|
8335
|
+
try {
|
|
8336
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
8337
|
+
} catch (e) {
|
|
8338
|
+
return handleResponseError(e, outgoing);
|
|
8339
|
+
}
|
|
8340
|
+
};
|
|
8341
|
+
};
|
|
8342
|
+
var createAdaptorServer = (options) => {
|
|
8343
|
+
const fetchCallback = options.fetch;
|
|
8344
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
8345
|
+
hostname: options.hostname,
|
|
8346
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
8347
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
8348
|
+
});
|
|
8349
|
+
return (options.createServer || createServer)(options.serverOptions || {}, requestListener);
|
|
8350
|
+
};
|
|
8351
|
+
var serve = (options, listeningListener) => {
|
|
8352
|
+
const server = createAdaptorServer(options);
|
|
8353
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
8354
|
+
const serverInfo = server.address();
|
|
8355
|
+
listeningListener && listeningListener(serverInfo);
|
|
8356
|
+
});
|
|
8357
|
+
return server;
|
|
8358
|
+
};
|
|
8359
|
+
//#endregion
|
|
8360
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/utils/color.js
|
|
8361
|
+
function getColorEnabled() {
|
|
8362
|
+
const { process, Deno } = globalThis;
|
|
8363
|
+
return !(typeof Deno?.noColor === "boolean" ? Deno.noColor : process !== void 0 ? "NO_COLOR" in process?.env : false);
|
|
8364
|
+
}
|
|
8365
|
+
async function getColorEnabledAsync() {
|
|
8366
|
+
const { navigator } = globalThis;
|
|
8367
|
+
const cfWorkers = "cloudflare:workers";
|
|
8368
|
+
return !(navigator !== void 0 && navigator.userAgent === "Cloudflare-Workers" ? await (async () => {
|
|
8369
|
+
try {
|
|
8370
|
+
return "NO_COLOR" in ((await import(cfWorkers)).env ?? {});
|
|
8371
|
+
} catch {
|
|
8372
|
+
return false;
|
|
8373
|
+
}
|
|
8374
|
+
})() : !getColorEnabled());
|
|
8375
|
+
}
|
|
8376
|
+
//#endregion
|
|
8377
|
+
//#region ../../node_modules/.pnpm/hono@4.12.19/node_modules/hono/dist/middleware/logger/index.js
|
|
8378
|
+
var humanize = (times) => {
|
|
8379
|
+
const [delimiter, separator] = [",", "."];
|
|
8380
|
+
return times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter)).join(separator);
|
|
8381
|
+
};
|
|
8382
|
+
var time = (start) => {
|
|
8383
|
+
const delta = Date.now() - start;
|
|
8384
|
+
return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]);
|
|
8385
|
+
};
|
|
8386
|
+
var colorStatus = async (status) => {
|
|
8387
|
+
if (await getColorEnabledAsync()) switch (status / 100 | 0) {
|
|
8388
|
+
case 5: return `\x1B[31m${status}\x1B[0m`;
|
|
8389
|
+
case 4: return `\x1B[33m${status}\x1B[0m`;
|
|
8390
|
+
case 3: return `\x1B[36m${status}\x1B[0m`;
|
|
8391
|
+
case 2: return `\x1B[32m${status}\x1B[0m`;
|
|
8392
|
+
}
|
|
8393
|
+
return `${status}`;
|
|
8394
|
+
};
|
|
8395
|
+
async function log(fn, prefix, method, path, status = 0, elapsed) {
|
|
8396
|
+
fn(prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`);
|
|
8397
|
+
}
|
|
8398
|
+
var logger = (fn = console.log) => {
|
|
8399
|
+
return async function logger2(c, next) {
|
|
8400
|
+
const { method, url } = c.req;
|
|
8401
|
+
const path = url.slice(url.indexOf("/", 8));
|
|
8402
|
+
await log(fn, "<--", method, path);
|
|
8403
|
+
const start = Date.now();
|
|
8404
|
+
await next();
|
|
8405
|
+
await log(fn, "-->", method, path, c.res.status, time(start));
|
|
8406
|
+
};
|
|
8407
|
+
};
|
|
8408
|
+
//#endregion
|
|
8409
|
+
//#region src/remote-control/dispatch.ts
|
|
8410
|
+
const ENGINE_COMMANDS = new Set([
|
|
8411
|
+
"get_caplet",
|
|
8412
|
+
"check_backend",
|
|
8413
|
+
"list_tools",
|
|
8414
|
+
"search_tools",
|
|
8415
|
+
"get_tool",
|
|
8416
|
+
"call_tool"
|
|
8417
|
+
]);
|
|
8418
|
+
async function dispatchRemoteCliRequest(request, context) {
|
|
8419
|
+
try {
|
|
8420
|
+
return {
|
|
8421
|
+
ok: true,
|
|
8422
|
+
result: await dispatch(request, context)
|
|
8423
|
+
};
|
|
8424
|
+
} catch (error) {
|
|
8425
|
+
const safe = toSafeError(error);
|
|
8426
|
+
const action = nextAction(safe.details);
|
|
8427
|
+
return {
|
|
8428
|
+
ok: false,
|
|
8429
|
+
error: {
|
|
8430
|
+
code: safe.code,
|
|
8431
|
+
message: redactControlErrorMessage(safe.message),
|
|
8432
|
+
...action ? { nextAction: action } : {}
|
|
8433
|
+
}
|
|
8434
|
+
};
|
|
8435
|
+
}
|
|
8436
|
+
}
|
|
8437
|
+
async function dispatch(request, context) {
|
|
8438
|
+
assertObject(request, "remote control request");
|
|
8439
|
+
assertObject(request.arguments, "remote control request arguments");
|
|
8440
|
+
if (request.command === "list") return listCaplets(loadConfigWithSources(context.configPath, context.projectConfigPath), { includeDisabled: optionalBoolean(request.arguments, "includeDisabled") ?? false });
|
|
8441
|
+
if (ENGINE_COMMANDS.has(request.command)) {
|
|
8442
|
+
const caplet = requiredString(request.arguments, "caplet");
|
|
8443
|
+
const toolRequest = requiredEngineRequest(request.arguments, request.command);
|
|
8444
|
+
const engine = new CapletsEngine(context);
|
|
8445
|
+
try {
|
|
8446
|
+
return await engine.execute(caplet, toolRequest);
|
|
8447
|
+
} finally {
|
|
8448
|
+
await engine.close();
|
|
8449
|
+
}
|
|
8450
|
+
}
|
|
8451
|
+
if (request.command === "init") return {
|
|
8452
|
+
remote: true,
|
|
8453
|
+
path: initConfig({
|
|
8454
|
+
...optionalProp("path", context.configPath),
|
|
8455
|
+
...optionalProp("force", optionalBoolean(request.arguments, "force"))
|
|
8456
|
+
})
|
|
8457
|
+
};
|
|
8458
|
+
if (request.command === "add") return dispatchAdd(request.arguments, context);
|
|
8459
|
+
if (request.command === "install") return {
|
|
8460
|
+
remote: true,
|
|
8461
|
+
...installCaplets(requiredString(request.arguments, "repo"), {
|
|
8462
|
+
...optionalProp("capletIds", optionalStringArray(request.arguments, "capletIds")),
|
|
8463
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8464
|
+
...optionalProp("force", optionalBoolean(request.arguments, "force"))
|
|
8465
|
+
})
|
|
8466
|
+
};
|
|
8467
|
+
if (request.command === "auth_list") return listAuthRows({
|
|
8468
|
+
...optionalProp("configPath", context.configPath),
|
|
8469
|
+
...optionalProp("authDir", context.authDir)
|
|
8470
|
+
});
|
|
8471
|
+
if (request.command === "auth_logout") return logoutAuthResult(requiredString(request.arguments, "server"), {
|
|
8472
|
+
...optionalProp("configPath", context.configPath),
|
|
8473
|
+
...optionalProp("authDir", context.authDir)
|
|
8474
|
+
});
|
|
8475
|
+
if (request.command === "auth_login_start") return startRemoteAuthLogin(requiredString(request.arguments, "server"), context);
|
|
8476
|
+
if (request.command === "auth_login_complete") return completeRemoteAuthLogin(requiredString(request.arguments, "flowId"), requiredString(request.arguments, "callbackUrl"), context);
|
|
8477
|
+
throw new CapletsError("UNKNOWN_OPERATION", `Unsupported remote control command ${request.command}`);
|
|
8478
|
+
}
|
|
8479
|
+
async function startRemoteAuthLogin(serverId, context) {
|
|
8480
|
+
if (!context.authFlowStore || !context.controlCallbackBaseUrl) throw new CapletsError("REQUEST_INVALID", "Remote auth login is not available on this server");
|
|
8481
|
+
const config = loadConfigWithSources(context.configPath, context.projectConfigPath).config;
|
|
8482
|
+
const target = findAuthTarget(serverId, config);
|
|
8483
|
+
assertLoginTarget(target, serverId);
|
|
8484
|
+
const flowId = randomUUID();
|
|
8485
|
+
const baseUrl = context.controlCallbackBaseUrl.endsWith("/") ? context.controlCallbackBaseUrl : `${context.controlCallbackBaseUrl}/`;
|
|
8486
|
+
const redirectUri = new URL(`auth/callback/${flowId}`, baseUrl).toString();
|
|
8487
|
+
const started = target.backend === "mcp" ? await startOAuthFlow(target, {
|
|
8488
|
+
redirectUri,
|
|
8489
|
+
...optionalProp("authDir", context.authDir)
|
|
8490
|
+
}) : await startGenericOAuthFlow(target, {
|
|
8491
|
+
redirectUri,
|
|
8492
|
+
...optionalProp("authDir", context.authDir)
|
|
8493
|
+
});
|
|
8494
|
+
if (!started.authorizationUrl) return {
|
|
8495
|
+
server: serverId,
|
|
8496
|
+
authenticated: true
|
|
8497
|
+
};
|
|
8498
|
+
const flow = context.authFlowStore.create({
|
|
8499
|
+
server: serverId,
|
|
8500
|
+
authorizationUrl: started.authorizationUrl,
|
|
8501
|
+
complete: started.complete
|
|
8502
|
+
}, flowId);
|
|
8503
|
+
return {
|
|
8504
|
+
server: serverId,
|
|
8505
|
+
flowId: flow.id,
|
|
8506
|
+
authorizationUrl: flow.authorizationUrl
|
|
8507
|
+
};
|
|
8508
|
+
}
|
|
8509
|
+
async function completeRemoteAuthLogin(flowId, callbackUrl, context) {
|
|
8510
|
+
const flow = context.authFlowStore?.get(flowId);
|
|
8511
|
+
if (!flow) throw new CapletsError("REQUEST_INVALID", `Unknown auth flow ${flowId}`);
|
|
8512
|
+
context.authFlowStore?.delete(flowId);
|
|
8513
|
+
await flow.complete(callbackUrl);
|
|
8514
|
+
return {
|
|
8515
|
+
server: flow.server,
|
|
8516
|
+
authenticated: true
|
|
8517
|
+
};
|
|
8518
|
+
}
|
|
8519
|
+
function dispatchAdd(args, context) {
|
|
8520
|
+
const kind = requiredString(args, "kind");
|
|
8521
|
+
const id = requiredString(args, "id");
|
|
8522
|
+
const options = remoteAddOptions$1(kind, optionalObject(args, "options"));
|
|
8523
|
+
switch (kind) {
|
|
8524
|
+
case "cli": return {
|
|
8525
|
+
remote: true,
|
|
8526
|
+
label: "CLI",
|
|
8527
|
+
...addCliCaplet(id, {
|
|
8528
|
+
...options,
|
|
8529
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8530
|
+
print: false
|
|
8531
|
+
})
|
|
8532
|
+
};
|
|
8533
|
+
case "mcp": return {
|
|
8534
|
+
remote: true,
|
|
8535
|
+
label: "MCP",
|
|
8536
|
+
...addMcpCaplet(id, {
|
|
8537
|
+
...options,
|
|
8538
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8539
|
+
print: false
|
|
8540
|
+
})
|
|
8541
|
+
};
|
|
8542
|
+
case "openapi": return {
|
|
8543
|
+
remote: true,
|
|
8544
|
+
label: "OpenAPI",
|
|
8545
|
+
...addOpenApiCaplet(id, {
|
|
8546
|
+
...options,
|
|
8547
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8548
|
+
print: false
|
|
8549
|
+
})
|
|
8550
|
+
};
|
|
8551
|
+
case "graphql": return {
|
|
8552
|
+
remote: true,
|
|
8553
|
+
label: "GraphQL",
|
|
8554
|
+
...addGraphqlCaplet(id, {
|
|
8555
|
+
...options,
|
|
8556
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8557
|
+
print: false
|
|
8558
|
+
})
|
|
8559
|
+
};
|
|
8560
|
+
case "http": return {
|
|
8561
|
+
remote: true,
|
|
8562
|
+
label: "HTTP",
|
|
8563
|
+
...addHttpCaplet(id, {
|
|
8564
|
+
...options,
|
|
8565
|
+
destinationRoot: context.projectCapletsRoot,
|
|
8566
|
+
print: false
|
|
8567
|
+
})
|
|
8568
|
+
};
|
|
8569
|
+
default: throw new CapletsError("REQUEST_INVALID", "add.kind must be cli, mcp, openapi, graphql, or http");
|
|
8570
|
+
}
|
|
8571
|
+
}
|
|
8572
|
+
function optionalProp(key, value) {
|
|
8573
|
+
return value === void 0 ? {} : { [key]: value };
|
|
8574
|
+
}
|
|
8575
|
+
function assertObject(value, label) {
|
|
8576
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new CapletsError("REQUEST_INVALID", `${label} must be an object`);
|
|
8577
|
+
}
|
|
8578
|
+
function requiredString(args, key) {
|
|
8579
|
+
const value = args[key];
|
|
8580
|
+
if (typeof value !== "string" || value.length === 0) throw new CapletsError("REQUEST_INVALID", `${key} must be a non-empty string`);
|
|
8581
|
+
return value;
|
|
8582
|
+
}
|
|
8583
|
+
function optionalObject(args, key) {
|
|
8584
|
+
const value = args[key];
|
|
8585
|
+
if (value === void 0) return {};
|
|
8586
|
+
assertObject(value, key);
|
|
8587
|
+
return value;
|
|
8588
|
+
}
|
|
8589
|
+
function requiredEngineRequest(args, command) {
|
|
8590
|
+
const toolRequest = optionalObject(args, "request");
|
|
8591
|
+
if (typeof toolRequest.operation !== "string") throw new CapletsError("REQUEST_INVALID", "request.operation must be a string");
|
|
8592
|
+
if (toolRequest.operation !== command) throw new CapletsError("REQUEST_INVALID", `request.operation must match remote command ${command}`);
|
|
8593
|
+
return toolRequest;
|
|
8594
|
+
}
|
|
8595
|
+
function remoteAddOptions$1(kind, options) {
|
|
8596
|
+
rejectServerOwnedAddOptions(options);
|
|
8597
|
+
switch (kind) {
|
|
8598
|
+
case "cli": return pickOptions(options, {
|
|
8599
|
+
repo: "string",
|
|
8600
|
+
include: "string",
|
|
8601
|
+
command: "string",
|
|
8602
|
+
force: "boolean"
|
|
8603
|
+
});
|
|
8604
|
+
case "mcp": return pickOptions(options, {
|
|
8605
|
+
command: "string",
|
|
8606
|
+
arg: "string-array",
|
|
8607
|
+
cwd: "string",
|
|
8608
|
+
env: "string-array",
|
|
8609
|
+
url: "string",
|
|
8610
|
+
transport: "string",
|
|
8611
|
+
tokenEnv: "string",
|
|
8612
|
+
force: "boolean"
|
|
8613
|
+
});
|
|
8614
|
+
case "openapi": return pickOptions(options, {
|
|
8615
|
+
spec: "string",
|
|
8616
|
+
baseUrl: "string",
|
|
8617
|
+
tokenEnv: "string",
|
|
8618
|
+
force: "boolean"
|
|
8619
|
+
});
|
|
8620
|
+
case "graphql": return pickOptions(options, {
|
|
8621
|
+
endpointUrl: "string",
|
|
8622
|
+
schema: "string",
|
|
8623
|
+
introspection: "boolean",
|
|
8624
|
+
tokenEnv: "string",
|
|
8625
|
+
force: "boolean"
|
|
8626
|
+
});
|
|
8627
|
+
case "http": return pickOptions(options, {
|
|
8628
|
+
baseUrl: "string",
|
|
8629
|
+
action: "string-array",
|
|
8630
|
+
tokenEnv: "string",
|
|
8631
|
+
force: "boolean"
|
|
8632
|
+
});
|
|
8633
|
+
default: return options;
|
|
8634
|
+
}
|
|
8635
|
+
}
|
|
8636
|
+
function pickOptions(options, schema) {
|
|
8637
|
+
const next = {};
|
|
8638
|
+
for (const [key, type] of Object.entries(schema)) {
|
|
8639
|
+
const value = options[key];
|
|
8640
|
+
if (value === void 0) continue;
|
|
8641
|
+
validateOptionType(key, value, type);
|
|
8642
|
+
next[key] = value;
|
|
8643
|
+
}
|
|
8644
|
+
return next;
|
|
8645
|
+
}
|
|
8646
|
+
function rejectServerOwnedAddOptions(options) {
|
|
8647
|
+
if ("output" in options) throw new CapletsError("REQUEST_INVALID", "Remote add output is not supported remotely; the server owns destinationRoot and output path selection");
|
|
8648
|
+
for (const key of ["destinationRoot", "print"]) if (key in options) throw new CapletsError("REQUEST_INVALID", `Remote add ${key} is not supported remotely; the server owns destinationRoot and print behavior`);
|
|
8649
|
+
}
|
|
8650
|
+
function validateOptionType(key, value, type) {
|
|
8651
|
+
if (type === "string" && typeof value !== "string") throw new CapletsError("REQUEST_INVALID", `add.options.${key} must be a string`);
|
|
8652
|
+
if (type === "boolean" && typeof value !== "boolean") throw new CapletsError("REQUEST_INVALID", `add.options.${key} must be a boolean`);
|
|
8653
|
+
if (type === "string-array") {
|
|
8654
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) throw new CapletsError("REQUEST_INVALID", `add.options.${key} must be an array of strings`);
|
|
8655
|
+
}
|
|
8656
|
+
}
|
|
8657
|
+
function optionalBoolean(args, key) {
|
|
8658
|
+
const value = args[key];
|
|
8659
|
+
if (value === void 0) return;
|
|
8660
|
+
if (typeof value !== "boolean") throw new CapletsError("REQUEST_INVALID", `${key} must be a boolean`);
|
|
8661
|
+
return value;
|
|
8662
|
+
}
|
|
8663
|
+
function optionalStringArray(args, key) {
|
|
8664
|
+
const value = args[key];
|
|
8665
|
+
if (value === void 0) return;
|
|
8666
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) throw new CapletsError("REQUEST_INVALID", `${key} must be an array of strings`);
|
|
8667
|
+
return value;
|
|
8668
|
+
}
|
|
8669
|
+
function nextAction(details) {
|
|
8670
|
+
if (details && typeof details === "object" && "nextAction" in details) {
|
|
8671
|
+
const value = details.nextAction;
|
|
8672
|
+
return typeof value === "string" ? value : void 0;
|
|
8673
|
+
}
|
|
8674
|
+
}
|
|
8675
|
+
function redactControlErrorMessage(message) {
|
|
8676
|
+
return message.replace(/(["'])(authorization|(?:access[_-]?)?token|refresh(?:[_-]?token)?|password|client[_-]?secret|clientsecret|api[-_]?key|apikey|secret|credential|code)\1\s*:\s*(["'])(?:\\.|[^\\])*?\3/giu, "$1$2$1:$3[REDACTED]$3").replace(/\b(authorization\s*:\s*(?:basic|bearer)\s+)[^\s,;]+/giu, "$1[REDACTED]").replace(/\b((?:access[_-]?)?token|refresh(?:[_-]?token)?|password|client[_-]?secret|clientsecret|api[-_]?key|apikey|secret|credential|code)(\s*[=:]\s*)[^\s,;]+/giu, "$1$2[REDACTED]");
|
|
8677
|
+
}
|
|
8678
|
+
//#endregion
|
|
8679
|
+
//#region src/remote-control/auth-flow.ts
|
|
8680
|
+
const DEFAULT_AUTH_FLOW_TTL_MS = 600 * 1e3;
|
|
8681
|
+
var RemoteAuthFlowStore = class {
|
|
8682
|
+
options;
|
|
8683
|
+
flows = /* @__PURE__ */ new Map();
|
|
8684
|
+
constructor(options = {}) {
|
|
8685
|
+
this.options = options;
|
|
8686
|
+
}
|
|
8687
|
+
create(flow, id = randomUUID()) {
|
|
8688
|
+
this.pruneExpired();
|
|
8689
|
+
const created = {
|
|
8690
|
+
id,
|
|
8691
|
+
createdAt: this.now(),
|
|
8692
|
+
...flow
|
|
8693
|
+
};
|
|
8694
|
+
this.flows.set(created.id, created);
|
|
8695
|
+
return { ...created };
|
|
8696
|
+
}
|
|
8697
|
+
get(id) {
|
|
8698
|
+
this.pruneExpired();
|
|
8699
|
+
const flow = this.flows.get(id);
|
|
8700
|
+
if (flow && this.isExpired(flow)) {
|
|
8701
|
+
this.flows.delete(id);
|
|
8702
|
+
return;
|
|
8703
|
+
}
|
|
8704
|
+
return flow;
|
|
8705
|
+
}
|
|
8706
|
+
delete(id) {
|
|
8707
|
+
this.flows.delete(id);
|
|
8708
|
+
}
|
|
8709
|
+
pruneExpired() {
|
|
8710
|
+
for (const [id, flow] of this.flows) if (this.isExpired(flow)) this.flows.delete(id);
|
|
8711
|
+
}
|
|
8712
|
+
isExpired(flow) {
|
|
8713
|
+
return this.now() - flow.createdAt > (this.options.ttlMs ?? DEFAULT_AUTH_FLOW_TTL_MS);
|
|
8714
|
+
}
|
|
8715
|
+
now() {
|
|
8716
|
+
return this.options.now?.() ?? Date.now();
|
|
8717
|
+
}
|
|
8718
|
+
};
|
|
8719
|
+
//#endregion
|
|
8720
|
+
//#region src/serve/http.ts
|
|
8721
|
+
function createHttpServeApp(options, engine, io = {}) {
|
|
8722
|
+
const app = new Hono();
|
|
8723
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
8724
|
+
const writeErr = io.writeErr ?? process.stderr.write.bind(process.stderr);
|
|
8725
|
+
const paths = servicePaths(options.path);
|
|
8726
|
+
const authFlowStore = io.authFlowStore ?? new RemoteAuthFlowStore();
|
|
8727
|
+
app.use("*", logger((message, ...rest) => {
|
|
8728
|
+
writeErr(`${[message, ...rest].join(" ")}\n`);
|
|
8729
|
+
}));
|
|
8730
|
+
app.get(paths.base, (c) => c.json({
|
|
8731
|
+
name: "caplets",
|
|
8732
|
+
transport: "http",
|
|
8733
|
+
base: paths.base,
|
|
8734
|
+
mcp: paths.mcp,
|
|
8735
|
+
control: paths.control,
|
|
8736
|
+
health: paths.health,
|
|
8737
|
+
auth: {
|
|
8738
|
+
type: "basic",
|
|
8739
|
+
enabled: options.auth.enabled
|
|
8740
|
+
}
|
|
8741
|
+
}));
|
|
8742
|
+
app.get(paths.health, (c) => c.json({
|
|
8743
|
+
status: "ok",
|
|
8744
|
+
transport: "http",
|
|
8745
|
+
base: paths.base,
|
|
8746
|
+
mcpPath: paths.mcp,
|
|
8747
|
+
controlPath: paths.control,
|
|
8748
|
+
healthPath: paths.health
|
|
8749
|
+
}));
|
|
8750
|
+
app.all(paths.mcp, basicAuth(options.auth), async (c) => {
|
|
8751
|
+
const sessionId = c.req.header("mcp-session-id");
|
|
8752
|
+
if (sessionId) {
|
|
8753
|
+
const existing = sessions.get(sessionId);
|
|
8754
|
+
if (!existing) return c.json({
|
|
8755
|
+
jsonrpc: "2.0",
|
|
8756
|
+
error: {
|
|
8757
|
+
code: -32001,
|
|
8758
|
+
message: "Session not found"
|
|
8759
|
+
},
|
|
8760
|
+
id: null
|
|
8761
|
+
}, 404);
|
|
8762
|
+
return existing.transport.handleRequest(c);
|
|
8763
|
+
}
|
|
8764
|
+
if (c.req.method !== "POST") return c.json({
|
|
8765
|
+
jsonrpc: "2.0",
|
|
8766
|
+
error: {
|
|
8767
|
+
code: -32e3,
|
|
8768
|
+
message: "Bad Request: Mcp-Session-Id header is required"
|
|
8769
|
+
},
|
|
8770
|
+
id: null
|
|
8771
|
+
}, 400);
|
|
8772
|
+
const nextSessionId = randomUUID();
|
|
8773
|
+
const session = await createHttpSession(engine, nextSessionId, options, async (closedSessionId) => {
|
|
8774
|
+
const closed = sessions.get(closedSessionId);
|
|
8775
|
+
sessions.delete(closedSessionId);
|
|
8776
|
+
if (closed) await closed.server.close();
|
|
8777
|
+
});
|
|
8778
|
+
sessions.set(nextSessionId, session);
|
|
8779
|
+
return session.transport.handleRequest(c);
|
|
8780
|
+
});
|
|
8781
|
+
app.post(paths.control, basicAuth(options.auth), async (c) => {
|
|
8782
|
+
let request;
|
|
8783
|
+
try {
|
|
8784
|
+
const parsed = await c.req.json();
|
|
8785
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new CapletsError("REQUEST_INVALID", "Control request JSON must be an object");
|
|
8786
|
+
request = parsed;
|
|
8787
|
+
} catch (error) {
|
|
8788
|
+
const safe = toSafeError(error instanceof CapletsError ? error : new CapletsError("REQUEST_INVALID", "Control request body must be valid JSON", error), "REQUEST_INVALID");
|
|
8789
|
+
return c.json({
|
|
8790
|
+
ok: false,
|
|
8791
|
+
error: {
|
|
8792
|
+
code: safe.code,
|
|
8793
|
+
message: safe.message
|
|
8794
|
+
}
|
|
8795
|
+
});
|
|
8796
|
+
}
|
|
8797
|
+
return c.json(await dispatchRemoteCliRequest(request, controlContext(io, writeErr, authFlowStore, c.req.url, paths.control, options.trustProxy, (name) => c.req.header(name))));
|
|
8798
|
+
});
|
|
8799
|
+
app.get(routePath(paths.control, "auth/callback/:flowId"), async (c) => {
|
|
8800
|
+
const flowId = c.req.param("flowId");
|
|
8801
|
+
const result = await dispatchRemoteCliRequest({
|
|
8802
|
+
command: "auth_login_complete",
|
|
8803
|
+
arguments: {
|
|
8804
|
+
flowId,
|
|
8805
|
+
callbackUrl: c.req.url
|
|
8806
|
+
}
|
|
8807
|
+
}, controlContext(io, writeErr, authFlowStore, c.req.url, paths.control, options.trustProxy, (name) => c.req.header(name)));
|
|
8808
|
+
if (!result.ok) writeErr(`Caplets authentication failed for flow ${flowId}: ${result.error.message}\n`);
|
|
8809
|
+
return result.ok ? c.text("Caplets authentication complete. You can return to your terminal.") : c.text("Caplets authentication failed. Check server logs for details.", 400);
|
|
8810
|
+
});
|
|
8811
|
+
app.notFound((c) => c.json({ error: "not_found" }, 404));
|
|
8812
|
+
app.closeCapletsSessions = async () => {
|
|
8813
|
+
await Promise.allSettled([...sessions.values()].map(async (session) => {
|
|
8814
|
+
await session.server.close();
|
|
8815
|
+
}));
|
|
8816
|
+
sessions.clear();
|
|
8817
|
+
};
|
|
8818
|
+
if (options.warnUnauthenticatedNetwork) writeErr(`Warning: Caplets MCP HTTP server is listening on ${options.host} without authentication.\n`);
|
|
8819
|
+
return app;
|
|
8820
|
+
}
|
|
8821
|
+
function controlContext(io, writeErr, authFlowStore, requestUrl, controlPath, trustProxy, header) {
|
|
8822
|
+
return {
|
|
8823
|
+
...io.control,
|
|
8824
|
+
projectCapletsRoot: io.control?.projectCapletsRoot ?? resolveProjectCapletsRoot(),
|
|
8825
|
+
authFlowStore,
|
|
8826
|
+
controlCallbackBaseUrl: new URL(controlPath, publicRequestOrigin(requestUrl, trustProxy, header)).toString(),
|
|
8827
|
+
writeErr
|
|
8828
|
+
};
|
|
8829
|
+
}
|
|
8830
|
+
function publicRequestOrigin(requestUrl, trustProxy, header) {
|
|
8831
|
+
const url = new URL(requestUrl);
|
|
8832
|
+
if (!trustProxy) return `${url.protocol.slice(0, -1)}://${header("host") ?? url.host}`;
|
|
8833
|
+
const forwardedProto = firstForwardedValue(header("x-forwarded-proto"));
|
|
8834
|
+
const forwardedHost = firstForwardedValue(header("x-forwarded-host"));
|
|
8835
|
+
return `${forwardedProto === "http" || forwardedProto === "https" ? forwardedProto : url.protocol.slice(0, -1)}://${forwardedHost ?? header("host") ?? url.host}`;
|
|
8836
|
+
}
|
|
8837
|
+
function firstForwardedValue(value) {
|
|
8838
|
+
return value?.split(",", 1)[0]?.trim() || void 0;
|
|
8839
|
+
}
|
|
8840
|
+
async function serveHttp(options, engineOptions = {}, writeErr = (value) => process.stderr.write(value)) {
|
|
8841
|
+
const engine = new CapletsEngine(engineOptions);
|
|
8842
|
+
const app = createHttpServeApp(options, engine, {
|
|
8843
|
+
writeErr,
|
|
8844
|
+
control: {
|
|
8845
|
+
...engineOptions,
|
|
8846
|
+
projectCapletsRoot: projectCapletsRootForEngineOptions(engineOptions)
|
|
8847
|
+
}
|
|
8848
|
+
});
|
|
8849
|
+
const paths = servicePaths(options.path);
|
|
8850
|
+
const origin = `http://${formatHost(options.host)}:${options.port}`;
|
|
8851
|
+
const baseUrl = `${origin}${paths.base === "/" ? "" : paths.base}`;
|
|
8852
|
+
installHttpSignalHandlers(serve({
|
|
8853
|
+
fetch: app.fetch,
|
|
8854
|
+
hostname: options.host,
|
|
8855
|
+
port: options.port
|
|
8856
|
+
}, () => {
|
|
8857
|
+
writeErr(`Caplets HTTP service listening on ${baseUrl}\n`);
|
|
8858
|
+
writeErr(`MCP endpoint: ${origin}${paths.mcp}\n`);
|
|
8859
|
+
writeErr(`Control endpoint: ${origin}${paths.control}\n`);
|
|
8860
|
+
writeErr(`Health check: ${origin}${paths.health}\n`);
|
|
8861
|
+
writeErr(`Basic Auth: ${options.auth.enabled ? `enabled (user: ${options.auth.user})` : "disabled"}\n`);
|
|
8862
|
+
}), app, engine, writeErr);
|
|
8863
|
+
}
|
|
8864
|
+
function projectCapletsRootForEngineOptions(engineOptions) {
|
|
8865
|
+
return engineOptions.projectConfigPath ? resolveProjectCapletsRootForConfigPath(engineOptions.projectConfigPath) : resolveProjectCapletsRoot();
|
|
8866
|
+
}
|
|
8867
|
+
function resolveProjectCapletsRootForConfigPath(projectConfigPath) {
|
|
8868
|
+
return dirname(projectConfigPath);
|
|
8869
|
+
}
|
|
8870
|
+
function routePath(base, path) {
|
|
8871
|
+
return base === "/" ? `/${path}` : `${base}/${path}`;
|
|
8872
|
+
}
|
|
8873
|
+
function servicePaths(base) {
|
|
8874
|
+
return {
|
|
8875
|
+
base,
|
|
8876
|
+
mcp: routePath(base, "mcp"),
|
|
8877
|
+
control: routePath(base, "control"),
|
|
8878
|
+
health: routePath(base, "healthz")
|
|
8879
|
+
};
|
|
8880
|
+
}
|
|
8881
|
+
async function createHttpSession(engine, sessionId, options, onClose) {
|
|
8882
|
+
const transport = new StreamableHTTPTransport({
|
|
8883
|
+
sessionIdGenerator: () => sessionId,
|
|
8884
|
+
onsessionclosed: onClose,
|
|
8885
|
+
...options.loopback ? dnsRebindingOptions(options) : {}
|
|
8886
|
+
});
|
|
8887
|
+
const server = new CapletsMcpSession(engine);
|
|
8888
|
+
await server.connect(transport);
|
|
8889
|
+
return {
|
|
8890
|
+
server,
|
|
8891
|
+
transport
|
|
8892
|
+
};
|
|
8893
|
+
}
|
|
8894
|
+
function basicAuth(auth) {
|
|
8895
|
+
return async (c, next) => {
|
|
8896
|
+
if (!auth.enabled) {
|
|
8897
|
+
await next();
|
|
8898
|
+
return;
|
|
8899
|
+
}
|
|
8900
|
+
const credentials = parseBasicAuth(c.req.header("authorization") ?? "");
|
|
8901
|
+
if (!credentials || !safeEqual(credentials.user, auth.user) || !safeEqual(credentials.password, auth.password)) {
|
|
8902
|
+
c.header("www-authenticate", "Basic realm=\"caplets\"");
|
|
8903
|
+
return c.text("Unauthorized", 401);
|
|
8904
|
+
}
|
|
8905
|
+
await next();
|
|
8906
|
+
};
|
|
8907
|
+
}
|
|
8908
|
+
function parseBasicAuth(header) {
|
|
8909
|
+
const [scheme, encoded] = header.split(" ");
|
|
8910
|
+
if (scheme?.toLocaleLowerCase() !== "basic" || !encoded) return;
|
|
8911
|
+
const decoded = Buffer.from(encoded, "base64").toString("utf8");
|
|
8912
|
+
const separator = decoded.indexOf(":");
|
|
8913
|
+
if (separator < 0) return;
|
|
8914
|
+
return {
|
|
8915
|
+
user: decoded.slice(0, separator),
|
|
8916
|
+
password: decoded.slice(separator + 1)
|
|
8917
|
+
};
|
|
8918
|
+
}
|
|
8919
|
+
function safeEqual(left, right) {
|
|
8920
|
+
const leftBuffer = Buffer.from(left);
|
|
8921
|
+
const rightBuffer = Buffer.from(right);
|
|
8922
|
+
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
|
8923
|
+
}
|
|
8924
|
+
function dnsRebindingOptions(options) {
|
|
8925
|
+
const hostForHeader = options.host === "::1" ? "[::1]" : options.host;
|
|
8926
|
+
return {
|
|
8927
|
+
enableDnsRebindingProtection: true,
|
|
8928
|
+
allowedHosts: [
|
|
8929
|
+
options.host,
|
|
8930
|
+
hostForHeader,
|
|
8931
|
+
`${hostForHeader}:${options.port}`,
|
|
8932
|
+
`localhost:${options.port}`
|
|
8933
|
+
]
|
|
8934
|
+
};
|
|
8935
|
+
}
|
|
8936
|
+
function installHttpSignalHandlers(server, app, engine, writeErr) {
|
|
8937
|
+
let closing;
|
|
8938
|
+
const close = async () => {
|
|
8939
|
+
closing ??= (async () => {
|
|
8940
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
8941
|
+
await app.closeCapletsSessions();
|
|
8942
|
+
await engine.close();
|
|
8943
|
+
})();
|
|
8944
|
+
return closing;
|
|
8945
|
+
};
|
|
8946
|
+
process.once("SIGINT", () => void close().catch((error) => writeErr(`${String(error)}\n`)).finally(() => process.exit(130)));
|
|
8947
|
+
process.once("SIGTERM", () => void close().catch((error) => writeErr(`${String(error)}\n`)).finally(() => process.exit(143)));
|
|
8948
|
+
}
|
|
8949
|
+
function formatHost(host) {
|
|
8950
|
+
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
|
8951
|
+
}
|
|
8952
|
+
//#endregion
|
|
8953
|
+
//#region src/serve/options.ts
|
|
8954
|
+
const HTTP_ONLY_OPTIONS = [
|
|
8955
|
+
"host",
|
|
8956
|
+
"port",
|
|
8957
|
+
"path",
|
|
8958
|
+
"user",
|
|
8959
|
+
"password",
|
|
8960
|
+
"allowUnauthenticatedHttp",
|
|
8961
|
+
"trustProxy"
|
|
8962
|
+
];
|
|
8963
|
+
function resolveServeOptions(raw, env = process.env) {
|
|
8964
|
+
const transport = parseTransport(raw.transport ?? "stdio");
|
|
8965
|
+
if (transport === "stdio") {
|
|
8966
|
+
const invalid = HTTP_ONLY_OPTIONS.filter((key) => raw[key] !== void 0);
|
|
8967
|
+
if (invalid.length > 0) throw new CapletsError("REQUEST_INVALID", `${invalid.map((key) => `--${key}`).join(", ")} ${invalid.length === 1 ? "is" : "are"} only valid with --transport http`);
|
|
8968
|
+
return { transport };
|
|
8969
|
+
}
|
|
8970
|
+
const serverUrl = env.CAPLETS_SERVER_URL ? parseServeServerUrl(nonEmpty(env.CAPLETS_SERVER_URL, "CAPLETS_SERVER_URL")) : void 0;
|
|
8971
|
+
const host = nonEmpty(raw.host, "--host") ?? serverUrlHost(serverUrl) ?? "127.0.0.1";
|
|
8972
|
+
const port = parsePort(raw.port ?? (serverUrl?.port ? Number(serverUrl.port) : 5387));
|
|
8973
|
+
const path = normalizeHttpPath(raw.path ?? serverUrl?.pathname ?? "/");
|
|
8974
|
+
const userWasExplicit = raw.user !== void 0 || hasEnv(env.CAPLETS_SERVER_USER);
|
|
8975
|
+
const user = nonEmpty(raw.user, "--user") ?? nonEmpty(env.CAPLETS_SERVER_USER, "CAPLETS_SERVER_USER") ?? "caplets";
|
|
8976
|
+
const password = nonEmpty(raw.password, "--password") ?? nonEmpty(env.CAPLETS_SERVER_PASSWORD, "CAPLETS_SERVER_PASSWORD");
|
|
8977
|
+
if (userWasExplicit && password === void 0) throw new CapletsError("REQUEST_INVALID", "HTTP Basic Auth requires a password; pass --password or set CAPLETS_SERVER_PASSWORD.");
|
|
8978
|
+
const loopback = isLoopbackHost(host);
|
|
8979
|
+
const auth = password === void 0 ? {
|
|
8980
|
+
enabled: false,
|
|
8981
|
+
user
|
|
8982
|
+
} : {
|
|
8983
|
+
enabled: true,
|
|
8984
|
+
user,
|
|
8985
|
+
password
|
|
8986
|
+
};
|
|
8987
|
+
if (!loopback && !auth.enabled && raw.allowUnauthenticatedHttp !== true) throw new CapletsError("REQUEST_INVALID", "Unauthenticated HTTP serving on non-loopback hosts requires --allow-unauthenticated-http.");
|
|
8988
|
+
return {
|
|
8989
|
+
transport,
|
|
8990
|
+
host,
|
|
8991
|
+
port,
|
|
8992
|
+
path,
|
|
8993
|
+
auth,
|
|
8994
|
+
warnUnauthenticatedNetwork: !loopback && !auth.enabled,
|
|
8995
|
+
loopback,
|
|
8996
|
+
trustProxy: raw.trustProxy === true
|
|
8997
|
+
};
|
|
8998
|
+
}
|
|
8999
|
+
function isLoopbackHost(host) {
|
|
9000
|
+
const normalized = host.toLocaleLowerCase();
|
|
9001
|
+
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
|
9002
|
+
}
|
|
9003
|
+
function parseServeServerUrl(value) {
|
|
9004
|
+
try {
|
|
9005
|
+
return parseServerBaseUrl(value);
|
|
9006
|
+
} catch (error) {
|
|
9007
|
+
if (error instanceof CapletsError && error.message.includes("must use https except loopback development URLs")) throw new CapletsError("REQUEST_INVALID", "CAPLETS_SERVER_URL must use https except loopback development URLs; use --host, --port, and --path separately for non-loopback HTTP bind addresses.");
|
|
9008
|
+
throw error;
|
|
9009
|
+
}
|
|
9010
|
+
}
|
|
9011
|
+
function parseTransport(value) {
|
|
9012
|
+
if (value === "stdio" || value === "http") return value;
|
|
9013
|
+
throw new CapletsError("REQUEST_INVALID", `Expected --transport to be stdio or http, got ${value}`);
|
|
9014
|
+
}
|
|
9015
|
+
function parsePort(value) {
|
|
9016
|
+
const parsed = typeof value === "number" ? value : Number(value);
|
|
9017
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) throw new CapletsError("REQUEST_INVALID", `Expected --port to be a valid TCP port, got ${value}`);
|
|
9018
|
+
return parsed;
|
|
9019
|
+
}
|
|
9020
|
+
function normalizeHttpPath(value) {
|
|
9021
|
+
if (!value.startsWith("/")) throw new CapletsError("REQUEST_INVALID", "HTTP --path must start with /");
|
|
9022
|
+
if (value.includes("?") || value.includes("#")) throw new CapletsError("REQUEST_INVALID", "HTTP --path must not include a query string or fragment");
|
|
9023
|
+
return value === "/" ? value : value.replace(/\/+$/u, "");
|
|
9024
|
+
}
|
|
9025
|
+
function serverUrlHost(url) {
|
|
9026
|
+
return url?.hostname.replace(/^\[(.*)\]$/u, "$1");
|
|
9027
|
+
}
|
|
9028
|
+
function nonEmpty(value, label) {
|
|
9029
|
+
if (value === void 0) return;
|
|
9030
|
+
const trimmed = value.trim();
|
|
9031
|
+
if (!trimmed) throw new CapletsError("REQUEST_INVALID", `${label} must not be empty`);
|
|
9032
|
+
return trimmed;
|
|
9033
|
+
}
|
|
9034
|
+
function hasEnv(value) {
|
|
9035
|
+
return value !== void 0 && value.trim() !== "";
|
|
9036
|
+
}
|
|
9037
|
+
//#endregion
|
|
9038
|
+
//#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
9039
|
+
/**
|
|
9040
|
+
* Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.
|
|
9041
|
+
*
|
|
9042
|
+
* This transport is only available in Node.js environments.
|
|
9043
|
+
*/
|
|
9044
|
+
var StdioServerTransport = class {
|
|
9045
|
+
constructor(_stdin = process$1.stdin, _stdout = process$1.stdout) {
|
|
9046
|
+
this._stdin = _stdin;
|
|
9047
|
+
this._stdout = _stdout;
|
|
9048
|
+
this._readBuffer = new ReadBuffer();
|
|
9049
|
+
this._started = false;
|
|
9050
|
+
this._ondata = (chunk) => {
|
|
9051
|
+
this._readBuffer.append(chunk);
|
|
9052
|
+
this.processReadBuffer();
|
|
9053
|
+
};
|
|
9054
|
+
this._onerror = (error) => {
|
|
9055
|
+
this.onerror?.(error);
|
|
9056
|
+
};
|
|
9057
|
+
}
|
|
9058
|
+
/**
|
|
9059
|
+
* Starts listening for messages on stdin.
|
|
9060
|
+
*/
|
|
9061
|
+
async start() {
|
|
9062
|
+
if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
|
|
9063
|
+
this._started = true;
|
|
9064
|
+
this._stdin.on("data", this._ondata);
|
|
9065
|
+
this._stdin.on("error", this._onerror);
|
|
9066
|
+
}
|
|
9067
|
+
processReadBuffer() {
|
|
9068
|
+
while (true) try {
|
|
9069
|
+
const message = this._readBuffer.readMessage();
|
|
9070
|
+
if (message === null) break;
|
|
9071
|
+
this.onmessage?.(message);
|
|
9072
|
+
} catch (error) {
|
|
9073
|
+
this.onerror?.(error);
|
|
9074
|
+
}
|
|
9075
|
+
}
|
|
9076
|
+
async close() {
|
|
9077
|
+
this._stdin.off("data", this._ondata);
|
|
9078
|
+
this._stdin.off("error", this._onerror);
|
|
9079
|
+
if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
|
|
9080
|
+
this._readBuffer.clear();
|
|
9081
|
+
this.onclose?.();
|
|
9082
|
+
}
|
|
9083
|
+
send(message) {
|
|
9084
|
+
return new Promise((resolve) => {
|
|
9085
|
+
const json = serializeMessage(message);
|
|
9086
|
+
if (this._stdout.write(json)) resolve();
|
|
9087
|
+
else this._stdout.once("drain", resolve);
|
|
9088
|
+
});
|
|
9089
|
+
}
|
|
9090
|
+
};
|
|
9091
|
+
//#endregion
|
|
9092
|
+
//#region src/serve/stdio.ts
|
|
9093
|
+
async function serveStdio(options = {}) {
|
|
9094
|
+
const engine = new CapletsEngine(options);
|
|
9095
|
+
const session = new CapletsMcpSession(engine);
|
|
9096
|
+
let closing = false;
|
|
9097
|
+
const close = async () => {
|
|
9098
|
+
if (closing) return;
|
|
9099
|
+
closing = true;
|
|
9100
|
+
try {
|
|
9101
|
+
await session.close();
|
|
9102
|
+
} finally {
|
|
9103
|
+
await engine.close();
|
|
9104
|
+
}
|
|
9105
|
+
};
|
|
9106
|
+
let sigintHandler;
|
|
9107
|
+
let sigtermHandler;
|
|
9108
|
+
if (options.signalHandling !== false) {
|
|
9109
|
+
sigintHandler = () => void close().finally(() => process.exit(130));
|
|
9110
|
+
sigtermHandler = () => void close().finally(() => process.exit(143));
|
|
9111
|
+
process.once("SIGINT", sigintHandler);
|
|
9112
|
+
process.once("SIGTERM", sigtermHandler);
|
|
9113
|
+
}
|
|
9114
|
+
try {
|
|
9115
|
+
await session.connect(new StdioServerTransport());
|
|
9116
|
+
} finally {
|
|
9117
|
+
if (sigintHandler) process.off("SIGINT", sigintHandler);
|
|
9118
|
+
if (sigtermHandler) process.off("SIGTERM", sigtermHandler);
|
|
9119
|
+
await close();
|
|
9120
|
+
}
|
|
9121
|
+
}
|
|
9122
|
+
//#endregion
|
|
9123
|
+
//#region src/serve/index.ts
|
|
9124
|
+
async function serveCaplets(options) {
|
|
9125
|
+
await serveResolvedCaplets(resolveServeOptions(options.raw, options.env ?? process.env), options.engine, options.writeErr);
|
|
9126
|
+
}
|
|
9127
|
+
async function serveResolvedCaplets(resolved, engineOptions = {}, writeErr) {
|
|
9128
|
+
if (resolved.transport === "stdio") {
|
|
9129
|
+
await serveStdio({
|
|
9130
|
+
...engineOptions,
|
|
9131
|
+
...writeErr ? { writeErr } : {}
|
|
9132
|
+
});
|
|
9133
|
+
return;
|
|
9134
|
+
}
|
|
9135
|
+
await serveHttp(resolved, {
|
|
9136
|
+
...engineOptions,
|
|
9137
|
+
...writeErr ? { writeErr } : {}
|
|
9138
|
+
}, writeErr);
|
|
9139
|
+
}
|
|
9140
|
+
//#endregion
|
|
9141
|
+
//#region src/cli.ts
|
|
9142
|
+
async function runCli(args, io = {}) {
|
|
9143
|
+
const program = createProgram(io);
|
|
9144
|
+
try {
|
|
9145
|
+
if (args.length === 0) {
|
|
9146
|
+
program.outputHelp();
|
|
9147
|
+
return;
|
|
9148
|
+
}
|
|
9149
|
+
await program.parseAsync([
|
|
9150
|
+
"node",
|
|
9151
|
+
"caplets",
|
|
9152
|
+
...args
|
|
9153
|
+
]);
|
|
9154
|
+
} catch (error) {
|
|
9155
|
+
if (error instanceof CommanderError) {
|
|
9156
|
+
if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.message === "(outputHelp)") return;
|
|
9157
|
+
throw new CapletsError("REQUEST_INVALID", error.message);
|
|
9158
|
+
}
|
|
9159
|
+
throw error;
|
|
9160
|
+
}
|
|
9161
|
+
}
|
|
9162
|
+
function createProgram(io = {}) {
|
|
9163
|
+
const writeOut = io.writeOut ?? ((value) => process.stdout.write(value));
|
|
9164
|
+
const writeErr = io.writeErr ?? ((value) => process.stderr.write(value));
|
|
9165
|
+
const env = io.env ?? process.env;
|
|
9166
|
+
const currentConfigPath = () => envConfigPath(env);
|
|
9167
|
+
const setExitCode = io.setExitCode ?? ((code) => {
|
|
9168
|
+
process.exitCode = code;
|
|
9169
|
+
});
|
|
9170
|
+
const program = new Command();
|
|
9171
|
+
program.name("caplets").description("Progressive-disclosure gateway for MCP servers.").version(io.version ?? version).exitOverride().configureOutput({
|
|
9172
|
+
writeOut,
|
|
9173
|
+
writeErr,
|
|
9174
|
+
outputError: (value, write) => write(value)
|
|
9175
|
+
});
|
|
9176
|
+
program.command("serve").description("Serve configured Caplets as an MCP server.").option("--transport <transport>", "server transport: stdio or http").option("--host <host>", "HTTP bind host").option("--port <port>", "HTTP bind port").option("--path <path>", "HTTP service base path").option("--user <user>", "HTTP Basic Auth username").option("--password <password>", "HTTP Basic Auth password").option("--allow-unauthenticated-http", "allow unauthenticated HTTP serving on non-loopback hosts").option("--trust-proxy", "trust X-Forwarded-* headers from a reverse proxy").action(async (options) => {
|
|
9177
|
+
const resolved = resolveServeOptions(options);
|
|
9178
|
+
const configPath = currentConfigPath();
|
|
9179
|
+
await (io.serve ?? ((serveOptions) => serveResolvedCaplets(serveOptions, {
|
|
9180
|
+
...configPath ? { configPath } : {},
|
|
9181
|
+
...io.authDir ? { authDir: io.authDir } : {}
|
|
9182
|
+
}, writeErr)))(resolved);
|
|
9183
|
+
});
|
|
9184
|
+
program.command("init").description("Create a starter Caplets config file.").option("--force", "overwrite an existing config file").action(async (options) => {
|
|
9185
|
+
const remote = remoteClientForCli(io);
|
|
9186
|
+
if (remote) {
|
|
9187
|
+
writeOut(`Created remote Caplets config at ${(await remote.request("init", { force: Boolean(options.force) })).path}\n`);
|
|
9188
|
+
return;
|
|
9189
|
+
}
|
|
9190
|
+
const configPath = currentConfigPath();
|
|
9191
|
+
writeOut(`Created Caplets config at ${initConfig({
|
|
9192
|
+
...configPath ? { path: configPath } : {},
|
|
9193
|
+
force: Boolean(options.force)
|
|
9194
|
+
})}\n`);
|
|
9195
|
+
});
|
|
9196
|
+
program.command("list").description("List configured Caplets.").option("--all", "include disabled Caplets").option("--json", "print JSON output").option("--format <format>", "output format: plain, markdown, md, or json", parseOutputFormat).action(async (options) => {
|
|
9197
|
+
const includeDisabled = Boolean(options.all);
|
|
9198
|
+
const remote = remoteClientForCli(io);
|
|
9199
|
+
if (remote) {
|
|
9200
|
+
const rows = await remote.request("list", { includeDisabled });
|
|
9201
|
+
if (options.json || options.format === "json") {
|
|
9202
|
+
writeOut(`${JSON.stringify(rows, null, 2)}\n`);
|
|
9203
|
+
return;
|
|
9204
|
+
}
|
|
9205
|
+
writeOut(formatCapletList(rows, options.format ?? "plain"));
|
|
9206
|
+
return;
|
|
9207
|
+
}
|
|
9208
|
+
const rows = listCaplets(loadConfigWithSources(currentConfigPath()), { includeDisabled });
|
|
9209
|
+
if (options.json || options.format === "json") {
|
|
9210
|
+
writeOut(`${JSON.stringify(rows, null, 2)}\n`);
|
|
9211
|
+
return;
|
|
9212
|
+
}
|
|
9213
|
+
writeOut(formatCapletList(rows, options.format ?? "plain"));
|
|
9214
|
+
});
|
|
9215
|
+
program.command("install").description("Install Caplets from a repo's caplets directory.").argument("<repo>", "local repo path, Git URL, or GitHub owner/repo").argument("[caplets...]", "optional Caplet IDs to install").option("-g, --global", "install to the user Caplets root").option("--force", "overwrite installed Caplets").action(async (repo, capletIds, options) => {
|
|
9216
|
+
const remote = remoteClientForCli(io);
|
|
9217
|
+
if (remote) {
|
|
9218
|
+
if (options.global) writeErr("Warning: --global is not supported in remote mode; the server controls the installation destination.\n");
|
|
9219
|
+
const result = await remote.request("install", {
|
|
9220
|
+
repo,
|
|
9221
|
+
capletIds,
|
|
9222
|
+
force: Boolean(options.force)
|
|
9223
|
+
});
|
|
9224
|
+
for (const caplet of result.installed) writeOut(`Installed ${caplet.id} to remote ${caplet.destination}\n`);
|
|
9225
|
+
return;
|
|
9226
|
+
}
|
|
9227
|
+
const result = installCaplets(repo, {
|
|
9228
|
+
capletIds,
|
|
9229
|
+
force: Boolean(options.force),
|
|
9230
|
+
destinationRoot: options.global ? resolveCapletsRoot(resolveConfigPath(currentConfigPath())) : resolveProjectCapletsRoot()
|
|
9231
|
+
});
|
|
9232
|
+
for (const caplet of result.installed) writeOut(`Installed ${caplet.id} to ${caplet.destination}\n`);
|
|
9233
|
+
});
|
|
9234
|
+
const add = program.command("add").description("Add generated Caplet files.");
|
|
9235
|
+
add.command("cli").description("Add a CLI tools Caplet.").argument("<id>", "Caplet ID/display seed").option("--repo <path>", "repository path to inspect").option("--include <items>", "comma-separated generators to include: git,gh,package").option("--command <name>", "single CLI command template to generate").option("-g, --global", "write to the user Caplets root").option("--print", "print generated Caplet text without writing a file").option("--output <path>", "output path").option("--force", "overwrite an existing destination file").action(async (id, options) => {
|
|
9236
|
+
const remote = remoteClientForCli(io);
|
|
9237
|
+
if (remote) {
|
|
9238
|
+
writeAddResult(writeOut, "CLI", await remote.request("add", {
|
|
9239
|
+
kind: "cli",
|
|
9240
|
+
id,
|
|
9241
|
+
options: remoteAddOptions(options)
|
|
9242
|
+
}));
|
|
9243
|
+
return;
|
|
9244
|
+
}
|
|
9245
|
+
const result = addCliCaplet(id, {
|
|
9246
|
+
...options,
|
|
9247
|
+
destinationRoot: options.global ? resolveCapletsRoot(resolveConfigPath(currentConfigPath())) : resolveProjectCapletsRoot()
|
|
9248
|
+
});
|
|
9249
|
+
if (result.path) {
|
|
9250
|
+
writeOut(`Wrote CLI Caplet to ${result.path}\n`);
|
|
9251
|
+
return;
|
|
9252
|
+
}
|
|
9253
|
+
writeOut(result.text);
|
|
9254
|
+
});
|
|
9255
|
+
add.command("mcp").description("Add an MCP backend Caplet.").argument("<id>", "Caplet ID/display seed").option("--command <name>", "stdio command").option("--arg <value>", "stdio command argument", collect, []).option("--cwd <path>", "stdio working directory").option("--env <KEY=VALUE>", "stdio environment variable", collect, []).option("--url <url>", "remote MCP server URL").option("--transport <transport>", "remote transport: http or sse").option("--token-env <ENV>", "bearer token environment variable reference").option("-g, --global", "write to the user Caplets root").option("--print", "print generated Caplet text without writing a file").option("--output <path>", "output path").option("--force", "overwrite an existing destination file").action(async (id, options) => {
|
|
9256
|
+
const remote = remoteClientForCli(io);
|
|
9257
|
+
if (remote) {
|
|
9258
|
+
writeAddResult(writeOut, "MCP", await remote.request("add", {
|
|
9259
|
+
kind: "mcp",
|
|
9260
|
+
id,
|
|
9261
|
+
options: remoteAddOptions(options)
|
|
9262
|
+
}));
|
|
9263
|
+
return;
|
|
9264
|
+
}
|
|
9265
|
+
writeAddResult(writeOut, "MCP", addMcpCaplet(id, {
|
|
9266
|
+
...options,
|
|
9267
|
+
destinationRoot: addDestinationRoot(options, currentConfigPath())
|
|
9268
|
+
}));
|
|
9269
|
+
});
|
|
9270
|
+
add.command("openapi").description("Add an OpenAPI backend Caplet.").argument("<id>", "Caplet ID/display seed").option("--spec <path-or-url>", "OpenAPI spec path or URL").option("--base-url <url>", "request base URL override").option("--token-env <ENV>", "bearer token environment variable reference").option("-g, --global", "write to the user Caplets root").option("--print", "print generated Caplet text without writing a file").option("--output <path>", "output path").option("--force", "overwrite an existing destination file").action(async (id, options) => {
|
|
9271
|
+
const remote = remoteClientForCli(io);
|
|
9272
|
+
if (remote) {
|
|
9273
|
+
writeAddResult(writeOut, "OpenAPI", await remote.request("add", {
|
|
9274
|
+
kind: "openapi",
|
|
9275
|
+
id,
|
|
9276
|
+
options: remoteAddOptions(options)
|
|
9277
|
+
}));
|
|
9278
|
+
return;
|
|
9279
|
+
}
|
|
9280
|
+
writeAddResult(writeOut, "OpenAPI", addOpenApiCaplet(id, {
|
|
9281
|
+
...options,
|
|
9282
|
+
destinationRoot: addDestinationRoot(options, currentConfigPath())
|
|
9283
|
+
}));
|
|
9284
|
+
});
|
|
9285
|
+
add.command("graphql").description("Add a GraphQL backend Caplet.").argument("<id>", "Caplet ID/display seed").option("--endpoint-url <url>", "GraphQL endpoint URL").option("--schema <path-or-url>", "GraphQL schema path or URL").option("--introspection", "load schema through endpoint introspection").option("--token-env <ENV>", "bearer token environment variable reference").option("-g, --global", "write to the user Caplets root").option("--print", "print generated Caplet text without writing a file").option("--output <path>", "output path").option("--force", "overwrite an existing destination file").action(async (id, options) => {
|
|
9286
|
+
const remote = remoteClientForCli(io);
|
|
9287
|
+
if (remote) {
|
|
9288
|
+
writeAddResult(writeOut, "GraphQL", await remote.request("add", {
|
|
9289
|
+
kind: "graphql",
|
|
9290
|
+
id,
|
|
9291
|
+
options: remoteAddOptions(options)
|
|
9292
|
+
}));
|
|
9293
|
+
return;
|
|
9294
|
+
}
|
|
9295
|
+
writeAddResult(writeOut, "GraphQL", addGraphqlCaplet(id, {
|
|
9296
|
+
...options,
|
|
9297
|
+
destinationRoot: addDestinationRoot(options, currentConfigPath())
|
|
9298
|
+
}));
|
|
9299
|
+
});
|
|
9300
|
+
add.command("http").description("Add an HTTP actions backend Caplet.").argument("<id>", "Caplet ID/display seed").option("--base-url <url>", "HTTP API base URL").option("--action <name:METHOD:/path>", "HTTP action", collect, []).option("--token-env <ENV>", "bearer token environment variable reference").option("-g, --global", "write to the user Caplets root").option("--print", "print generated Caplet text without writing a file").option("--output <path>", "output path").option("--force", "overwrite an existing destination file").action(async (id, options) => {
|
|
9301
|
+
const remote = remoteClientForCli(io);
|
|
9302
|
+
if (remote) {
|
|
9303
|
+
writeAddResult(writeOut, "HTTP", await remote.request("add", {
|
|
9304
|
+
kind: "http",
|
|
9305
|
+
id,
|
|
9306
|
+
options: remoteAddOptions(options)
|
|
9307
|
+
}));
|
|
9308
|
+
return;
|
|
9309
|
+
}
|
|
9310
|
+
writeAddResult(writeOut, "HTTP", addHttpCaplet(id, {
|
|
9311
|
+
...options,
|
|
9312
|
+
destinationRoot: addDestinationRoot(options, currentConfigPath())
|
|
9313
|
+
}));
|
|
9314
|
+
});
|
|
9315
|
+
program.command("get-caplet").description("Print a configured Caplet card.").argument("<caplet>", "configured Caplet ID").option("--format <format>", "output format: markdown, md, plain, or json", parseOutputFormat).action(async (caplet, options) => {
|
|
9316
|
+
await executeOperation(caplet, { operation: "get_caplet" }, {
|
|
9317
|
+
writeOut,
|
|
9318
|
+
writeErr,
|
|
9319
|
+
setExitCode,
|
|
9320
|
+
authDir: io.authDir,
|
|
9321
|
+
env,
|
|
9322
|
+
remote: remoteClientForCli(io),
|
|
9323
|
+
format: options.format
|
|
9324
|
+
});
|
|
9325
|
+
});
|
|
9326
|
+
program.command("check-backend").description("Check backend availability for a configured Caplet.").argument("<caplet>", "configured Caplet ID").option("--format <format>", "output format: markdown, md, plain, or json", parseOutputFormat).action(async (caplet, options) => {
|
|
9327
|
+
await executeOperation(caplet, { operation: "check_backend" }, {
|
|
9328
|
+
writeOut,
|
|
9329
|
+
writeErr,
|
|
9330
|
+
setExitCode,
|
|
9331
|
+
authDir: io.authDir,
|
|
9332
|
+
env,
|
|
9333
|
+
remote: remoteClientForCli(io),
|
|
9334
|
+
format: options.format
|
|
9335
|
+
});
|
|
9336
|
+
});
|
|
9337
|
+
program.command("list-tools").description("List downstream tools for a configured Caplet.").argument("<caplet>", "configured Caplet ID").option("--format <format>", "output format: markdown, md, plain, or json", parseOutputFormat).action(async (caplet, options) => {
|
|
9338
|
+
await executeOperation(caplet, { operation: "list_tools" }, {
|
|
9339
|
+
writeOut,
|
|
9340
|
+
writeErr,
|
|
9341
|
+
setExitCode,
|
|
9342
|
+
authDir: io.authDir,
|
|
9343
|
+
env,
|
|
9344
|
+
remote: remoteClientForCli(io),
|
|
9345
|
+
format: options.format
|
|
9346
|
+
});
|
|
9347
|
+
});
|
|
9348
|
+
program.command("search-tools").description("Search downstream tools for a configured Caplet.").argument("<caplet>", "configured Caplet ID").argument("<query>", "search query").option("--limit <n>", "maximum number of tools to return", parsePositiveInteger).option("--format <format>", "output format: markdown, md, plain, or json", parseOutputFormat).action(async (caplet, query, options) => {
|
|
9349
|
+
await executeOperation(caplet, options.limit === void 0 ? {
|
|
9350
|
+
operation: "search_tools",
|
|
9351
|
+
query
|
|
9352
|
+
} : {
|
|
9353
|
+
operation: "search_tools",
|
|
9354
|
+
query,
|
|
9355
|
+
limit: options.limit
|
|
5483
9356
|
}, {
|
|
5484
9357
|
writeOut,
|
|
5485
9358
|
writeErr,
|
|
5486
9359
|
setExitCode,
|
|
5487
9360
|
authDir: io.authDir,
|
|
9361
|
+
env,
|
|
9362
|
+
remote: remoteClientForCli(io),
|
|
5488
9363
|
format: options.format
|
|
5489
9364
|
});
|
|
5490
9365
|
});
|
|
@@ -5498,6 +9373,8 @@ function createProgram(io = {}) {
|
|
|
5498
9373
|
writeErr,
|
|
5499
9374
|
setExitCode,
|
|
5500
9375
|
authDir: io.authDir,
|
|
9376
|
+
env,
|
|
9377
|
+
remote: remoteClientForCli(io),
|
|
5501
9378
|
format: options.format
|
|
5502
9379
|
});
|
|
5503
9380
|
});
|
|
@@ -5513,15 +9390,17 @@ function createProgram(io = {}) {
|
|
|
5513
9390
|
writeErr,
|
|
5514
9391
|
setExitCode,
|
|
5515
9392
|
authDir: io.authDir,
|
|
9393
|
+
env,
|
|
9394
|
+
remote: remoteClientForCli(io),
|
|
5516
9395
|
format: options.format
|
|
5517
9396
|
});
|
|
5518
9397
|
});
|
|
5519
9398
|
const config = program.command("config").description("Inspect Caplets config locations.");
|
|
5520
9399
|
config.command("path").description("Print the effective user config path.").action(() => {
|
|
5521
|
-
writeOut(`${resolveConfigPath(
|
|
9400
|
+
writeOut(`${resolveConfigPath(currentConfigPath())}\n`);
|
|
5522
9401
|
});
|
|
5523
9402
|
config.command("paths").description("Print resolved Caplets config, root, and auth paths.").option("--json", "print JSON output").option("--format <format>", "output format: plain, markdown, md, or json", parseOutputFormat).action((options) => {
|
|
5524
|
-
const paths = resolveCliConfigPaths(
|
|
9403
|
+
const paths = resolveCliConfigPaths(currentConfigPath(), io.authDir);
|
|
5525
9404
|
if (options.json || options.format === "json") {
|
|
5526
9405
|
writeOut(`${JSON.stringify(paths, null, 2)}\n`);
|
|
5527
9406
|
return;
|
|
@@ -5530,7 +9409,19 @@ function createProgram(io = {}) {
|
|
|
5530
9409
|
});
|
|
5531
9410
|
const auth = program.command("auth").description("Manage OAuth credentials for remote servers.");
|
|
5532
9411
|
auth.command("login").description("Authenticate a configured remote OAuth server.").argument("<server>", "configured server ID").option("--no-open", "print the authorization URL without opening a browser").action(async (serverId, options) => {
|
|
5533
|
-
const
|
|
9412
|
+
const remote = remoteClientForCli(io);
|
|
9413
|
+
if (remote) {
|
|
9414
|
+
const started = await remote.request("auth_login_start", { server: serverId });
|
|
9415
|
+
if (started.authorizationUrl) {
|
|
9416
|
+
writeOut(`Open this URL to authorize ${serverId}:\n${started.authorizationUrl}\n`);
|
|
9417
|
+
if (options.open !== false) await openBrowser(started.authorizationUrl);
|
|
9418
|
+
writeOut("Complete authentication in your browser. The server callback will store credentials.\n");
|
|
9419
|
+
return;
|
|
9420
|
+
}
|
|
9421
|
+
if (started.authenticated) writeOut(`Authenticated \`${serverId}\`.\n`);
|
|
9422
|
+
return;
|
|
9423
|
+
}
|
|
9424
|
+
const configPath = currentConfigPath();
|
|
5534
9425
|
await loginAuth(serverId, {
|
|
5535
9426
|
noOpen: options.open === false,
|
|
5536
9427
|
writeOut,
|
|
@@ -5539,27 +9430,78 @@ function createProgram(io = {}) {
|
|
|
5539
9430
|
...io.authDir ? { authDir: io.authDir } : {}
|
|
5540
9431
|
});
|
|
5541
9432
|
});
|
|
5542
|
-
auth.command("logout").description("Delete stored OAuth credentials for a server.").argument("<server>", "configured server ID").action((serverId) => {
|
|
5543
|
-
const
|
|
9433
|
+
auth.command("logout").description("Delete stored OAuth credentials for a server.").argument("<server>", "configured server ID").action(async (serverId) => {
|
|
9434
|
+
const remote = remoteClientForCli(io);
|
|
9435
|
+
if (remote) {
|
|
9436
|
+
writeOut((await remote.request("auth_logout", { server: serverId })).deleted ? `Deleted remote OAuth credentials for \`${serverId}\`.\n` : `No remote OAuth credentials found for \`${serverId}\`.\n`);
|
|
9437
|
+
return;
|
|
9438
|
+
}
|
|
9439
|
+
const configPath = currentConfigPath();
|
|
5544
9440
|
logoutAuth(serverId, {
|
|
5545
9441
|
writeOut,
|
|
5546
9442
|
...configPath ? { configPath } : {},
|
|
5547
9443
|
...io.authDir ? { authDir: io.authDir } : {}
|
|
5548
9444
|
});
|
|
5549
9445
|
});
|
|
5550
|
-
auth.command("list").description("List servers with stored OAuth credentials.").option("--json", "print JSON output").option("--format <format>", "output format: plain, markdown, md, or json", parseOutputFormat).action((options) => {
|
|
5551
|
-
const configPath =
|
|
9446
|
+
auth.command("list").description("List servers with stored OAuth credentials.").option("--json", "print JSON output").option("--format <format>", "output format: plain, markdown, md, or json", parseOutputFormat).action(async (options) => {
|
|
9447
|
+
const configPath = currentConfigPath();
|
|
9448
|
+
const format = options.json || options.format === "json" ? "json" : options.format ?? "plain";
|
|
9449
|
+
const remote = remoteClientForCli(io);
|
|
9450
|
+
if (remote) {
|
|
9451
|
+
const rows = await remote.request("auth_list", {});
|
|
9452
|
+
if (format === "json") {
|
|
9453
|
+
writeOut(`${JSON.stringify(rows, null, 2)}\n`);
|
|
9454
|
+
return;
|
|
9455
|
+
}
|
|
9456
|
+
writeOut(formatAuthRows(rows, format));
|
|
9457
|
+
return;
|
|
9458
|
+
}
|
|
5552
9459
|
listAuth({
|
|
5553
9460
|
writeOut,
|
|
5554
|
-
format
|
|
9461
|
+
format,
|
|
5555
9462
|
...configPath ? { configPath } : {},
|
|
5556
9463
|
...io.authDir ? { authDir: io.authDir } : {}
|
|
5557
9464
|
});
|
|
5558
9465
|
});
|
|
5559
9466
|
return program;
|
|
5560
9467
|
}
|
|
5561
|
-
function envConfigPath() {
|
|
5562
|
-
return
|
|
9468
|
+
function envConfigPath(env) {
|
|
9469
|
+
return env.CAPLETS_CONFIG?.trim() || void 0;
|
|
9470
|
+
}
|
|
9471
|
+
function remoteClientForCli(io) {
|
|
9472
|
+
const env = io.env ?? process.env;
|
|
9473
|
+
if (resolveCapletsMode({}, env).mode !== "remote") return;
|
|
9474
|
+
return new RemoteControlClient(resolveCapletsServer(io.fetch ? { fetch: io.fetch } : {}, env));
|
|
9475
|
+
}
|
|
9476
|
+
async function openBrowser(url) {
|
|
9477
|
+
const { spawn } = await import("node:child_process");
|
|
9478
|
+
spawn(process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open", process.platform === "win32" ? [
|
|
9479
|
+
"/c",
|
|
9480
|
+
"start",
|
|
9481
|
+
"",
|
|
9482
|
+
url
|
|
9483
|
+
] : [url], {
|
|
9484
|
+
stdio: "ignore",
|
|
9485
|
+
detached: true
|
|
9486
|
+
}).unref();
|
|
9487
|
+
}
|
|
9488
|
+
function remoteCommandForOperation(operation) {
|
|
9489
|
+
switch (operation) {
|
|
9490
|
+
case "get_caplet":
|
|
9491
|
+
case "check_backend":
|
|
9492
|
+
case "list_tools":
|
|
9493
|
+
case "search_tools":
|
|
9494
|
+
case "get_tool":
|
|
9495
|
+
case "call_tool": return operation;
|
|
9496
|
+
default: return;
|
|
9497
|
+
}
|
|
9498
|
+
}
|
|
9499
|
+
function remoteAddOptions(options) {
|
|
9500
|
+
const { output, print, global, destinationRoot, ...remoteOptions } = options;
|
|
9501
|
+
if (global) throw new CapletsError("REQUEST_INVALID", "--global is not supported in remote mode; the server controls the add destination.");
|
|
9502
|
+
if (print) throw new CapletsError("REQUEST_INVALID", "--print is not supported in remote mode; the server controls add output.");
|
|
9503
|
+
if (output !== void 0) throw new CapletsError("REQUEST_INVALID", "--output is not supported in remote mode; the server controls the add destination.");
|
|
9504
|
+
return remoteOptions;
|
|
5563
9505
|
}
|
|
5564
9506
|
function collect(value, previous) {
|
|
5565
9507
|
previous.push(value);
|
|
@@ -5602,7 +9544,21 @@ function isPlainObject(value) {
|
|
|
5602
9544
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5603
9545
|
}
|
|
5604
9546
|
async function executeOperation(caplet, request, io) {
|
|
5605
|
-
const
|
|
9547
|
+
const command = remoteCommandForOperation(request.operation);
|
|
9548
|
+
if (io.remote && command) {
|
|
9549
|
+
const result = await io.remote.request(command, {
|
|
9550
|
+
caplet,
|
|
9551
|
+
request
|
|
9552
|
+
});
|
|
9553
|
+
const output = cliOutputForOperation(result, {
|
|
9554
|
+
...request,
|
|
9555
|
+
caplet
|
|
9556
|
+
}, io.format ?? "markdown");
|
|
9557
|
+
io.writeOut(typeof output === "string" ? `${output}\n` : `${JSON.stringify(output, null, 2)}\n`);
|
|
9558
|
+
if (isPlainObject(result) && result.isError === true) io.setExitCode(1);
|
|
9559
|
+
return;
|
|
9560
|
+
}
|
|
9561
|
+
const configPath = envConfigPath(io.env ?? process.env);
|
|
5606
9562
|
const engine = new CapletsEngine({
|
|
5607
9563
|
...configPath ? { configPath } : {},
|
|
5608
9564
|
...io.authDir ? { authDir: io.authDir } : {},
|
|
@@ -5848,15 +9804,15 @@ function schemaSummary(schema) {
|
|
|
5848
9804
|
required.length > 0 ? `required ${required.join(", ")}` : "no required fields"
|
|
5849
9805
|
].filter((part) => Boolean(part)).join("; ");
|
|
5850
9806
|
}
|
|
5851
|
-
function addDestinationRoot(options) {
|
|
5852
|
-
return options.global ? resolveCapletsRoot(resolveConfigPath(
|
|
9807
|
+
function addDestinationRoot(options, configPath) {
|
|
9808
|
+
return options.global ? resolveCapletsRoot(resolveConfigPath(configPath)) : resolveProjectCapletsRoot();
|
|
5853
9809
|
}
|
|
5854
9810
|
function writeAddResult(writeOut, label, result) {
|
|
5855
9811
|
if (result.path) {
|
|
5856
|
-
writeOut(`Wrote ${label} Caplet to ${result.path}\n`);
|
|
9812
|
+
writeOut(`Wrote ${result.remote ? "remote " : ""}${label} Caplet to ${result.path}\n`);
|
|
5857
9813
|
return;
|
|
5858
9814
|
}
|
|
5859
9815
|
writeOut(result.text);
|
|
5860
9816
|
}
|
|
5861
9817
|
//#endregion
|
|
5862
|
-
export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, loadConfig, parseConfig, runCli };
|
|
9818
|
+
export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, loadConfig, parseConfig, runCli, serveCaplets, serveHttp, serveResolvedCaplets, serveStdio };
|