@feynmanzhang/open-party 0.1.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/LICENSE +21 -0
- package/dist/claude-code/open-party-0.1.0/.claude-plugin/plugin.json +5 -0
- package/dist/claude-code/open-party-0.1.0/.mcp.json +9 -0
- package/dist/cli/index.js +5414 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/hook-handler.js +548 -0
- package/dist/hook-handler.js.map +1 -0
- package/dist/mcp-server.js +21324 -0
- package/dist/mcp-server.js.map +1 -0
- package/dist/party-server.js +4639 -0
- package/dist/party-server.js.map +1 -0
- package/package.json +34 -0
|
@@ -0,0 +1,4639 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __esm = (fn, res) => function __init() {
|
|
6
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
7
|
+
};
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// src/server/config.ts
|
|
14
|
+
var PARTY_PORT, HEARTBEAT_TIMEOUT, CLEANUP_INTERVAL, DISCOVERY_INTERVAL, REMOTE_STALE_FACTOR, PROBE_TIMEOUT;
|
|
15
|
+
var init_config = __esm({
|
|
16
|
+
"src/server/config.ts"() {
|
|
17
|
+
"use strict";
|
|
18
|
+
PARTY_PORT = parseInt(process.env.PARTY_PORT || "8000", 10);
|
|
19
|
+
HEARTBEAT_TIMEOUT = parseFloat(process.env.HEARTBEAT_TIMEOUT || "30");
|
|
20
|
+
CLEANUP_INTERVAL = parseFloat(process.env.CLEANUP_INTERVAL || "10");
|
|
21
|
+
DISCOVERY_INTERVAL = parseFloat(process.env.DISCOVERY_INTERVAL || "20");
|
|
22
|
+
REMOTE_STALE_FACTOR = parseInt(process.env.REMOTE_STALE_FACTOR || "3", 10);
|
|
23
|
+
PROBE_TIMEOUT = parseFloat(process.env.PROBE_TIMEOUT || "5");
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// src/infra/tailscale.ts
|
|
28
|
+
import { execFileSync, execSync } from "child_process";
|
|
29
|
+
import { existsSync } from "fs";
|
|
30
|
+
import { join } from "path";
|
|
31
|
+
function parsePossiblyNoisyJson(raw2) {
|
|
32
|
+
const trimmed = raw2.trim();
|
|
33
|
+
const start = trimmed.indexOf("{");
|
|
34
|
+
const end = trimmed.lastIndexOf("}");
|
|
35
|
+
if (start >= 0 && end > start) {
|
|
36
|
+
return JSON.parse(trimmed.slice(start, end + 1));
|
|
37
|
+
}
|
|
38
|
+
return JSON.parse(trimmed);
|
|
39
|
+
}
|
|
40
|
+
function runExec(cmd, timeout = 5e3) {
|
|
41
|
+
return execFileSync(cmd[0], cmd.slice(1), {
|
|
42
|
+
timeout,
|
|
43
|
+
encoding: "utf-8",
|
|
44
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
45
|
+
windowsHide: true
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function checkBinary(path, timeout = 3e3) {
|
|
49
|
+
if (!path || !existsSync(path)) return false;
|
|
50
|
+
try {
|
|
51
|
+
execFileSync(path, ["--version"], { timeout, encoding: "utf-8", stdio: "pipe", windowsHide: true });
|
|
52
|
+
return true;
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function findTailscaleBinary() {
|
|
58
|
+
try {
|
|
59
|
+
const which = process.platform === "win32" ? "where" : "which";
|
|
60
|
+
const result = execFileSync(which, ["tailscale"], { timeout: 3e3, encoding: "utf-8", stdio: "pipe", windowsHide: true });
|
|
61
|
+
const fromPath = result.trim().split(/\r?\n/)[0];
|
|
62
|
+
if (fromPath && checkBinary(fromPath)) return fromPath;
|
|
63
|
+
} catch {
|
|
64
|
+
}
|
|
65
|
+
const knownPaths = process.platform === "win32" ? [
|
|
66
|
+
join(process.env.ProgramFiles || "C:\\Program Files", "Tailscale", "tailscale.exe"),
|
|
67
|
+
join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Tailscale", "tailscale.exe"),
|
|
68
|
+
join(process.env.LOCALAPPDATA || "", "Tailscale", "tailscale.exe")
|
|
69
|
+
] : [
|
|
70
|
+
"/Applications/Tailscale.app/Contents/MacOS/Tailscale",
|
|
71
|
+
"/usr/bin/tailscale",
|
|
72
|
+
"/usr/local/bin/tailscale"
|
|
73
|
+
];
|
|
74
|
+
for (const candidate of knownPaths) {
|
|
75
|
+
if (checkBinary(candidate)) return candidate;
|
|
76
|
+
}
|
|
77
|
+
if (process.platform !== "win32") {
|
|
78
|
+
try {
|
|
79
|
+
const result = execSync(
|
|
80
|
+
'find /Applications -maxdepth 3 -name Tailscale -path "*/Tailscale.app/Contents/MacOS/Tailscale"',
|
|
81
|
+
{ timeout: 5e3, encoding: "utf-8" }
|
|
82
|
+
);
|
|
83
|
+
const first = result.trim().split("\n")[0];
|
|
84
|
+
if (first && checkBinary(first)) return first;
|
|
85
|
+
} catch {
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
function getTailscaleBinary() {
|
|
91
|
+
const forced = (process.env.OPENCLAW_TEST_TAILSCALE_BINARY ?? "").trim();
|
|
92
|
+
if (forced) {
|
|
93
|
+
cachedBinary = forced;
|
|
94
|
+
return forced;
|
|
95
|
+
}
|
|
96
|
+
if (cachedBinary !== null) return cachedBinary;
|
|
97
|
+
cachedBinary = findTailscaleBinary() ?? (process.platform === "win32" ? "tailscale.exe" : "tailscale");
|
|
98
|
+
return cachedBinary;
|
|
99
|
+
}
|
|
100
|
+
function readTailscaleStatus(timeout = 5e3) {
|
|
101
|
+
const binary = getTailscaleBinary();
|
|
102
|
+
const stdout = runExec([binary, "status", "--json"], timeout);
|
|
103
|
+
return stdout.trim() ? parsePossiblyNoisyJson(stdout) : {};
|
|
104
|
+
}
|
|
105
|
+
function getTailnetHostname(binary) {
|
|
106
|
+
const candidates = binary ? [binary] : [
|
|
107
|
+
getTailscaleBinary(),
|
|
108
|
+
"/Applications/Tailscale.app/Contents/MacOS/Tailscale"
|
|
109
|
+
];
|
|
110
|
+
let lastErr = null;
|
|
111
|
+
for (const candidate of candidates) {
|
|
112
|
+
if (candidate.startsWith("/") && !existsSync(candidate)) continue;
|
|
113
|
+
try {
|
|
114
|
+
const stdout = runExec([candidate, "status", "--json"], 5e3);
|
|
115
|
+
const parsed = stdout.trim() ? parsePossiblyNoisyJson(stdout) : {};
|
|
116
|
+
const selfInfo = parsed.Self ?? {};
|
|
117
|
+
const dns = selfInfo.DNSName;
|
|
118
|
+
if (typeof dns === "string" && dns) return dns.replace(/\.$/, "");
|
|
119
|
+
const ips = selfInfo.TailscaleIPs;
|
|
120
|
+
if (ips && ips.length > 0) return ips[0];
|
|
121
|
+
throw new Error("Could not determine Tailscale DNS or IP");
|
|
122
|
+
} catch (exc) {
|
|
123
|
+
lastErr = exc;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
throw lastErr ?? new Error("Could not determine Tailscale DNS or IP");
|
|
127
|
+
}
|
|
128
|
+
function getTailscaleIps() {
|
|
129
|
+
const status = readTailscaleStatus();
|
|
130
|
+
const selfInfo = status.Self;
|
|
131
|
+
if (selfInfo && Array.isArray(selfInfo.TailscaleIPs)) {
|
|
132
|
+
return selfInfo.TailscaleIPs;
|
|
133
|
+
}
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
function execWithSudoFallback(cmd, timeout = 15e3) {
|
|
137
|
+
try {
|
|
138
|
+
return runExec(cmd, timeout);
|
|
139
|
+
} catch (exc) {
|
|
140
|
+
const err = exc;
|
|
141
|
+
const stderrLower = (err.stderr ?? "").toLowerCase();
|
|
142
|
+
if (PERMISSION_KEYWORDS.some((kw) => stderrLower.includes(kw))) {
|
|
143
|
+
try {
|
|
144
|
+
return runExec(["sudo", "-n", ...cmd], timeout);
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
throw exc;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function joinTailnet(authKey, timeout = 3e4) {
|
|
152
|
+
const binary = getTailscaleBinary();
|
|
153
|
+
try {
|
|
154
|
+
const output = execWithSudoFallback(
|
|
155
|
+
[binary, "up", "--authkey", authKey, "--accept-routes"],
|
|
156
|
+
timeout
|
|
157
|
+
);
|
|
158
|
+
return { success: true, output: output.trim() };
|
|
159
|
+
} catch (e) {
|
|
160
|
+
const err = e;
|
|
161
|
+
return { success: false, output: (err.stderr ?? err.message ?? "").trim() };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function getTailscaleInstallationStatus() {
|
|
165
|
+
const binary = findTailscaleBinary();
|
|
166
|
+
if (!binary) {
|
|
167
|
+
return { state: "not_installed", platform: process.platform };
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const status = readTailscaleStatus();
|
|
171
|
+
const self = status.Self ?? {};
|
|
172
|
+
const online = self.Online === true;
|
|
173
|
+
if (online) {
|
|
174
|
+
const ips = self.TailscaleIPs;
|
|
175
|
+
const dns = self.DNSName?.replace(/\.$/, "");
|
|
176
|
+
return {
|
|
177
|
+
state: "connected",
|
|
178
|
+
binary,
|
|
179
|
+
tailscale_ip: ips?.[0] ?? "127.0.0.1",
|
|
180
|
+
hostname: dns ?? null
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
return { state: "not_connected", binary };
|
|
184
|
+
} catch (e) {
|
|
185
|
+
return {
|
|
186
|
+
state: "not_connected",
|
|
187
|
+
binary,
|
|
188
|
+
error: e.message
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function resetTailscaleBinaryCache() {
|
|
193
|
+
cachedBinary = null;
|
|
194
|
+
}
|
|
195
|
+
function getInstallInstructions(platform) {
|
|
196
|
+
switch (platform) {
|
|
197
|
+
case "linux":
|
|
198
|
+
return {
|
|
199
|
+
os: "linux",
|
|
200
|
+
download_url: "https://tailscale.com/download/linux",
|
|
201
|
+
commands: ["curl -fsSL https://tailscale.com/install.sh | sh"],
|
|
202
|
+
needs_sudo: true
|
|
203
|
+
};
|
|
204
|
+
case "darwin":
|
|
205
|
+
return {
|
|
206
|
+
os: "macOS",
|
|
207
|
+
download_url: "https://tailscale.com/download/mac",
|
|
208
|
+
commands: ["brew install tailscale"],
|
|
209
|
+
needs_sudo: false
|
|
210
|
+
};
|
|
211
|
+
case "win32":
|
|
212
|
+
return {
|
|
213
|
+
os: "windows",
|
|
214
|
+
download_url: "https://tailscale.com/download/windows",
|
|
215
|
+
commands: ["winget install Tailscale.Tailscale"],
|
|
216
|
+
needs_sudo: false
|
|
217
|
+
};
|
|
218
|
+
default:
|
|
219
|
+
return {
|
|
220
|
+
os: platform,
|
|
221
|
+
download_url: "https://tailscale.com/download/",
|
|
222
|
+
commands: [],
|
|
223
|
+
needs_sudo: false
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
var cachedBinary, PERMISSION_KEYWORDS;
|
|
228
|
+
var init_tailscale = __esm({
|
|
229
|
+
"src/infra/tailscale.ts"() {
|
|
230
|
+
"use strict";
|
|
231
|
+
cachedBinary = null;
|
|
232
|
+
PERMISSION_KEYWORDS = [
|
|
233
|
+
"permission denied",
|
|
234
|
+
"access denied",
|
|
235
|
+
"operation not permitted",
|
|
236
|
+
"not permitted",
|
|
237
|
+
"requires root",
|
|
238
|
+
"must be run as root",
|
|
239
|
+
"must be run with sudo",
|
|
240
|
+
"requires sudo",
|
|
241
|
+
"need sudo"
|
|
242
|
+
];
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// src/server/message-queue.ts
|
|
247
|
+
var HISTORY_CAP, MessageQueue;
|
|
248
|
+
var init_message_queue = __esm({
|
|
249
|
+
"src/server/message-queue.ts"() {
|
|
250
|
+
"use strict";
|
|
251
|
+
HISTORY_CAP = 200;
|
|
252
|
+
MessageQueue = class {
|
|
253
|
+
_queues = /* @__PURE__ */ new Map();
|
|
254
|
+
_history = /* @__PURE__ */ new Map();
|
|
255
|
+
/** Enqueue a message for agentId. Returns the queue length after enqueue. */
|
|
256
|
+
enqueue(agentId, envelope) {
|
|
257
|
+
let q = this._queues.get(agentId);
|
|
258
|
+
if (!q) {
|
|
259
|
+
q = [];
|
|
260
|
+
this._queues.set(agentId, q);
|
|
261
|
+
}
|
|
262
|
+
q.push(envelope);
|
|
263
|
+
return q.length;
|
|
264
|
+
}
|
|
265
|
+
/** Pop up to maxCount messages for agentId. */
|
|
266
|
+
dequeue(agentId, maxCount = 50) {
|
|
267
|
+
const q = this._queues.get(agentId);
|
|
268
|
+
if (!q) return [];
|
|
269
|
+
return q.splice(0, Math.min(maxCount, q.length));
|
|
270
|
+
}
|
|
271
|
+
/** Return the number of pending messages for agentId. */
|
|
272
|
+
pendingCount(agentId) {
|
|
273
|
+
return this._queues.get(agentId)?.length ?? 0;
|
|
274
|
+
}
|
|
275
|
+
/** Clean up queue when agent is removed. */
|
|
276
|
+
removeAgent(agentId) {
|
|
277
|
+
this._queues.delete(agentId);
|
|
278
|
+
}
|
|
279
|
+
/** Record a message in an agent's history. */
|
|
280
|
+
logToHistory(agentId, direction, envelope) {
|
|
281
|
+
let h = this._history.get(agentId);
|
|
282
|
+
if (!h) {
|
|
283
|
+
h = [];
|
|
284
|
+
this._history.set(agentId, h);
|
|
285
|
+
}
|
|
286
|
+
h.push({
|
|
287
|
+
direction,
|
|
288
|
+
sender_id: envelope.sender_id,
|
|
289
|
+
recipient_id: envelope.recipient_id,
|
|
290
|
+
summary: envelope.summary,
|
|
291
|
+
content: envelope.content,
|
|
292
|
+
timestamp: envelope.timestamp ?? Date.now() / 1e3
|
|
293
|
+
});
|
|
294
|
+
if (h.length > HISTORY_CAP) {
|
|
295
|
+
this._history.set(agentId, h.slice(-HISTORY_CAP));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/** Get recent N history entries for an agent. */
|
|
299
|
+
getHistory(agentId, limit = 20) {
|
|
300
|
+
const h = this._history.get(agentId);
|
|
301
|
+
if (!h) return [];
|
|
302
|
+
return h.slice(-limit);
|
|
303
|
+
}
|
|
304
|
+
/** Clean up history when agent is removed. */
|
|
305
|
+
removeAgentHistory(agentId) {
|
|
306
|
+
this._history.delete(agentId);
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
// src/server/peer-discovery.ts
|
|
313
|
+
function classifyFetchError(error) {
|
|
314
|
+
if (error instanceof TypeError && /fetch failed/i.test(error.message)) {
|
|
315
|
+
const cause = error.cause;
|
|
316
|
+
if (cause?.code === "ECONNREFUSED") return false;
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
if (error instanceof DOMException && error.name === "AbortError") return null;
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
function sleep(ms) {
|
|
323
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
324
|
+
}
|
|
325
|
+
var UNKNOWN, PARTY_SERVER, DEGRADED, SUSPECT, DOWN, NOT_SERVER, MAYBE, MAYBE_MAX_RETRIES, BACKOFF_BASE, BACKOFF_CAP, FAILURE_SUSPECT, FAILURE_DOWN, PeerDiscovery;
|
|
326
|
+
var init_peer_discovery = __esm({
|
|
327
|
+
"src/server/peer-discovery.ts"() {
|
|
328
|
+
"use strict";
|
|
329
|
+
init_config();
|
|
330
|
+
init_tailscale();
|
|
331
|
+
UNKNOWN = "UNKNOWN";
|
|
332
|
+
PARTY_SERVER = "PARTY_SERVER";
|
|
333
|
+
DEGRADED = "DEGRADED";
|
|
334
|
+
SUSPECT = "SUSPECT";
|
|
335
|
+
DOWN = "DOWN";
|
|
336
|
+
NOT_SERVER = "NOT_SERVER";
|
|
337
|
+
MAYBE = "MAYBE";
|
|
338
|
+
MAYBE_MAX_RETRIES = 3;
|
|
339
|
+
BACKOFF_BASE = 60;
|
|
340
|
+
BACKOFF_CAP = 900;
|
|
341
|
+
FAILURE_SUSPECT = 2;
|
|
342
|
+
FAILURE_DOWN = 3;
|
|
343
|
+
PeerDiscovery = class {
|
|
344
|
+
_selfIp;
|
|
345
|
+
_peers = /* @__PURE__ */ new Map();
|
|
346
|
+
_remoteAgents = /* @__PURE__ */ new Map();
|
|
347
|
+
constructor(selfIp) {
|
|
348
|
+
this._selfIp = selfIp;
|
|
349
|
+
}
|
|
350
|
+
// ------------------------------------------------------------------
|
|
351
|
+
// Public query API (used by router)
|
|
352
|
+
// ------------------------------------------------------------------
|
|
353
|
+
/** Return the peer IP that owns agentId, or undefined. */
|
|
354
|
+
getPeerForAgent(agentId) {
|
|
355
|
+
return this._remoteAgents.get(agentId)?.sourcePeerIp;
|
|
356
|
+
}
|
|
357
|
+
/** Return true if the peer is in a serving state. */
|
|
358
|
+
isPeerReachable(peerIp) {
|
|
359
|
+
const ps = this._peers.get(peerIp);
|
|
360
|
+
return ps !== void 0 && (ps.status === PARTY_SERVER || ps.status === DEGRADED || ps.status === SUSPECT);
|
|
361
|
+
}
|
|
362
|
+
/** Return all remote agents (including unreachable ones). */
|
|
363
|
+
getAllRemoteAgents() {
|
|
364
|
+
return Array.from(this._remoteAgents.values(), (e) => e.agentInfo);
|
|
365
|
+
}
|
|
366
|
+
/** Return only reachable remote agents. */
|
|
367
|
+
getReachableRemoteAgents() {
|
|
368
|
+
return Array.from(this._remoteAgents.values()).filter((e) => e.reachable).map((e) => e.agentInfo);
|
|
369
|
+
}
|
|
370
|
+
/** Return all known peer states for dashboard consumption. */
|
|
371
|
+
getPeerStates() {
|
|
372
|
+
return Array.from(this._peers.values()).map((ps) => ({
|
|
373
|
+
ip: ps.ip,
|
|
374
|
+
status: ps.status,
|
|
375
|
+
consecutiveFailures: ps.consecutiveFailures,
|
|
376
|
+
lastProbeAt: ps.lastProbeAt,
|
|
377
|
+
backoffUntil: ps.backoffUntil
|
|
378
|
+
}));
|
|
379
|
+
}
|
|
380
|
+
/** Return remote agent entries with peer mapping info. */
|
|
381
|
+
getRemoteAgentEntries() {
|
|
382
|
+
return Array.from(this._remoteAgents.values()).map((e) => ({
|
|
383
|
+
agentInfo: e.agentInfo,
|
|
384
|
+
sourcePeerIp: e.sourcePeerIp,
|
|
385
|
+
lastSyncedAt: e.lastSyncedAt,
|
|
386
|
+
reachable: e.reachable
|
|
387
|
+
}));
|
|
388
|
+
}
|
|
389
|
+
// ------------------------------------------------------------------
|
|
390
|
+
// Main discovery loop
|
|
391
|
+
// ------------------------------------------------------------------
|
|
392
|
+
async runLoop() {
|
|
393
|
+
while (true) {
|
|
394
|
+
try {
|
|
395
|
+
await this.discoveryCycle();
|
|
396
|
+
} catch (e) {
|
|
397
|
+
console.error("[Discovery] Cycle failed:", e);
|
|
398
|
+
}
|
|
399
|
+
await sleep(DISCOVERY_INTERVAL * 1e3);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
async discoveryCycle() {
|
|
403
|
+
const peerIps = this.getTailscalePeers();
|
|
404
|
+
for (const ip of peerIps) {
|
|
405
|
+
if (!this._peers.has(ip)) {
|
|
406
|
+
this._peers.set(ip, { ip, status: UNKNOWN, consecutiveFailures: 0, lastProbeAt: 0, backoffUntil: null, maybeRetries: 0 });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
const now = performance.now() / 1e3;
|
|
410
|
+
for (const ip of peerIps) {
|
|
411
|
+
const ps = this._peers.get(ip);
|
|
412
|
+
if (ps.status === NOT_SERVER) {
|
|
413
|
+
if (ps.backoffUntil !== null && now < ps.backoffUntil) continue;
|
|
414
|
+
ps.status = UNKNOWN;
|
|
415
|
+
}
|
|
416
|
+
if (ps.status === MAYBE && ps.maybeRetries >= MAYBE_MAX_RETRIES) {
|
|
417
|
+
this.transition(ps, NOT_SERVER);
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
await this.probePeer(ps);
|
|
421
|
+
}
|
|
422
|
+
this.evictDownAgents();
|
|
423
|
+
this.evictStaleAgents();
|
|
424
|
+
}
|
|
425
|
+
// ------------------------------------------------------------------
|
|
426
|
+
// Tailscale peer enumeration
|
|
427
|
+
// ------------------------------------------------------------------
|
|
428
|
+
getTailscalePeers() {
|
|
429
|
+
let status;
|
|
430
|
+
try {
|
|
431
|
+
status = readTailscaleStatus();
|
|
432
|
+
} catch {
|
|
433
|
+
console.warn("[Discovery] Failed to read Tailscale status");
|
|
434
|
+
return [];
|
|
435
|
+
}
|
|
436
|
+
const peersRaw = status.Peer;
|
|
437
|
+
if (!peersRaw || typeof peersRaw !== "object") return [];
|
|
438
|
+
const ips = [];
|
|
439
|
+
for (const peer of Object.values(peersRaw)) {
|
|
440
|
+
if (typeof peer !== "object" || !peer) continue;
|
|
441
|
+
if (!peer.Online) continue;
|
|
442
|
+
if (peer.ExitNode) continue;
|
|
443
|
+
const tailscaleIps = peer.TailscaleIPs;
|
|
444
|
+
if (!tailscaleIps) continue;
|
|
445
|
+
for (const ip of tailscaleIps) {
|
|
446
|
+
if (ip.includes(".") && !ip.includes(":")) {
|
|
447
|
+
if (ip !== this._selfIp) ips.push(ip);
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return ips;
|
|
453
|
+
}
|
|
454
|
+
// ------------------------------------------------------------------
|
|
455
|
+
// Peer probing
|
|
456
|
+
// ------------------------------------------------------------------
|
|
457
|
+
async probePeer(ps) {
|
|
458
|
+
ps.lastProbeAt = performance.now() / 1e3;
|
|
459
|
+
const healthy = await this.checkHealth(ps.ip);
|
|
460
|
+
if (healthy === null) {
|
|
461
|
+
this.handleProbeFailure(ps, true);
|
|
462
|
+
} else if (healthy) {
|
|
463
|
+
await this.handleProbeSuccess(ps);
|
|
464
|
+
} else {
|
|
465
|
+
this.handleProbeFailure(ps, false);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async checkHealth(ip) {
|
|
469
|
+
const url = `http://${ip}:${PARTY_PORT}/proxy/health`;
|
|
470
|
+
try {
|
|
471
|
+
const controller = new AbortController();
|
|
472
|
+
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT * 1e3);
|
|
473
|
+
const resp = await fetch(url, { signal: controller.signal });
|
|
474
|
+
clearTimeout(timer);
|
|
475
|
+
const data = await resp.json();
|
|
476
|
+
return resp.status === 200 && "status" in data;
|
|
477
|
+
} catch (e) {
|
|
478
|
+
return classifyFetchError(e);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
// ------------------------------------------------------------------
|
|
482
|
+
// State machine transitions
|
|
483
|
+
// ------------------------------------------------------------------
|
|
484
|
+
async handleProbeSuccess(ps) {
|
|
485
|
+
ps.consecutiveFailures = 0;
|
|
486
|
+
ps.maybeRetries = 0;
|
|
487
|
+
ps.backoffUntil = null;
|
|
488
|
+
if (ps.status !== PARTY_SERVER) {
|
|
489
|
+
this.transition(ps, PARTY_SERVER);
|
|
490
|
+
}
|
|
491
|
+
await this.syncAgents(ps.ip);
|
|
492
|
+
}
|
|
493
|
+
handleProbeFailure(ps, timeout) {
|
|
494
|
+
if (ps.status === UNKNOWN || ps.status === MAYBE) {
|
|
495
|
+
if (timeout) {
|
|
496
|
+
ps.maybeRetries++;
|
|
497
|
+
if (ps.maybeRetries >= MAYBE_MAX_RETRIES) {
|
|
498
|
+
this.transition(ps, NOT_SERVER);
|
|
499
|
+
} else {
|
|
500
|
+
this.transition(ps, MAYBE);
|
|
501
|
+
}
|
|
502
|
+
} else {
|
|
503
|
+
this.transition(ps, NOT_SERVER);
|
|
504
|
+
}
|
|
505
|
+
} else if (ps.status === PARTY_SERVER) {
|
|
506
|
+
ps.consecutiveFailures++;
|
|
507
|
+
if (ps.consecutiveFailures >= FAILURE_DOWN) {
|
|
508
|
+
this.transition(ps, DOWN);
|
|
509
|
+
} else if (ps.consecutiveFailures >= FAILURE_SUSPECT) {
|
|
510
|
+
this.transition(ps, SUSPECT);
|
|
511
|
+
} else {
|
|
512
|
+
this.transition(ps, DEGRADED);
|
|
513
|
+
}
|
|
514
|
+
} else if (ps.status === DEGRADED || ps.status === SUSPECT) {
|
|
515
|
+
ps.consecutiveFailures++;
|
|
516
|
+
if (ps.consecutiveFailures >= FAILURE_DOWN) {
|
|
517
|
+
this.transition(ps, DOWN);
|
|
518
|
+
} else if (ps.status === DEGRADED && ps.consecutiveFailures >= FAILURE_SUSPECT) {
|
|
519
|
+
this.transition(ps, SUSPECT);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
transition(ps, newStatus) {
|
|
524
|
+
const old = ps.status;
|
|
525
|
+
ps.status = newStatus;
|
|
526
|
+
if (old !== newStatus) {
|
|
527
|
+
console.log(`[Discovery] Peer ${ps.ip}: ${old} -> ${newStatus}`);
|
|
528
|
+
}
|
|
529
|
+
if (newStatus === NOT_SERVER) {
|
|
530
|
+
const retries = ps.maybeRetries > 0 ? ps.maybeRetries : 1;
|
|
531
|
+
const delay = Math.min(BACKOFF_BASE * Math.pow(2, retries - 1), BACKOFF_CAP);
|
|
532
|
+
ps.backoffUntil = performance.now() / 1e3 + delay;
|
|
533
|
+
}
|
|
534
|
+
if (newStatus === DOWN) {
|
|
535
|
+
for (const entry of this._remoteAgents.values()) {
|
|
536
|
+
if (entry.sourcePeerIp === ps.ip) {
|
|
537
|
+
entry.reachable = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
// ------------------------------------------------------------------
|
|
543
|
+
// Agent synchronization
|
|
544
|
+
// ------------------------------------------------------------------
|
|
545
|
+
async syncAgents(peerIp) {
|
|
546
|
+
const url = `http://${peerIp}:${PARTY_PORT}/proxy/list_agents`;
|
|
547
|
+
try {
|
|
548
|
+
const controller = new AbortController();
|
|
549
|
+
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT * 1e3);
|
|
550
|
+
const resp = await fetch(url, { signal: controller.signal });
|
|
551
|
+
clearTimeout(timer);
|
|
552
|
+
const data = await resp.json();
|
|
553
|
+
const agentsRaw = data.agents ?? [];
|
|
554
|
+
const now = Date.now() / 1e3;
|
|
555
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
556
|
+
for (const a of agentsRaw) {
|
|
557
|
+
seenIds.add(a.agent_id);
|
|
558
|
+
this._remoteAgents.set(a.agent_id, {
|
|
559
|
+
agentInfo: a,
|
|
560
|
+
sourcePeerIp: peerIp,
|
|
561
|
+
lastSyncedAt: now,
|
|
562
|
+
reachable: true
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
for (const [aid, entry] of this._remoteAgents) {
|
|
566
|
+
if (entry.sourcePeerIp === peerIp && !seenIds.has(aid)) {
|
|
567
|
+
this._remoteAgents.delete(aid);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
} catch {
|
|
571
|
+
console.warn(`[Discovery] Failed to sync agents from ${peerIp}`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
// ------------------------------------------------------------------
|
|
575
|
+
// Cleanup
|
|
576
|
+
// ------------------------------------------------------------------
|
|
577
|
+
evictDownAgents() {
|
|
578
|
+
const downPeers = /* @__PURE__ */ new Set();
|
|
579
|
+
for (const [ip, ps] of this._peers) {
|
|
580
|
+
if (ps.status === DOWN) downPeers.add(ip);
|
|
581
|
+
}
|
|
582
|
+
if (!downPeers.size) return;
|
|
583
|
+
for (const [aid, entry] of this._remoteAgents) {
|
|
584
|
+
if (downPeers.has(entry.sourcePeerIp)) {
|
|
585
|
+
this._remoteAgents.delete(aid);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
evictStaleAgents() {
|
|
590
|
+
const threshold = DISCOVERY_INTERVAL * REMOTE_STALE_FACTOR;
|
|
591
|
+
const now = Date.now() / 1e3;
|
|
592
|
+
for (const [aid, entry] of this._remoteAgents) {
|
|
593
|
+
if (now - entry.lastSyncedAt > threshold) {
|
|
594
|
+
this._remoteAgents.delete(aid);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
// src/server/registry.ts
|
|
603
|
+
var AgentRegistry;
|
|
604
|
+
var init_registry = __esm({
|
|
605
|
+
"src/server/registry.ts"() {
|
|
606
|
+
"use strict";
|
|
607
|
+
AgentRegistry = class {
|
|
608
|
+
_agents = /* @__PURE__ */ new Map();
|
|
609
|
+
_selfIp;
|
|
610
|
+
constructor(selfIp) {
|
|
611
|
+
this._selfIp = selfIp;
|
|
612
|
+
}
|
|
613
|
+
register(req) {
|
|
614
|
+
const now = Date.now() / 1e3;
|
|
615
|
+
const info = {
|
|
616
|
+
agent_id: req.agent_id,
|
|
617
|
+
display_name: req.display_name,
|
|
618
|
+
host_ip: this._selfIp,
|
|
619
|
+
registered_at: now,
|
|
620
|
+
last_heartbeat: now,
|
|
621
|
+
metadata: req.metadata ?? {}
|
|
622
|
+
};
|
|
623
|
+
this._agents.set(req.agent_id, info);
|
|
624
|
+
return info;
|
|
625
|
+
}
|
|
626
|
+
remove(agentId) {
|
|
627
|
+
return this._agents.delete(agentId);
|
|
628
|
+
}
|
|
629
|
+
heartbeat(agentId) {
|
|
630
|
+
const info = this._agents.get(agentId);
|
|
631
|
+
if (!info) throw new Error(`Agent '${agentId}' not registered`);
|
|
632
|
+
info.last_heartbeat = Date.now() / 1e3;
|
|
633
|
+
return info;
|
|
634
|
+
}
|
|
635
|
+
get(agentId) {
|
|
636
|
+
return this._agents.get(agentId);
|
|
637
|
+
}
|
|
638
|
+
listAll() {
|
|
639
|
+
return Array.from(this._agents.values());
|
|
640
|
+
}
|
|
641
|
+
/** Remove agents whose last heartbeat is older than timeout seconds. */
|
|
642
|
+
cleanupStale(timeout) {
|
|
643
|
+
const now = Date.now() / 1e3;
|
|
644
|
+
const stale = [];
|
|
645
|
+
for (const [aid, info] of this._agents) {
|
|
646
|
+
if (now - info.last_heartbeat > timeout) {
|
|
647
|
+
stale.push(aid);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
for (const aid of stale) {
|
|
651
|
+
this._agents.delete(aid);
|
|
652
|
+
}
|
|
653
|
+
return stale;
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
// src/server/state.ts
|
|
660
|
+
var state_exports = {};
|
|
661
|
+
__export(state_exports, {
|
|
662
|
+
STARTED_AT: () => STARTED_AT,
|
|
663
|
+
discovery: () => discovery,
|
|
664
|
+
getSelfIp: () => getSelfIp,
|
|
665
|
+
messageQueue: () => messageQueue,
|
|
666
|
+
refreshSelfIp: () => refreshSelfIp,
|
|
667
|
+
registry: () => registry
|
|
668
|
+
});
|
|
669
|
+
function resolveSelfIp() {
|
|
670
|
+
try {
|
|
671
|
+
const ips = getTailscaleIps();
|
|
672
|
+
for (const ip of ips) {
|
|
673
|
+
if (ip.includes(".") && !ip.includes(":")) return ip;
|
|
674
|
+
}
|
|
675
|
+
return ips.length > 0 ? ips[0] : "127.0.0.1";
|
|
676
|
+
} catch {
|
|
677
|
+
return "127.0.0.1";
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function getSelfIp() {
|
|
681
|
+
return _selfIp;
|
|
682
|
+
}
|
|
683
|
+
function refreshSelfIp() {
|
|
684
|
+
_selfIp = resolveSelfIp();
|
|
685
|
+
return _selfIp;
|
|
686
|
+
}
|
|
687
|
+
var _selfIp, STARTED_AT, registry, messageQueue, discovery;
|
|
688
|
+
var init_state = __esm({
|
|
689
|
+
"src/server/state.ts"() {
|
|
690
|
+
"use strict";
|
|
691
|
+
init_tailscale();
|
|
692
|
+
init_message_queue();
|
|
693
|
+
init_peer_discovery();
|
|
694
|
+
init_registry();
|
|
695
|
+
_selfIp = resolveSelfIp();
|
|
696
|
+
STARTED_AT = Date.now();
|
|
697
|
+
registry = new AgentRegistry(getSelfIp());
|
|
698
|
+
messageQueue = new MessageQueue();
|
|
699
|
+
discovery = new PeerDiscovery(getSelfIp());
|
|
700
|
+
}
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
// node_modules/hono/dist/compose.js
|
|
704
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
705
|
+
return (context, next) => {
|
|
706
|
+
let index = -1;
|
|
707
|
+
return dispatch(0);
|
|
708
|
+
async function dispatch(i) {
|
|
709
|
+
if (i <= index) {
|
|
710
|
+
throw new Error("next() called multiple times");
|
|
711
|
+
}
|
|
712
|
+
index = i;
|
|
713
|
+
let res;
|
|
714
|
+
let isError = false;
|
|
715
|
+
let handler;
|
|
716
|
+
if (middleware[i]) {
|
|
717
|
+
handler = middleware[i][0][0];
|
|
718
|
+
context.req.routeIndex = i;
|
|
719
|
+
} else {
|
|
720
|
+
handler = i === middleware.length && next || void 0;
|
|
721
|
+
}
|
|
722
|
+
if (handler) {
|
|
723
|
+
try {
|
|
724
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
725
|
+
} catch (err) {
|
|
726
|
+
if (err instanceof Error && onError) {
|
|
727
|
+
context.error = err;
|
|
728
|
+
res = await onError(err, context);
|
|
729
|
+
isError = true;
|
|
730
|
+
} else {
|
|
731
|
+
throw err;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
} else {
|
|
735
|
+
if (context.finalized === false && onNotFound) {
|
|
736
|
+
res = await onNotFound(context);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
if (res && (context.finalized === false || isError)) {
|
|
740
|
+
context.res = res;
|
|
741
|
+
}
|
|
742
|
+
return context;
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
// node_modules/hono/dist/request/constants.js
|
|
748
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
749
|
+
|
|
750
|
+
// node_modules/hono/dist/utils/body.js
|
|
751
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
752
|
+
const { all = false, dot = false } = options;
|
|
753
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
754
|
+
const contentType = headers.get("Content-Type");
|
|
755
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
756
|
+
return parseFormData(request, { all, dot });
|
|
757
|
+
}
|
|
758
|
+
return {};
|
|
759
|
+
};
|
|
760
|
+
async function parseFormData(request, options) {
|
|
761
|
+
const formData = await request.formData();
|
|
762
|
+
if (formData) {
|
|
763
|
+
return convertFormDataToBodyData(formData, options);
|
|
764
|
+
}
|
|
765
|
+
return {};
|
|
766
|
+
}
|
|
767
|
+
function convertFormDataToBodyData(formData, options) {
|
|
768
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
769
|
+
formData.forEach((value, key) => {
|
|
770
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
771
|
+
if (!shouldParseAllValues) {
|
|
772
|
+
form[key] = value;
|
|
773
|
+
} else {
|
|
774
|
+
handleParsingAllValues(form, key, value);
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
if (options.dot) {
|
|
778
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
779
|
+
const shouldParseDotValues = key.includes(".");
|
|
780
|
+
if (shouldParseDotValues) {
|
|
781
|
+
handleParsingNestedValues(form, key, value);
|
|
782
|
+
delete form[key];
|
|
783
|
+
}
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
return form;
|
|
787
|
+
}
|
|
788
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
789
|
+
if (form[key] !== void 0) {
|
|
790
|
+
if (Array.isArray(form[key])) {
|
|
791
|
+
;
|
|
792
|
+
form[key].push(value);
|
|
793
|
+
} else {
|
|
794
|
+
form[key] = [form[key], value];
|
|
795
|
+
}
|
|
796
|
+
} else {
|
|
797
|
+
if (!key.endsWith("[]")) {
|
|
798
|
+
form[key] = value;
|
|
799
|
+
} else {
|
|
800
|
+
form[key] = [value];
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
805
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
let nestedForm = form;
|
|
809
|
+
const keys = key.split(".");
|
|
810
|
+
keys.forEach((key2, index) => {
|
|
811
|
+
if (index === keys.length - 1) {
|
|
812
|
+
nestedForm[key2] = value;
|
|
813
|
+
} else {
|
|
814
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
815
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
816
|
+
}
|
|
817
|
+
nestedForm = nestedForm[key2];
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
// node_modules/hono/dist/utils/url.js
|
|
823
|
+
var splitPath = (path) => {
|
|
824
|
+
const paths = path.split("/");
|
|
825
|
+
if (paths[0] === "") {
|
|
826
|
+
paths.shift();
|
|
827
|
+
}
|
|
828
|
+
return paths;
|
|
829
|
+
};
|
|
830
|
+
var splitRoutingPath = (routePath) => {
|
|
831
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
832
|
+
const paths = splitPath(path);
|
|
833
|
+
return replaceGroupMarks(paths, groups);
|
|
834
|
+
};
|
|
835
|
+
var extractGroupsFromPath = (path) => {
|
|
836
|
+
const groups = [];
|
|
837
|
+
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
838
|
+
const mark = `@${index}`;
|
|
839
|
+
groups.push([mark, match2]);
|
|
840
|
+
return mark;
|
|
841
|
+
});
|
|
842
|
+
return { groups, path };
|
|
843
|
+
};
|
|
844
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
845
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
846
|
+
const [mark] = groups[i];
|
|
847
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
848
|
+
if (paths[j].includes(mark)) {
|
|
849
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
850
|
+
break;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return paths;
|
|
855
|
+
};
|
|
856
|
+
var patternCache = {};
|
|
857
|
+
var getPattern = (label, next) => {
|
|
858
|
+
if (label === "*") {
|
|
859
|
+
return "*";
|
|
860
|
+
}
|
|
861
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
862
|
+
if (match2) {
|
|
863
|
+
const cacheKey2 = `${label}#${next}`;
|
|
864
|
+
if (!patternCache[cacheKey2]) {
|
|
865
|
+
if (match2[2]) {
|
|
866
|
+
patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
867
|
+
} else {
|
|
868
|
+
patternCache[cacheKey2] = [label, match2[1], true];
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return patternCache[cacheKey2];
|
|
872
|
+
}
|
|
873
|
+
return null;
|
|
874
|
+
};
|
|
875
|
+
var tryDecode = (str, decoder) => {
|
|
876
|
+
try {
|
|
877
|
+
return decoder(str);
|
|
878
|
+
} catch {
|
|
879
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
880
|
+
try {
|
|
881
|
+
return decoder(match2);
|
|
882
|
+
} catch {
|
|
883
|
+
return match2;
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
889
|
+
var getPath = (request) => {
|
|
890
|
+
const url = request.url;
|
|
891
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
892
|
+
let i = start;
|
|
893
|
+
for (; i < url.length; i++) {
|
|
894
|
+
const charCode = url.charCodeAt(i);
|
|
895
|
+
if (charCode === 37) {
|
|
896
|
+
const queryIndex = url.indexOf("?", i);
|
|
897
|
+
const hashIndex = url.indexOf("#", i);
|
|
898
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
899
|
+
const path = url.slice(start, end);
|
|
900
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
901
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
902
|
+
break;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return url.slice(start, i);
|
|
906
|
+
};
|
|
907
|
+
var getPathNoStrict = (request) => {
|
|
908
|
+
const result = getPath(request);
|
|
909
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
910
|
+
};
|
|
911
|
+
var mergePath = (base, sub, ...rest) => {
|
|
912
|
+
if (rest.length) {
|
|
913
|
+
sub = mergePath(sub, ...rest);
|
|
914
|
+
}
|
|
915
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
916
|
+
};
|
|
917
|
+
var checkOptionalParameter = (path) => {
|
|
918
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
const segments = path.split("/");
|
|
922
|
+
const results = [];
|
|
923
|
+
let basePath = "";
|
|
924
|
+
segments.forEach((segment) => {
|
|
925
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
926
|
+
basePath += "/" + segment;
|
|
927
|
+
} else if (/\:/.test(segment)) {
|
|
928
|
+
if (/\?/.test(segment)) {
|
|
929
|
+
if (results.length === 0 && basePath === "") {
|
|
930
|
+
results.push("/");
|
|
931
|
+
} else {
|
|
932
|
+
results.push(basePath);
|
|
933
|
+
}
|
|
934
|
+
const optionalSegment = segment.replace("?", "");
|
|
935
|
+
basePath += "/" + optionalSegment;
|
|
936
|
+
results.push(basePath);
|
|
937
|
+
} else {
|
|
938
|
+
basePath += "/" + segment;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
943
|
+
};
|
|
944
|
+
var _decodeURI = (value) => {
|
|
945
|
+
if (!/[%+]/.test(value)) {
|
|
946
|
+
return value;
|
|
947
|
+
}
|
|
948
|
+
if (value.indexOf("+") !== -1) {
|
|
949
|
+
value = value.replace(/\+/g, " ");
|
|
950
|
+
}
|
|
951
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
952
|
+
};
|
|
953
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
954
|
+
let encoded;
|
|
955
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
956
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
957
|
+
if (keyIndex2 === -1) {
|
|
958
|
+
return void 0;
|
|
959
|
+
}
|
|
960
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
961
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
962
|
+
}
|
|
963
|
+
while (keyIndex2 !== -1) {
|
|
964
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
965
|
+
if (trailingKeyCode === 61) {
|
|
966
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
967
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
968
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
969
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
970
|
+
return "";
|
|
971
|
+
}
|
|
972
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
973
|
+
}
|
|
974
|
+
encoded = /[%+]/.test(url);
|
|
975
|
+
if (!encoded) {
|
|
976
|
+
return void 0;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
const results = {};
|
|
980
|
+
encoded ??= /[%+]/.test(url);
|
|
981
|
+
let keyIndex = url.indexOf("?", 8);
|
|
982
|
+
while (keyIndex !== -1) {
|
|
983
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
984
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
985
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
986
|
+
valueIndex = -1;
|
|
987
|
+
}
|
|
988
|
+
let name = url.slice(
|
|
989
|
+
keyIndex + 1,
|
|
990
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
991
|
+
);
|
|
992
|
+
if (encoded) {
|
|
993
|
+
name = _decodeURI(name);
|
|
994
|
+
}
|
|
995
|
+
keyIndex = nextKeyIndex;
|
|
996
|
+
if (name === "") {
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
let value;
|
|
1000
|
+
if (valueIndex === -1) {
|
|
1001
|
+
value = "";
|
|
1002
|
+
} else {
|
|
1003
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
1004
|
+
if (encoded) {
|
|
1005
|
+
value = _decodeURI(value);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (multiple) {
|
|
1009
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1010
|
+
results[name] = [];
|
|
1011
|
+
}
|
|
1012
|
+
;
|
|
1013
|
+
results[name].push(value);
|
|
1014
|
+
} else {
|
|
1015
|
+
results[name] ??= value;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
return key ? results[key] : results;
|
|
1019
|
+
};
|
|
1020
|
+
var getQueryParam = _getQueryParam;
|
|
1021
|
+
var getQueryParams = (url, key) => {
|
|
1022
|
+
return _getQueryParam(url, key, true);
|
|
1023
|
+
};
|
|
1024
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1025
|
+
|
|
1026
|
+
// node_modules/hono/dist/request.js
|
|
1027
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1028
|
+
var HonoRequest = class {
|
|
1029
|
+
/**
|
|
1030
|
+
* `.raw` can get the raw Request object.
|
|
1031
|
+
*
|
|
1032
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1033
|
+
*
|
|
1034
|
+
* @example
|
|
1035
|
+
* ```ts
|
|
1036
|
+
* // For Cloudflare Workers
|
|
1037
|
+
* app.post('/', async (c) => {
|
|
1038
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1039
|
+
* ...
|
|
1040
|
+
* })
|
|
1041
|
+
* ```
|
|
1042
|
+
*/
|
|
1043
|
+
raw;
|
|
1044
|
+
#validatedData;
|
|
1045
|
+
// Short name of validatedData
|
|
1046
|
+
#matchResult;
|
|
1047
|
+
routeIndex = 0;
|
|
1048
|
+
/**
|
|
1049
|
+
* `.path` can get the pathname of the request.
|
|
1050
|
+
*
|
|
1051
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1052
|
+
*
|
|
1053
|
+
* @example
|
|
1054
|
+
* ```ts
|
|
1055
|
+
* app.get('/about/me', (c) => {
|
|
1056
|
+
* const pathname = c.req.path // `/about/me`
|
|
1057
|
+
* })
|
|
1058
|
+
* ```
|
|
1059
|
+
*/
|
|
1060
|
+
path;
|
|
1061
|
+
bodyCache = {};
|
|
1062
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1063
|
+
this.raw = request;
|
|
1064
|
+
this.path = path;
|
|
1065
|
+
this.#matchResult = matchResult;
|
|
1066
|
+
this.#validatedData = {};
|
|
1067
|
+
}
|
|
1068
|
+
param(key) {
|
|
1069
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1070
|
+
}
|
|
1071
|
+
#getDecodedParam(key) {
|
|
1072
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1073
|
+
const param = this.#getParamValue(paramKey);
|
|
1074
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1075
|
+
}
|
|
1076
|
+
#getAllDecodedParams() {
|
|
1077
|
+
const decoded = {};
|
|
1078
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1079
|
+
for (const key of keys) {
|
|
1080
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1081
|
+
if (value !== void 0) {
|
|
1082
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return decoded;
|
|
1086
|
+
}
|
|
1087
|
+
#getParamValue(paramKey) {
|
|
1088
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1089
|
+
}
|
|
1090
|
+
query(key) {
|
|
1091
|
+
return getQueryParam(this.url, key);
|
|
1092
|
+
}
|
|
1093
|
+
queries(key) {
|
|
1094
|
+
return getQueryParams(this.url, key);
|
|
1095
|
+
}
|
|
1096
|
+
header(name) {
|
|
1097
|
+
if (name) {
|
|
1098
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1099
|
+
}
|
|
1100
|
+
const headerData = {};
|
|
1101
|
+
this.raw.headers.forEach((value, key) => {
|
|
1102
|
+
headerData[key] = value;
|
|
1103
|
+
});
|
|
1104
|
+
return headerData;
|
|
1105
|
+
}
|
|
1106
|
+
async parseBody(options) {
|
|
1107
|
+
return parseBody(this, options);
|
|
1108
|
+
}
|
|
1109
|
+
#cachedBody = (key) => {
|
|
1110
|
+
const { bodyCache, raw: raw2 } = this;
|
|
1111
|
+
const cachedBody = bodyCache[key];
|
|
1112
|
+
if (cachedBody) {
|
|
1113
|
+
return cachedBody;
|
|
1114
|
+
}
|
|
1115
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1116
|
+
if (anyCachedKey) {
|
|
1117
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1118
|
+
if (anyCachedKey === "json") {
|
|
1119
|
+
body = JSON.stringify(body);
|
|
1120
|
+
}
|
|
1121
|
+
return new Response(body)[key]();
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
return bodyCache[key] = raw2[key]();
|
|
1125
|
+
};
|
|
1126
|
+
/**
|
|
1127
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1128
|
+
*
|
|
1129
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
* ```ts
|
|
1133
|
+
* app.post('/entry', async (c) => {
|
|
1134
|
+
* const body = await c.req.json()
|
|
1135
|
+
* })
|
|
1136
|
+
* ```
|
|
1137
|
+
*/
|
|
1138
|
+
json() {
|
|
1139
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1143
|
+
*
|
|
1144
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1145
|
+
*
|
|
1146
|
+
* @example
|
|
1147
|
+
* ```ts
|
|
1148
|
+
* app.post('/entry', async (c) => {
|
|
1149
|
+
* const body = await c.req.text()
|
|
1150
|
+
* })
|
|
1151
|
+
* ```
|
|
1152
|
+
*/
|
|
1153
|
+
text() {
|
|
1154
|
+
return this.#cachedBody("text");
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1158
|
+
*
|
|
1159
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1160
|
+
*
|
|
1161
|
+
* @example
|
|
1162
|
+
* ```ts
|
|
1163
|
+
* app.post('/entry', async (c) => {
|
|
1164
|
+
* const body = await c.req.arrayBuffer()
|
|
1165
|
+
* })
|
|
1166
|
+
* ```
|
|
1167
|
+
*/
|
|
1168
|
+
arrayBuffer() {
|
|
1169
|
+
return this.#cachedBody("arrayBuffer");
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
1173
|
+
*
|
|
1174
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
1175
|
+
*
|
|
1176
|
+
* @example
|
|
1177
|
+
* ```ts
|
|
1178
|
+
* app.post('/entry', async (c) => {
|
|
1179
|
+
* const body = await c.req.bytes()
|
|
1180
|
+
* })
|
|
1181
|
+
* ```
|
|
1182
|
+
*/
|
|
1183
|
+
bytes() {
|
|
1184
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Parses the request body as a `Blob`.
|
|
1188
|
+
* @example
|
|
1189
|
+
* ```ts
|
|
1190
|
+
* app.post('/entry', async (c) => {
|
|
1191
|
+
* const body = await c.req.blob();
|
|
1192
|
+
* });
|
|
1193
|
+
* ```
|
|
1194
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
1195
|
+
*/
|
|
1196
|
+
blob() {
|
|
1197
|
+
return this.#cachedBody("blob");
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Parses the request body as `FormData`.
|
|
1201
|
+
* @example
|
|
1202
|
+
* ```ts
|
|
1203
|
+
* app.post('/entry', async (c) => {
|
|
1204
|
+
* const body = await c.req.formData();
|
|
1205
|
+
* });
|
|
1206
|
+
* ```
|
|
1207
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
1208
|
+
*/
|
|
1209
|
+
formData() {
|
|
1210
|
+
return this.#cachedBody("formData");
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Adds validated data to the request.
|
|
1214
|
+
*
|
|
1215
|
+
* @param target - The target of the validation.
|
|
1216
|
+
* @param data - The validated data to add.
|
|
1217
|
+
*/
|
|
1218
|
+
addValidatedData(target, data) {
|
|
1219
|
+
this.#validatedData[target] = data;
|
|
1220
|
+
}
|
|
1221
|
+
valid(target) {
|
|
1222
|
+
return this.#validatedData[target];
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* `.url()` can get the request url strings.
|
|
1226
|
+
*
|
|
1227
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
1228
|
+
*
|
|
1229
|
+
* @example
|
|
1230
|
+
* ```ts
|
|
1231
|
+
* app.get('/about/me', (c) => {
|
|
1232
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
1233
|
+
* ...
|
|
1234
|
+
* })
|
|
1235
|
+
* ```
|
|
1236
|
+
*/
|
|
1237
|
+
get url() {
|
|
1238
|
+
return this.raw.url;
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* `.method()` can get the method name of the request.
|
|
1242
|
+
*
|
|
1243
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
1244
|
+
*
|
|
1245
|
+
* @example
|
|
1246
|
+
* ```ts
|
|
1247
|
+
* app.get('/about/me', (c) => {
|
|
1248
|
+
* const method = c.req.method // `GET`
|
|
1249
|
+
* })
|
|
1250
|
+
* ```
|
|
1251
|
+
*/
|
|
1252
|
+
get method() {
|
|
1253
|
+
return this.raw.method;
|
|
1254
|
+
}
|
|
1255
|
+
get [GET_MATCH_RESULT]() {
|
|
1256
|
+
return this.#matchResult;
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
1260
|
+
*
|
|
1261
|
+
* @deprecated
|
|
1262
|
+
*
|
|
1263
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
1264
|
+
*
|
|
1265
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
1266
|
+
*
|
|
1267
|
+
* @example
|
|
1268
|
+
* ```ts
|
|
1269
|
+
* app.use('*', async function logger(c, next) {
|
|
1270
|
+
* await next()
|
|
1271
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
1272
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
1273
|
+
* console.log(
|
|
1274
|
+
* method,
|
|
1275
|
+
* ' ',
|
|
1276
|
+
* path,
|
|
1277
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
1278
|
+
* name,
|
|
1279
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
1280
|
+
* )
|
|
1281
|
+
* })
|
|
1282
|
+
* })
|
|
1283
|
+
* ```
|
|
1284
|
+
*/
|
|
1285
|
+
get matchedRoutes() {
|
|
1286
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
1290
|
+
*
|
|
1291
|
+
* @deprecated
|
|
1292
|
+
*
|
|
1293
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
1294
|
+
*
|
|
1295
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
1296
|
+
*
|
|
1297
|
+
* @example
|
|
1298
|
+
* ```ts
|
|
1299
|
+
* app.get('/posts/:id', (c) => {
|
|
1300
|
+
* return c.json({ path: c.req.routePath })
|
|
1301
|
+
* })
|
|
1302
|
+
* ```
|
|
1303
|
+
*/
|
|
1304
|
+
get routePath() {
|
|
1305
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
// node_modules/hono/dist/utils/html.js
|
|
1310
|
+
var HtmlEscapedCallbackPhase = {
|
|
1311
|
+
Stringify: 1,
|
|
1312
|
+
BeforeStream: 2,
|
|
1313
|
+
Stream: 3
|
|
1314
|
+
};
|
|
1315
|
+
var raw = (value, callbacks) => {
|
|
1316
|
+
const escapedString = new String(value);
|
|
1317
|
+
escapedString.isEscaped = true;
|
|
1318
|
+
escapedString.callbacks = callbacks;
|
|
1319
|
+
return escapedString;
|
|
1320
|
+
};
|
|
1321
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1322
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1323
|
+
if (!(str instanceof Promise)) {
|
|
1324
|
+
str = str.toString();
|
|
1325
|
+
}
|
|
1326
|
+
if (str instanceof Promise) {
|
|
1327
|
+
str = await str;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
const callbacks = str.callbacks;
|
|
1331
|
+
if (!callbacks?.length) {
|
|
1332
|
+
return Promise.resolve(str);
|
|
1333
|
+
}
|
|
1334
|
+
if (buffer) {
|
|
1335
|
+
buffer[0] += str;
|
|
1336
|
+
} else {
|
|
1337
|
+
buffer = [str];
|
|
1338
|
+
}
|
|
1339
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
1340
|
+
(res) => Promise.all(
|
|
1341
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
1342
|
+
).then(() => buffer[0])
|
|
1343
|
+
);
|
|
1344
|
+
if (preserveCallbacks) {
|
|
1345
|
+
return raw(await resStr, callbacks);
|
|
1346
|
+
} else {
|
|
1347
|
+
return resStr;
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
|
|
1351
|
+
// node_modules/hono/dist/context.js
|
|
1352
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1353
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1354
|
+
return {
|
|
1355
|
+
"Content-Type": contentType,
|
|
1356
|
+
...headers
|
|
1357
|
+
};
|
|
1358
|
+
};
|
|
1359
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
1360
|
+
var Context = class {
|
|
1361
|
+
#rawRequest;
|
|
1362
|
+
#req;
|
|
1363
|
+
/**
|
|
1364
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
1365
|
+
*
|
|
1366
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
1367
|
+
*
|
|
1368
|
+
* @example
|
|
1369
|
+
* ```ts
|
|
1370
|
+
* // Environment object for Cloudflare Workers
|
|
1371
|
+
* app.get('*', async c => {
|
|
1372
|
+
* const counter = c.env.COUNTER
|
|
1373
|
+
* })
|
|
1374
|
+
* ```
|
|
1375
|
+
*/
|
|
1376
|
+
env = {};
|
|
1377
|
+
#var;
|
|
1378
|
+
finalized = false;
|
|
1379
|
+
/**
|
|
1380
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
1381
|
+
*
|
|
1382
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
1383
|
+
*
|
|
1384
|
+
* @example
|
|
1385
|
+
* ```ts
|
|
1386
|
+
* app.use('*', async (c, next) => {
|
|
1387
|
+
* await next()
|
|
1388
|
+
* if (c.error) {
|
|
1389
|
+
* // do something...
|
|
1390
|
+
* }
|
|
1391
|
+
* })
|
|
1392
|
+
* ```
|
|
1393
|
+
*/
|
|
1394
|
+
error;
|
|
1395
|
+
#status;
|
|
1396
|
+
#executionCtx;
|
|
1397
|
+
#res;
|
|
1398
|
+
#layout;
|
|
1399
|
+
#renderer;
|
|
1400
|
+
#notFoundHandler;
|
|
1401
|
+
#preparedHeaders;
|
|
1402
|
+
#matchResult;
|
|
1403
|
+
#path;
|
|
1404
|
+
/**
|
|
1405
|
+
* Creates an instance of the Context class.
|
|
1406
|
+
*
|
|
1407
|
+
* @param req - The Request object.
|
|
1408
|
+
* @param options - Optional configuration options for the context.
|
|
1409
|
+
*/
|
|
1410
|
+
constructor(req, options) {
|
|
1411
|
+
this.#rawRequest = req;
|
|
1412
|
+
if (options) {
|
|
1413
|
+
this.#executionCtx = options.executionCtx;
|
|
1414
|
+
this.env = options.env;
|
|
1415
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1416
|
+
this.#path = options.path;
|
|
1417
|
+
this.#matchResult = options.matchResult;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
1422
|
+
*/
|
|
1423
|
+
get req() {
|
|
1424
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1425
|
+
return this.#req;
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
1429
|
+
* The FetchEvent associated with the current request.
|
|
1430
|
+
*
|
|
1431
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
1432
|
+
*/
|
|
1433
|
+
get event() {
|
|
1434
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1435
|
+
return this.#executionCtx;
|
|
1436
|
+
} else {
|
|
1437
|
+
throw Error("This context has no FetchEvent");
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
1442
|
+
* The ExecutionContext associated with the current request.
|
|
1443
|
+
*
|
|
1444
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
1445
|
+
*/
|
|
1446
|
+
get executionCtx() {
|
|
1447
|
+
if (this.#executionCtx) {
|
|
1448
|
+
return this.#executionCtx;
|
|
1449
|
+
} else {
|
|
1450
|
+
throw Error("This context has no ExecutionContext");
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
1455
|
+
* The Response object for the current request.
|
|
1456
|
+
*/
|
|
1457
|
+
get res() {
|
|
1458
|
+
return this.#res ||= createResponseInstance(null, {
|
|
1459
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* Sets the Response object for the current request.
|
|
1464
|
+
*
|
|
1465
|
+
* @param _res - The Response object to set.
|
|
1466
|
+
*/
|
|
1467
|
+
set res(_res) {
|
|
1468
|
+
if (this.#res && _res) {
|
|
1469
|
+
_res = createResponseInstance(_res.body, _res);
|
|
1470
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1471
|
+
if (k === "content-type") {
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
if (k === "set-cookie") {
|
|
1475
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1476
|
+
_res.headers.delete("set-cookie");
|
|
1477
|
+
for (const cookie of cookies) {
|
|
1478
|
+
_res.headers.append("set-cookie", cookie);
|
|
1479
|
+
}
|
|
1480
|
+
} else {
|
|
1481
|
+
_res.headers.set(k, v);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
this.#res = _res;
|
|
1486
|
+
this.finalized = true;
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* `.render()` can create a response within a layout.
|
|
1490
|
+
*
|
|
1491
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1492
|
+
*
|
|
1493
|
+
* @example
|
|
1494
|
+
* ```ts
|
|
1495
|
+
* app.get('/', (c) => {
|
|
1496
|
+
* return c.render('Hello!')
|
|
1497
|
+
* })
|
|
1498
|
+
* ```
|
|
1499
|
+
*/
|
|
1500
|
+
render = (...args) => {
|
|
1501
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1502
|
+
return this.#renderer(...args);
|
|
1503
|
+
};
|
|
1504
|
+
/**
|
|
1505
|
+
* Sets the layout for the response.
|
|
1506
|
+
*
|
|
1507
|
+
* @param layout - The layout to set.
|
|
1508
|
+
* @returns The layout function.
|
|
1509
|
+
*/
|
|
1510
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1511
|
+
/**
|
|
1512
|
+
* Gets the current layout for the response.
|
|
1513
|
+
*
|
|
1514
|
+
* @returns The current layout function.
|
|
1515
|
+
*/
|
|
1516
|
+
getLayout = () => this.#layout;
|
|
1517
|
+
/**
|
|
1518
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
1519
|
+
*
|
|
1520
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1521
|
+
*
|
|
1522
|
+
* @example
|
|
1523
|
+
* ```tsx
|
|
1524
|
+
* app.use('*', async (c, next) => {
|
|
1525
|
+
* c.setRenderer((content) => {
|
|
1526
|
+
* return c.html(
|
|
1527
|
+
* <html>
|
|
1528
|
+
* <body>
|
|
1529
|
+
* <p>{content}</p>
|
|
1530
|
+
* </body>
|
|
1531
|
+
* </html>
|
|
1532
|
+
* )
|
|
1533
|
+
* })
|
|
1534
|
+
* await next()
|
|
1535
|
+
* })
|
|
1536
|
+
* ```
|
|
1537
|
+
*/
|
|
1538
|
+
setRenderer = (renderer) => {
|
|
1539
|
+
this.#renderer = renderer;
|
|
1540
|
+
};
|
|
1541
|
+
/**
|
|
1542
|
+
* `.header()` can set headers.
|
|
1543
|
+
*
|
|
1544
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
1545
|
+
*
|
|
1546
|
+
* @example
|
|
1547
|
+
* ```ts
|
|
1548
|
+
* app.get('/welcome', (c) => {
|
|
1549
|
+
* // Set headers
|
|
1550
|
+
* c.header('X-Message', 'Hello!')
|
|
1551
|
+
* c.header('Content-Type', 'text/plain')
|
|
1552
|
+
*
|
|
1553
|
+
* return c.body('Thank you for coming')
|
|
1554
|
+
* })
|
|
1555
|
+
* ```
|
|
1556
|
+
*/
|
|
1557
|
+
header = (name, value, options) => {
|
|
1558
|
+
if (this.finalized) {
|
|
1559
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
1560
|
+
}
|
|
1561
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
1562
|
+
if (value === void 0) {
|
|
1563
|
+
headers.delete(name);
|
|
1564
|
+
} else if (options?.append) {
|
|
1565
|
+
headers.append(name, value);
|
|
1566
|
+
} else {
|
|
1567
|
+
headers.set(name, value);
|
|
1568
|
+
}
|
|
1569
|
+
};
|
|
1570
|
+
status = (status) => {
|
|
1571
|
+
this.#status = status;
|
|
1572
|
+
};
|
|
1573
|
+
/**
|
|
1574
|
+
* `.set()` can set the value specified by the key.
|
|
1575
|
+
*
|
|
1576
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1577
|
+
*
|
|
1578
|
+
* @example
|
|
1579
|
+
* ```ts
|
|
1580
|
+
* app.use('*', async (c, next) => {
|
|
1581
|
+
* c.set('message', 'Hono is hot!!')
|
|
1582
|
+
* await next()
|
|
1583
|
+
* })
|
|
1584
|
+
* ```
|
|
1585
|
+
*/
|
|
1586
|
+
set = (key, value) => {
|
|
1587
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
1588
|
+
this.#var.set(key, value);
|
|
1589
|
+
};
|
|
1590
|
+
/**
|
|
1591
|
+
* `.get()` can use the value specified by the key.
|
|
1592
|
+
*
|
|
1593
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1594
|
+
*
|
|
1595
|
+
* @example
|
|
1596
|
+
* ```ts
|
|
1597
|
+
* app.get('/', (c) => {
|
|
1598
|
+
* const message = c.get('message')
|
|
1599
|
+
* return c.text(`The message is "${message}"`)
|
|
1600
|
+
* })
|
|
1601
|
+
* ```
|
|
1602
|
+
*/
|
|
1603
|
+
get = (key) => {
|
|
1604
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
1605
|
+
};
|
|
1606
|
+
/**
|
|
1607
|
+
* `.var` can access the value of a variable.
|
|
1608
|
+
*
|
|
1609
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
1610
|
+
*
|
|
1611
|
+
* @example
|
|
1612
|
+
* ```ts
|
|
1613
|
+
* const result = c.var.client.oneMethod()
|
|
1614
|
+
* ```
|
|
1615
|
+
*/
|
|
1616
|
+
// c.var.propName is a read-only
|
|
1617
|
+
get var() {
|
|
1618
|
+
if (!this.#var) {
|
|
1619
|
+
return {};
|
|
1620
|
+
}
|
|
1621
|
+
return Object.fromEntries(this.#var);
|
|
1622
|
+
}
|
|
1623
|
+
#newResponse(data, arg, headers) {
|
|
1624
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
1625
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
1626
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
1627
|
+
for (const [key, value] of argHeaders) {
|
|
1628
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1629
|
+
responseHeaders.append(key, value);
|
|
1630
|
+
} else {
|
|
1631
|
+
responseHeaders.set(key, value);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (headers) {
|
|
1636
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1637
|
+
if (typeof v === "string") {
|
|
1638
|
+
responseHeaders.set(k, v);
|
|
1639
|
+
} else {
|
|
1640
|
+
responseHeaders.delete(k);
|
|
1641
|
+
for (const v2 of v) {
|
|
1642
|
+
responseHeaders.append(k, v2);
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1648
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
1649
|
+
}
|
|
1650
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1651
|
+
/**
|
|
1652
|
+
* `.body()` can return the HTTP response.
|
|
1653
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
1654
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
1655
|
+
*
|
|
1656
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
1657
|
+
*
|
|
1658
|
+
* @example
|
|
1659
|
+
* ```ts
|
|
1660
|
+
* app.get('/welcome', (c) => {
|
|
1661
|
+
* // Set headers
|
|
1662
|
+
* c.header('X-Message', 'Hello!')
|
|
1663
|
+
* c.header('Content-Type', 'text/plain')
|
|
1664
|
+
* // Set HTTP status code
|
|
1665
|
+
* c.status(201)
|
|
1666
|
+
*
|
|
1667
|
+
* // Return the response body
|
|
1668
|
+
* return c.body('Thank you for coming')
|
|
1669
|
+
* })
|
|
1670
|
+
* ```
|
|
1671
|
+
*/
|
|
1672
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1673
|
+
/**
|
|
1674
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
1675
|
+
*
|
|
1676
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
1677
|
+
*
|
|
1678
|
+
* @example
|
|
1679
|
+
* ```ts
|
|
1680
|
+
* app.get('/say', (c) => {
|
|
1681
|
+
* return c.text('Hello!')
|
|
1682
|
+
* })
|
|
1683
|
+
* ```
|
|
1684
|
+
*/
|
|
1685
|
+
text = (text, arg, headers) => {
|
|
1686
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
1687
|
+
text,
|
|
1688
|
+
arg,
|
|
1689
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
1690
|
+
);
|
|
1691
|
+
};
|
|
1692
|
+
/**
|
|
1693
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
1694
|
+
*
|
|
1695
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
1696
|
+
*
|
|
1697
|
+
* @example
|
|
1698
|
+
* ```ts
|
|
1699
|
+
* app.get('/api', (c) => {
|
|
1700
|
+
* return c.json({ message: 'Hello!' })
|
|
1701
|
+
* })
|
|
1702
|
+
* ```
|
|
1703
|
+
*/
|
|
1704
|
+
json = (object, arg, headers) => {
|
|
1705
|
+
return this.#newResponse(
|
|
1706
|
+
JSON.stringify(object),
|
|
1707
|
+
arg,
|
|
1708
|
+
setDefaultContentType("application/json", headers)
|
|
1709
|
+
);
|
|
1710
|
+
};
|
|
1711
|
+
html = (html, arg, headers) => {
|
|
1712
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1713
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1714
|
+
};
|
|
1715
|
+
/**
|
|
1716
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1717
|
+
*
|
|
1718
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1719
|
+
*
|
|
1720
|
+
* @example
|
|
1721
|
+
* ```ts
|
|
1722
|
+
* app.get('/redirect', (c) => {
|
|
1723
|
+
* return c.redirect('/')
|
|
1724
|
+
* })
|
|
1725
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1726
|
+
* return c.redirect('/', 301)
|
|
1727
|
+
* })
|
|
1728
|
+
* ```
|
|
1729
|
+
*/
|
|
1730
|
+
redirect = (location, status) => {
|
|
1731
|
+
const locationString = String(location);
|
|
1732
|
+
this.header(
|
|
1733
|
+
"Location",
|
|
1734
|
+
// Multibyes should be encoded
|
|
1735
|
+
// eslint-disable-next-line no-control-regex
|
|
1736
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1737
|
+
);
|
|
1738
|
+
return this.newResponse(null, status ?? 302);
|
|
1739
|
+
};
|
|
1740
|
+
/**
|
|
1741
|
+
* `.notFound()` can return the Not Found Response.
|
|
1742
|
+
*
|
|
1743
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1744
|
+
*
|
|
1745
|
+
* @example
|
|
1746
|
+
* ```ts
|
|
1747
|
+
* app.get('/notfound', (c) => {
|
|
1748
|
+
* return c.notFound()
|
|
1749
|
+
* })
|
|
1750
|
+
* ```
|
|
1751
|
+
*/
|
|
1752
|
+
notFound = () => {
|
|
1753
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1754
|
+
return this.#notFoundHandler(this);
|
|
1755
|
+
};
|
|
1756
|
+
};
|
|
1757
|
+
|
|
1758
|
+
// node_modules/hono/dist/router.js
|
|
1759
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1760
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1761
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1762
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1763
|
+
var UnsupportedPathError = class extends Error {
|
|
1764
|
+
};
|
|
1765
|
+
|
|
1766
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1767
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1768
|
+
|
|
1769
|
+
// node_modules/hono/dist/hono-base.js
|
|
1770
|
+
var notFoundHandler = (c) => {
|
|
1771
|
+
return c.text("404 Not Found", 404);
|
|
1772
|
+
};
|
|
1773
|
+
var errorHandler = (err, c) => {
|
|
1774
|
+
if ("getResponse" in err) {
|
|
1775
|
+
const res = err.getResponse();
|
|
1776
|
+
return c.newResponse(res.body, res);
|
|
1777
|
+
}
|
|
1778
|
+
console.error(err);
|
|
1779
|
+
return c.text("Internal Server Error", 500);
|
|
1780
|
+
};
|
|
1781
|
+
var Hono = class _Hono {
|
|
1782
|
+
get;
|
|
1783
|
+
post;
|
|
1784
|
+
put;
|
|
1785
|
+
delete;
|
|
1786
|
+
options;
|
|
1787
|
+
patch;
|
|
1788
|
+
all;
|
|
1789
|
+
on;
|
|
1790
|
+
use;
|
|
1791
|
+
/*
|
|
1792
|
+
This class is like an abstract class and does not have a router.
|
|
1793
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1794
|
+
*/
|
|
1795
|
+
router;
|
|
1796
|
+
getPath;
|
|
1797
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1798
|
+
_basePath = "/";
|
|
1799
|
+
#path = "/";
|
|
1800
|
+
routes = [];
|
|
1801
|
+
constructor(options = {}) {
|
|
1802
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1803
|
+
allMethods.forEach((method) => {
|
|
1804
|
+
this[method] = (args1, ...args) => {
|
|
1805
|
+
if (typeof args1 === "string") {
|
|
1806
|
+
this.#path = args1;
|
|
1807
|
+
} else {
|
|
1808
|
+
this.#addRoute(method, this.#path, args1);
|
|
1809
|
+
}
|
|
1810
|
+
args.forEach((handler) => {
|
|
1811
|
+
this.#addRoute(method, this.#path, handler);
|
|
1812
|
+
});
|
|
1813
|
+
return this;
|
|
1814
|
+
};
|
|
1815
|
+
});
|
|
1816
|
+
this.on = (method, path, ...handlers) => {
|
|
1817
|
+
for (const p of [path].flat()) {
|
|
1818
|
+
this.#path = p;
|
|
1819
|
+
for (const m of [method].flat()) {
|
|
1820
|
+
handlers.map((handler) => {
|
|
1821
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
return this;
|
|
1826
|
+
};
|
|
1827
|
+
this.use = (arg1, ...handlers) => {
|
|
1828
|
+
if (typeof arg1 === "string") {
|
|
1829
|
+
this.#path = arg1;
|
|
1830
|
+
} else {
|
|
1831
|
+
this.#path = "*";
|
|
1832
|
+
handlers.unshift(arg1);
|
|
1833
|
+
}
|
|
1834
|
+
handlers.forEach((handler) => {
|
|
1835
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1836
|
+
});
|
|
1837
|
+
return this;
|
|
1838
|
+
};
|
|
1839
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1840
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1841
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1842
|
+
}
|
|
1843
|
+
#clone() {
|
|
1844
|
+
const clone = new _Hono({
|
|
1845
|
+
router: this.router,
|
|
1846
|
+
getPath: this.getPath
|
|
1847
|
+
});
|
|
1848
|
+
clone.errorHandler = this.errorHandler;
|
|
1849
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1850
|
+
clone.routes = this.routes;
|
|
1851
|
+
return clone;
|
|
1852
|
+
}
|
|
1853
|
+
#notFoundHandler = notFoundHandler;
|
|
1854
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1855
|
+
errorHandler = errorHandler;
|
|
1856
|
+
/**
|
|
1857
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1858
|
+
*
|
|
1859
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1860
|
+
*
|
|
1861
|
+
* @param {string} path - base Path
|
|
1862
|
+
* @param {Hono} app - other Hono instance
|
|
1863
|
+
* @returns {Hono} routed Hono instance
|
|
1864
|
+
*
|
|
1865
|
+
* @example
|
|
1866
|
+
* ```ts
|
|
1867
|
+
* const app = new Hono()
|
|
1868
|
+
* const app2 = new Hono()
|
|
1869
|
+
*
|
|
1870
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1871
|
+
* app.route("/api", app2) // GET /api/user
|
|
1872
|
+
* ```
|
|
1873
|
+
*/
|
|
1874
|
+
route(path, app2) {
|
|
1875
|
+
const subApp = this.basePath(path);
|
|
1876
|
+
app2.routes.map((r) => {
|
|
1877
|
+
let handler;
|
|
1878
|
+
if (app2.errorHandler === errorHandler) {
|
|
1879
|
+
handler = r.handler;
|
|
1880
|
+
} else {
|
|
1881
|
+
handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1882
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1883
|
+
}
|
|
1884
|
+
subApp.#addRoute(r.method, r.path, handler, r.basePath);
|
|
1885
|
+
});
|
|
1886
|
+
return this;
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* `.basePath()` allows base paths to be specified.
|
|
1890
|
+
*
|
|
1891
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1892
|
+
*
|
|
1893
|
+
* @param {string} path - base Path
|
|
1894
|
+
* @returns {Hono} changed Hono instance
|
|
1895
|
+
*
|
|
1896
|
+
* @example
|
|
1897
|
+
* ```ts
|
|
1898
|
+
* const api = new Hono().basePath('/api')
|
|
1899
|
+
* ```
|
|
1900
|
+
*/
|
|
1901
|
+
basePath(path) {
|
|
1902
|
+
const subApp = this.#clone();
|
|
1903
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
1904
|
+
return subApp;
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
1908
|
+
*
|
|
1909
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
1910
|
+
*
|
|
1911
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
1912
|
+
* @returns {Hono} changed Hono instance
|
|
1913
|
+
*
|
|
1914
|
+
* @example
|
|
1915
|
+
* ```ts
|
|
1916
|
+
* app.onError((err, c) => {
|
|
1917
|
+
* console.error(`${err}`)
|
|
1918
|
+
* return c.text('Custom Error Message', 500)
|
|
1919
|
+
* })
|
|
1920
|
+
* ```
|
|
1921
|
+
*/
|
|
1922
|
+
onError = (handler) => {
|
|
1923
|
+
this.errorHandler = handler;
|
|
1924
|
+
return this;
|
|
1925
|
+
};
|
|
1926
|
+
/**
|
|
1927
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
1928
|
+
*
|
|
1929
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
1930
|
+
*
|
|
1931
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
1932
|
+
* @returns {Hono} changed Hono instance
|
|
1933
|
+
*
|
|
1934
|
+
* @example
|
|
1935
|
+
* ```ts
|
|
1936
|
+
* app.notFound((c) => {
|
|
1937
|
+
* return c.text('Custom 404 Message', 404)
|
|
1938
|
+
* })
|
|
1939
|
+
* ```
|
|
1940
|
+
*/
|
|
1941
|
+
notFound = (handler) => {
|
|
1942
|
+
this.#notFoundHandler = handler;
|
|
1943
|
+
return this;
|
|
1944
|
+
};
|
|
1945
|
+
/**
|
|
1946
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
1947
|
+
*
|
|
1948
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
1949
|
+
*
|
|
1950
|
+
* @param {string} path - base Path
|
|
1951
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
1952
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
1953
|
+
* @returns {Hono} mounted Hono instance
|
|
1954
|
+
*
|
|
1955
|
+
* @example
|
|
1956
|
+
* ```ts
|
|
1957
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
1958
|
+
* import { Hono } from 'hono'
|
|
1959
|
+
* // Create itty-router application
|
|
1960
|
+
* const ittyRouter = IttyRouter()
|
|
1961
|
+
* // GET /itty-router/hello
|
|
1962
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
1963
|
+
*
|
|
1964
|
+
* const app = new Hono()
|
|
1965
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
1966
|
+
* ```
|
|
1967
|
+
*
|
|
1968
|
+
* @example
|
|
1969
|
+
* ```ts
|
|
1970
|
+
* const app = new Hono()
|
|
1971
|
+
* // Send the request to another application without modification.
|
|
1972
|
+
* app.mount('/app', anotherApp, {
|
|
1973
|
+
* replaceRequest: (req) => req,
|
|
1974
|
+
* })
|
|
1975
|
+
* ```
|
|
1976
|
+
*/
|
|
1977
|
+
mount(path, applicationHandler, options) {
|
|
1978
|
+
let replaceRequest;
|
|
1979
|
+
let optionHandler;
|
|
1980
|
+
if (options) {
|
|
1981
|
+
if (typeof options === "function") {
|
|
1982
|
+
optionHandler = options;
|
|
1983
|
+
} else {
|
|
1984
|
+
optionHandler = options.optionHandler;
|
|
1985
|
+
if (options.replaceRequest === false) {
|
|
1986
|
+
replaceRequest = (request) => request;
|
|
1987
|
+
} else {
|
|
1988
|
+
replaceRequest = options.replaceRequest;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
const getOptions = optionHandler ? (c) => {
|
|
1993
|
+
const options2 = optionHandler(c);
|
|
1994
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
1995
|
+
} : (c) => {
|
|
1996
|
+
let executionContext = void 0;
|
|
1997
|
+
try {
|
|
1998
|
+
executionContext = c.executionCtx;
|
|
1999
|
+
} catch {
|
|
2000
|
+
}
|
|
2001
|
+
return [c.env, executionContext];
|
|
2002
|
+
};
|
|
2003
|
+
replaceRequest ||= (() => {
|
|
2004
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
2005
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2006
|
+
return (request) => {
|
|
2007
|
+
const url = new URL(request.url);
|
|
2008
|
+
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
|
|
2009
|
+
return new Request(url, request);
|
|
2010
|
+
};
|
|
2011
|
+
})();
|
|
2012
|
+
const handler = async (c, next) => {
|
|
2013
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2014
|
+
if (res) {
|
|
2015
|
+
return res;
|
|
2016
|
+
}
|
|
2017
|
+
await next();
|
|
2018
|
+
};
|
|
2019
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
2020
|
+
return this;
|
|
2021
|
+
}
|
|
2022
|
+
#addRoute(method, path, handler, baseRoutePath) {
|
|
2023
|
+
method = method.toUpperCase();
|
|
2024
|
+
path = mergePath(this._basePath, path);
|
|
2025
|
+
const r = {
|
|
2026
|
+
basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
|
|
2027
|
+
path,
|
|
2028
|
+
method,
|
|
2029
|
+
handler
|
|
2030
|
+
};
|
|
2031
|
+
this.router.add(method, path, [handler, r]);
|
|
2032
|
+
this.routes.push(r);
|
|
2033
|
+
}
|
|
2034
|
+
#handleError(err, c) {
|
|
2035
|
+
if (err instanceof Error) {
|
|
2036
|
+
return this.errorHandler(err, c);
|
|
2037
|
+
}
|
|
2038
|
+
throw err;
|
|
2039
|
+
}
|
|
2040
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2041
|
+
if (method === "HEAD") {
|
|
2042
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2043
|
+
}
|
|
2044
|
+
const path = this.getPath(request, { env });
|
|
2045
|
+
const matchResult = this.router.match(method, path);
|
|
2046
|
+
const c = new Context(request, {
|
|
2047
|
+
path,
|
|
2048
|
+
matchResult,
|
|
2049
|
+
env,
|
|
2050
|
+
executionCtx,
|
|
2051
|
+
notFoundHandler: this.#notFoundHandler
|
|
2052
|
+
});
|
|
2053
|
+
if (matchResult[0].length === 1) {
|
|
2054
|
+
let res;
|
|
2055
|
+
try {
|
|
2056
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2057
|
+
c.res = await this.#notFoundHandler(c);
|
|
2058
|
+
});
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
return this.#handleError(err, c);
|
|
2061
|
+
}
|
|
2062
|
+
return res instanceof Promise ? res.then(
|
|
2063
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
2064
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2065
|
+
}
|
|
2066
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2067
|
+
return (async () => {
|
|
2068
|
+
try {
|
|
2069
|
+
const context = await composed(c);
|
|
2070
|
+
if (!context.finalized) {
|
|
2071
|
+
throw new Error(
|
|
2072
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
return context.res;
|
|
2076
|
+
} catch (err) {
|
|
2077
|
+
return this.#handleError(err, c);
|
|
2078
|
+
}
|
|
2079
|
+
})();
|
|
2080
|
+
}
|
|
2081
|
+
/**
|
|
2082
|
+
* `.fetch()` will be entry point of your app.
|
|
2083
|
+
*
|
|
2084
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
2085
|
+
*
|
|
2086
|
+
* @param {Request} request - request Object of request
|
|
2087
|
+
* @param {Env} Env - env Object
|
|
2088
|
+
* @param {ExecutionContext} - context of execution
|
|
2089
|
+
* @returns {Response | Promise<Response>} response of request
|
|
2090
|
+
*
|
|
2091
|
+
*/
|
|
2092
|
+
fetch = (request, ...rest) => {
|
|
2093
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2094
|
+
};
|
|
2095
|
+
/**
|
|
2096
|
+
* `.request()` is a useful method for testing.
|
|
2097
|
+
* You can pass a URL or pathname to send a GET request.
|
|
2098
|
+
* app will return a Response object.
|
|
2099
|
+
* ```ts
|
|
2100
|
+
* test('GET /hello is ok', async () => {
|
|
2101
|
+
* const res = await app.request('/hello')
|
|
2102
|
+
* expect(res.status).toBe(200)
|
|
2103
|
+
* })
|
|
2104
|
+
* ```
|
|
2105
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
2106
|
+
*/
|
|
2107
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2108
|
+
if (input instanceof Request) {
|
|
2109
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2110
|
+
}
|
|
2111
|
+
input = input.toString();
|
|
2112
|
+
return this.fetch(
|
|
2113
|
+
new Request(
|
|
2114
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
2115
|
+
requestInit
|
|
2116
|
+
),
|
|
2117
|
+
Env,
|
|
2118
|
+
executionCtx
|
|
2119
|
+
);
|
|
2120
|
+
};
|
|
2121
|
+
/**
|
|
2122
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
2123
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
2124
|
+
* @deprecated
|
|
2125
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
2126
|
+
* ```ts
|
|
2127
|
+
* import { Hono } from 'hono'
|
|
2128
|
+
* import { fire } from 'hono/service-worker'
|
|
2129
|
+
*
|
|
2130
|
+
* const app = new Hono()
|
|
2131
|
+
* // ...
|
|
2132
|
+
* fire(app)
|
|
2133
|
+
* ```
|
|
2134
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
2135
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
2136
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
2137
|
+
*/
|
|
2138
|
+
fire = () => {
|
|
2139
|
+
addEventListener("fetch", (event) => {
|
|
2140
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
2141
|
+
});
|
|
2142
|
+
};
|
|
2143
|
+
};
|
|
2144
|
+
|
|
2145
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2146
|
+
var emptyParam = [];
|
|
2147
|
+
function match(method, path) {
|
|
2148
|
+
const matchers = this.buildAllMatchers();
|
|
2149
|
+
const match2 = ((method2, path2) => {
|
|
2150
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2151
|
+
const staticMatch = matcher[2][path2];
|
|
2152
|
+
if (staticMatch) {
|
|
2153
|
+
return staticMatch;
|
|
2154
|
+
}
|
|
2155
|
+
const match3 = path2.match(matcher[0]);
|
|
2156
|
+
if (!match3) {
|
|
2157
|
+
return [[], emptyParam];
|
|
2158
|
+
}
|
|
2159
|
+
const index = match3.indexOf("", 1);
|
|
2160
|
+
return [matcher[1][index], match3];
|
|
2161
|
+
});
|
|
2162
|
+
this.match = match2;
|
|
2163
|
+
return match2(method, path);
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2167
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2168
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2169
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2170
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2171
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2172
|
+
function compareKey(a, b) {
|
|
2173
|
+
if (a.length === 1) {
|
|
2174
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2175
|
+
}
|
|
2176
|
+
if (b.length === 1) {
|
|
2177
|
+
return 1;
|
|
2178
|
+
}
|
|
2179
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2180
|
+
return 1;
|
|
2181
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2182
|
+
return -1;
|
|
2183
|
+
}
|
|
2184
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
2185
|
+
return 1;
|
|
2186
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
2187
|
+
return -1;
|
|
2188
|
+
}
|
|
2189
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
2190
|
+
}
|
|
2191
|
+
var Node = class _Node {
|
|
2192
|
+
#index;
|
|
2193
|
+
#varIndex;
|
|
2194
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
2195
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
2196
|
+
if (tokens.length === 0) {
|
|
2197
|
+
if (this.#index !== void 0) {
|
|
2198
|
+
throw PATH_ERROR;
|
|
2199
|
+
}
|
|
2200
|
+
if (pathErrorCheckOnly) {
|
|
2201
|
+
return;
|
|
2202
|
+
}
|
|
2203
|
+
this.#index = index;
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
const [token, ...restTokens] = tokens;
|
|
2207
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2208
|
+
let node;
|
|
2209
|
+
if (pattern) {
|
|
2210
|
+
const name = pattern[1];
|
|
2211
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
2212
|
+
if (name && pattern[2]) {
|
|
2213
|
+
if (regexpStr === ".*") {
|
|
2214
|
+
throw PATH_ERROR;
|
|
2215
|
+
}
|
|
2216
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
2217
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
2218
|
+
throw PATH_ERROR;
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
node = this.#children[regexpStr];
|
|
2222
|
+
if (!node) {
|
|
2223
|
+
if (Object.keys(this.#children).some(
|
|
2224
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2225
|
+
)) {
|
|
2226
|
+
throw PATH_ERROR;
|
|
2227
|
+
}
|
|
2228
|
+
if (pathErrorCheckOnly) {
|
|
2229
|
+
return;
|
|
2230
|
+
}
|
|
2231
|
+
node = this.#children[regexpStr] = new _Node();
|
|
2232
|
+
if (name !== "") {
|
|
2233
|
+
node.#varIndex = context.varIndex++;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
2237
|
+
paramMap.push([name, node.#varIndex]);
|
|
2238
|
+
}
|
|
2239
|
+
} else {
|
|
2240
|
+
node = this.#children[token];
|
|
2241
|
+
if (!node) {
|
|
2242
|
+
if (Object.keys(this.#children).some(
|
|
2243
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2244
|
+
)) {
|
|
2245
|
+
throw PATH_ERROR;
|
|
2246
|
+
}
|
|
2247
|
+
if (pathErrorCheckOnly) {
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
node = this.#children[token] = new _Node();
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
2254
|
+
}
|
|
2255
|
+
buildRegExpStr() {
|
|
2256
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
2257
|
+
const strList = childKeys.map((k) => {
|
|
2258
|
+
const c = this.#children[k];
|
|
2259
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
2260
|
+
});
|
|
2261
|
+
if (typeof this.#index === "number") {
|
|
2262
|
+
strList.unshift(`#${this.#index}`);
|
|
2263
|
+
}
|
|
2264
|
+
if (strList.length === 0) {
|
|
2265
|
+
return "";
|
|
2266
|
+
}
|
|
2267
|
+
if (strList.length === 1) {
|
|
2268
|
+
return strList[0];
|
|
2269
|
+
}
|
|
2270
|
+
return "(?:" + strList.join("|") + ")";
|
|
2271
|
+
}
|
|
2272
|
+
};
|
|
2273
|
+
|
|
2274
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
2275
|
+
var Trie = class {
|
|
2276
|
+
#context = { varIndex: 0 };
|
|
2277
|
+
#root = new Node();
|
|
2278
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
2279
|
+
const paramAssoc = [];
|
|
2280
|
+
const groups = [];
|
|
2281
|
+
for (let i = 0; ; ) {
|
|
2282
|
+
let replaced = false;
|
|
2283
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
2284
|
+
const mark = `@\\${i}`;
|
|
2285
|
+
groups[i] = [mark, m];
|
|
2286
|
+
i++;
|
|
2287
|
+
replaced = true;
|
|
2288
|
+
return mark;
|
|
2289
|
+
});
|
|
2290
|
+
if (!replaced) {
|
|
2291
|
+
break;
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
2295
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
2296
|
+
const [mark] = groups[i];
|
|
2297
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
2298
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
2299
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
2300
|
+
break;
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
2305
|
+
return paramAssoc;
|
|
2306
|
+
}
|
|
2307
|
+
buildRegExp() {
|
|
2308
|
+
let regexp = this.#root.buildRegExpStr();
|
|
2309
|
+
if (regexp === "") {
|
|
2310
|
+
return [/^$/, [], []];
|
|
2311
|
+
}
|
|
2312
|
+
let captureIndex = 0;
|
|
2313
|
+
const indexReplacementMap = [];
|
|
2314
|
+
const paramReplacementMap = [];
|
|
2315
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
2316
|
+
if (handlerIndex !== void 0) {
|
|
2317
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
2318
|
+
return "$()";
|
|
2319
|
+
}
|
|
2320
|
+
if (paramIndex !== void 0) {
|
|
2321
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
2322
|
+
return "";
|
|
2323
|
+
}
|
|
2324
|
+
return "";
|
|
2325
|
+
});
|
|
2326
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
2327
|
+
}
|
|
2328
|
+
};
|
|
2329
|
+
|
|
2330
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
2331
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
2332
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2333
|
+
function buildWildcardRegExp(path) {
|
|
2334
|
+
return wildcardRegExpCache[path] ??= new RegExp(
|
|
2335
|
+
path === "*" ? "" : `^${path.replace(
|
|
2336
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
2337
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
2338
|
+
)}$`
|
|
2339
|
+
);
|
|
2340
|
+
}
|
|
2341
|
+
function clearWildcardRegExpCache() {
|
|
2342
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2343
|
+
}
|
|
2344
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
2345
|
+
const trie = new Trie();
|
|
2346
|
+
const handlerData = [];
|
|
2347
|
+
if (routes.length === 0) {
|
|
2348
|
+
return nullMatcher;
|
|
2349
|
+
}
|
|
2350
|
+
const routesWithStaticPathFlag = routes.map(
|
|
2351
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
2352
|
+
).sort(
|
|
2353
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
2354
|
+
);
|
|
2355
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
2356
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
2357
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
2358
|
+
if (pathErrorCheckOnly) {
|
|
2359
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
2360
|
+
} else {
|
|
2361
|
+
j++;
|
|
2362
|
+
}
|
|
2363
|
+
let paramAssoc;
|
|
2364
|
+
try {
|
|
2365
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
2366
|
+
} catch (e) {
|
|
2367
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
2368
|
+
}
|
|
2369
|
+
if (pathErrorCheckOnly) {
|
|
2370
|
+
continue;
|
|
2371
|
+
}
|
|
2372
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
2373
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
2374
|
+
paramCount -= 1;
|
|
2375
|
+
for (; paramCount >= 0; paramCount--) {
|
|
2376
|
+
const [key, value] = paramAssoc[paramCount];
|
|
2377
|
+
paramIndexMap[key] = value;
|
|
2378
|
+
}
|
|
2379
|
+
return [h, paramIndexMap];
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
2383
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
2384
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
2385
|
+
const map = handlerData[i][j]?.[1];
|
|
2386
|
+
if (!map) {
|
|
2387
|
+
continue;
|
|
2388
|
+
}
|
|
2389
|
+
const keys = Object.keys(map);
|
|
2390
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
2391
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
const handlerMap = [];
|
|
2396
|
+
for (const i in indexReplacementMap) {
|
|
2397
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
2398
|
+
}
|
|
2399
|
+
return [regexp, handlerMap, staticMap];
|
|
2400
|
+
}
|
|
2401
|
+
function findMiddleware(middleware, path) {
|
|
2402
|
+
if (!middleware) {
|
|
2403
|
+
return void 0;
|
|
2404
|
+
}
|
|
2405
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
2406
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
2407
|
+
return [...middleware[k]];
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
return void 0;
|
|
2411
|
+
}
|
|
2412
|
+
var RegExpRouter = class {
|
|
2413
|
+
name = "RegExpRouter";
|
|
2414
|
+
#middleware;
|
|
2415
|
+
#routes;
|
|
2416
|
+
constructor() {
|
|
2417
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2418
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2419
|
+
}
|
|
2420
|
+
add(method, path, handler) {
|
|
2421
|
+
const middleware = this.#middleware;
|
|
2422
|
+
const routes = this.#routes;
|
|
2423
|
+
if (!middleware || !routes) {
|
|
2424
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2425
|
+
}
|
|
2426
|
+
if (!middleware[method]) {
|
|
2427
|
+
;
|
|
2428
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
2429
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
2430
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
2431
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
2432
|
+
});
|
|
2433
|
+
});
|
|
2434
|
+
}
|
|
2435
|
+
if (path === "/*") {
|
|
2436
|
+
path = "*";
|
|
2437
|
+
}
|
|
2438
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
2439
|
+
if (/\*$/.test(path)) {
|
|
2440
|
+
const re = buildWildcardRegExp(path);
|
|
2441
|
+
if (method === METHOD_NAME_ALL) {
|
|
2442
|
+
Object.keys(middleware).forEach((m) => {
|
|
2443
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2444
|
+
});
|
|
2445
|
+
} else {
|
|
2446
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2447
|
+
}
|
|
2448
|
+
Object.keys(middleware).forEach((m) => {
|
|
2449
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2450
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
2451
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
2452
|
+
});
|
|
2453
|
+
}
|
|
2454
|
+
});
|
|
2455
|
+
Object.keys(routes).forEach((m) => {
|
|
2456
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2457
|
+
Object.keys(routes[m]).forEach(
|
|
2458
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
2459
|
+
);
|
|
2460
|
+
}
|
|
2461
|
+
});
|
|
2462
|
+
return;
|
|
2463
|
+
}
|
|
2464
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
2465
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
2466
|
+
const path2 = paths[i];
|
|
2467
|
+
Object.keys(routes).forEach((m) => {
|
|
2468
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2469
|
+
routes[m][path2] ||= [
|
|
2470
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
2471
|
+
];
|
|
2472
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
2473
|
+
}
|
|
2474
|
+
});
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
match = match;
|
|
2478
|
+
buildAllMatchers() {
|
|
2479
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
2480
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
2481
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
2482
|
+
});
|
|
2483
|
+
this.#middleware = this.#routes = void 0;
|
|
2484
|
+
clearWildcardRegExpCache();
|
|
2485
|
+
return matchers;
|
|
2486
|
+
}
|
|
2487
|
+
#buildMatcher(method) {
|
|
2488
|
+
const routes = [];
|
|
2489
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
2490
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
2491
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
2492
|
+
if (ownRoute.length !== 0) {
|
|
2493
|
+
hasOwnRoute ||= true;
|
|
2494
|
+
routes.push(...ownRoute);
|
|
2495
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
2496
|
+
routes.push(
|
|
2497
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
2498
|
+
);
|
|
2499
|
+
}
|
|
2500
|
+
});
|
|
2501
|
+
if (!hasOwnRoute) {
|
|
2502
|
+
return null;
|
|
2503
|
+
} else {
|
|
2504
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
};
|
|
2508
|
+
|
|
2509
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
2510
|
+
var SmartRouter = class {
|
|
2511
|
+
name = "SmartRouter";
|
|
2512
|
+
#routers = [];
|
|
2513
|
+
#routes = [];
|
|
2514
|
+
constructor(init) {
|
|
2515
|
+
this.#routers = init.routers;
|
|
2516
|
+
}
|
|
2517
|
+
add(method, path, handler) {
|
|
2518
|
+
if (!this.#routes) {
|
|
2519
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2520
|
+
}
|
|
2521
|
+
this.#routes.push([method, path, handler]);
|
|
2522
|
+
}
|
|
2523
|
+
match(method, path) {
|
|
2524
|
+
if (!this.#routes) {
|
|
2525
|
+
throw new Error("Fatal error");
|
|
2526
|
+
}
|
|
2527
|
+
const routers = this.#routers;
|
|
2528
|
+
const routes = this.#routes;
|
|
2529
|
+
const len = routers.length;
|
|
2530
|
+
let i = 0;
|
|
2531
|
+
let res;
|
|
2532
|
+
for (; i < len; i++) {
|
|
2533
|
+
const router = routers[i];
|
|
2534
|
+
try {
|
|
2535
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
2536
|
+
router.add(...routes[i2]);
|
|
2537
|
+
}
|
|
2538
|
+
res = router.match(method, path);
|
|
2539
|
+
} catch (e) {
|
|
2540
|
+
if (e instanceof UnsupportedPathError) {
|
|
2541
|
+
continue;
|
|
2542
|
+
}
|
|
2543
|
+
throw e;
|
|
2544
|
+
}
|
|
2545
|
+
this.match = router.match.bind(router);
|
|
2546
|
+
this.#routers = [router];
|
|
2547
|
+
this.#routes = void 0;
|
|
2548
|
+
break;
|
|
2549
|
+
}
|
|
2550
|
+
if (i === len) {
|
|
2551
|
+
throw new Error("Fatal error");
|
|
2552
|
+
}
|
|
2553
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2554
|
+
return res;
|
|
2555
|
+
}
|
|
2556
|
+
get activeRouter() {
|
|
2557
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2558
|
+
throw new Error("No active router has been determined yet.");
|
|
2559
|
+
}
|
|
2560
|
+
return this.#routers[0];
|
|
2561
|
+
}
|
|
2562
|
+
};
|
|
2563
|
+
|
|
2564
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
2565
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
2566
|
+
var hasChildren = (children) => {
|
|
2567
|
+
for (const _ in children) {
|
|
2568
|
+
return true;
|
|
2569
|
+
}
|
|
2570
|
+
return false;
|
|
2571
|
+
};
|
|
2572
|
+
var Node2 = class _Node2 {
|
|
2573
|
+
#methods;
|
|
2574
|
+
#children;
|
|
2575
|
+
#patterns;
|
|
2576
|
+
#order = 0;
|
|
2577
|
+
#params = emptyParams;
|
|
2578
|
+
constructor(method, handler, children) {
|
|
2579
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
2580
|
+
this.#methods = [];
|
|
2581
|
+
if (method && handler) {
|
|
2582
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
2583
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
2584
|
+
this.#methods = [m];
|
|
2585
|
+
}
|
|
2586
|
+
this.#patterns = [];
|
|
2587
|
+
}
|
|
2588
|
+
insert(method, path, handler) {
|
|
2589
|
+
this.#order = ++this.#order;
|
|
2590
|
+
let curNode = this;
|
|
2591
|
+
const parts = splitRoutingPath(path);
|
|
2592
|
+
const possibleKeys = [];
|
|
2593
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
2594
|
+
const p = parts[i];
|
|
2595
|
+
const nextP = parts[i + 1];
|
|
2596
|
+
const pattern = getPattern(p, nextP);
|
|
2597
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
2598
|
+
if (key in curNode.#children) {
|
|
2599
|
+
curNode = curNode.#children[key];
|
|
2600
|
+
if (pattern) {
|
|
2601
|
+
possibleKeys.push(pattern[1]);
|
|
2602
|
+
}
|
|
2603
|
+
continue;
|
|
2604
|
+
}
|
|
2605
|
+
curNode.#children[key] = new _Node2();
|
|
2606
|
+
if (pattern) {
|
|
2607
|
+
curNode.#patterns.push(pattern);
|
|
2608
|
+
possibleKeys.push(pattern[1]);
|
|
2609
|
+
}
|
|
2610
|
+
curNode = curNode.#children[key];
|
|
2611
|
+
}
|
|
2612
|
+
curNode.#methods.push({
|
|
2613
|
+
[method]: {
|
|
2614
|
+
handler,
|
|
2615
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
2616
|
+
score: this.#order
|
|
2617
|
+
}
|
|
2618
|
+
});
|
|
2619
|
+
return curNode;
|
|
2620
|
+
}
|
|
2621
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
2622
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
2623
|
+
const m = node.#methods[i];
|
|
2624
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2625
|
+
const processedSet = {};
|
|
2626
|
+
if (handlerSet !== void 0) {
|
|
2627
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
2628
|
+
handlerSets.push(handlerSet);
|
|
2629
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
2630
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
2631
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2632
|
+
const processed = processedSet[handlerSet.score];
|
|
2633
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2634
|
+
processedSet[handlerSet.score] = true;
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
search(method, path) {
|
|
2641
|
+
const handlerSets = [];
|
|
2642
|
+
this.#params = emptyParams;
|
|
2643
|
+
const curNode = this;
|
|
2644
|
+
let curNodes = [curNode];
|
|
2645
|
+
const parts = splitPath(path);
|
|
2646
|
+
const curNodesQueue = [];
|
|
2647
|
+
const len = parts.length;
|
|
2648
|
+
let partOffsets = null;
|
|
2649
|
+
for (let i = 0; i < len; i++) {
|
|
2650
|
+
const part = parts[i];
|
|
2651
|
+
const isLast = i === len - 1;
|
|
2652
|
+
const tempNodes = [];
|
|
2653
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
2654
|
+
const node = curNodes[j];
|
|
2655
|
+
const nextNode = node.#children[part];
|
|
2656
|
+
if (nextNode) {
|
|
2657
|
+
nextNode.#params = node.#params;
|
|
2658
|
+
if (isLast) {
|
|
2659
|
+
if (nextNode.#children["*"]) {
|
|
2660
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
2661
|
+
}
|
|
2662
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
2663
|
+
} else {
|
|
2664
|
+
tempNodes.push(nextNode);
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
2668
|
+
const pattern = node.#patterns[k];
|
|
2669
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2670
|
+
if (pattern === "*") {
|
|
2671
|
+
const astNode = node.#children["*"];
|
|
2672
|
+
if (astNode) {
|
|
2673
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
2674
|
+
astNode.#params = params;
|
|
2675
|
+
tempNodes.push(astNode);
|
|
2676
|
+
}
|
|
2677
|
+
continue;
|
|
2678
|
+
}
|
|
2679
|
+
const [key, name, matcher] = pattern;
|
|
2680
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
2681
|
+
continue;
|
|
2682
|
+
}
|
|
2683
|
+
const child = node.#children[key];
|
|
2684
|
+
if (matcher instanceof RegExp) {
|
|
2685
|
+
if (partOffsets === null) {
|
|
2686
|
+
partOffsets = new Array(len);
|
|
2687
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
2688
|
+
for (let p = 0; p < len; p++) {
|
|
2689
|
+
partOffsets[p] = offset;
|
|
2690
|
+
offset += parts[p].length + 1;
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
2694
|
+
const m = matcher.exec(restPathString);
|
|
2695
|
+
if (m) {
|
|
2696
|
+
params[name] = m[0];
|
|
2697
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
2698
|
+
if (hasChildren(child.#children)) {
|
|
2699
|
+
child.#params = params;
|
|
2700
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2701
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2702
|
+
targetCurNodes.push(child);
|
|
2703
|
+
}
|
|
2704
|
+
continue;
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
if (matcher === true || matcher.test(part)) {
|
|
2708
|
+
params[name] = part;
|
|
2709
|
+
if (isLast) {
|
|
2710
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
2711
|
+
if (child.#children["*"]) {
|
|
2712
|
+
this.#pushHandlerSets(
|
|
2713
|
+
handlerSets,
|
|
2714
|
+
child.#children["*"],
|
|
2715
|
+
method,
|
|
2716
|
+
params,
|
|
2717
|
+
node.#params
|
|
2718
|
+
);
|
|
2719
|
+
}
|
|
2720
|
+
} else {
|
|
2721
|
+
child.#params = params;
|
|
2722
|
+
tempNodes.push(child);
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
const shifted = curNodesQueue.shift();
|
|
2728
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2729
|
+
}
|
|
2730
|
+
if (handlerSets.length > 1) {
|
|
2731
|
+
handlerSets.sort((a, b) => {
|
|
2732
|
+
return a.score - b.score;
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2736
|
+
}
|
|
2737
|
+
};
|
|
2738
|
+
|
|
2739
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2740
|
+
var TrieRouter = class {
|
|
2741
|
+
name = "TrieRouter";
|
|
2742
|
+
#node;
|
|
2743
|
+
constructor() {
|
|
2744
|
+
this.#node = new Node2();
|
|
2745
|
+
}
|
|
2746
|
+
add(method, path, handler) {
|
|
2747
|
+
const results = checkOptionalParameter(path);
|
|
2748
|
+
if (results) {
|
|
2749
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
2750
|
+
this.#node.insert(method, results[i], handler);
|
|
2751
|
+
}
|
|
2752
|
+
return;
|
|
2753
|
+
}
|
|
2754
|
+
this.#node.insert(method, path, handler);
|
|
2755
|
+
}
|
|
2756
|
+
match(method, path) {
|
|
2757
|
+
return this.#node.search(method, path);
|
|
2758
|
+
}
|
|
2759
|
+
};
|
|
2760
|
+
|
|
2761
|
+
// node_modules/hono/dist/hono.js
|
|
2762
|
+
var Hono2 = class extends Hono {
|
|
2763
|
+
/**
|
|
2764
|
+
* Creates an instance of the Hono class.
|
|
2765
|
+
*
|
|
2766
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2767
|
+
*/
|
|
2768
|
+
constructor(options = {}) {
|
|
2769
|
+
super(options);
|
|
2770
|
+
this.router = options.router ?? new SmartRouter({
|
|
2771
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2772
|
+
});
|
|
2773
|
+
}
|
|
2774
|
+
};
|
|
2775
|
+
|
|
2776
|
+
// node_modules/hono/dist/middleware/cors/index.js
|
|
2777
|
+
var cors = (options) => {
|
|
2778
|
+
const opts = {
|
|
2779
|
+
origin: "*",
|
|
2780
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
2781
|
+
allowHeaders: [],
|
|
2782
|
+
exposeHeaders: [],
|
|
2783
|
+
...options
|
|
2784
|
+
};
|
|
2785
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
2786
|
+
if (typeof optsOrigin === "string") {
|
|
2787
|
+
if (optsOrigin === "*") {
|
|
2788
|
+
if (opts.credentials) {
|
|
2789
|
+
return (origin) => origin || null;
|
|
2790
|
+
}
|
|
2791
|
+
return () => optsOrigin;
|
|
2792
|
+
} else {
|
|
2793
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
2794
|
+
}
|
|
2795
|
+
} else if (typeof optsOrigin === "function") {
|
|
2796
|
+
return optsOrigin;
|
|
2797
|
+
} else {
|
|
2798
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
2799
|
+
}
|
|
2800
|
+
})(opts.origin);
|
|
2801
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
2802
|
+
if (typeof optsAllowMethods === "function") {
|
|
2803
|
+
return optsAllowMethods;
|
|
2804
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
2805
|
+
return () => optsAllowMethods;
|
|
2806
|
+
} else {
|
|
2807
|
+
return () => [];
|
|
2808
|
+
}
|
|
2809
|
+
})(opts.allowMethods);
|
|
2810
|
+
return async function cors2(c, next) {
|
|
2811
|
+
function set(key, value) {
|
|
2812
|
+
c.res.headers.set(key, value);
|
|
2813
|
+
}
|
|
2814
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
2815
|
+
if (allowOrigin) {
|
|
2816
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
2817
|
+
}
|
|
2818
|
+
if (opts.credentials) {
|
|
2819
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
2820
|
+
}
|
|
2821
|
+
if (opts.exposeHeaders?.length) {
|
|
2822
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
2823
|
+
}
|
|
2824
|
+
if (c.req.method === "OPTIONS") {
|
|
2825
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2826
|
+
set("Vary", "Origin");
|
|
2827
|
+
}
|
|
2828
|
+
if (opts.maxAge != null) {
|
|
2829
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
2830
|
+
}
|
|
2831
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
2832
|
+
if (allowMethods.length) {
|
|
2833
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
2834
|
+
}
|
|
2835
|
+
let headers = opts.allowHeaders;
|
|
2836
|
+
if (!headers?.length) {
|
|
2837
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
2838
|
+
if (requestHeaders) {
|
|
2839
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
if (headers?.length) {
|
|
2843
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
2844
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
2845
|
+
}
|
|
2846
|
+
c.res.headers.delete("Content-Length");
|
|
2847
|
+
c.res.headers.delete("Content-Type");
|
|
2848
|
+
return new Response(null, {
|
|
2849
|
+
headers: c.res.headers,
|
|
2850
|
+
status: 204,
|
|
2851
|
+
statusText: "No Content"
|
|
2852
|
+
});
|
|
2853
|
+
}
|
|
2854
|
+
await next();
|
|
2855
|
+
if (opts.origin !== "*" || opts.credentials) {
|
|
2856
|
+
c.header("Vary", "Origin", { append: true });
|
|
2857
|
+
}
|
|
2858
|
+
};
|
|
2859
|
+
};
|
|
2860
|
+
|
|
2861
|
+
// node_modules/@hono/node-server/dist/index.mjs
|
|
2862
|
+
import { createServer as createServerHTTP } from "http";
|
|
2863
|
+
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
2864
|
+
import { Http2ServerRequest } from "http2";
|
|
2865
|
+
import { Readable } from "stream";
|
|
2866
|
+
import crypto from "crypto";
|
|
2867
|
+
var RequestError = class extends Error {
|
|
2868
|
+
constructor(message, options) {
|
|
2869
|
+
super(message, options);
|
|
2870
|
+
this.name = "RequestError";
|
|
2871
|
+
}
|
|
2872
|
+
};
|
|
2873
|
+
var toRequestError = (e) => {
|
|
2874
|
+
if (e instanceof RequestError) {
|
|
2875
|
+
return e;
|
|
2876
|
+
}
|
|
2877
|
+
return new RequestError(e.message, { cause: e });
|
|
2878
|
+
};
|
|
2879
|
+
var GlobalRequest = global.Request;
|
|
2880
|
+
var Request2 = class extends GlobalRequest {
|
|
2881
|
+
constructor(input, options) {
|
|
2882
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
2883
|
+
input = input[getRequestCache]();
|
|
2884
|
+
}
|
|
2885
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
2886
|
+
;
|
|
2887
|
+
options.duplex ??= "half";
|
|
2888
|
+
}
|
|
2889
|
+
super(input, options);
|
|
2890
|
+
}
|
|
2891
|
+
};
|
|
2892
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
2893
|
+
const headerRecord = [];
|
|
2894
|
+
const rawHeaders = incoming.rawHeaders;
|
|
2895
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
2896
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
2897
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
2898
|
+
58) {
|
|
2899
|
+
headerRecord.push([key, value]);
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
return new Headers(headerRecord);
|
|
2903
|
+
};
|
|
2904
|
+
var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
|
|
2905
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
2906
|
+
const init = {
|
|
2907
|
+
method,
|
|
2908
|
+
headers,
|
|
2909
|
+
signal: abortController.signal
|
|
2910
|
+
};
|
|
2911
|
+
if (method === "TRACE") {
|
|
2912
|
+
init.method = "GET";
|
|
2913
|
+
const req = new Request2(url, init);
|
|
2914
|
+
Object.defineProperty(req, "method", {
|
|
2915
|
+
get() {
|
|
2916
|
+
return "TRACE";
|
|
2917
|
+
}
|
|
2918
|
+
});
|
|
2919
|
+
return req;
|
|
2920
|
+
}
|
|
2921
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
2922
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
2923
|
+
init.body = new ReadableStream({
|
|
2924
|
+
start(controller) {
|
|
2925
|
+
controller.enqueue(incoming.rawBody);
|
|
2926
|
+
controller.close();
|
|
2927
|
+
}
|
|
2928
|
+
});
|
|
2929
|
+
} else if (incoming[wrapBodyStream]) {
|
|
2930
|
+
let reader;
|
|
2931
|
+
init.body = new ReadableStream({
|
|
2932
|
+
async pull(controller) {
|
|
2933
|
+
try {
|
|
2934
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
2935
|
+
const { done, value } = await reader.read();
|
|
2936
|
+
if (done) {
|
|
2937
|
+
controller.close();
|
|
2938
|
+
} else {
|
|
2939
|
+
controller.enqueue(value);
|
|
2940
|
+
}
|
|
2941
|
+
} catch (error) {
|
|
2942
|
+
controller.error(error);
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
});
|
|
2946
|
+
} else {
|
|
2947
|
+
init.body = Readable.toWeb(incoming);
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
return new Request2(url, init);
|
|
2951
|
+
};
|
|
2952
|
+
var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
|
|
2953
|
+
var requestCache = /* @__PURE__ */ Symbol("requestCache");
|
|
2954
|
+
var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
|
|
2955
|
+
var urlKey = /* @__PURE__ */ Symbol("urlKey");
|
|
2956
|
+
var headersKey = /* @__PURE__ */ Symbol("headersKey");
|
|
2957
|
+
var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
|
|
2958
|
+
var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
|
|
2959
|
+
var requestPrototype = {
|
|
2960
|
+
get method() {
|
|
2961
|
+
return this[incomingKey].method || "GET";
|
|
2962
|
+
},
|
|
2963
|
+
get url() {
|
|
2964
|
+
return this[urlKey];
|
|
2965
|
+
},
|
|
2966
|
+
get headers() {
|
|
2967
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
2968
|
+
},
|
|
2969
|
+
[getAbortController]() {
|
|
2970
|
+
this[getRequestCache]();
|
|
2971
|
+
return this[abortControllerKey];
|
|
2972
|
+
},
|
|
2973
|
+
[getRequestCache]() {
|
|
2974
|
+
this[abortControllerKey] ||= new AbortController();
|
|
2975
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
2976
|
+
this.method,
|
|
2977
|
+
this[urlKey],
|
|
2978
|
+
this.headers,
|
|
2979
|
+
this[incomingKey],
|
|
2980
|
+
this[abortControllerKey]
|
|
2981
|
+
);
|
|
2982
|
+
}
|
|
2983
|
+
};
|
|
2984
|
+
[
|
|
2985
|
+
"body",
|
|
2986
|
+
"bodyUsed",
|
|
2987
|
+
"cache",
|
|
2988
|
+
"credentials",
|
|
2989
|
+
"destination",
|
|
2990
|
+
"integrity",
|
|
2991
|
+
"mode",
|
|
2992
|
+
"redirect",
|
|
2993
|
+
"referrer",
|
|
2994
|
+
"referrerPolicy",
|
|
2995
|
+
"signal",
|
|
2996
|
+
"keepalive"
|
|
2997
|
+
].forEach((k) => {
|
|
2998
|
+
Object.defineProperty(requestPrototype, k, {
|
|
2999
|
+
get() {
|
|
3000
|
+
return this[getRequestCache]()[k];
|
|
3001
|
+
}
|
|
3002
|
+
});
|
|
3003
|
+
});
|
|
3004
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
3005
|
+
Object.defineProperty(requestPrototype, k, {
|
|
3006
|
+
value: function() {
|
|
3007
|
+
return this[getRequestCache]()[k]();
|
|
3008
|
+
}
|
|
3009
|
+
});
|
|
3010
|
+
});
|
|
3011
|
+
Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
3012
|
+
value: function(depth, options, inspectFn) {
|
|
3013
|
+
const props = {
|
|
3014
|
+
method: this.method,
|
|
3015
|
+
url: this.url,
|
|
3016
|
+
headers: this.headers,
|
|
3017
|
+
nativeRequest: this[requestCache]
|
|
3018
|
+
};
|
|
3019
|
+
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
3020
|
+
}
|
|
3021
|
+
});
|
|
3022
|
+
Object.setPrototypeOf(requestPrototype, Request2.prototype);
|
|
3023
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
3024
|
+
const req = Object.create(requestPrototype);
|
|
3025
|
+
req[incomingKey] = incoming;
|
|
3026
|
+
const incomingUrl = incoming.url || "";
|
|
3027
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
3028
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
3029
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
3030
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
3031
|
+
}
|
|
3032
|
+
try {
|
|
3033
|
+
const url2 = new URL(incomingUrl);
|
|
3034
|
+
req[urlKey] = url2.href;
|
|
3035
|
+
} catch (e) {
|
|
3036
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
3037
|
+
}
|
|
3038
|
+
return req;
|
|
3039
|
+
}
|
|
3040
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
3041
|
+
if (!host) {
|
|
3042
|
+
throw new RequestError("Missing host header");
|
|
3043
|
+
}
|
|
3044
|
+
let scheme;
|
|
3045
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
3046
|
+
scheme = incoming.scheme;
|
|
3047
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
3048
|
+
throw new RequestError("Unsupported scheme");
|
|
3049
|
+
}
|
|
3050
|
+
} else {
|
|
3051
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
3052
|
+
}
|
|
3053
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
3054
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
3055
|
+
throw new RequestError("Invalid host header");
|
|
3056
|
+
}
|
|
3057
|
+
req[urlKey] = url.href;
|
|
3058
|
+
return req;
|
|
3059
|
+
};
|
|
3060
|
+
var responseCache = /* @__PURE__ */ Symbol("responseCache");
|
|
3061
|
+
var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
|
|
3062
|
+
var cacheKey = /* @__PURE__ */ Symbol("cache");
|
|
3063
|
+
var GlobalResponse = global.Response;
|
|
3064
|
+
var Response2 = class _Response {
|
|
3065
|
+
#body;
|
|
3066
|
+
#init;
|
|
3067
|
+
[getResponseCache]() {
|
|
3068
|
+
delete this[cacheKey];
|
|
3069
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
3070
|
+
}
|
|
3071
|
+
constructor(body, init) {
|
|
3072
|
+
let headers;
|
|
3073
|
+
this.#body = body;
|
|
3074
|
+
if (init instanceof _Response) {
|
|
3075
|
+
const cachedGlobalResponse = init[responseCache];
|
|
3076
|
+
if (cachedGlobalResponse) {
|
|
3077
|
+
this.#init = cachedGlobalResponse;
|
|
3078
|
+
this[getResponseCache]();
|
|
3079
|
+
return;
|
|
3080
|
+
} else {
|
|
3081
|
+
this.#init = init.#init;
|
|
3082
|
+
headers = new Headers(init.#init.headers);
|
|
3083
|
+
}
|
|
3084
|
+
} else {
|
|
3085
|
+
this.#init = init;
|
|
3086
|
+
}
|
|
3087
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
3088
|
+
;
|
|
3089
|
+
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
|
3090
|
+
}
|
|
3091
|
+
}
|
|
3092
|
+
get headers() {
|
|
3093
|
+
const cache = this[cacheKey];
|
|
3094
|
+
if (cache) {
|
|
3095
|
+
if (!(cache[2] instanceof Headers)) {
|
|
3096
|
+
cache[2] = new Headers(
|
|
3097
|
+
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
|
3098
|
+
);
|
|
3099
|
+
}
|
|
3100
|
+
return cache[2];
|
|
3101
|
+
}
|
|
3102
|
+
return this[getResponseCache]().headers;
|
|
3103
|
+
}
|
|
3104
|
+
get status() {
|
|
3105
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
3106
|
+
}
|
|
3107
|
+
get ok() {
|
|
3108
|
+
const status = this.status;
|
|
3109
|
+
return status >= 200 && status < 300;
|
|
3110
|
+
}
|
|
3111
|
+
};
|
|
3112
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
3113
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
3114
|
+
get() {
|
|
3115
|
+
return this[getResponseCache]()[k];
|
|
3116
|
+
}
|
|
3117
|
+
});
|
|
3118
|
+
});
|
|
3119
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
3120
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
3121
|
+
value: function() {
|
|
3122
|
+
return this[getResponseCache]()[k]();
|
|
3123
|
+
}
|
|
3124
|
+
});
|
|
3125
|
+
});
|
|
3126
|
+
Object.defineProperty(Response2.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
|
|
3127
|
+
value: function(depth, options, inspectFn) {
|
|
3128
|
+
const props = {
|
|
3129
|
+
status: this.status,
|
|
3130
|
+
headers: this.headers,
|
|
3131
|
+
ok: this.ok,
|
|
3132
|
+
nativeResponse: this[responseCache]
|
|
3133
|
+
};
|
|
3134
|
+
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
3135
|
+
}
|
|
3136
|
+
});
|
|
3137
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
3138
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
3139
|
+
async function readWithoutBlocking(readPromise) {
|
|
3140
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
3141
|
+
}
|
|
3142
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
3143
|
+
const cancel = (error) => {
|
|
3144
|
+
reader.cancel(error).catch(() => {
|
|
3145
|
+
});
|
|
3146
|
+
};
|
|
3147
|
+
writable.on("close", cancel);
|
|
3148
|
+
writable.on("error", cancel);
|
|
3149
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
3150
|
+
return reader.closed.finally(() => {
|
|
3151
|
+
writable.off("close", cancel);
|
|
3152
|
+
writable.off("error", cancel);
|
|
3153
|
+
});
|
|
3154
|
+
function handleStreamError(error) {
|
|
3155
|
+
if (error) {
|
|
3156
|
+
writable.destroy(error);
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
function onDrain() {
|
|
3160
|
+
reader.read().then(flow, handleStreamError);
|
|
3161
|
+
}
|
|
3162
|
+
function flow({ done, value }) {
|
|
3163
|
+
try {
|
|
3164
|
+
if (done) {
|
|
3165
|
+
writable.end();
|
|
3166
|
+
} else if (!writable.write(value)) {
|
|
3167
|
+
writable.once("drain", onDrain);
|
|
3168
|
+
} else {
|
|
3169
|
+
return reader.read().then(flow, handleStreamError);
|
|
3170
|
+
}
|
|
3171
|
+
} catch (e) {
|
|
3172
|
+
handleStreamError(e);
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
}
|
|
3176
|
+
function writeFromReadableStream(stream, writable) {
|
|
3177
|
+
if (stream.locked) {
|
|
3178
|
+
throw new TypeError("ReadableStream is locked.");
|
|
3179
|
+
} else if (writable.destroyed) {
|
|
3180
|
+
return;
|
|
3181
|
+
}
|
|
3182
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
3183
|
+
}
|
|
3184
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
3185
|
+
const res = {};
|
|
3186
|
+
if (!(headers instanceof Headers)) {
|
|
3187
|
+
headers = new Headers(headers ?? void 0);
|
|
3188
|
+
}
|
|
3189
|
+
const cookies = [];
|
|
3190
|
+
for (const [k, v] of headers) {
|
|
3191
|
+
if (k === "set-cookie") {
|
|
3192
|
+
cookies.push(v);
|
|
3193
|
+
} else {
|
|
3194
|
+
res[k] = v;
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
if (cookies.length > 0) {
|
|
3198
|
+
res["set-cookie"] = cookies;
|
|
3199
|
+
}
|
|
3200
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
3201
|
+
return res;
|
|
3202
|
+
};
|
|
3203
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
3204
|
+
if (typeof global.crypto === "undefined") {
|
|
3205
|
+
global.crypto = crypto;
|
|
3206
|
+
}
|
|
3207
|
+
var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
|
|
3208
|
+
var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
|
|
3209
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
3210
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
3211
|
+
var drainIncoming = (incoming) => {
|
|
3212
|
+
const incomingWithDrainState = incoming;
|
|
3213
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
|
3214
|
+
return;
|
|
3215
|
+
}
|
|
3216
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
3217
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
3218
|
+
try {
|
|
3219
|
+
;
|
|
3220
|
+
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
|
3221
|
+
} catch {
|
|
3222
|
+
}
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
3225
|
+
let bytesRead = 0;
|
|
3226
|
+
const cleanup = () => {
|
|
3227
|
+
clearTimeout(timer);
|
|
3228
|
+
incoming.off("data", onData);
|
|
3229
|
+
incoming.off("end", cleanup);
|
|
3230
|
+
incoming.off("error", cleanup);
|
|
3231
|
+
};
|
|
3232
|
+
const forceClose = () => {
|
|
3233
|
+
cleanup();
|
|
3234
|
+
const socket = incoming.socket;
|
|
3235
|
+
if (socket && !socket.destroyed) {
|
|
3236
|
+
socket.destroySoon();
|
|
3237
|
+
}
|
|
3238
|
+
};
|
|
3239
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
3240
|
+
timer.unref?.();
|
|
3241
|
+
const onData = (chunk) => {
|
|
3242
|
+
bytesRead += chunk.length;
|
|
3243
|
+
if (bytesRead > MAX_DRAIN_BYTES) {
|
|
3244
|
+
forceClose();
|
|
3245
|
+
}
|
|
3246
|
+
};
|
|
3247
|
+
incoming.on("data", onData);
|
|
3248
|
+
incoming.on("end", cleanup);
|
|
3249
|
+
incoming.on("error", cleanup);
|
|
3250
|
+
incoming.resume();
|
|
3251
|
+
};
|
|
3252
|
+
var handleRequestError = () => new Response(null, {
|
|
3253
|
+
status: 400
|
|
3254
|
+
});
|
|
3255
|
+
var handleFetchError = (e) => new Response(null, {
|
|
3256
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
3257
|
+
});
|
|
3258
|
+
var handleResponseError = (e, outgoing) => {
|
|
3259
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
3260
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
3261
|
+
console.info("The user aborted a request.");
|
|
3262
|
+
} else {
|
|
3263
|
+
console.error(e);
|
|
3264
|
+
if (!outgoing.headersSent) {
|
|
3265
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
3266
|
+
}
|
|
3267
|
+
outgoing.end(`Error: ${err.message}`);
|
|
3268
|
+
outgoing.destroy(err);
|
|
3269
|
+
}
|
|
3270
|
+
};
|
|
3271
|
+
var flushHeaders = (outgoing) => {
|
|
3272
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
3273
|
+
outgoing.flushHeaders();
|
|
3274
|
+
}
|
|
3275
|
+
};
|
|
3276
|
+
var responseViaCache = async (res, outgoing) => {
|
|
3277
|
+
let [status, body, header] = res[cacheKey];
|
|
3278
|
+
let hasContentLength = false;
|
|
3279
|
+
if (!header) {
|
|
3280
|
+
header = { "content-type": "text/plain; charset=UTF-8" };
|
|
3281
|
+
} else if (header instanceof Headers) {
|
|
3282
|
+
hasContentLength = header.has("content-length");
|
|
3283
|
+
header = buildOutgoingHttpHeaders(header);
|
|
3284
|
+
} else if (Array.isArray(header)) {
|
|
3285
|
+
const headerObj = new Headers(header);
|
|
3286
|
+
hasContentLength = headerObj.has("content-length");
|
|
3287
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
3288
|
+
} else {
|
|
3289
|
+
for (const key in header) {
|
|
3290
|
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
3291
|
+
hasContentLength = true;
|
|
3292
|
+
break;
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
if (!hasContentLength) {
|
|
3297
|
+
if (typeof body === "string") {
|
|
3298
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
3299
|
+
} else if (body instanceof Uint8Array) {
|
|
3300
|
+
header["Content-Length"] = body.byteLength;
|
|
3301
|
+
} else if (body instanceof Blob) {
|
|
3302
|
+
header["Content-Length"] = body.size;
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
outgoing.writeHead(status, header);
|
|
3306
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
3307
|
+
outgoing.end(body);
|
|
3308
|
+
} else if (body instanceof Blob) {
|
|
3309
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
3310
|
+
} else {
|
|
3311
|
+
flushHeaders(outgoing);
|
|
3312
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
3313
|
+
(e) => handleResponseError(e, outgoing)
|
|
3314
|
+
);
|
|
3315
|
+
}
|
|
3316
|
+
;
|
|
3317
|
+
outgoing[outgoingEnded]?.();
|
|
3318
|
+
};
|
|
3319
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
3320
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
3321
|
+
if (isPromise(res)) {
|
|
3322
|
+
if (options.errorHandler) {
|
|
3323
|
+
try {
|
|
3324
|
+
res = await res;
|
|
3325
|
+
} catch (err) {
|
|
3326
|
+
const errRes = await options.errorHandler(err);
|
|
3327
|
+
if (!errRes) {
|
|
3328
|
+
return;
|
|
3329
|
+
}
|
|
3330
|
+
res = errRes;
|
|
3331
|
+
}
|
|
3332
|
+
} else {
|
|
3333
|
+
res = await res.catch(handleFetchError);
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
if (cacheKey in res) {
|
|
3337
|
+
return responseViaCache(res, outgoing);
|
|
3338
|
+
}
|
|
3339
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
3340
|
+
if (res.body) {
|
|
3341
|
+
const reader = res.body.getReader();
|
|
3342
|
+
const values = [];
|
|
3343
|
+
let done = false;
|
|
3344
|
+
let currentReadPromise = void 0;
|
|
3345
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
3346
|
+
let maxReadCount = 2;
|
|
3347
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
3348
|
+
currentReadPromise ||= reader.read();
|
|
3349
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
3350
|
+
console.error(e);
|
|
3351
|
+
done = true;
|
|
3352
|
+
});
|
|
3353
|
+
if (!chunk) {
|
|
3354
|
+
if (i === 1) {
|
|
3355
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
3356
|
+
maxReadCount = 3;
|
|
3357
|
+
continue;
|
|
3358
|
+
}
|
|
3359
|
+
break;
|
|
3360
|
+
}
|
|
3361
|
+
currentReadPromise = void 0;
|
|
3362
|
+
if (chunk.value) {
|
|
3363
|
+
values.push(chunk.value);
|
|
3364
|
+
}
|
|
3365
|
+
if (chunk.done) {
|
|
3366
|
+
done = true;
|
|
3367
|
+
break;
|
|
3368
|
+
}
|
|
3369
|
+
}
|
|
3370
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
3371
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
3375
|
+
values.forEach((value) => {
|
|
3376
|
+
;
|
|
3377
|
+
outgoing.write(value);
|
|
3378
|
+
});
|
|
3379
|
+
if (done) {
|
|
3380
|
+
outgoing.end();
|
|
3381
|
+
} else {
|
|
3382
|
+
if (values.length === 0) {
|
|
3383
|
+
flushHeaders(outgoing);
|
|
3384
|
+
}
|
|
3385
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
3386
|
+
}
|
|
3387
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
3388
|
+
} else {
|
|
3389
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
3390
|
+
outgoing.end();
|
|
3391
|
+
}
|
|
3392
|
+
;
|
|
3393
|
+
outgoing[outgoingEnded]?.();
|
|
3394
|
+
};
|
|
3395
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
3396
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
3397
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
|
|
3398
|
+
Object.defineProperty(global, "Request", {
|
|
3399
|
+
value: Request2
|
|
3400
|
+
});
|
|
3401
|
+
Object.defineProperty(global, "Response", {
|
|
3402
|
+
value: Response2
|
|
3403
|
+
});
|
|
3404
|
+
}
|
|
3405
|
+
return async (incoming, outgoing) => {
|
|
3406
|
+
let res, req;
|
|
3407
|
+
try {
|
|
3408
|
+
req = newRequest(incoming, options.hostname);
|
|
3409
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
3410
|
+
if (!incomingEnded) {
|
|
3411
|
+
;
|
|
3412
|
+
incoming[wrapBodyStream] = true;
|
|
3413
|
+
incoming.on("end", () => {
|
|
3414
|
+
incomingEnded = true;
|
|
3415
|
+
});
|
|
3416
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
3417
|
+
;
|
|
3418
|
+
outgoing[outgoingEnded] = () => {
|
|
3419
|
+
if (!incomingEnded) {
|
|
3420
|
+
setTimeout(() => {
|
|
3421
|
+
if (!incomingEnded) {
|
|
3422
|
+
setTimeout(() => {
|
|
3423
|
+
drainIncoming(incoming);
|
|
3424
|
+
});
|
|
3425
|
+
}
|
|
3426
|
+
});
|
|
3427
|
+
}
|
|
3428
|
+
};
|
|
3429
|
+
}
|
|
3430
|
+
outgoing.on("finish", () => {
|
|
3431
|
+
if (!incomingEnded) {
|
|
3432
|
+
drainIncoming(incoming);
|
|
3433
|
+
}
|
|
3434
|
+
});
|
|
3435
|
+
}
|
|
3436
|
+
outgoing.on("close", () => {
|
|
3437
|
+
const abortController = req[abortControllerKey];
|
|
3438
|
+
if (abortController) {
|
|
3439
|
+
if (incoming.errored) {
|
|
3440
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
3441
|
+
} else if (!outgoing.writableFinished) {
|
|
3442
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
if (!incomingEnded) {
|
|
3446
|
+
setTimeout(() => {
|
|
3447
|
+
if (!incomingEnded) {
|
|
3448
|
+
setTimeout(() => {
|
|
3449
|
+
drainIncoming(incoming);
|
|
3450
|
+
});
|
|
3451
|
+
}
|
|
3452
|
+
});
|
|
3453
|
+
}
|
|
3454
|
+
});
|
|
3455
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
3456
|
+
if (cacheKey in res) {
|
|
3457
|
+
return responseViaCache(res, outgoing);
|
|
3458
|
+
}
|
|
3459
|
+
} catch (e) {
|
|
3460
|
+
if (!res) {
|
|
3461
|
+
if (options.errorHandler) {
|
|
3462
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
3463
|
+
if (!res) {
|
|
3464
|
+
return;
|
|
3465
|
+
}
|
|
3466
|
+
} else if (!req) {
|
|
3467
|
+
res = handleRequestError();
|
|
3468
|
+
} else {
|
|
3469
|
+
res = handleFetchError(e);
|
|
3470
|
+
}
|
|
3471
|
+
} else {
|
|
3472
|
+
return handleResponseError(e, outgoing);
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
try {
|
|
3476
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
3477
|
+
} catch (e) {
|
|
3478
|
+
return handleResponseError(e, outgoing);
|
|
3479
|
+
}
|
|
3480
|
+
};
|
|
3481
|
+
};
|
|
3482
|
+
var createAdaptorServer = (options) => {
|
|
3483
|
+
const fetchCallback = options.fetch;
|
|
3484
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
3485
|
+
hostname: options.hostname,
|
|
3486
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
3487
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
3488
|
+
});
|
|
3489
|
+
const createServer = options.createServer || createServerHTTP;
|
|
3490
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
3491
|
+
return server;
|
|
3492
|
+
};
|
|
3493
|
+
var serve = (options, listeningListener) => {
|
|
3494
|
+
const server = createAdaptorServer(options);
|
|
3495
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
3496
|
+
const serverInfo = server.address();
|
|
3497
|
+
listeningListener && listeningListener(serverInfo);
|
|
3498
|
+
});
|
|
3499
|
+
return server;
|
|
3500
|
+
};
|
|
3501
|
+
|
|
3502
|
+
// src/server/index.ts
|
|
3503
|
+
init_config();
|
|
3504
|
+
init_state();
|
|
3505
|
+
|
|
3506
|
+
// src/server/models.ts
|
|
3507
|
+
function sanitizeAgentInfo(info) {
|
|
3508
|
+
const { host_ip: _, ...publicInfo } = info;
|
|
3509
|
+
return publicInfo;
|
|
3510
|
+
}
|
|
3511
|
+
function sanitizeAgentList(agents) {
|
|
3512
|
+
return agents.map(sanitizeAgentInfo);
|
|
3513
|
+
}
|
|
3514
|
+
|
|
3515
|
+
// src/server/routes/agent.ts
|
|
3516
|
+
init_config();
|
|
3517
|
+
var agentRoutes = new Hono2();
|
|
3518
|
+
async function forwardToPeer(peerIp, envelope) {
|
|
3519
|
+
const url = `http://${peerIp}:${PARTY_PORT}/proxy/receive`;
|
|
3520
|
+
const payload = { sender_id: envelope.sender_id, content: envelope.content };
|
|
3521
|
+
if (envelope.recipient_id) payload.recipient_id = envelope.recipient_id;
|
|
3522
|
+
if (envelope.group_id) payload.group_id = envelope.group_id;
|
|
3523
|
+
try {
|
|
3524
|
+
await fetch(url, {
|
|
3525
|
+
method: "POST",
|
|
3526
|
+
headers: { "Content-Type": "application/json" },
|
|
3527
|
+
body: JSON.stringify(payload)
|
|
3528
|
+
});
|
|
3529
|
+
return { status: "forwarded", target: peerIp };
|
|
3530
|
+
} catch (e) {
|
|
3531
|
+
return { status: "error", target: peerIp, error: e.message };
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
agentRoutes.post("/register", async (c) => {
|
|
3535
|
+
const { registry: registry2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3536
|
+
const req = await c.req.json();
|
|
3537
|
+
const info = registry2.register(req);
|
|
3538
|
+
return c.json(sanitizeAgentInfo(info));
|
|
3539
|
+
});
|
|
3540
|
+
agentRoutes.post("/remove", async (c) => {
|
|
3541
|
+
const { registry: registry2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3542
|
+
const req = await c.req.json();
|
|
3543
|
+
const removed = registry2.remove(req.agent_id);
|
|
3544
|
+
return c.json({ status: removed ? "removed" : "not_found" });
|
|
3545
|
+
});
|
|
3546
|
+
agentRoutes.post("/heartbeat", async (c) => {
|
|
3547
|
+
const { registry: registry2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3548
|
+
const req = await c.req.json();
|
|
3549
|
+
const info = registry2.heartbeat(req.agent_id);
|
|
3550
|
+
return c.json({ status: "ok", last_heartbeat: info.last_heartbeat });
|
|
3551
|
+
});
|
|
3552
|
+
agentRoutes.get("/list", async (c) => {
|
|
3553
|
+
const { registry: registry2, discovery: discovery2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3554
|
+
const localAgents = registry2.listAll();
|
|
3555
|
+
const remoteAgents = discovery2.getReachableRemoteAgents();
|
|
3556
|
+
const allAgents = localAgents.concat(remoteAgents);
|
|
3557
|
+
return c.json({ agents: sanitizeAgentList(allAgents), count: allAgents.length });
|
|
3558
|
+
});
|
|
3559
|
+
agentRoutes.post("/send", async (c) => {
|
|
3560
|
+
const { registry: registry2, messageQueue: messageQueue2, discovery: discovery2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3561
|
+
const envelope = await c.req.json();
|
|
3562
|
+
const recipient = envelope.recipient_id;
|
|
3563
|
+
if (!recipient) {
|
|
3564
|
+
return c.json({ status: "error", error: "recipient_id is required" });
|
|
3565
|
+
}
|
|
3566
|
+
if (registry2.get(recipient)) {
|
|
3567
|
+
const stamped = { ...envelope, timestamp: envelope.timestamp ?? Date.now() / 1e3 };
|
|
3568
|
+
const count = messageQueue2.enqueue(recipient, stamped);
|
|
3569
|
+
messageQueue2.logToHistory(envelope.sender_id, "sent", stamped);
|
|
3570
|
+
messageQueue2.logToHistory(recipient, "received", stamped);
|
|
3571
|
+
return c.json({ status: "delivered_locally", target: recipient });
|
|
3572
|
+
}
|
|
3573
|
+
const peerIp = discovery2.getPeerForAgent(recipient);
|
|
3574
|
+
if (peerIp) {
|
|
3575
|
+
if (discovery2.isPeerReachable(peerIp)) {
|
|
3576
|
+
const result = await forwardToPeer(peerIp, envelope);
|
|
3577
|
+
if (result.status === "forwarded") {
|
|
3578
|
+
messageQueue2.logToHistory(envelope.sender_id, "sent", { ...envelope, timestamp: envelope.timestamp ?? Date.now() / 1e3 });
|
|
3579
|
+
}
|
|
3580
|
+
return c.json(result);
|
|
3581
|
+
} else {
|
|
3582
|
+
return c.json({ status: "peer_unreachable", target: peerIp });
|
|
3583
|
+
}
|
|
3584
|
+
}
|
|
3585
|
+
return c.json({ status: "agent_not_found", target: recipient });
|
|
3586
|
+
});
|
|
3587
|
+
agentRoutes.get("/messages/:agent_id", async (c) => {
|
|
3588
|
+
const { messageQueue: messageQueue2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3589
|
+
const agentId = c.req.param("agent_id");
|
|
3590
|
+
const maxCount = parseInt(c.req.query("max_count") || "50", 10);
|
|
3591
|
+
const msgs = messageQueue2.dequeue(agentId, maxCount);
|
|
3592
|
+
return c.json({ messages: msgs, count: msgs.length });
|
|
3593
|
+
});
|
|
3594
|
+
agentRoutes.get("/history/:agent_id", async (c) => {
|
|
3595
|
+
const { messageQueue: messageQueue2 } = await Promise.resolve().then(() => (init_state(), state_exports));
|
|
3596
|
+
const agentId = c.req.param("agent_id");
|
|
3597
|
+
const limit = parseInt(c.req.query("limit") || "20", 10);
|
|
3598
|
+
const history = messageQueue2.getHistory(agentId, limit);
|
|
3599
|
+
return c.json({ history, count: history.length });
|
|
3600
|
+
});
|
|
3601
|
+
|
|
3602
|
+
// src/server/routes/proxy.ts
|
|
3603
|
+
init_config();
|
|
3604
|
+
init_tailscale();
|
|
3605
|
+
init_state();
|
|
3606
|
+
var proxyRoutes = new Hono2();
|
|
3607
|
+
proxyRoutes.get("/health", async (c) => {
|
|
3608
|
+
let hostname = "127.0.0.1";
|
|
3609
|
+
try {
|
|
3610
|
+
hostname = getTailnetHostname();
|
|
3611
|
+
} catch {
|
|
3612
|
+
}
|
|
3613
|
+
return c.json({
|
|
3614
|
+
status: "ok",
|
|
3615
|
+
tailscale_ip: getSelfIp(),
|
|
3616
|
+
hostname,
|
|
3617
|
+
agent_count: registry.listAll().length
|
|
3618
|
+
});
|
|
3619
|
+
});
|
|
3620
|
+
proxyRoutes.get("/list_agents", async (c) => {
|
|
3621
|
+
const agents = registry.listAll();
|
|
3622
|
+
return c.json({ agents, count: agents.length });
|
|
3623
|
+
});
|
|
3624
|
+
proxyRoutes.post("/receive", async (c) => {
|
|
3625
|
+
const envelope = await c.req.json();
|
|
3626
|
+
const stamped = { ...envelope, timestamp: envelope.timestamp ?? Date.now() / 1e3 };
|
|
3627
|
+
if (envelope.recipient_id) {
|
|
3628
|
+
messageQueue.enqueue(envelope.recipient_id, stamped);
|
|
3629
|
+
messageQueue.logToHistory(envelope.recipient_id, "received", stamped);
|
|
3630
|
+
console.log(`[\u6536\u5230\u6D88\u606F] ${envelope.sender_id} -> ${envelope.recipient_id}: ${envelope.content}`);
|
|
3631
|
+
} else {
|
|
3632
|
+
for (const agent of registry.listAll()) {
|
|
3633
|
+
messageQueue.enqueue(agent.agent_id, stamped);
|
|
3634
|
+
messageQueue.logToHistory(agent.agent_id, "received", stamped);
|
|
3635
|
+
}
|
|
3636
|
+
console.log(`[\u5E7F\u64AD\u6D88\u606F] ${envelope.sender_id} -> all: ${envelope.content}`);
|
|
3637
|
+
}
|
|
3638
|
+
return c.json({ status: "received" });
|
|
3639
|
+
});
|
|
3640
|
+
proxyRoutes.post("/send/:target_ip", async (c) => {
|
|
3641
|
+
const targetIp = c.req.param("target_ip");
|
|
3642
|
+
const envelope = await c.req.json();
|
|
3643
|
+
const senderId = envelope.sender_id || getSelfIp();
|
|
3644
|
+
const url = `http://${targetIp}:${PARTY_PORT}/proxy/receive`;
|
|
3645
|
+
const payload = { sender_id: senderId, content: envelope.content };
|
|
3646
|
+
if (envelope.recipient_id) payload.recipient_id = envelope.recipient_id;
|
|
3647
|
+
if (envelope.group_id) payload.group_id = envelope.group_id;
|
|
3648
|
+
try {
|
|
3649
|
+
await fetch(url, {
|
|
3650
|
+
method: "POST",
|
|
3651
|
+
headers: { "Content-Type": "application/json" },
|
|
3652
|
+
body: JSON.stringify(payload)
|
|
3653
|
+
});
|
|
3654
|
+
console.log(`[\u53D1\u9001\u6210\u529F] \u76EE\u6807 ${targetIp}`);
|
|
3655
|
+
return c.json({ status: "forwarded", target: targetIp });
|
|
3656
|
+
} catch (e) {
|
|
3657
|
+
console.log(`[\u53D1\u9001\u5931\u8D25] \u76EE\u6807 ${targetIp}, \u9519\u8BEF: ${e.message}`);
|
|
3658
|
+
return c.json({ status: "error", target: targetIp, error: e.message });
|
|
3659
|
+
}
|
|
3660
|
+
});
|
|
3661
|
+
|
|
3662
|
+
// src/server/dashboard-html.ts
|
|
3663
|
+
var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
3664
|
+
<html lang="zh-CN">
|
|
3665
|
+
<head>
|
|
3666
|
+
<meta charset="UTF-8">
|
|
3667
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
3668
|
+
<title>OPEN PARTY // Dashboard</title>
|
|
3669
|
+
<style>
|
|
3670
|
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
3671
|
+
:root{
|
|
3672
|
+
--bg:#0a0a0f;--card:#12121a;--border:#1e1e2e;--border-bright:#2a2a3e;
|
|
3673
|
+
--text:#e0e0e8;--muted:#6a6a8a;
|
|
3674
|
+
--cyan:#00fff0;--magenta:#ff00ff;--green:#00ff88;--red:#ff3366;--yellow:#ffaa00;--orange:#ff8800;
|
|
3675
|
+
--font-mono:'JetBrains Mono','Fira Code','Cascadia Code','Consolas','Courier New',monospace;
|
|
3676
|
+
--font-sans:'Inter','Segoe UI',system-ui,-apple-system,sans-serif;
|
|
3677
|
+
}
|
|
3678
|
+
html{font-size:14px}
|
|
3679
|
+
body{
|
|
3680
|
+
background:var(--bg);color:var(--text);font-family:var(--font-sans);
|
|
3681
|
+
min-height:100vh;overflow-x:hidden;position:relative;
|
|
3682
|
+
}
|
|
3683
|
+
/* Grid background */
|
|
3684
|
+
body::before{
|
|
3685
|
+
content:'';position:fixed;inset:0;z-index:0;pointer-events:none;
|
|
3686
|
+
background-image:
|
|
3687
|
+
linear-gradient(rgba(0,255,240,0.03) 1px,transparent 1px),
|
|
3688
|
+
linear-gradient(90deg,rgba(0,255,240,0.03) 1px,transparent 1px);
|
|
3689
|
+
background-size:40px 40px;
|
|
3690
|
+
}
|
|
3691
|
+
/* Scanline overlay */
|
|
3692
|
+
body::after{
|
|
3693
|
+
content:'';position:fixed;inset:0;z-index:9999;pointer-events:none;
|
|
3694
|
+
background:repeating-linear-gradient(
|
|
3695
|
+
0deg,transparent,transparent 2px,rgba(0,0,0,0.08) 2px,rgba(0,0,0,0.08) 4px
|
|
3696
|
+
);
|
|
3697
|
+
}
|
|
3698
|
+
#app{position:relative;z-index:1;max-width:1400px;margin:0 auto;padding:0 20px 40px}
|
|
3699
|
+
|
|
3700
|
+
/* ===== Header ===== */
|
|
3701
|
+
.header{
|
|
3702
|
+
display:flex;align-items:center;justify-content:space-between;
|
|
3703
|
+
padding:16px 0;border-bottom:1px solid var(--border);
|
|
3704
|
+
margin-bottom:20px;flex-wrap:wrap;gap:12px;
|
|
3705
|
+
}
|
|
3706
|
+
.header-title{
|
|
3707
|
+
font-family:var(--font-mono);font-size:1.4rem;font-weight:700;
|
|
3708
|
+
color:var(--cyan);letter-spacing:3px;
|
|
3709
|
+
text-shadow:0 0 10px rgba(0,255,240,0.5),0 0 30px rgba(0,255,240,0.2);
|
|
3710
|
+
}
|
|
3711
|
+
.header-title span{color:var(--muted);font-weight:400;font-size:0.9rem;margin-left:8px;letter-spacing:1px}
|
|
3712
|
+
.header-center{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
|
|
3713
|
+
.header-status{display:flex;align-items:center;gap:6px;font-family:var(--font-mono);font-size:0.85rem}
|
|
3714
|
+
.status-dot{
|
|
3715
|
+
width:8px;height:8px;border-radius:50%;background:var(--green);
|
|
3716
|
+
box-shadow:0 0 6px var(--green);animation:pulse 2s ease-in-out infinite;
|
|
3717
|
+
}
|
|
3718
|
+
.status-dot.offline{background:var(--red);box-shadow:0 0 6px var(--red)}
|
|
3719
|
+
.status-dot.not-installed{background:var(--red);box-shadow:0 0 6px var(--red)}
|
|
3720
|
+
.status-dot.not-connected{background:var(--yellow);box-shadow:0 0 6px var(--yellow)}
|
|
3721
|
+
@keyframes pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(0.8)}}
|
|
3722
|
+
.header-meta{color:var(--muted);font-family:var(--font-mono);font-size:0.8rem}
|
|
3723
|
+
.header-right{font-family:var(--font-mono);font-size:0.85rem;color:var(--muted)}
|
|
3724
|
+
.header-right .value{color:var(--cyan)}
|
|
3725
|
+
|
|
3726
|
+
/* ===== Stats Cards ===== */
|
|
3727
|
+
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
|
|
3728
|
+
@media(max-width:768px){.stats-row{grid-template-columns:repeat(2,1fr)}}
|
|
3729
|
+
.stat-card{
|
|
3730
|
+
background:var(--card);border:1px solid var(--border);border-radius:8px;
|
|
3731
|
+
padding:16px 20px;position:relative;overflow:hidden;
|
|
3732
|
+
transition:border-color 0.3s;
|
|
3733
|
+
}
|
|
3734
|
+
.stat-card:hover{border-color:var(--border-bright)}
|
|
3735
|
+
.stat-card::before{
|
|
3736
|
+
content:'';position:absolute;top:0;left:0;right:0;height:2px;
|
|
3737
|
+
}
|
|
3738
|
+
.stat-card.cyan::before{background:var(--cyan);box-shadow:0 0 10px var(--cyan)}
|
|
3739
|
+
.stat-card.green::before{background:var(--green);box-shadow:0 0 10px var(--green)}
|
|
3740
|
+
.stat-card.magenta::before{background:var(--magenta);box-shadow:0 0 10px var(--magenta)}
|
|
3741
|
+
.stat-card.yellow::before{background:var(--yellow);box-shadow:0 0 10px var(--yellow)}
|
|
3742
|
+
.stat-value{
|
|
3743
|
+
font-family:var(--font-mono);font-size:2rem;font-weight:700;
|
|
3744
|
+
transition:color 0.3s;
|
|
3745
|
+
}
|
|
3746
|
+
.stat-card.cyan .stat-value{color:var(--cyan)}
|
|
3747
|
+
.stat-card.green .stat-value{color:var(--green)}
|
|
3748
|
+
.stat-card.magenta .stat-value{color:var(--magenta)}
|
|
3749
|
+
.stat-card.yellow .stat-value{color:var(--yellow)}
|
|
3750
|
+
.stat-label{color:var(--muted);font-size:0.8rem;margin-top:4px;text-transform:uppercase;letter-spacing:1px}
|
|
3751
|
+
.stat-value.flash{animation:flash 0.3s ease}
|
|
3752
|
+
@keyframes flash{0%{opacity:1}50%{opacity:0.3}100%{opacity:1}}
|
|
3753
|
+
|
|
3754
|
+
/* ===== Main Grid ===== */
|
|
3755
|
+
.main-grid{display:grid;grid-template-columns:2fr 1fr;gap:20px;margin-bottom:24px}
|
|
3756
|
+
@media(max-width:1024px){.main-grid{grid-template-columns:1fr}}
|
|
3757
|
+
.section{
|
|
3758
|
+
background:var(--card);border:1px solid var(--border);border-radius:8px;
|
|
3759
|
+
overflow:hidden;
|
|
3760
|
+
}
|
|
3761
|
+
.section-header{
|
|
3762
|
+
padding:12px 16px;border-bottom:1px solid var(--border);
|
|
3763
|
+
font-family:var(--font-mono);font-size:0.8rem;font-weight:600;
|
|
3764
|
+
color:var(--muted);letter-spacing:2px;text-transform:uppercase;
|
|
3765
|
+
display:flex;align-items:center;gap:8px;
|
|
3766
|
+
}
|
|
3767
|
+
.section-header .dot{width:6px;height:6px;border-radius:50%;background:var(--cyan)}
|
|
3768
|
+
.section-body{padding:16px}
|
|
3769
|
+
|
|
3770
|
+
/* ===== Topology ===== */
|
|
3771
|
+
.topology-container{display:flex;justify-content:center;align-items:center;min-height:300px}
|
|
3772
|
+
.topology-container svg{width:100%;max-width:500px;height:300px}
|
|
3773
|
+
.topo-node{cursor:pointer;transition:filter 0.3s}
|
|
3774
|
+
.topo-node:hover{filter:brightness(1.3)}
|
|
3775
|
+
.topo-label{font-family:var(--font-mono);font-size:10px;fill:var(--muted)}
|
|
3776
|
+
.topo-badge{
|
|
3777
|
+
font-family:var(--font-mono);font-size:9px;fill:var(--bg);
|
|
3778
|
+
font-weight:700;
|
|
3779
|
+
}
|
|
3780
|
+
|
|
3781
|
+
/* ===== Peer Table ===== */
|
|
3782
|
+
.peer-table{width:100%;border-collapse:collapse;font-size:0.85rem}
|
|
3783
|
+
.peer-table th{
|
|
3784
|
+
text-align:left;padding:8px 10px;color:var(--muted);font-weight:600;
|
|
3785
|
+
font-family:var(--font-mono);font-size:0.75rem;text-transform:uppercase;
|
|
3786
|
+
letter-spacing:1px;border-bottom:1px solid var(--border);
|
|
3787
|
+
}
|
|
3788
|
+
.peer-table td{padding:8px 10px;border-bottom:1px solid var(--border);font-family:var(--font-mono);font-size:0.8rem}
|
|
3789
|
+
.peer-table tr:last-child td{border-bottom:none}
|
|
3790
|
+
.peer-table tr:hover td{background:rgba(255,255,255,0.02)}
|
|
3791
|
+
.badge{
|
|
3792
|
+
display:inline-block;padding:2px 8px;border-radius:4px;font-size:0.7rem;
|
|
3793
|
+
font-weight:600;text-transform:uppercase;letter-spacing:0.5px;
|
|
3794
|
+
}
|
|
3795
|
+
.badge-party{background:rgba(0,255,136,0.15);color:var(--green)}
|
|
3796
|
+
.badge-degraded{background:rgba(255,170,0,0.15);color:var(--yellow)}
|
|
3797
|
+
.badge-suspect{background:rgba(255,136,0,0.15);color:var(--orange)}
|
|
3798
|
+
.badge-down{background:rgba(255,51,102,0.15);color:var(--red)}
|
|
3799
|
+
.badge-unknown{background:rgba(106,106,138,0.15);color:var(--muted)}
|
|
3800
|
+
.badge-not_server{background:rgba(106,106,138,0.1);color:var(--muted)}
|
|
3801
|
+
.badge-maybe{background:rgba(0,255,240,0.1);color:var(--cyan)}
|
|
3802
|
+
.empty-state{text-align:center;color:var(--muted);padding:40px 20px;font-family:var(--font-mono);font-size:0.85rem}
|
|
3803
|
+
|
|
3804
|
+
/* ===== Agent & Message Grid ===== */
|
|
3805
|
+
.bottom-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px}
|
|
3806
|
+
@media(max-width:1024px){.bottom-grid{grid-template-columns:1fr}}
|
|
3807
|
+
|
|
3808
|
+
/* Agent cards */
|
|
3809
|
+
.agent-list{display:flex;flex-direction:column;gap:8px;max-height:400px;overflow-y:auto}
|
|
3810
|
+
.agent-card{
|
|
3811
|
+
display:flex;align-items:center;gap:12px;padding:10px 14px;
|
|
3812
|
+
border:1px solid var(--border);border-radius:6px;transition:border-color 0.3s;
|
|
3813
|
+
}
|
|
3814
|
+
.agent-card:hover{border-color:var(--border-bright)}
|
|
3815
|
+
.agent-card.local{border-left:3px solid var(--cyan)}
|
|
3816
|
+
.agent-card.remote{border-left:3px solid var(--green)}
|
|
3817
|
+
.agent-icon{
|
|
3818
|
+
width:36px;height:36px;border-radius:6px;display:flex;align-items:center;
|
|
3819
|
+
justify-content:center;font-family:var(--font-mono);font-size:0.9rem;font-weight:700;
|
|
3820
|
+
flex-shrink:0;
|
|
3821
|
+
}
|
|
3822
|
+
.agent-card.local .agent-icon{background:rgba(0,255,240,0.1);color:var(--cyan)}
|
|
3823
|
+
.agent-card.remote .agent-icon{background:rgba(0,255,136,0.1);color:var(--green)}
|
|
3824
|
+
.agent-info{flex:1;min-width:0}
|
|
3825
|
+
.agent-name{font-weight:600;font-size:0.9rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
3826
|
+
.agent-id{font-family:var(--font-mono);font-size:0.7rem;color:var(--muted);margin-top:2px}
|
|
3827
|
+
.agent-meta{display:flex;gap:6px;flex-shrink:0;align-items:center}
|
|
3828
|
+
.agent-tag{
|
|
3829
|
+
font-family:var(--font-mono);font-size:0.65rem;padding:2px 6px;
|
|
3830
|
+
border-radius:3px;background:rgba(255,255,255,0.05);color:var(--muted);
|
|
3831
|
+
}
|
|
3832
|
+
.agent-tag.unreachable{background:rgba(255,51,102,0.1);color:var(--red)}
|
|
3833
|
+
|
|
3834
|
+
/* Message feed */
|
|
3835
|
+
.msg-feed{display:flex;flex-direction:column;gap:6px;max-height:400px;overflow-y:auto}
|
|
3836
|
+
.msg-item{
|
|
3837
|
+
padding:10px 12px;border:1px solid var(--border);border-radius:6px;
|
|
3838
|
+
border-left:3px solid var(--cyan);font-size:0.8rem;
|
|
3839
|
+
}
|
|
3840
|
+
.msg-item.received{border-left-color:var(--magenta)}
|
|
3841
|
+
.msg-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:4px}
|
|
3842
|
+
.msg-flow{font-family:var(--font-mono);font-size:0.75rem;color:var(--cyan)}
|
|
3843
|
+
.msg-flow .arrow{color:var(--muted);margin:0 4px}
|
|
3844
|
+
.msg-time{font-family:var(--font-mono);font-size:0.65rem;color:var(--muted)}
|
|
3845
|
+
.msg-content{color:var(--text);font-size:0.8rem;line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
3846
|
+
|
|
3847
|
+
/* Scrollbar */
|
|
3848
|
+
::-webkit-scrollbar{width:4px}
|
|
3849
|
+
::-webkit-scrollbar-track{background:var(--bg)}
|
|
3850
|
+
::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
|
|
3851
|
+
::-webkit-scrollbar-thumb:hover{background:var(--border-bright)}
|
|
3852
|
+
|
|
3853
|
+
/* Footer */
|
|
3854
|
+
.footer{
|
|
3855
|
+
text-align:center;padding:20px 0;border-top:1px solid var(--border);
|
|
3856
|
+
color:var(--muted);font-family:var(--font-mono);font-size:0.75rem;
|
|
3857
|
+
letter-spacing:1px;
|
|
3858
|
+
}
|
|
3859
|
+
|
|
3860
|
+
/* Join Network Button */
|
|
3861
|
+
.btn-join{
|
|
3862
|
+
font-family:var(--font-mono);font-size:0.75rem;letter-spacing:1px;
|
|
3863
|
+
padding:6px 14px;border:1px solid var(--cyan);border-radius:4px;
|
|
3864
|
+
background:rgba(0,255,240,0.08);color:var(--cyan);cursor:pointer;
|
|
3865
|
+
transition:all 0.2s;text-transform:uppercase;margin-left:12px;
|
|
3866
|
+
}
|
|
3867
|
+
.btn-join:hover{background:rgba(0,255,240,0.18);box-shadow:0 0 10px rgba(0,255,240,0.2)}
|
|
3868
|
+
.btn-join:active{transform:scale(0.97)}
|
|
3869
|
+
.btn-join.connected{border-color:var(--green);color:var(--green);background:rgba(0,255,136,0.08)}
|
|
3870
|
+
|
|
3871
|
+
/* Modal */
|
|
3872
|
+
.modal-overlay{
|
|
3873
|
+
position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:10000;
|
|
3874
|
+
display:flex;align-items:center;justify-content:center;
|
|
3875
|
+
opacity:0;pointer-events:none;transition:opacity 0.25s;
|
|
3876
|
+
}
|
|
3877
|
+
.modal-overlay.open{opacity:1;pointer-events:all}
|
|
3878
|
+
.modal{
|
|
3879
|
+
background:var(--card);border:1px solid var(--border-bright);border-radius:10px;
|
|
3880
|
+
padding:28px 32px;width:90%;max-width:440px;
|
|
3881
|
+
box-shadow:0 0 40px rgba(0,255,240,0.08),0 8px 32px rgba(0,0,0,0.5);
|
|
3882
|
+
}
|
|
3883
|
+
.modal-title{
|
|
3884
|
+
font-family:var(--font-mono);font-size:1rem;font-weight:700;color:var(--cyan);
|
|
3885
|
+
letter-spacing:2px;margin-bottom:6px;
|
|
3886
|
+
text-shadow:0 0 8px rgba(0,255,240,0.3);
|
|
3887
|
+
}
|
|
3888
|
+
.modal-desc{color:var(--muted);font-size:0.8rem;margin-bottom:20px;line-height:1.5}
|
|
3889
|
+
.modal-input{
|
|
3890
|
+
width:100%;padding:10px 14px;background:var(--bg);border:1px solid var(--border);
|
|
3891
|
+
border-radius:6px;color:var(--text);font-family:var(--font-mono);font-size:0.85rem;
|
|
3892
|
+
outline:none;transition:border-color 0.2s;
|
|
3893
|
+
}
|
|
3894
|
+
.modal-input:focus{border-color:var(--cyan);box-shadow:0 0 8px rgba(0,255,240,0.15)}
|
|
3895
|
+
.modal-input::placeholder{color:var(--muted)}
|
|
3896
|
+
.modal-actions{display:flex;gap:10px;margin-top:18px;justify-content:flex-end}
|
|
3897
|
+
.modal-btn{
|
|
3898
|
+
font-family:var(--font-mono);font-size:0.8rem;padding:8px 18px;
|
|
3899
|
+
border-radius:4px;cursor:pointer;transition:all 0.2s;letter-spacing:0.5px;
|
|
3900
|
+
}
|
|
3901
|
+
.modal-btn-cancel{
|
|
3902
|
+
border:1px solid var(--border);background:transparent;color:var(--muted);
|
|
3903
|
+
}
|
|
3904
|
+
.modal-btn-cancel:hover{border-color:var(--muted);color:var(--text)}
|
|
3905
|
+
.modal-btn-submit{
|
|
3906
|
+
border:1px solid var(--cyan);background:rgba(0,255,240,0.12);color:var(--cyan);
|
|
3907
|
+
}
|
|
3908
|
+
.modal-btn-submit:hover{background:rgba(0,255,240,0.22);box-shadow:0 0 10px rgba(0,255,240,0.2)}
|
|
3909
|
+
.modal-btn-submit:disabled{opacity:0.4;cursor:not-allowed}
|
|
3910
|
+
.modal-status{
|
|
3911
|
+
margin-top:12px;padding:8px 12px;border-radius:4px;font-size:0.78rem;
|
|
3912
|
+
font-family:var(--font-mono);display:none;
|
|
3913
|
+
}
|
|
3914
|
+
.modal-status.success{display:block;background:rgba(0,255,136,0.1);border:1px solid rgba(0,255,136,0.3);color:var(--green)}
|
|
3915
|
+
.modal-status.error{display:block;background:rgba(255,51,102,0.1);border:1px solid rgba(255,51,102,0.3);color:var(--red)}
|
|
3916
|
+
.spinner{
|
|
3917
|
+
display:inline-block;width:12px;height:12px;border:2px solid transparent;
|
|
3918
|
+
border-top-color:var(--cyan);border-radius:50%;animation:spin 0.6s linear infinite;
|
|
3919
|
+
vertical-align:middle;margin-right:6px;
|
|
3920
|
+
}
|
|
3921
|
+
@keyframes spin{to{transform:rotate(360deg)}}
|
|
3922
|
+
|
|
3923
|
+
/* ===== Tailscale Status Panel ===== */
|
|
3924
|
+
.ts-panel{
|
|
3925
|
+
margin-top:12px;padding:16px 20px;background:var(--card);border:1px solid var(--border);
|
|
3926
|
+
border-radius:8px;font-family:var(--font-mono);font-size:0.8rem;
|
|
3927
|
+
}
|
|
3928
|
+
.ts-panel-title{
|
|
3929
|
+
font-weight:700;letter-spacing:2px;text-transform:uppercase;margin-bottom:10px;
|
|
3930
|
+
display:flex;align-items:center;gap:8px;
|
|
3931
|
+
}
|
|
3932
|
+
.ts-panel-title.connected{color:var(--green)}
|
|
3933
|
+
.ts-panel-title.not-installed{color:var(--red)}
|
|
3934
|
+
.ts-panel-title.not-connected{color:var(--yellow)}
|
|
3935
|
+
.ts-info-row{display:flex;gap:8px;margin:4px 0;color:var(--muted)}
|
|
3936
|
+
.ts-info-row .label{min-width:100px;color:var(--muted)}
|
|
3937
|
+
.ts-info-row .value{color:var(--text)}
|
|
3938
|
+
.ts-install-guide{
|
|
3939
|
+
margin-top:12px;padding:12px 16px;background:rgba(0,0,0,0.3);border:1px solid var(--border);
|
|
3940
|
+
border-radius:6px;
|
|
3941
|
+
}
|
|
3942
|
+
.ts-install-guide .cmd{
|
|
3943
|
+
display:flex;align-items:center;justify-content:space-between;
|
|
3944
|
+
padding:6px 10px;background:rgba(255,255,255,0.04);border-radius:4px;
|
|
3945
|
+
margin:6px 0;font-size:0.8rem;cursor:pointer;transition:background 0.2s;
|
|
3946
|
+
}
|
|
3947
|
+
.ts-install-guide .cmd:hover{background:rgba(255,255,255,0.08)}
|
|
3948
|
+
.ts-install-guide .cmd code{color:var(--cyan)}
|
|
3949
|
+
.ts-install-guide .copy-hint{color:var(--muted);font-size:0.7rem}
|
|
3950
|
+
.ts-install-guide a{color:var(--cyan);text-decoration:none}
|
|
3951
|
+
.ts-install-guide a:hover{text-decoration:underline}
|
|
3952
|
+
.ts-setup-hint{
|
|
3953
|
+
margin-top:10px;padding:8px 12px;background:rgba(0,255,240,0.05);border:1px solid rgba(0,255,240,0.15);
|
|
3954
|
+
border-radius:4px;color:var(--cyan);font-size:0.78rem;
|
|
3955
|
+
}
|
|
3956
|
+
.btn-redetect{
|
|
3957
|
+
font-family:var(--font-mono);font-size:0.7rem;padding:4px 12px;
|
|
3958
|
+
border:1px solid var(--border-bright);border-radius:4px;background:transparent;
|
|
3959
|
+
color:var(--muted);cursor:pointer;transition:all 0.2s;margin-top:8px;
|
|
3960
|
+
}
|
|
3961
|
+
.btn-redetect:hover{border-color:var(--cyan);color:var(--cyan)}
|
|
3962
|
+
</style>
|
|
3963
|
+
</head>
|
|
3964
|
+
<body>
|
|
3965
|
+
<div id="app">
|
|
3966
|
+
<header class="header">
|
|
3967
|
+
<div class="header-title">OPEN PARTY<span>// Dashboard</span></div>
|
|
3968
|
+
<div class="header-center">
|
|
3969
|
+
<div class="header-status">
|
|
3970
|
+
<div class="status-dot" id="statusDot"></div>
|
|
3971
|
+
<span id="statusText">CONNECTING</span>
|
|
3972
|
+
</div>
|
|
3973
|
+
<div class="header-meta" id="serverInfo">--</div>
|
|
3974
|
+
</div>
|
|
3975
|
+
<div class="header-right">
|
|
3976
|
+
UPTIME <span class="value" id="uptime">--:--:--</span>
|
|
3977
|
+
<button class="btn-join" id="btnJoinNetwork" title="Join Tailscale Network">Join Network</button>
|
|
3978
|
+
</div>
|
|
3979
|
+
</header>
|
|
3980
|
+
|
|
3981
|
+
<!-- Tailscale status panel (shown when not connected) -->
|
|
3982
|
+
<div id="tsPanel" class="ts-panel" style="display:none"></div>
|
|
3983
|
+
|
|
3984
|
+
<div class="stats-row" id="statsRow">
|
|
3985
|
+
<div class="stat-card cyan">
|
|
3986
|
+
<div class="stat-value" id="localAgentCount">-</div>
|
|
3987
|
+
<div class="stat-label">Local Agents</div>
|
|
3988
|
+
</div>
|
|
3989
|
+
<div class="stat-card green">
|
|
3990
|
+
<div class="stat-value" id="remoteAgentCount">-</div>
|
|
3991
|
+
<div class="stat-label">Remote Agents</div>
|
|
3992
|
+
</div>
|
|
3993
|
+
<div class="stat-card magenta">
|
|
3994
|
+
<div class="stat-value" id="peerCount">-</div>
|
|
3995
|
+
<div class="stat-label">Known Peers</div>
|
|
3996
|
+
</div>
|
|
3997
|
+
<div class="stat-card yellow">
|
|
3998
|
+
<div class="stat-value" id="partyServerCount">-</div>
|
|
3999
|
+
<div class="stat-label">Party Servers</div>
|
|
4000
|
+
</div>
|
|
4001
|
+
</div>
|
|
4002
|
+
|
|
4003
|
+
<div class="main-grid">
|
|
4004
|
+
<div class="section">
|
|
4005
|
+
<div class="section-header"><div class="dot"></div>NETWORK TOPOLOGY</div>
|
|
4006
|
+
<div class="section-body">
|
|
4007
|
+
<div class="topology-container" id="topologyContainer">
|
|
4008
|
+
<svg id="topologySvg" viewBox="0 0 500 300"></svg>
|
|
4009
|
+
</div>
|
|
4010
|
+
</div>
|
|
4011
|
+
</div>
|
|
4012
|
+
<div class="section">
|
|
4013
|
+
<div class="section-header"><div class="dot" style="background:var(--green)"></div>PEER HEALTH</div>
|
|
4014
|
+
<div class="section-body" style="padding:0">
|
|
4015
|
+
<div id="peerTableContainer">
|
|
4016
|
+
<table class="peer-table">
|
|
4017
|
+
<thead><tr><th>IP</th><th>Status</th><th>Fails</th><th>Last Probe</th></tr></thead>
|
|
4018
|
+
<tbody id="peerTableBody"></tbody>
|
|
4019
|
+
</table>
|
|
4020
|
+
</div>
|
|
4021
|
+
</div>
|
|
4022
|
+
</div>
|
|
4023
|
+
</div>
|
|
4024
|
+
|
|
4025
|
+
<div class="bottom-grid">
|
|
4026
|
+
<div class="section">
|
|
4027
|
+
<div class="section-header"><div class="dot" style="background:var(--cyan)"></div>AGENT DIRECTORY</div>
|
|
4028
|
+
<div class="section-body">
|
|
4029
|
+
<div class="agent-list" id="agentList"></div>
|
|
4030
|
+
</div>
|
|
4031
|
+
</div>
|
|
4032
|
+
<div class="section">
|
|
4033
|
+
<div class="section-header"><div class="dot" style="background:var(--magenta)"></div>MESSAGE FLOW</div>
|
|
4034
|
+
<div class="section-body">
|
|
4035
|
+
<div class="msg-feed" id="msgFeed"></div>
|
|
4036
|
+
</div>
|
|
4037
|
+
</div>
|
|
4038
|
+
</div>
|
|
4039
|
+
|
|
4040
|
+
<div class="footer">OPEN PARTY v0.1 // DECENTRALIZED AGENT NETWORK</div>
|
|
4041
|
+
|
|
4042
|
+
<!-- Join Network Modal -->
|
|
4043
|
+
<div class="modal-overlay" id="joinModal">
|
|
4044
|
+
<div class="modal">
|
|
4045
|
+
<div class="modal-title">JOIN TAILNET</div>
|
|
4046
|
+
<div class="modal-desc">Enter your Tailscale auth key to join the network.<br>You can generate one from the Tailscale admin console.</div>
|
|
4047
|
+
<input type="password" class="modal-input" id="authKeyInput" placeholder="tskey-auth-xxxxx..." autocomplete="off" spellcheck="false" />
|
|
4048
|
+
<div class="modal-status" id="joinStatus"></div>
|
|
4049
|
+
<div class="modal-actions">
|
|
4050
|
+
<button class="modal-btn modal-btn-cancel" id="btnCancelJoin">Cancel</button>
|
|
4051
|
+
<button class="modal-btn modal-btn-submit" id="btnSubmitJoin">Connect</button>
|
|
4052
|
+
</div>
|
|
4053
|
+
</div>
|
|
4054
|
+
</div>
|
|
4055
|
+
</div>
|
|
4056
|
+
|
|
4057
|
+
<script>
|
|
4058
|
+
(function() {
|
|
4059
|
+
'use strict';
|
|
4060
|
+
|
|
4061
|
+
// ---- Helpers ----
|
|
4062
|
+
const $ = (s) => document.querySelector(s);
|
|
4063
|
+
const $$ = (s) => document.querySelectorAll(s);
|
|
4064
|
+
|
|
4065
|
+
function formatUptime(seconds) {
|
|
4066
|
+
const h = Math.floor(seconds / 3600);
|
|
4067
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
4068
|
+
const s = seconds % 60;
|
|
4069
|
+
return String(h).padStart(2,'0') + ':' + String(m).padStart(2,'0') + ':' + String(s).padStart(2,'0');
|
|
4070
|
+
}
|
|
4071
|
+
|
|
4072
|
+
function timeAgo(ts) {
|
|
4073
|
+
if (!ts) return '--';
|
|
4074
|
+
const diff = Math.floor(Date.now() / 1000 - ts);
|
|
4075
|
+
if (diff < 0) return 'now';
|
|
4076
|
+
if (diff < 60) return diff + 's ago';
|
|
4077
|
+
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
|
|
4078
|
+
return Math.floor(diff / 3600) + 'h ago';
|
|
4079
|
+
}
|
|
4080
|
+
|
|
4081
|
+
function flashEl(el) {
|
|
4082
|
+
el.classList.remove('flash');
|
|
4083
|
+
void el.offsetWidth;
|
|
4084
|
+
el.classList.add('flash');
|
|
4085
|
+
}
|
|
4086
|
+
|
|
4087
|
+
const statusColors = {
|
|
4088
|
+
PARTY_SERVER: '#00ff88',
|
|
4089
|
+
DEGRADED: '#ffaa00',
|
|
4090
|
+
SUSPECT: '#ff8800',
|
|
4091
|
+
DOWN: '#ff3366',
|
|
4092
|
+
UNKNOWN: '#6a6a8a',
|
|
4093
|
+
NOT_SERVER: '#6a6a8a',
|
|
4094
|
+
MAYBE: '#00fff0',
|
|
4095
|
+
};
|
|
4096
|
+
|
|
4097
|
+
const statusBadgeClass = {
|
|
4098
|
+
PARTY_SERVER: 'badge-party',
|
|
4099
|
+
DEGRADED: 'badge-degraded',
|
|
4100
|
+
SUSPECT: 'badge-suspect',
|
|
4101
|
+
DOWN: 'badge-down',
|
|
4102
|
+
UNKNOWN: 'badge-unknown',
|
|
4103
|
+
NOT_SERVER: 'badge-not_server',
|
|
4104
|
+
MAYBE: 'badge-maybe',
|
|
4105
|
+
};
|
|
4106
|
+
|
|
4107
|
+
// ---- State ----
|
|
4108
|
+
let overview = null;
|
|
4109
|
+
let prevStats = null;
|
|
4110
|
+
|
|
4111
|
+
// ---- Fetch helpers ----
|
|
4112
|
+
async function fetchStats() {
|
|
4113
|
+
try {
|
|
4114
|
+
const r = await fetch('/dashboard/api/stats');
|
|
4115
|
+
return await r.json();
|
|
4116
|
+
} catch { return null; }
|
|
4117
|
+
}
|
|
4118
|
+
|
|
4119
|
+
async function fetchOverview() {
|
|
4120
|
+
try {
|
|
4121
|
+
const r = await fetch('/dashboard/api/overview');
|
|
4122
|
+
return await r.json();
|
|
4123
|
+
} catch { return null; }
|
|
4124
|
+
}
|
|
4125
|
+
|
|
4126
|
+
// ---- Render functions ----
|
|
4127
|
+
function renderHeader(data) {
|
|
4128
|
+
const s = data.server;
|
|
4129
|
+
if (tsState && tsState.state === 'connected') {
|
|
4130
|
+
$('#statusDot').className = 'status-dot';
|
|
4131
|
+
$('#statusText').textContent = 'ONLINE';
|
|
4132
|
+
$('#serverInfo').textContent = s.tailscale_ip + ' // ' + s.hostname;
|
|
4133
|
+
} else if (tsState && tsState.state === 'not_connected') {
|
|
4134
|
+
$('#statusDot').className = 'status-dot not-connected';
|
|
4135
|
+
$('#statusText').textContent = 'NOT CONNECTED';
|
|
4136
|
+
$('#serverInfo').textContent = 'Tailscale installed but not authenticated';
|
|
4137
|
+
} else if (tsState && tsState.state === 'not_installed') {
|
|
4138
|
+
$('#statusDot').className = 'status-dot not-installed';
|
|
4139
|
+
$('#statusText').textContent = 'NO TAILSCALE';
|
|
4140
|
+
$('#serverInfo').textContent = 'Tailscale not installed - local mode';
|
|
4141
|
+
} else {
|
|
4142
|
+
$('#statusDot').className = 'status-dot';
|
|
4143
|
+
$('#statusText').textContent = 'ONLINE';
|
|
4144
|
+
$('#serverInfo').textContent = s.tailscale_ip + ' // ' + s.hostname;
|
|
4145
|
+
}
|
|
4146
|
+
$('#uptime').textContent = formatUptime(s.uptime_seconds);
|
|
4147
|
+
}
|
|
4148
|
+
|
|
4149
|
+
function renderStats(data) {
|
|
4150
|
+
const prev = {
|
|
4151
|
+
local: parseInt($('#localAgentCount').textContent) || 0,
|
|
4152
|
+
remote: parseInt($('#remoteAgentCount').textContent) || 0,
|
|
4153
|
+
peer: parseInt($('#peerCount').textContent) || 0,
|
|
4154
|
+
party: parseInt($('#partyServerCount').textContent) || 0,
|
|
4155
|
+
};
|
|
4156
|
+
const vals = {
|
|
4157
|
+
local: data.agents.local_count,
|
|
4158
|
+
remote: data.agents.remote_count,
|
|
4159
|
+
peer: data.peers.total,
|
|
4160
|
+
party: data.peers.party_servers,
|
|
4161
|
+
};
|
|
4162
|
+
if (vals.local !== prev.local) { $('#localAgentCount').textContent = vals.local; flashEl($('#localAgentCount')); }
|
|
4163
|
+
if (vals.remote !== prev.remote) { $('#remoteAgentCount').textContent = vals.remote; flashEl($('#remoteAgentCount')); }
|
|
4164
|
+
if (vals.peer !== prev.peer) { $('#peerCount').textContent = vals.peer; flashEl($('#peerCount')); }
|
|
4165
|
+
if (vals.party !== prev.party) { $('#partyServerCount').textContent = vals.party; flashEl($('#partyServerCount')); }
|
|
4166
|
+
}
|
|
4167
|
+
|
|
4168
|
+
function renderTopology(data) {
|
|
4169
|
+
const svg = $('#topologySvg');
|
|
4170
|
+
const peers = data.peers.details || [];
|
|
4171
|
+
const cx = 250, cy = 150, radius = 100;
|
|
4172
|
+
|
|
4173
|
+
let html = '';
|
|
4174
|
+
|
|
4175
|
+
// Center node
|
|
4176
|
+
html += '<circle cx="' + cx + '" cy="' + cy + '" r="24" fill="rgba(0,255,240,0.15)" stroke="#00fff0" stroke-width="2">';
|
|
4177
|
+
html += '<animate attributeName="r" values="24;26;24" dur="3s" repeatCount="indefinite"/>';
|
|
4178
|
+
html += '</circle>';
|
|
4179
|
+
html += '<text x="' + cx + '" y="' + cy + '" text-anchor="middle" dominant-baseline="central" fill="#00fff0" font-family="var(--font-mono)" font-size="10" font-weight="700">SELF</text>';
|
|
4180
|
+
html += '<text x="' + cx + '" y="' + (cy + 38) + '" text-anchor="middle" class="topo-label">' + data.server.tailscale_ip + '</text>';
|
|
4181
|
+
|
|
4182
|
+
if (peers.length === 0) {
|
|
4183
|
+
html += '<text x="' + cx + '" y="' + (cy + 60) + '" text-anchor="middle" fill="#6a6a8a" font-family="var(--font-mono)" font-size="11">No peers discovered</text>';
|
|
4184
|
+
}
|
|
4185
|
+
|
|
4186
|
+
peers.forEach(function(p, i) {
|
|
4187
|
+
const angle = (2 * Math.PI * i / Math.max(peers.length, 1)) - Math.PI / 2;
|
|
4188
|
+
const px = cx + radius * Math.cos(angle);
|
|
4189
|
+
const py = cy + radius * Math.sin(angle);
|
|
4190
|
+
const color = statusColors[p.status] || '#6a6a8a';
|
|
4191
|
+
const opacity = (p.status === 'PARTY_SERVER' || p.status === 'DEGRADED' || p.status === 'SUSPECT') ? 1 : 0.4;
|
|
4192
|
+
|
|
4193
|
+
// Connection line
|
|
4194
|
+
html += '<line x1="' + cx + '" y1="' + cy + '" x2="' + px + '" y2="' + py + '" stroke="' + color + '" stroke-width="1" opacity="' + (opacity * 0.3) + '"/>';
|
|
4195
|
+
|
|
4196
|
+
// Peer node
|
|
4197
|
+
html += '<g class="topo-node"><circle cx="' + px + '" cy="' + py + '" r="16" fill="rgba(255,255,255,0.03)" stroke="' + color + '" stroke-width="1.5" opacity="' + opacity + '"/>';
|
|
4198
|
+
html += '<text x="' + px + '" y="' + py + '" text-anchor="middle" dominant-baseline="central" fill="' + color + '" font-family="var(--font-mono)" font-size="8" opacity="' + opacity + '">' + p.ip.split('.').slice(-1)[0] + '</text></g>';
|
|
4199
|
+
|
|
4200
|
+
// IP label
|
|
4201
|
+
html += '<text x="' + px + '" y="' + (py + 26) + '" text-anchor="middle" class="topo-label">' + p.ip + '</text>';
|
|
4202
|
+
});
|
|
4203
|
+
|
|
4204
|
+
svg.innerHTML = html;
|
|
4205
|
+
}
|
|
4206
|
+
|
|
4207
|
+
function renderPeerTable(data) {
|
|
4208
|
+
const tbody = $('#peerTableBody');
|
|
4209
|
+
const peers = data.peers.details || [];
|
|
4210
|
+
|
|
4211
|
+
if (peers.length === 0) {
|
|
4212
|
+
tbody.innerHTML = '<tr><td colspan="4" class="empty-state">No peers discovered</td></tr>';
|
|
4213
|
+
return;
|
|
4214
|
+
}
|
|
4215
|
+
|
|
4216
|
+
// Sort: PARTY_SERVER first, then by severity
|
|
4217
|
+
const order = { PARTY_SERVER: 0, DEGRADED: 1, SUSPECT: 2, MAYBE: 3, UNKNOWN: 4, NOT_SERVER: 5, DOWN: 6 };
|
|
4218
|
+
const sorted = [...peers].sort(function(a, b) { return (order[a.status] || 99) - (order[b.status] || 99); });
|
|
4219
|
+
|
|
4220
|
+
tbody.innerHTML = sorted.map(function(p) {
|
|
4221
|
+
const badge = statusBadgeClass[p.status] || 'badge-unknown';
|
|
4222
|
+
const label = p.status === 'PARTY_SERVER' ? 'SERVER' : p.status === 'NOT_SERVER' ? 'NOT_SVR' : p.status;
|
|
4223
|
+
return '<tr>'
|
|
4224
|
+
+ '<td>' + p.ip + '</td>'
|
|
4225
|
+
+ '<td><span class="badge ' + badge + '">' + label + '</span></td>'
|
|
4226
|
+
+ '<td>' + p.consecutiveFailures + '</td>'
|
|
4227
|
+
+ '<td>' + timeAgo(p.lastProbeAt) + '</td>'
|
|
4228
|
+
+ '</tr>';
|
|
4229
|
+
}).join('');
|
|
4230
|
+
}
|
|
4231
|
+
|
|
4232
|
+
function renderAgents(data) {
|
|
4233
|
+
const container = $('#agentList');
|
|
4234
|
+
const local = data.agents.local_agents || [];
|
|
4235
|
+
const remote = data.agents.remote_agents || [];
|
|
4236
|
+
const all = [
|
|
4237
|
+
...local.map(function(a) { return { ...a, type: 'local' }; }),
|
|
4238
|
+
...remote.map(function(a) { return { ...a, type: 'remote' }; }),
|
|
4239
|
+
];
|
|
4240
|
+
|
|
4241
|
+
if (all.length === 0) {
|
|
4242
|
+
container.innerHTML = '<div class="empty-state">No agents registered</div>';
|
|
4243
|
+
return;
|
|
4244
|
+
}
|
|
4245
|
+
|
|
4246
|
+
container.innerHTML = all.map(function(a) {
|
|
4247
|
+
const initials = (a.display_name || a.agent_id).substring(0, 2).toUpperCase();
|
|
4248
|
+
const tags = [];
|
|
4249
|
+
if (a.type === 'remote') {
|
|
4250
|
+
tags.push('<span class="agent-tag">' + a.source_peer_ip + '</span>');
|
|
4251
|
+
if (!a.reachable) tags.push('<span class="agent-tag unreachable">offline</span>');
|
|
4252
|
+
} else {
|
|
4253
|
+
tags.push('<span class="agent-tag">local</span>');
|
|
4254
|
+
}
|
|
4255
|
+
return '<div class="agent-card ' + a.type + '">'
|
|
4256
|
+
+ '<div class="agent-icon">' + initials + '</div>'
|
|
4257
|
+
+ '<div class="agent-info">'
|
|
4258
|
+
+ '<div class="agent-name">' + (a.display_name || a.agent_id) + '</div>'
|
|
4259
|
+
+ '<div class="agent-id">' + a.agent_id + '</div>'
|
|
4260
|
+
+ '</div>'
|
|
4261
|
+
+ '<div class="agent-meta">' + tags.join('') + '</div>'
|
|
4262
|
+
+ '</div>';
|
|
4263
|
+
}).join('');
|
|
4264
|
+
}
|
|
4265
|
+
|
|
4266
|
+
function renderMessages(data) {
|
|
4267
|
+
const container = $('#msgFeed');
|
|
4268
|
+
const msgs = data.messages.recent || [];
|
|
4269
|
+
|
|
4270
|
+
if (msgs.length === 0) {
|
|
4271
|
+
container.innerHTML = '<div class="empty-state">No recent messages</div>';
|
|
4272
|
+
return;
|
|
4273
|
+
}
|
|
4274
|
+
|
|
4275
|
+
container.innerHTML = msgs.map(function(m) {
|
|
4276
|
+
const dir = m.direction === 'received' ? 'received' : '';
|
|
4277
|
+
const arrow = m.direction === 'received' ? '←' : '→';
|
|
4278
|
+
const flow = m.direction === 'received'
|
|
4279
|
+
? m.sender_id + ' <span class="arrow">' + arrow + '</span> ' + (m.agent_id || '?')
|
|
4280
|
+
: (m.agent_id || '?') + ' <span class="arrow">' + arrow + '</span> ' + (m.recipient_id || 'broadcast');
|
|
4281
|
+
return '<div class="msg-item ' + dir + '">'
|
|
4282
|
+
+ '<div class="msg-top">'
|
|
4283
|
+
+ '<div class="msg-flow">' + flow + '</div>'
|
|
4284
|
+
+ '<div class="msg-time">' + timeAgo(m.timestamp) + '</div>'
|
|
4285
|
+
+ '</div>'
|
|
4286
|
+
+ '<div class="msg-content">' + (m.summary || m.content) + '</div>'
|
|
4287
|
+
+ '</div>';
|
|
4288
|
+
}).join('');
|
|
4289
|
+
}
|
|
4290
|
+
|
|
4291
|
+
function renderAll(data) {
|
|
4292
|
+
renderHeader(data);
|
|
4293
|
+
renderStats(data);
|
|
4294
|
+
renderTopology(data);
|
|
4295
|
+
renderPeerTable(data);
|
|
4296
|
+
renderAgents(data);
|
|
4297
|
+
renderMessages(data);
|
|
4298
|
+
}
|
|
4299
|
+
|
|
4300
|
+
// ---- Polling ----
|
|
4301
|
+
let fullTimer = null;
|
|
4302
|
+
let fastTimer = null;
|
|
4303
|
+
|
|
4304
|
+
async function fullRefresh() {
|
|
4305
|
+
const data = await fetchOverview();
|
|
4306
|
+
if (!data) {
|
|
4307
|
+
$('#statusDot').className = 'status-dot offline';
|
|
4308
|
+
$('#statusText').textContent = 'OFFLINE';
|
|
4309
|
+
return;
|
|
4310
|
+
}
|
|
4311
|
+
overview = data;
|
|
4312
|
+
renderAll(data);
|
|
4313
|
+
}
|
|
4314
|
+
|
|
4315
|
+
async function fastRefresh() {
|
|
4316
|
+
const stats = await fetchStats();
|
|
4317
|
+
if (!stats) return;
|
|
4318
|
+
const changed = JSON.stringify(stats) !== JSON.stringify(prevStats);
|
|
4319
|
+
prevStats = stats;
|
|
4320
|
+
if (changed) {
|
|
4321
|
+
fullRefresh();
|
|
4322
|
+
}
|
|
4323
|
+
}
|
|
4324
|
+
|
|
4325
|
+
// ---- Init ----
|
|
4326
|
+
fullRefresh();
|
|
4327
|
+
fastTimer = setInterval(fastRefresh, 3000);
|
|
4328
|
+
fullTimer = setInterval(fullRefresh, 5000);
|
|
4329
|
+
|
|
4330
|
+
// Update uptime display every second
|
|
4331
|
+
setInterval(function() {
|
|
4332
|
+
if (overview && overview.server) {
|
|
4333
|
+
overview.server.uptime_seconds++;
|
|
4334
|
+
$('#uptime').textContent = formatUptime(overview.server.uptime_seconds);
|
|
4335
|
+
}
|
|
4336
|
+
}, 1000);
|
|
4337
|
+
|
|
4338
|
+
// ---- Join Network Modal ----
|
|
4339
|
+
const joinModal = $('#joinModal');
|
|
4340
|
+
const btnJoin = $('#btnJoinNetwork');
|
|
4341
|
+
const btnCancel = $('#btnCancelJoin');
|
|
4342
|
+
const btnSubmit = $('#btnSubmitJoin');
|
|
4343
|
+
const authKeyInput = $('#authKeyInput');
|
|
4344
|
+
const joinStatus = $('#joinStatus');
|
|
4345
|
+
|
|
4346
|
+
function openJoinModal() {
|
|
4347
|
+
joinStatus.className = 'modal-status';
|
|
4348
|
+
joinStatus.textContent = '';
|
|
4349
|
+
authKeyInput.value = '';
|
|
4350
|
+
joinModal.classList.add('open');
|
|
4351
|
+
setTimeout(function() { authKeyInput.focus(); }, 100);
|
|
4352
|
+
}
|
|
4353
|
+
|
|
4354
|
+
function closeJoinModal() {
|
|
4355
|
+
joinModal.classList.remove('open');
|
|
4356
|
+
}
|
|
4357
|
+
|
|
4358
|
+
btnJoin.addEventListener('click', openJoinModal);
|
|
4359
|
+
btnCancel.addEventListener('click', closeJoinModal);
|
|
4360
|
+
joinModal.addEventListener('click', function(e) {
|
|
4361
|
+
if (e.target === joinModal) closeJoinModal();
|
|
4362
|
+
});
|
|
4363
|
+
authKeyInput.addEventListener('keydown', function(e) {
|
|
4364
|
+
if (e.key === 'Enter') btnSubmit.click();
|
|
4365
|
+
if (e.key === 'Escape') closeJoinModal();
|
|
4366
|
+
});
|
|
4367
|
+
|
|
4368
|
+
btnSubmit.addEventListener('click', async function() {
|
|
4369
|
+
const key = authKeyInput.value.trim();
|
|
4370
|
+
if (!key) {
|
|
4371
|
+
authKeyInput.focus();
|
|
4372
|
+
return;
|
|
4373
|
+
}
|
|
4374
|
+
btnSubmit.disabled = true;
|
|
4375
|
+
btnSubmit.innerHTML = '<span class="spinner"></span>Connecting...';
|
|
4376
|
+
joinStatus.className = 'modal-status';
|
|
4377
|
+
joinStatus.textContent = '';
|
|
4378
|
+
|
|
4379
|
+
try {
|
|
4380
|
+
const r = await fetch('/dashboard/api/join-network', {
|
|
4381
|
+
method: 'POST',
|
|
4382
|
+
headers: { 'Content-Type': 'application/json' },
|
|
4383
|
+
body: JSON.stringify({ auth_key: key }),
|
|
4384
|
+
});
|
|
4385
|
+
const data = await r.json();
|
|
4386
|
+
if (data.success) {
|
|
4387
|
+
joinStatus.className = 'modal-status success';
|
|
4388
|
+
joinStatus.textContent = 'Successfully joined network!';
|
|
4389
|
+
btnJoin.textContent = 'Connected';
|
|
4390
|
+
btnJoin.classList.add('connected');
|
|
4391
|
+
setTimeout(function() { closeJoinModal(); fullRefresh(); }, 1500);
|
|
4392
|
+
} else {
|
|
4393
|
+
joinStatus.className = 'modal-status error';
|
|
4394
|
+
joinStatus.textContent = data.output || 'Failed to join network';
|
|
4395
|
+
}
|
|
4396
|
+
} catch (e) {
|
|
4397
|
+
joinStatus.className = 'modal-status error';
|
|
4398
|
+
joinStatus.textContent = 'Network error: ' + (e.message || 'unknown');
|
|
4399
|
+
}
|
|
4400
|
+
btnSubmit.disabled = false;
|
|
4401
|
+
btnSubmit.textContent = 'Connect';
|
|
4402
|
+
});
|
|
4403
|
+
|
|
4404
|
+
// Check initial Tailscale status (tri-state)
|
|
4405
|
+
let tsState = null;
|
|
4406
|
+
let tsInstallInfo = null;
|
|
4407
|
+
|
|
4408
|
+
async function checkTailscaleStatus() {
|
|
4409
|
+
try {
|
|
4410
|
+
const r = await fetch('/dashboard/api/tailscale-status');
|
|
4411
|
+
tsState = await r.json();
|
|
4412
|
+
} catch { tsState = { state: 'not_installed', platform: 'unknown' }; }
|
|
4413
|
+
|
|
4414
|
+
const dot = $('#statusDot');
|
|
4415
|
+
const text = $('#statusText');
|
|
4416
|
+
const btnJoin = $('#btnJoinNetwork');
|
|
4417
|
+
const panel = $('#tsPanel');
|
|
4418
|
+
|
|
4419
|
+
if (tsState.state === 'connected') {
|
|
4420
|
+
dot.className = 'status-dot';
|
|
4421
|
+
text.textContent = 'ONLINE';
|
|
4422
|
+
btnJoin.textContent = 'Connected';
|
|
4423
|
+
btnJoin.classList.add('connected');
|
|
4424
|
+
panel.style.display = 'none';
|
|
4425
|
+
} else if (tsState.state === 'not_installed') {
|
|
4426
|
+
dot.className = 'status-dot not-installed';
|
|
4427
|
+
text.textContent = 'NOT INSTALLED';
|
|
4428
|
+
btnJoin.style.display = 'none';
|
|
4429
|
+
await renderNotInstalledPanel();
|
|
4430
|
+
} else {
|
|
4431
|
+
dot.className = 'status-dot not-connected';
|
|
4432
|
+
text.textContent = 'NOT CONNECTED';
|
|
4433
|
+
await renderNotConnectedPanel();
|
|
4434
|
+
}
|
|
4435
|
+
}
|
|
4436
|
+
|
|
4437
|
+
async function fetchInstallInfo() {
|
|
4438
|
+
if (tsInstallInfo) return tsInstallInfo;
|
|
4439
|
+
try {
|
|
4440
|
+
const r = await fetch('/dashboard/api/tailscale-install-info');
|
|
4441
|
+
tsInstallInfo = await r.json();
|
|
4442
|
+
} catch { tsInstallInfo = null; }
|
|
4443
|
+
return tsInstallInfo;
|
|
4444
|
+
}
|
|
4445
|
+
|
|
4446
|
+
async function renderNotInstalledPanel() {
|
|
4447
|
+
const info = await fetchInstallInfo();
|
|
4448
|
+
const panel = $('#tsPanel');
|
|
4449
|
+
let html = '<div class="ts-panel-title not-installed">Tailscale Not Installed</div>';
|
|
4450
|
+
html += '<div class="ts-info-row"><span class="label">Status:</span><span class="value" style="color:var(--red)">Tailscale is not detected on this system</span></div>';
|
|
4451
|
+
|
|
4452
|
+
if (info && info.commands && info.commands.length > 0) {
|
|
4453
|
+
html += '<div class="ts-install-guide">';
|
|
4454
|
+
html += '<div style="color:var(--muted);margin-bottom:6px">Install for ' + info.os + ':</div>';
|
|
4455
|
+
info.commands.forEach(function(cmd) {
|
|
4456
|
+
const display = info.needs_sudo ? 'sudo ' + cmd : cmd;
|
|
4457
|
+
html += '<div class="cmd" onclick="navigator.clipboard.writeText('' + display.replace(/'/g, "\\'") + '').then(function(){this.querySelector('.copy-hint').textContent='Copied!'}.bind(this))">';
|
|
4458
|
+
html += '<code>' + display + '</code><span class="copy-hint">Click to copy</span></div>';
|
|
4459
|
+
});
|
|
4460
|
+
if (info.download_url) {
|
|
4461
|
+
html += '<div style="margin-top:8px">Download: <a href="' + info.download_url + '" target="_blank">' + info.download_url + '</a></div>';
|
|
4462
|
+
}
|
|
4463
|
+
html += '</div>';
|
|
4464
|
+
}
|
|
4465
|
+
|
|
4466
|
+
html += '<div class="ts-setup-hint">Or run <code style="color:var(--cyan)">npx open-party setup</code> for guided installation</div>';
|
|
4467
|
+
html += '<button class="btn-redetect" onclick="window.__redetectTailscale()">Re-detect</button>';
|
|
4468
|
+
panel.innerHTML = html;
|
|
4469
|
+
panel.style.display = 'block';
|
|
4470
|
+
}
|
|
4471
|
+
|
|
4472
|
+
async function renderNotConnectedPanel() {
|
|
4473
|
+
const panel = $('#tsPanel');
|
|
4474
|
+
const btnJoin = $('#btnJoinNetwork');
|
|
4475
|
+
btnJoin.style.display = '';
|
|
4476
|
+
btnJoin.textContent = 'Join Network';
|
|
4477
|
+
btnJoin.classList.remove('connected');
|
|
4478
|
+
|
|
4479
|
+
let html = '<div class="ts-panel-title not-connected">Tailscale Not Connected</div>';
|
|
4480
|
+
html += '<div class="ts-info-row"><span class="label">Status:</span><span class="value" style="color:var(--yellow)">Installed but not authenticated</span></div>';
|
|
4481
|
+
html += '<div class="ts-setup-hint">Run <code style="color:var(--cyan)">npx open-party setup</code> to log in, or use the Join Network button to enter an Auth Key</div>';
|
|
4482
|
+
html += '<button class="btn-redetect" onclick="window.__redetectTailscale()">Re-detect</button>';
|
|
4483
|
+
panel.innerHTML = html;
|
|
4484
|
+
panel.style.display = 'block';
|
|
4485
|
+
}
|
|
4486
|
+
|
|
4487
|
+
window.__redetectTailscale = async function() {
|
|
4488
|
+
const panel = $('#tsPanel');
|
|
4489
|
+
panel.innerHTML = '<div style="color:var(--muted);padding:12px"><span class="spinner"></span> Re-detecting Tailscale...</div>';
|
|
4490
|
+
try {
|
|
4491
|
+
await fetch('/dashboard/api/tailscale-detect', { method: 'POST' });
|
|
4492
|
+
} catch { /* ignore */ }
|
|
4493
|
+
await checkTailscaleStatus();
|
|
4494
|
+
fullRefresh();
|
|
4495
|
+
};
|
|
4496
|
+
|
|
4497
|
+
checkTailscaleStatus();
|
|
4498
|
+
|
|
4499
|
+
})();
|
|
4500
|
+
</script>
|
|
4501
|
+
</body>
|
|
4502
|
+
</html>`;
|
|
4503
|
+
|
|
4504
|
+
// src/server/routes/dashboard.ts
|
|
4505
|
+
init_tailscale();
|
|
4506
|
+
init_state();
|
|
4507
|
+
var dashboardRoutes = new Hono2();
|
|
4508
|
+
dashboardRoutes.get("/", (c) => {
|
|
4509
|
+
return c.html(DASHBOARD_HTML);
|
|
4510
|
+
});
|
|
4511
|
+
dashboardRoutes.get("/api/stats", async (c) => {
|
|
4512
|
+
const localAgents = registry.listAll();
|
|
4513
|
+
const remoteAgents = discovery.getReachableRemoteAgents();
|
|
4514
|
+
const peerStates = discovery.getPeerStates();
|
|
4515
|
+
const partyServers = peerStates.filter((p) => p.status === "PARTY_SERVER" || p.status === "DEGRADED" || p.status === "SUSPECT");
|
|
4516
|
+
return c.json({
|
|
4517
|
+
local_agent_count: localAgents.length,
|
|
4518
|
+
remote_agent_count: remoteAgents.length,
|
|
4519
|
+
peer_count: peerStates.length,
|
|
4520
|
+
party_server_count: partyServers.length
|
|
4521
|
+
});
|
|
4522
|
+
});
|
|
4523
|
+
dashboardRoutes.get("/api/overview", async (c) => {
|
|
4524
|
+
let hostname = "127.0.0.1";
|
|
4525
|
+
try {
|
|
4526
|
+
hostname = getTailnetHostname();
|
|
4527
|
+
} catch {
|
|
4528
|
+
}
|
|
4529
|
+
const localAgents = sanitizeAgentList(registry.listAll());
|
|
4530
|
+
const remoteEntries = discovery.getRemoteAgentEntries();
|
|
4531
|
+
const peerStates = discovery.getPeerStates();
|
|
4532
|
+
const recentMessages = [];
|
|
4533
|
+
for (const agent of localAgents) {
|
|
4534
|
+
const history = messageQueue.getHistory(agent.agent_id, 5);
|
|
4535
|
+
for (const entry of history) {
|
|
4536
|
+
recentMessages.push({ agent_id: agent.agent_id, ...entry });
|
|
4537
|
+
}
|
|
4538
|
+
}
|
|
4539
|
+
recentMessages.sort((a, b) => b.timestamp - a.timestamp);
|
|
4540
|
+
if (recentMessages.length > 20) recentMessages.length = 20;
|
|
4541
|
+
const partyServers = peerStates.filter(
|
|
4542
|
+
(p) => p.status === "PARTY_SERVER" || p.status === "DEGRADED" || p.status === "SUSPECT"
|
|
4543
|
+
);
|
|
4544
|
+
return c.json({
|
|
4545
|
+
server: {
|
|
4546
|
+
status: "ok",
|
|
4547
|
+
tailscale_ip: getSelfIp(),
|
|
4548
|
+
hostname,
|
|
4549
|
+
uptime_seconds: Math.floor((Date.now() - STARTED_AT) / 1e3)
|
|
4550
|
+
},
|
|
4551
|
+
agents: {
|
|
4552
|
+
local_count: localAgents.length,
|
|
4553
|
+
remote_count: remoteEntries.length,
|
|
4554
|
+
local_agents: localAgents,
|
|
4555
|
+
remote_agents: remoteEntries.map((e) => ({
|
|
4556
|
+
...sanitizeAgentList([e.agentInfo])[0],
|
|
4557
|
+
source_peer_ip: e.sourcePeerIp,
|
|
4558
|
+
reachable: e.reachable
|
|
4559
|
+
}))
|
|
4560
|
+
},
|
|
4561
|
+
peers: {
|
|
4562
|
+
total: peerStates.length,
|
|
4563
|
+
party_servers: partyServers.length,
|
|
4564
|
+
down: peerStates.filter((p) => p.status === "DOWN").length,
|
|
4565
|
+
unknown: peerStates.filter((p) => p.status === "UNKNOWN" || p.status === "MAYBE").length,
|
|
4566
|
+
details: peerStates
|
|
4567
|
+
},
|
|
4568
|
+
messages: {
|
|
4569
|
+
recent: recentMessages
|
|
4570
|
+
}
|
|
4571
|
+
});
|
|
4572
|
+
});
|
|
4573
|
+
dashboardRoutes.get("/api/tailscale-status", async (c) => {
|
|
4574
|
+
try {
|
|
4575
|
+
return c.json(getTailscaleInstallationStatus());
|
|
4576
|
+
} catch (e) {
|
|
4577
|
+
return c.json({ state: "not_installed", platform: process.platform, error: e.message });
|
|
4578
|
+
}
|
|
4579
|
+
});
|
|
4580
|
+
dashboardRoutes.post("/api/tailscale-detect", async (c) => {
|
|
4581
|
+
resetTailscaleBinaryCache();
|
|
4582
|
+
const state = getTailscaleInstallationStatus();
|
|
4583
|
+
if (state.state === "connected") {
|
|
4584
|
+
refreshSelfIp();
|
|
4585
|
+
}
|
|
4586
|
+
return c.json(state);
|
|
4587
|
+
});
|
|
4588
|
+
dashboardRoutes.get("/api/tailscale-install-info", async (c) => {
|
|
4589
|
+
return c.json(getInstallInstructions(process.platform));
|
|
4590
|
+
});
|
|
4591
|
+
dashboardRoutes.post("/api/join-network", async (c) => {
|
|
4592
|
+
try {
|
|
4593
|
+
const body = await c.req.json();
|
|
4594
|
+
const authKey = (body.auth_key ?? "").trim();
|
|
4595
|
+
if (!authKey) {
|
|
4596
|
+
return c.json({ success: false, output: "auth_key is required" }, 400);
|
|
4597
|
+
}
|
|
4598
|
+
const result = joinTailnet(authKey);
|
|
4599
|
+
return c.json(result, result.success ? 200 : 500);
|
|
4600
|
+
} catch (e) {
|
|
4601
|
+
return c.json({ success: false, output: e.message }, 500);
|
|
4602
|
+
}
|
|
4603
|
+
});
|
|
4604
|
+
|
|
4605
|
+
// src/server/index.ts
|
|
4606
|
+
async function periodicCleanup() {
|
|
4607
|
+
}
|
|
4608
|
+
var app = new Hono2();
|
|
4609
|
+
app.use("*", cors());
|
|
4610
|
+
app.route("/agent", agentRoutes);
|
|
4611
|
+
app.route("/proxy", proxyRoutes);
|
|
4612
|
+
app.route("/dashboard", dashboardRoutes);
|
|
4613
|
+
async function main() {
|
|
4614
|
+
console.log(`Starting Party Server on port ${PARTY_PORT} (Tailscale IP: ${getSelfIp()})`);
|
|
4615
|
+
process.on("SIGHUP", () => {
|
|
4616
|
+
});
|
|
4617
|
+
const server = serve({ fetch: app.fetch, port: PARTY_PORT });
|
|
4618
|
+
const discoveryPromise = discovery.runLoop();
|
|
4619
|
+
const cleanupPromise = periodicCleanup();
|
|
4620
|
+
const shutdown = () => {
|
|
4621
|
+
console.log("\nShutting down Party Server...");
|
|
4622
|
+
server.close();
|
|
4623
|
+
process.exit(0);
|
|
4624
|
+
};
|
|
4625
|
+
process.on("SIGINT", shutdown);
|
|
4626
|
+
process.on("SIGTERM", shutdown);
|
|
4627
|
+
await Promise.race([discoveryPromise, cleanupPromise]);
|
|
4628
|
+
}
|
|
4629
|
+
main().catch((e) => {
|
|
4630
|
+
console.error("Fatal error:", e);
|
|
4631
|
+
process.exit(1);
|
|
4632
|
+
});
|
|
4633
|
+
process.on("uncaughtException", (e) => {
|
|
4634
|
+
console.error("Uncaught exception:", e);
|
|
4635
|
+
});
|
|
4636
|
+
process.on("unhandledRejection", (e) => {
|
|
4637
|
+
console.error("Unhandled rejection:", e);
|
|
4638
|
+
});
|
|
4639
|
+
//# sourceMappingURL=party-server.js.map
|