pi-control-bridge 0.3.10
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.
Potentially problematic release.
This version of pi-control-bridge might be problematic. Click here for more details.
- package/README.md +98 -0
- package/bridge.config.example.json +10 -0
- package/dist/bridge/main.js +4173 -0
- package/extension/bridge_client.ts +76 -0
- package/extension/command_handler.ts +39 -0
- package/extension/ensure_bridge.ts +78 -0
- package/extension/hooks.ts +291 -0
- package/extension/index.ts +7 -0
- package/extension/messages.ts +132 -0
- package/extension/session_metadata.ts +84 -0
- package/extension/session_status.ts +19 -0
- package/package.json +47 -0
- package/shared/agent_dir.ts +17 -0
- package/shared/ansi.ts +9 -0
- package/shared/config.ts +152 -0
- package/shared/constants.ts +13 -0
- package/shared/device_state.ts +21 -0
- package/shared/locale.ts +30 -0
- package/shared/logger.ts +54 -0
- package/shared/migrate.ts +39 -0
- package/shared/telegram.ts +136 -0
- package/shared/types.ts +107 -0
|
@@ -0,0 +1,4173 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// shared/config.ts
|
|
4
|
+
import { existsSync as existsSync2, readFileSync } from "node:fs";
|
|
5
|
+
import { homedir as homedir3 } from "node:os";
|
|
6
|
+
import { dirname, join as join3 } from "node:path";
|
|
7
|
+
|
|
8
|
+
// shared/agent_dir.ts
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { join, resolve } from "node:path";
|
|
11
|
+
function getAgentDir() {
|
|
12
|
+
const configured = process.env.PI_CODING_AGENT_DIR?.trim();
|
|
13
|
+
if (!configured) {
|
|
14
|
+
return join(homedir(), ".pi", "agent");
|
|
15
|
+
}
|
|
16
|
+
if (configured === "~") {
|
|
17
|
+
return homedir();
|
|
18
|
+
}
|
|
19
|
+
if (configured.startsWith("~/")) {
|
|
20
|
+
return resolve(homedir(), configured.slice(2));
|
|
21
|
+
}
|
|
22
|
+
return resolve(configured);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// shared/constants.ts
|
|
26
|
+
var PACKAGE_VERSION = "0.3.3";
|
|
27
|
+
var DEFAULT_HUB_URL = "http://127.0.0.1:8000";
|
|
28
|
+
var DEFAULT_POLL_INTERVAL_SEC = 2;
|
|
29
|
+
var DEFAULT_HEARTBEAT_INTERVAL_SEC = 15;
|
|
30
|
+
var DEFAULT_COMMAND_BATCH_SIZE = 10;
|
|
31
|
+
var DEFAULT_BRIDGE_LOG_LEVEL = "INFO";
|
|
32
|
+
var DEFAULT_IPC_PORT = 9473;
|
|
33
|
+
var PROJECT_CONFIG_RELATIVE_PATH = ".pi/bridge.json";
|
|
34
|
+
var IPC_COMMAND_WAIT_TIMEOUT_MS = 3e4;
|
|
35
|
+
var COMMAND_RETRY_ATTEMPTS = 3;
|
|
36
|
+
var COMMAND_RETRY_DELAY_MS = 2e3;
|
|
37
|
+
|
|
38
|
+
// shared/migrate.ts
|
|
39
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync } from "node:fs";
|
|
40
|
+
import { homedir as homedir2 } from "node:os";
|
|
41
|
+
import { join as join2 } from "node:path";
|
|
42
|
+
function legacyBridgeDataDir() {
|
|
43
|
+
return join2(homedir2(), ".pi", "bridge");
|
|
44
|
+
}
|
|
45
|
+
function defaultBridgeDataDir() {
|
|
46
|
+
return join2(getAgentDir(), "bridge");
|
|
47
|
+
}
|
|
48
|
+
function migrateLegacyBridgePaths() {
|
|
49
|
+
const oldDir = legacyBridgeDataDir();
|
|
50
|
+
const newDir = defaultBridgeDataDir();
|
|
51
|
+
if (oldDir === newDir || !existsSync(oldDir)) return;
|
|
52
|
+
if (!existsSync(newDir)) {
|
|
53
|
+
mkdirSync(getAgentDir(), { recursive: true });
|
|
54
|
+
try {
|
|
55
|
+
renameSync(oldDir, newDir);
|
|
56
|
+
return;
|
|
57
|
+
} catch {
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
mkdirSync(newDir, { recursive: true, mode: 448 });
|
|
61
|
+
for (const name of readdirSync(oldDir)) {
|
|
62
|
+
const source = join2(oldDir, name);
|
|
63
|
+
const target = join2(newDir, name);
|
|
64
|
+
if (!existsSync(target)) {
|
|
65
|
+
copyFileSync(source, target);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// shared/config.ts
|
|
71
|
+
function expandHome(path) {
|
|
72
|
+
return path.startsWith("~/") ? join3(homedir3(), path.slice(2)) : path;
|
|
73
|
+
}
|
|
74
|
+
function positiveNumber(value, fallback) {
|
|
75
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
|
|
76
|
+
if (typeof value === "string") {
|
|
77
|
+
const parsed = Number(value);
|
|
78
|
+
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
|
79
|
+
}
|
|
80
|
+
return fallback;
|
|
81
|
+
}
|
|
82
|
+
function defaultConfig() {
|
|
83
|
+
return {
|
|
84
|
+
hubUrl: DEFAULT_HUB_URL,
|
|
85
|
+
pollIntervalSec: DEFAULT_POLL_INTERVAL_SEC,
|
|
86
|
+
heartbeatIntervalSec: DEFAULT_HEARTBEAT_INTERVAL_SEC,
|
|
87
|
+
commandBatchSize: DEFAULT_COMMAND_BATCH_SIZE,
|
|
88
|
+
bridgeLogLevel: DEFAULT_BRIDGE_LOG_LEVEL,
|
|
89
|
+
bridgeDataDir: defaultBridgeDataDir(),
|
|
90
|
+
ipcPort: DEFAULT_IPC_PORT,
|
|
91
|
+
autoStartBridge: true
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function readConfigFile(path) {
|
|
95
|
+
if (!existsSync2(path)) return null;
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(readFileSync(path, "utf-8"));
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function applyConfigFile(base, file) {
|
|
103
|
+
return {
|
|
104
|
+
hubUrl: typeof file.hub_url === "string" && file.hub_url.trim() ? file.hub_url.trim() : base.hubUrl,
|
|
105
|
+
pollIntervalSec: positiveNumber(file.poll_interval_sec, base.pollIntervalSec),
|
|
106
|
+
heartbeatIntervalSec: positiveNumber(
|
|
107
|
+
file.heartbeat_interval_sec,
|
|
108
|
+
base.heartbeatIntervalSec
|
|
109
|
+
),
|
|
110
|
+
commandBatchSize: positiveNumber(file.command_batch_size, base.commandBatchSize),
|
|
111
|
+
bridgeLogLevel: typeof file.bridge_log_level === "string" && file.bridge_log_level.trim() ? file.bridge_log_level.trim() : base.bridgeLogLevel,
|
|
112
|
+
bridgeDataDir: typeof file.bridge_data_dir === "string" && file.bridge_data_dir.trim() ? expandHome(file.bridge_data_dir.trim()) : base.bridgeDataDir,
|
|
113
|
+
ipcPort: positiveNumber(file.ipc_port, base.ipcPort),
|
|
114
|
+
autoStartBridge: typeof file.auto_start_bridge === "boolean" ? file.auto_start_bridge : base.autoStartBridge
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function userConfigPath() {
|
|
118
|
+
return join3(getAgentDir(), "bridge", "config.json");
|
|
119
|
+
}
|
|
120
|
+
function findProjectConfigPath(startDir = process.cwd()) {
|
|
121
|
+
let current = startDir;
|
|
122
|
+
while (true) {
|
|
123
|
+
const candidate = join3(current, PROJECT_CONFIG_RELATIVE_PATH);
|
|
124
|
+
if (existsSync2(candidate)) return candidate;
|
|
125
|
+
const parent = dirname(current);
|
|
126
|
+
if (parent === current) return null;
|
|
127
|
+
current = parent;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function loadBridgeConfig(options = {}) {
|
|
131
|
+
if (!options.skipMigration) {
|
|
132
|
+
migrateLegacyBridgePaths();
|
|
133
|
+
}
|
|
134
|
+
let config = defaultConfig();
|
|
135
|
+
const userPath = options.userConfigPath === null ? null : options.userConfigPath ?? userConfigPath();
|
|
136
|
+
if (userPath) {
|
|
137
|
+
const userFile = readConfigFile(userPath);
|
|
138
|
+
if (userFile) config = applyConfigFile(config, userFile);
|
|
139
|
+
}
|
|
140
|
+
const projectPath = options.projectConfigPath === null ? null : options.projectConfigPath ?? findProjectConfigPath(options.cwd);
|
|
141
|
+
if (projectPath) {
|
|
142
|
+
const projectFile = readConfigFile(projectPath);
|
|
143
|
+
if (projectFile) config = applyConfigFile(config, projectFile);
|
|
144
|
+
}
|
|
145
|
+
return config;
|
|
146
|
+
}
|
|
147
|
+
function ipcBaseUrl(port) {
|
|
148
|
+
return `http://127.0.0.1:${port}`;
|
|
149
|
+
}
|
|
150
|
+
function stateFilePath(dataDir) {
|
|
151
|
+
return join3(dataDir, "state.json");
|
|
152
|
+
}
|
|
153
|
+
function eventsQueuePath(dataDir) {
|
|
154
|
+
return join3(dataDir, "events-queue.jsonl");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// shared/device_state.ts
|
|
158
|
+
function shouldProbeTelegramLink(state) {
|
|
159
|
+
if (!state?.deviceToken) return false;
|
|
160
|
+
return state.telegramBindPending === true || state.telegramLinked === true;
|
|
161
|
+
}
|
|
162
|
+
function clearDeviceCredentials(state) {
|
|
163
|
+
return {
|
|
164
|
+
...state,
|
|
165
|
+
deviceId: "",
|
|
166
|
+
deviceToken: "",
|
|
167
|
+
telegramLinked: false,
|
|
168
|
+
telegramBindPending: false
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// shared/logger.ts
|
|
173
|
+
var LEVEL_ORDER = {
|
|
174
|
+
DEBUG: 10,
|
|
175
|
+
INFO: 20,
|
|
176
|
+
WARN: 30,
|
|
177
|
+
ERROR: 40
|
|
178
|
+
};
|
|
179
|
+
var Logger = class {
|
|
180
|
+
minLevel;
|
|
181
|
+
constructor(level) {
|
|
182
|
+
const normalized = level.toUpperCase();
|
|
183
|
+
this.minLevel = LEVEL_ORDER[normalized] ?? LEVEL_ORDER.INFO;
|
|
184
|
+
}
|
|
185
|
+
write(level, message, context) {
|
|
186
|
+
if (LEVEL_ORDER[level] < this.minLevel) return;
|
|
187
|
+
const entry = {
|
|
188
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
189
|
+
level,
|
|
190
|
+
message,
|
|
191
|
+
...context
|
|
192
|
+
};
|
|
193
|
+
console.error(JSON.stringify(entry));
|
|
194
|
+
}
|
|
195
|
+
debug(message, context) {
|
|
196
|
+
this.write("DEBUG", message, context);
|
|
197
|
+
}
|
|
198
|
+
info(message, context) {
|
|
199
|
+
this.write("INFO", message, context);
|
|
200
|
+
}
|
|
201
|
+
warn(message, context) {
|
|
202
|
+
this.write("WARN", message, context);
|
|
203
|
+
}
|
|
204
|
+
error(message, context) {
|
|
205
|
+
this.write("ERROR", message, context);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// bridge/backend_client.ts
|
|
210
|
+
import { hostname, platform } from "node:os";
|
|
211
|
+
|
|
212
|
+
// shared/telegram.ts
|
|
213
|
+
function buildTelegramBotLink(botUsername, token) {
|
|
214
|
+
const username = botUsername.replace(/^@/, "");
|
|
215
|
+
const base = `https://t.me/${username}`;
|
|
216
|
+
if (!token) return base;
|
|
217
|
+
return `${base}?start=${encodeURIComponent(token)}`;
|
|
218
|
+
}
|
|
219
|
+
function buildAlreadyLinkedTelegramResponse(connection) {
|
|
220
|
+
return {
|
|
221
|
+
token: "",
|
|
222
|
+
expiresAt: "",
|
|
223
|
+
alreadyLinked: true,
|
|
224
|
+
botUsername: connection.bot.username,
|
|
225
|
+
botLink: connection.bot.link,
|
|
226
|
+
telegramUsername: connection.telegram.username
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function parseTelegramLinkResponse(raw2) {
|
|
230
|
+
const alreadyLinked = raw2.already_linked === true || raw2.alreadyLinked === true;
|
|
231
|
+
const token = String(raw2.token ?? "");
|
|
232
|
+
const expiresAt = String(raw2.expires_at ?? raw2.expiresAt ?? "");
|
|
233
|
+
const telegramUsernameRaw = raw2.telegram_username ?? raw2.telegramUsername;
|
|
234
|
+
const telegramUsername = typeof telegramUsernameRaw === "string" && telegramUsernameRaw.length > 0 ? telegramUsernameRaw : void 0;
|
|
235
|
+
const botUsernameRaw = raw2.bot_username ?? raw2.botUsername;
|
|
236
|
+
const botUsername = typeof botUsernameRaw === "string" && botUsernameRaw.length > 0 ? botUsernameRaw : void 0;
|
|
237
|
+
const botLinkRaw = raw2.bot_link ?? raw2.botLink;
|
|
238
|
+
const botLink = typeof botLinkRaw === "string" && botLinkRaw.length > 0 ? botLinkRaw : botUsername ? buildTelegramBotLink(botUsername, token) : void 0;
|
|
239
|
+
return { token, expiresAt, botUsername, botLink, alreadyLinked, telegramUsername };
|
|
240
|
+
}
|
|
241
|
+
function readTelegramBlock(raw2) {
|
|
242
|
+
const telegram = raw2.telegram;
|
|
243
|
+
return telegram && typeof telegram === "object" ? telegram : void 0;
|
|
244
|
+
}
|
|
245
|
+
function readBotBlock(raw2) {
|
|
246
|
+
const bot = raw2.bot;
|
|
247
|
+
return bot && typeof bot === "object" ? bot : void 0;
|
|
248
|
+
}
|
|
249
|
+
function parseHubConnectionInfo(raw2) {
|
|
250
|
+
const telegramBlock = readTelegramBlock(raw2);
|
|
251
|
+
const botBlock = readBotBlock(raw2);
|
|
252
|
+
const linked = telegramBlock?.linked === true || raw2.telegram_linked === true || raw2.telegramLinked === true;
|
|
253
|
+
const telegramUsernameRaw = telegramBlock?.username ?? raw2.telegram_username ?? raw2.telegramUsername;
|
|
254
|
+
const telegramUsername = typeof telegramUsernameRaw === "string" && telegramUsernameRaw.length > 0 ? telegramUsernameRaw : void 0;
|
|
255
|
+
const chatIdRaw = telegramBlock?.chat_id ?? telegramBlock?.chatId ?? raw2.telegram_chat_id;
|
|
256
|
+
const chatId = typeof chatIdRaw === "number" ? chatIdRaw : typeof chatIdRaw === "string" && chatIdRaw.length > 0 ? Number(chatIdRaw) : void 0;
|
|
257
|
+
const botUsernameRaw = botBlock?.username ?? raw2.bot_username ?? raw2.botUsername;
|
|
258
|
+
const botUsername = typeof botUsernameRaw === "string" && botUsernameRaw.length > 0 ? botUsernameRaw : void 0;
|
|
259
|
+
const botLinkRaw = botBlock?.link ?? raw2.bot_link ?? raw2.botLink;
|
|
260
|
+
const botLink = typeof botLinkRaw === "string" && botLinkRaw.length > 0 ? botLinkRaw : botUsername ? buildTelegramBotLink(botUsername) : void 0;
|
|
261
|
+
return {
|
|
262
|
+
deviceId: typeof raw2.device_id === "string" ? raw2.device_id : typeof raw2.deviceId === "string" ? raw2.deviceId : void 0,
|
|
263
|
+
telegram: {
|
|
264
|
+
linked,
|
|
265
|
+
username: telegramUsername,
|
|
266
|
+
chatId: Number.isFinite(chatId) ? chatId : void 0
|
|
267
|
+
},
|
|
268
|
+
bot: {
|
|
269
|
+
username: botUsername,
|
|
270
|
+
link: botLink
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// bridge/backend_client.ts
|
|
276
|
+
var TELEGRAM_LINKED_CACHE_TTL_MS = 3e4;
|
|
277
|
+
var TELEGRAM_UNLINKED_CACHE_TTL_MS = 2e3;
|
|
278
|
+
var BackendAuthError = class extends Error {
|
|
279
|
+
constructor(message) {
|
|
280
|
+
super(message);
|
|
281
|
+
this.name = "BackendAuthError";
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
function mapDeviceRegister(raw2) {
|
|
285
|
+
return {
|
|
286
|
+
deviceId: String(raw2.device_id ?? raw2.deviceId),
|
|
287
|
+
deviceToken: String(raw2.device_token ?? raw2.deviceToken),
|
|
288
|
+
status: String(raw2.status ?? "pending")
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function mapSessionRegister(raw2) {
|
|
292
|
+
return {
|
|
293
|
+
sessionId: String(raw2.session_id ?? raw2.sessionId),
|
|
294
|
+
status: String(raw2.status ?? "running")
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
var BackendClient = class {
|
|
298
|
+
constructor(config, logger) {
|
|
299
|
+
this.config = config;
|
|
300
|
+
this.logger = logger;
|
|
301
|
+
}
|
|
302
|
+
degraded = false;
|
|
303
|
+
lastCorrelationId;
|
|
304
|
+
telegramLinkedCache = null;
|
|
305
|
+
isDegraded() {
|
|
306
|
+
return this.degraded;
|
|
307
|
+
}
|
|
308
|
+
getLastCorrelationId() {
|
|
309
|
+
return this.lastCorrelationId;
|
|
310
|
+
}
|
|
311
|
+
async request(method, path, options) {
|
|
312
|
+
const url = new URL(path, this.config.hubUrl);
|
|
313
|
+
if (options?.query) {
|
|
314
|
+
for (const [key, value] of Object.entries(options.query)) {
|
|
315
|
+
url.searchParams.set(key, value);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
let response;
|
|
319
|
+
try {
|
|
320
|
+
response = await fetch(url, {
|
|
321
|
+
method,
|
|
322
|
+
headers: { "Content-Type": "application/json" },
|
|
323
|
+
body: options?.body ? JSON.stringify(options.body) : void 0
|
|
324
|
+
});
|
|
325
|
+
this.degraded = false;
|
|
326
|
+
} catch (error) {
|
|
327
|
+
this.degraded = true;
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
const correlationId = response.headers.get("x-correlation-id") ?? void 0;
|
|
331
|
+
this.lastCorrelationId = correlationId;
|
|
332
|
+
if (!response.ok) {
|
|
333
|
+
const text = await response.text();
|
|
334
|
+
this.logger.warn("Backend request failed", {
|
|
335
|
+
correlationId,
|
|
336
|
+
status: response.status,
|
|
337
|
+
path
|
|
338
|
+
});
|
|
339
|
+
if (response.status === 401) {
|
|
340
|
+
throw new BackendAuthError(`Backend ${method} ${path} failed: ${response.status} ${text}`);
|
|
341
|
+
}
|
|
342
|
+
throw new Error(`Backend ${method} ${path} failed: ${response.status} ${text}`);
|
|
343
|
+
}
|
|
344
|
+
if (response.status === 204) {
|
|
345
|
+
return void 0;
|
|
346
|
+
}
|
|
347
|
+
return await response.json();
|
|
348
|
+
}
|
|
349
|
+
async registerDevice(fingerprint, deviceToken) {
|
|
350
|
+
const raw2 = await this.request("POST", "/devices/register", {
|
|
351
|
+
body: {
|
|
352
|
+
fingerprint,
|
|
353
|
+
name: hostname(),
|
|
354
|
+
platform: platform(),
|
|
355
|
+
hostname: hostname(),
|
|
356
|
+
device_token: deviceToken
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
return mapDeviceRegister(raw2);
|
|
360
|
+
}
|
|
361
|
+
async validateToken(deviceToken) {
|
|
362
|
+
const info = await this.getConnectionInfo(deviceToken);
|
|
363
|
+
return { device_id: info.deviceId ?? "" };
|
|
364
|
+
}
|
|
365
|
+
async getConnectionInfo(deviceToken) {
|
|
366
|
+
const raw2 = await this.request("GET", "/me", {
|
|
367
|
+
query: { device_token: deviceToken }
|
|
368
|
+
});
|
|
369
|
+
return parseHubConnectionInfo(raw2);
|
|
370
|
+
}
|
|
371
|
+
invalidateTelegramLinkedCache() {
|
|
372
|
+
this.telegramLinkedCache = null;
|
|
373
|
+
}
|
|
374
|
+
telegramLinkedCacheTtlMs(maxAgeMs) {
|
|
375
|
+
if (maxAgeMs !== void 0) return maxAgeMs;
|
|
376
|
+
if (!this.telegramLinkedCache) return 0;
|
|
377
|
+
return this.telegramLinkedCache.value ? TELEGRAM_LINKED_CACHE_TTL_MS : TELEGRAM_UNLINKED_CACHE_TTL_MS;
|
|
378
|
+
}
|
|
379
|
+
async isTelegramLinked(deviceToken, maxAgeMs) {
|
|
380
|
+
if (!deviceToken) {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
const now = Date.now();
|
|
384
|
+
const cacheTtl = this.telegramLinkedCacheTtlMs(maxAgeMs);
|
|
385
|
+
if (this.telegramLinkedCache && cacheTtl > 0 && now - this.telegramLinkedCache.checkedAt < cacheTtl) {
|
|
386
|
+
return this.telegramLinkedCache.value;
|
|
387
|
+
}
|
|
388
|
+
try {
|
|
389
|
+
const info = await this.getConnectionInfo(deviceToken);
|
|
390
|
+
const linked = info.telegram.linked === true;
|
|
391
|
+
this.telegramLinkedCache = { value: linked, checkedAt: now };
|
|
392
|
+
return linked;
|
|
393
|
+
} catch (error) {
|
|
394
|
+
if (error instanceof BackendAuthError) {
|
|
395
|
+
this.telegramLinkedCache = { value: false, checkedAt: now };
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
this.telegramLinkedCache = { value: false, checkedAt: now };
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
async heartbeat(deviceToken) {
|
|
403
|
+
await this.request("POST", "/devices/heartbeat", {
|
|
404
|
+
body: { device_token: deviceToken }
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
async registerSession(deviceToken, payload) {
|
|
408
|
+
const raw2 = await this.request("POST", "/sessions/register", {
|
|
409
|
+
body: {
|
|
410
|
+
device_token: deviceToken,
|
|
411
|
+
external_session_id: payload.external_session_id,
|
|
412
|
+
title: payload.title,
|
|
413
|
+
project_path: payload.project_path,
|
|
414
|
+
cwd: payload.cwd,
|
|
415
|
+
status: payload.status ?? "running"
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
return mapSessionRegister(raw2);
|
|
419
|
+
}
|
|
420
|
+
async getNextCommands(deviceId, deviceToken) {
|
|
421
|
+
const result = await this.request(
|
|
422
|
+
"GET",
|
|
423
|
+
`/commands/devices/${deviceId}/next`,
|
|
424
|
+
{ query: { device_token: deviceToken } }
|
|
425
|
+
);
|
|
426
|
+
return result.items ?? [];
|
|
427
|
+
}
|
|
428
|
+
async ackCommand(commandId, deviceToken) {
|
|
429
|
+
await this.request("POST", `/commands/${commandId}/ack`, {
|
|
430
|
+
body: { device_token: deviceToken }
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
async postSessionEvent(deviceToken, payload) {
|
|
434
|
+
await this.request("POST", "/session-events", {
|
|
435
|
+
body: {
|
|
436
|
+
device_token: deviceToken,
|
|
437
|
+
external_session_id: payload.external_session_id,
|
|
438
|
+
event_type: payload.event_type,
|
|
439
|
+
status: payload.status,
|
|
440
|
+
payload: payload.payload,
|
|
441
|
+
event_id: payload.event_id
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
async createLinkToken(deviceToken) {
|
|
446
|
+
const raw2 = await this.request("POST", "/telegram/link-token", {
|
|
447
|
+
body: { device_token: deviceToken }
|
|
448
|
+
});
|
|
449
|
+
return parseTelegramLinkResponse(raw2);
|
|
450
|
+
}
|
|
451
|
+
toDeviceState(result, fingerprint, previous) {
|
|
452
|
+
return {
|
|
453
|
+
deviceId: result.deviceId,
|
|
454
|
+
deviceToken: result.deviceToken,
|
|
455
|
+
fingerprint,
|
|
456
|
+
hubUrl: this.config.hubUrl,
|
|
457
|
+
lastRegisterAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
458
|
+
lastHeartbeatAt: previous?.lastHeartbeatAt,
|
|
459
|
+
telegramBindPending: previous?.telegramBindPending,
|
|
460
|
+
telegramLinked: previous?.telegramLinked
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
// bridge/command_dispatcher.ts
|
|
466
|
+
var CommandDispatcher = class {
|
|
467
|
+
constructor(registry, backend, logger, getDeviceToken) {
|
|
468
|
+
this.registry = registry;
|
|
469
|
+
this.backend = backend;
|
|
470
|
+
this.logger = logger;
|
|
471
|
+
this.getDeviceToken = getDeviceToken;
|
|
472
|
+
}
|
|
473
|
+
held = /* @__PURE__ */ new Map();
|
|
474
|
+
async dispatch(command) {
|
|
475
|
+
const localId = this.registry.getLocalIdByHubSessionId(command.session_id);
|
|
476
|
+
const pending = {
|
|
477
|
+
commandId: command.command_id,
|
|
478
|
+
hubSessionId: command.session_id,
|
|
479
|
+
kind: command.kind,
|
|
480
|
+
payload: command.payload,
|
|
481
|
+
queuedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
482
|
+
};
|
|
483
|
+
if (!localId) {
|
|
484
|
+
const held = this.held.get(command.command_id) ?? {
|
|
485
|
+
command,
|
|
486
|
+
attempts: 0
|
|
487
|
+
};
|
|
488
|
+
held.attempts += 1;
|
|
489
|
+
this.held.set(command.command_id, held);
|
|
490
|
+
this.logger.warn("Command session not found locally, holding", {
|
|
491
|
+
commandId: command.command_id,
|
|
492
|
+
hubSessionId: command.session_id,
|
|
493
|
+
attempts: held.attempts
|
|
494
|
+
});
|
|
495
|
+
if (held.attempts >= COMMAND_RETRY_ATTEMPTS) {
|
|
496
|
+
this.logger.error("Command dropped after retries", {
|
|
497
|
+
commandId: command.command_id
|
|
498
|
+
});
|
|
499
|
+
this.held.delete(command.command_id);
|
|
500
|
+
await this.ack(command.command_id);
|
|
501
|
+
}
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const accepted = this.registry.enqueueCommand(localId, pending);
|
|
505
|
+
if (!accepted) {
|
|
506
|
+
this.logger.warn("Failed to enqueue command", {
|
|
507
|
+
commandId: command.command_id,
|
|
508
|
+
localId
|
|
509
|
+
});
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
await this.ack(command.command_id);
|
|
513
|
+
this.held.delete(command.command_id);
|
|
514
|
+
}
|
|
515
|
+
retryHeldCommands() {
|
|
516
|
+
for (const [commandId, held] of [...this.held.entries()]) {
|
|
517
|
+
const localId = this.registry.getLocalIdByHubSessionId(held.command.session_id);
|
|
518
|
+
if (!localId) continue;
|
|
519
|
+
void this.dispatch(held.command).finally(() => {
|
|
520
|
+
if (this.held.has(commandId)) {
|
|
521
|
+
setTimeout(() => this.retryHeldCommands(), COMMAND_RETRY_DELAY_MS);
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async ack(commandId) {
|
|
527
|
+
const token = this.getDeviceToken();
|
|
528
|
+
if (!token) return;
|
|
529
|
+
try {
|
|
530
|
+
await this.backend.ackCommand(commandId, token);
|
|
531
|
+
this.logger.info("Command acked", {
|
|
532
|
+
commandId,
|
|
533
|
+
correlationId: this.backend.getLastCorrelationId()
|
|
534
|
+
});
|
|
535
|
+
} catch (error) {
|
|
536
|
+
this.logger.warn("Command ack failed", { commandId, error: String(error) });
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// bridge/device_state_store.ts
|
|
542
|
+
import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
543
|
+
var DeviceStateStore = class {
|
|
544
|
+
filePath;
|
|
545
|
+
constructor(dataDir) {
|
|
546
|
+
mkdirSync2(dataDir, { recursive: true, mode: 448 });
|
|
547
|
+
this.filePath = stateFilePath(dataDir);
|
|
548
|
+
}
|
|
549
|
+
load() {
|
|
550
|
+
if (!existsSync3(this.filePath)) return null;
|
|
551
|
+
try {
|
|
552
|
+
return JSON.parse(readFileSync2(this.filePath, "utf-8"));
|
|
553
|
+
} catch {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
save(state) {
|
|
558
|
+
writeFileSync(this.filePath, `${JSON.stringify(state, null, 2)}
|
|
559
|
+
`, {
|
|
560
|
+
encoding: "utf-8",
|
|
561
|
+
mode: 384
|
|
562
|
+
});
|
|
563
|
+
chmodSync(this.filePath, 384);
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// bridge/event_sender.ts
|
|
568
|
+
var EventSender = class {
|
|
569
|
+
constructor(backend, retryQueue, logger, getDeviceState) {
|
|
570
|
+
this.backend = backend;
|
|
571
|
+
this.retryQueue = retryQueue;
|
|
572
|
+
this.logger = logger;
|
|
573
|
+
this.getDeviceState = getDeviceState;
|
|
574
|
+
}
|
|
575
|
+
pendingCount = 0;
|
|
576
|
+
pendingEventsCount() {
|
|
577
|
+
return this.pendingCount;
|
|
578
|
+
}
|
|
579
|
+
async enqueue(externalSessionId, event) {
|
|
580
|
+
this.pendingCount += 1;
|
|
581
|
+
this.retryQueue.enqueue({
|
|
582
|
+
externalSessionId,
|
|
583
|
+
event,
|
|
584
|
+
attempts: 0
|
|
585
|
+
});
|
|
586
|
+
this.logger.debug("Session event queued", {
|
|
587
|
+
externalSessionId,
|
|
588
|
+
eventId: event.eventId,
|
|
589
|
+
eventType: event.eventType
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
async send(externalSessionId, event) {
|
|
593
|
+
const state = this.getDeviceState();
|
|
594
|
+
if (!state) {
|
|
595
|
+
this.logger.warn("Cannot send event without device state", { eventId: event.eventId });
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
let telegramLinked = state.telegramLinked === true;
|
|
599
|
+
if (!telegramLinked) {
|
|
600
|
+
if (!shouldProbeTelegramLink(state)) {
|
|
601
|
+
await this.enqueue(externalSessionId, event);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
telegramLinked = await this.backend.isTelegramLinked(state.deviceToken);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
if (error instanceof BackendAuthError) {
|
|
608
|
+
await this.enqueue(externalSessionId, event);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
throw error;
|
|
612
|
+
}
|
|
613
|
+
if (!telegramLinked) {
|
|
614
|
+
await this.enqueue(externalSessionId, event);
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
try {
|
|
619
|
+
await this.backend.postSessionEvent(state.deviceToken, {
|
|
620
|
+
external_session_id: externalSessionId,
|
|
621
|
+
event_type: event.eventType,
|
|
622
|
+
status: event.status,
|
|
623
|
+
payload: event.payload,
|
|
624
|
+
event_id: event.eventId
|
|
625
|
+
});
|
|
626
|
+
this.logger.info("Session event sent", {
|
|
627
|
+
deviceId: state.deviceId,
|
|
628
|
+
externalSessionId,
|
|
629
|
+
eventId: event.eventId,
|
|
630
|
+
correlationId: this.backend.getLastCorrelationId()
|
|
631
|
+
});
|
|
632
|
+
} catch (error) {
|
|
633
|
+
await this.enqueue(externalSessionId, event);
|
|
634
|
+
this.logger.warn("Session event queued for retry", {
|
|
635
|
+
externalSessionId,
|
|
636
|
+
eventId: event.eventId,
|
|
637
|
+
error: String(error)
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
async flushRetryQueue() {
|
|
642
|
+
const state = this.getDeviceState();
|
|
643
|
+
if (!state) return;
|
|
644
|
+
let telegramLinked = state.telegramLinked === true;
|
|
645
|
+
if (!telegramLinked) {
|
|
646
|
+
if (!shouldProbeTelegramLink(state)) return;
|
|
647
|
+
try {
|
|
648
|
+
telegramLinked = await this.backend.isTelegramLinked(state.deviceToken);
|
|
649
|
+
} catch (error) {
|
|
650
|
+
if (error instanceof BackendAuthError) return;
|
|
651
|
+
throw error;
|
|
652
|
+
}
|
|
653
|
+
if (!telegramLinked) return;
|
|
654
|
+
}
|
|
655
|
+
const queued = this.retryQueue.load();
|
|
656
|
+
if (queued.length === 0) return;
|
|
657
|
+
const remaining = [];
|
|
658
|
+
for (const item of queued) {
|
|
659
|
+
try {
|
|
660
|
+
await this.backend.postSessionEvent(state.deviceToken, {
|
|
661
|
+
external_session_id: item.externalSessionId,
|
|
662
|
+
event_type: item.event.eventType,
|
|
663
|
+
status: item.event.status,
|
|
664
|
+
payload: item.event.payload,
|
|
665
|
+
event_id: item.event.eventId
|
|
666
|
+
});
|
|
667
|
+
this.pendingCount = Math.max(0, this.pendingCount - 1);
|
|
668
|
+
} catch {
|
|
669
|
+
item.attempts += 1;
|
|
670
|
+
if (item.attempts < 5) {
|
|
671
|
+
remaining.push(item);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
this.retryQueue.persist(remaining);
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
// bridge/fingerprint.ts
|
|
680
|
+
import { createHash } from "node:crypto";
|
|
681
|
+
import { hostname as hostname2, platform as platform2 } from "node:os";
|
|
682
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
683
|
+
function computeDeviceFingerprint() {
|
|
684
|
+
const parts = [hostname2(), platform2()];
|
|
685
|
+
for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
|
|
686
|
+
try {
|
|
687
|
+
const value = readFileSync3(path, "utf-8").trim();
|
|
688
|
+
if (value) {
|
|
689
|
+
parts.push(value);
|
|
690
|
+
break;
|
|
691
|
+
}
|
|
692
|
+
} catch {
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
return createHash("sha256").update(parts.join(":")).digest("hex");
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// bridge/loops.ts
|
|
699
|
+
function startHeartbeatLoop(config, backend, logger, getDeviceState, onHeartbeat, hasActiveSessions, shouldProbeTelegram, onAuthFailure) {
|
|
700
|
+
let stopped = false;
|
|
701
|
+
const tick = async () => {
|
|
702
|
+
if (stopped) return;
|
|
703
|
+
if (!hasActiveSessions()) return;
|
|
704
|
+
const state = getDeviceState();
|
|
705
|
+
if (!state) return;
|
|
706
|
+
let telegramLinked = state.telegramLinked === true;
|
|
707
|
+
if (!telegramLinked) {
|
|
708
|
+
if (!shouldProbeTelegram(state)) return;
|
|
709
|
+
try {
|
|
710
|
+
telegramLinked = await backend.isTelegramLinked(state.deviceToken);
|
|
711
|
+
} catch (error) {
|
|
712
|
+
if (error instanceof BackendAuthError) {
|
|
713
|
+
onAuthFailure?.();
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (!telegramLinked) return;
|
|
719
|
+
}
|
|
720
|
+
try {
|
|
721
|
+
await backend.heartbeat(state.deviceToken);
|
|
722
|
+
onHeartbeat({
|
|
723
|
+
...state,
|
|
724
|
+
lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
725
|
+
});
|
|
726
|
+
logger.debug("Heartbeat ok", { deviceId: state.deviceId });
|
|
727
|
+
} catch (error) {
|
|
728
|
+
logger.warn("Heartbeat failed", { deviceId: state.deviceId, error: String(error) });
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
void tick();
|
|
732
|
+
const timer = setInterval(() => void tick(), config.heartbeatIntervalSec * 1e3);
|
|
733
|
+
return () => {
|
|
734
|
+
stopped = true;
|
|
735
|
+
clearInterval(timer);
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function startPollerLoop(config, backend, dispatcher, eventSender, logger, getDeviceState, hasActiveSessions, shouldProbeTelegram, onTelegramLinked, onAuthFailure) {
|
|
739
|
+
let stopped = false;
|
|
740
|
+
let previousLinked = false;
|
|
741
|
+
const tick = async () => {
|
|
742
|
+
if (stopped) return;
|
|
743
|
+
const state = getDeviceState();
|
|
744
|
+
if (!state) return;
|
|
745
|
+
let telegramLinked = state.telegramLinked === true;
|
|
746
|
+
if (!telegramLinked) {
|
|
747
|
+
if (!shouldProbeTelegram(state)) {
|
|
748
|
+
previousLinked = false;
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
try {
|
|
752
|
+
telegramLinked = await backend.isTelegramLinked(
|
|
753
|
+
state.deviceToken,
|
|
754
|
+
previousLinked ? void 0 : 0
|
|
755
|
+
);
|
|
756
|
+
} catch (error) {
|
|
757
|
+
if (error instanceof BackendAuthError) {
|
|
758
|
+
onAuthFailure?.();
|
|
759
|
+
previousLinked = false;
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (telegramLinked && !previousLinked) {
|
|
766
|
+
await onTelegramLinked?.();
|
|
767
|
+
}
|
|
768
|
+
previousLinked = telegramLinked;
|
|
769
|
+
if (!telegramLinked) return;
|
|
770
|
+
const active = hasActiveSessions();
|
|
771
|
+
const hasPendingEvents = eventSender.pendingEventsCount() > 0;
|
|
772
|
+
if (!active && !hasPendingEvents) return;
|
|
773
|
+
try {
|
|
774
|
+
if (hasPendingEvents) {
|
|
775
|
+
await eventSender.flushRetryQueue();
|
|
776
|
+
}
|
|
777
|
+
if (!active) return;
|
|
778
|
+
const commands = await backend.getNextCommands(state.deviceId, state.deviceToken);
|
|
779
|
+
for (const command of commands) {
|
|
780
|
+
await dispatcher.dispatch(command);
|
|
781
|
+
}
|
|
782
|
+
dispatcher.retryHeldCommands();
|
|
783
|
+
} catch (error) {
|
|
784
|
+
logger.warn("Command polling failed", {
|
|
785
|
+
deviceId: state.deviceId,
|
|
786
|
+
error: String(error)
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
void tick();
|
|
791
|
+
const timer = setInterval(() => void tick(), config.pollIntervalSec * 1e3);
|
|
792
|
+
return () => {
|
|
793
|
+
stopped = true;
|
|
794
|
+
clearInterval(timer);
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// bridge/ipc_server.ts
|
|
799
|
+
import { randomUUID } from "node:crypto";
|
|
800
|
+
|
|
801
|
+
// node_modules/hono/dist/compose.js
|
|
802
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
803
|
+
return (context, next) => {
|
|
804
|
+
let index = -1;
|
|
805
|
+
return dispatch(0);
|
|
806
|
+
async function dispatch(i) {
|
|
807
|
+
if (i <= index) {
|
|
808
|
+
throw new Error("next() called multiple times");
|
|
809
|
+
}
|
|
810
|
+
index = i;
|
|
811
|
+
let res;
|
|
812
|
+
let isError = false;
|
|
813
|
+
let handler;
|
|
814
|
+
if (middleware[i]) {
|
|
815
|
+
handler = middleware[i][0][0];
|
|
816
|
+
context.req.routeIndex = i;
|
|
817
|
+
} else {
|
|
818
|
+
handler = i === middleware.length && next || void 0;
|
|
819
|
+
}
|
|
820
|
+
if (handler) {
|
|
821
|
+
try {
|
|
822
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
823
|
+
} catch (err) {
|
|
824
|
+
if (err instanceof Error && onError) {
|
|
825
|
+
context.error = err;
|
|
826
|
+
res = await onError(err, context);
|
|
827
|
+
isError = true;
|
|
828
|
+
} else {
|
|
829
|
+
throw err;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
} else {
|
|
833
|
+
if (context.finalized === false && onNotFound) {
|
|
834
|
+
res = await onNotFound(context);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
if (res && (context.finalized === false || isError)) {
|
|
838
|
+
context.res = res;
|
|
839
|
+
}
|
|
840
|
+
return context;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
// node_modules/hono/dist/request/constants.js
|
|
846
|
+
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
|
|
847
|
+
|
|
848
|
+
// node_modules/hono/dist/utils/body.js
|
|
849
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
850
|
+
const { all = false, dot = false } = options;
|
|
851
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
852
|
+
const contentType = headers.get("Content-Type");
|
|
853
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
854
|
+
return parseFormData(request, { all, dot });
|
|
855
|
+
}
|
|
856
|
+
return {};
|
|
857
|
+
};
|
|
858
|
+
async function parseFormData(request, options) {
|
|
859
|
+
const formData = await request.formData();
|
|
860
|
+
if (formData) {
|
|
861
|
+
return convertFormDataToBodyData(formData, options);
|
|
862
|
+
}
|
|
863
|
+
return {};
|
|
864
|
+
}
|
|
865
|
+
function convertFormDataToBodyData(formData, options) {
|
|
866
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
867
|
+
formData.forEach((value, key) => {
|
|
868
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
869
|
+
if (!shouldParseAllValues) {
|
|
870
|
+
form[key] = value;
|
|
871
|
+
} else {
|
|
872
|
+
handleParsingAllValues(form, key, value);
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
if (options.dot) {
|
|
876
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
877
|
+
const shouldParseDotValues = key.includes(".");
|
|
878
|
+
if (shouldParseDotValues) {
|
|
879
|
+
handleParsingNestedValues(form, key, value);
|
|
880
|
+
delete form[key];
|
|
881
|
+
}
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
return form;
|
|
885
|
+
}
|
|
886
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
887
|
+
if (form[key] !== void 0) {
|
|
888
|
+
if (Array.isArray(form[key])) {
|
|
889
|
+
;
|
|
890
|
+
form[key].push(value);
|
|
891
|
+
} else {
|
|
892
|
+
form[key] = [form[key], value];
|
|
893
|
+
}
|
|
894
|
+
} else {
|
|
895
|
+
if (!key.endsWith("[]")) {
|
|
896
|
+
form[key] = value;
|
|
897
|
+
} else {
|
|
898
|
+
form[key] = [value];
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
903
|
+
if (/(?:^|\.)__proto__\./.test(key)) {
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
let nestedForm = form;
|
|
907
|
+
const keys = key.split(".");
|
|
908
|
+
keys.forEach((key2, index) => {
|
|
909
|
+
if (index === keys.length - 1) {
|
|
910
|
+
nestedForm[key2] = value;
|
|
911
|
+
} else {
|
|
912
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
913
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
914
|
+
}
|
|
915
|
+
nestedForm = nestedForm[key2];
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
// node_modules/hono/dist/utils/url.js
|
|
921
|
+
var splitPath = (path) => {
|
|
922
|
+
const paths = path.split("/");
|
|
923
|
+
if (paths[0] === "") {
|
|
924
|
+
paths.shift();
|
|
925
|
+
}
|
|
926
|
+
return paths;
|
|
927
|
+
};
|
|
928
|
+
var splitRoutingPath = (routePath) => {
|
|
929
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
930
|
+
const paths = splitPath(path);
|
|
931
|
+
return replaceGroupMarks(paths, groups);
|
|
932
|
+
};
|
|
933
|
+
var extractGroupsFromPath = (path) => {
|
|
934
|
+
const groups = [];
|
|
935
|
+
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
|
|
936
|
+
const mark = `@${index}`;
|
|
937
|
+
groups.push([mark, match2]);
|
|
938
|
+
return mark;
|
|
939
|
+
});
|
|
940
|
+
return { groups, path };
|
|
941
|
+
};
|
|
942
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
943
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
944
|
+
const [mark] = groups[i];
|
|
945
|
+
for (let j = paths.length - 1; j >= 0; j--) {
|
|
946
|
+
if (paths[j].includes(mark)) {
|
|
947
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
948
|
+
break;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return paths;
|
|
953
|
+
};
|
|
954
|
+
var patternCache = {};
|
|
955
|
+
var getPattern = (label, next) => {
|
|
956
|
+
if (label === "*") {
|
|
957
|
+
return "*";
|
|
958
|
+
}
|
|
959
|
+
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
960
|
+
if (match2) {
|
|
961
|
+
const cacheKey2 = `${label}#${next}`;
|
|
962
|
+
if (!patternCache[cacheKey2]) {
|
|
963
|
+
if (match2[2]) {
|
|
964
|
+
patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
|
|
965
|
+
} else {
|
|
966
|
+
patternCache[cacheKey2] = [label, match2[1], true];
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
return patternCache[cacheKey2];
|
|
970
|
+
}
|
|
971
|
+
return null;
|
|
972
|
+
};
|
|
973
|
+
var tryDecode = (str, decoder) => {
|
|
974
|
+
try {
|
|
975
|
+
return decoder(str);
|
|
976
|
+
} catch {
|
|
977
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
|
|
978
|
+
try {
|
|
979
|
+
return decoder(match2);
|
|
980
|
+
} catch {
|
|
981
|
+
return match2;
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
987
|
+
var getPath = (request) => {
|
|
988
|
+
const url = request.url;
|
|
989
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
990
|
+
let i = start;
|
|
991
|
+
for (; i < url.length; i++) {
|
|
992
|
+
const charCode = url.charCodeAt(i);
|
|
993
|
+
if (charCode === 37) {
|
|
994
|
+
const queryIndex = url.indexOf("?", i);
|
|
995
|
+
const hashIndex = url.indexOf("#", i);
|
|
996
|
+
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
997
|
+
const path = url.slice(start, end);
|
|
998
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
999
|
+
} else if (charCode === 63 || charCode === 35) {
|
|
1000
|
+
break;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
return url.slice(start, i);
|
|
1004
|
+
};
|
|
1005
|
+
var getPathNoStrict = (request) => {
|
|
1006
|
+
const result = getPath(request);
|
|
1007
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
1008
|
+
};
|
|
1009
|
+
var mergePath = (base, sub, ...rest) => {
|
|
1010
|
+
if (rest.length) {
|
|
1011
|
+
sub = mergePath(sub, ...rest);
|
|
1012
|
+
}
|
|
1013
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
1014
|
+
};
|
|
1015
|
+
var checkOptionalParameter = (path) => {
|
|
1016
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
const segments = path.split("/");
|
|
1020
|
+
const results = [];
|
|
1021
|
+
let basePath = "";
|
|
1022
|
+
segments.forEach((segment) => {
|
|
1023
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
1024
|
+
basePath += "/" + segment;
|
|
1025
|
+
} else if (/\:/.test(segment)) {
|
|
1026
|
+
if (/\?/.test(segment)) {
|
|
1027
|
+
if (results.length === 0 && basePath === "") {
|
|
1028
|
+
results.push("/");
|
|
1029
|
+
} else {
|
|
1030
|
+
results.push(basePath);
|
|
1031
|
+
}
|
|
1032
|
+
const optionalSegment = segment.replace("?", "");
|
|
1033
|
+
basePath += "/" + optionalSegment;
|
|
1034
|
+
results.push(basePath);
|
|
1035
|
+
} else {
|
|
1036
|
+
basePath += "/" + segment;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
1041
|
+
};
|
|
1042
|
+
var _decodeURI = (value) => {
|
|
1043
|
+
if (!/[%+]/.test(value)) {
|
|
1044
|
+
return value;
|
|
1045
|
+
}
|
|
1046
|
+
if (value.indexOf("+") !== -1) {
|
|
1047
|
+
value = value.replace(/\+/g, " ");
|
|
1048
|
+
}
|
|
1049
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
1050
|
+
};
|
|
1051
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
1052
|
+
let encoded;
|
|
1053
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
1054
|
+
let keyIndex2 = url.indexOf("?", 8);
|
|
1055
|
+
if (keyIndex2 === -1) {
|
|
1056
|
+
return void 0;
|
|
1057
|
+
}
|
|
1058
|
+
if (!url.startsWith(key, keyIndex2 + 1)) {
|
|
1059
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1060
|
+
}
|
|
1061
|
+
while (keyIndex2 !== -1) {
|
|
1062
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
1063
|
+
if (trailingKeyCode === 61) {
|
|
1064
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
1065
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
1066
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
1067
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
1068
|
+
return "";
|
|
1069
|
+
}
|
|
1070
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
1071
|
+
}
|
|
1072
|
+
encoded = /[%+]/.test(url);
|
|
1073
|
+
if (!encoded) {
|
|
1074
|
+
return void 0;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
const results = {};
|
|
1078
|
+
encoded ??= /[%+]/.test(url);
|
|
1079
|
+
let keyIndex = url.indexOf("?", 8);
|
|
1080
|
+
while (keyIndex !== -1) {
|
|
1081
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
1082
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
1083
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
1084
|
+
valueIndex = -1;
|
|
1085
|
+
}
|
|
1086
|
+
let name = url.slice(
|
|
1087
|
+
keyIndex + 1,
|
|
1088
|
+
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
1089
|
+
);
|
|
1090
|
+
if (encoded) {
|
|
1091
|
+
name = _decodeURI(name);
|
|
1092
|
+
}
|
|
1093
|
+
keyIndex = nextKeyIndex;
|
|
1094
|
+
if (name === "") {
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
let value;
|
|
1098
|
+
if (valueIndex === -1) {
|
|
1099
|
+
value = "";
|
|
1100
|
+
} else {
|
|
1101
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
1102
|
+
if (encoded) {
|
|
1103
|
+
value = _decodeURI(value);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
if (multiple) {
|
|
1107
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
1108
|
+
results[name] = [];
|
|
1109
|
+
}
|
|
1110
|
+
;
|
|
1111
|
+
results[name].push(value);
|
|
1112
|
+
} else {
|
|
1113
|
+
results[name] ??= value;
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
return key ? results[key] : results;
|
|
1117
|
+
};
|
|
1118
|
+
var getQueryParam = _getQueryParam;
|
|
1119
|
+
var getQueryParams = (url, key) => {
|
|
1120
|
+
return _getQueryParam(url, key, true);
|
|
1121
|
+
};
|
|
1122
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
1123
|
+
|
|
1124
|
+
// node_modules/hono/dist/request.js
|
|
1125
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1126
|
+
var HonoRequest = class {
|
|
1127
|
+
/**
|
|
1128
|
+
* `.raw` can get the raw Request object.
|
|
1129
|
+
*
|
|
1130
|
+
* @see {@link https://hono.dev/docs/api/request#raw}
|
|
1131
|
+
*
|
|
1132
|
+
* @example
|
|
1133
|
+
* ```ts
|
|
1134
|
+
* // For Cloudflare Workers
|
|
1135
|
+
* app.post('/', async (c) => {
|
|
1136
|
+
* const metadata = c.req.raw.cf?.hostMetadata?
|
|
1137
|
+
* ...
|
|
1138
|
+
* })
|
|
1139
|
+
* ```
|
|
1140
|
+
*/
|
|
1141
|
+
raw;
|
|
1142
|
+
#validatedData;
|
|
1143
|
+
// Short name of validatedData
|
|
1144
|
+
#matchResult;
|
|
1145
|
+
routeIndex = 0;
|
|
1146
|
+
/**
|
|
1147
|
+
* `.path` can get the pathname of the request.
|
|
1148
|
+
*
|
|
1149
|
+
* @see {@link https://hono.dev/docs/api/request#path}
|
|
1150
|
+
*
|
|
1151
|
+
* @example
|
|
1152
|
+
* ```ts
|
|
1153
|
+
* app.get('/about/me', (c) => {
|
|
1154
|
+
* const pathname = c.req.path // `/about/me`
|
|
1155
|
+
* })
|
|
1156
|
+
* ```
|
|
1157
|
+
*/
|
|
1158
|
+
path;
|
|
1159
|
+
bodyCache = {};
|
|
1160
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1161
|
+
this.raw = request;
|
|
1162
|
+
this.path = path;
|
|
1163
|
+
this.#matchResult = matchResult;
|
|
1164
|
+
this.#validatedData = {};
|
|
1165
|
+
}
|
|
1166
|
+
param(key) {
|
|
1167
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1168
|
+
}
|
|
1169
|
+
#getDecodedParam(key) {
|
|
1170
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1171
|
+
const param = this.#getParamValue(paramKey);
|
|
1172
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1173
|
+
}
|
|
1174
|
+
#getAllDecodedParams() {
|
|
1175
|
+
const decoded = {};
|
|
1176
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1177
|
+
for (const key of keys) {
|
|
1178
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1179
|
+
if (value !== void 0) {
|
|
1180
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
return decoded;
|
|
1184
|
+
}
|
|
1185
|
+
#getParamValue(paramKey) {
|
|
1186
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1187
|
+
}
|
|
1188
|
+
query(key) {
|
|
1189
|
+
return getQueryParam(this.url, key);
|
|
1190
|
+
}
|
|
1191
|
+
queries(key) {
|
|
1192
|
+
return getQueryParams(this.url, key);
|
|
1193
|
+
}
|
|
1194
|
+
header(name) {
|
|
1195
|
+
if (name) {
|
|
1196
|
+
return this.raw.headers.get(name) ?? void 0;
|
|
1197
|
+
}
|
|
1198
|
+
const headerData = {};
|
|
1199
|
+
this.raw.headers.forEach((value, key) => {
|
|
1200
|
+
headerData[key] = value;
|
|
1201
|
+
});
|
|
1202
|
+
return headerData;
|
|
1203
|
+
}
|
|
1204
|
+
async parseBody(options) {
|
|
1205
|
+
return parseBody(this, options);
|
|
1206
|
+
}
|
|
1207
|
+
#cachedBody = (key) => {
|
|
1208
|
+
const { bodyCache, raw: raw2 } = this;
|
|
1209
|
+
const cachedBody = bodyCache[key];
|
|
1210
|
+
if (cachedBody) {
|
|
1211
|
+
return cachedBody;
|
|
1212
|
+
}
|
|
1213
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1214
|
+
if (anyCachedKey) {
|
|
1215
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1216
|
+
if (anyCachedKey === "json") {
|
|
1217
|
+
body = JSON.stringify(body);
|
|
1218
|
+
}
|
|
1219
|
+
return new Response(body)[key]();
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
return bodyCache[key] = raw2[key]();
|
|
1223
|
+
};
|
|
1224
|
+
/**
|
|
1225
|
+
* `.json()` can parse Request body of type `application/json`
|
|
1226
|
+
*
|
|
1227
|
+
* @see {@link https://hono.dev/docs/api/request#json}
|
|
1228
|
+
*
|
|
1229
|
+
* @example
|
|
1230
|
+
* ```ts
|
|
1231
|
+
* app.post('/entry', async (c) => {
|
|
1232
|
+
* const body = await c.req.json()
|
|
1233
|
+
* })
|
|
1234
|
+
* ```
|
|
1235
|
+
*/
|
|
1236
|
+
json() {
|
|
1237
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* `.text()` can parse Request body of type `text/plain`
|
|
1241
|
+
*
|
|
1242
|
+
* @see {@link https://hono.dev/docs/api/request#text}
|
|
1243
|
+
*
|
|
1244
|
+
* @example
|
|
1245
|
+
* ```ts
|
|
1246
|
+
* app.post('/entry', async (c) => {
|
|
1247
|
+
* const body = await c.req.text()
|
|
1248
|
+
* })
|
|
1249
|
+
* ```
|
|
1250
|
+
*/
|
|
1251
|
+
text() {
|
|
1252
|
+
return this.#cachedBody("text");
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
|
|
1256
|
+
*
|
|
1257
|
+
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
|
|
1258
|
+
*
|
|
1259
|
+
* @example
|
|
1260
|
+
* ```ts
|
|
1261
|
+
* app.post('/entry', async (c) => {
|
|
1262
|
+
* const body = await c.req.arrayBuffer()
|
|
1263
|
+
* })
|
|
1264
|
+
* ```
|
|
1265
|
+
*/
|
|
1266
|
+
arrayBuffer() {
|
|
1267
|
+
return this.#cachedBody("arrayBuffer");
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* `.bytes()` parses the request body as a `Uint8Array`.
|
|
1271
|
+
*
|
|
1272
|
+
* @see {@link https://hono.dev/docs/api/request#bytes}
|
|
1273
|
+
*
|
|
1274
|
+
* @example
|
|
1275
|
+
* ```ts
|
|
1276
|
+
* app.post('/entry', async (c) => {
|
|
1277
|
+
* const body = await c.req.bytes()
|
|
1278
|
+
* })
|
|
1279
|
+
* ```
|
|
1280
|
+
*/
|
|
1281
|
+
bytes() {
|
|
1282
|
+
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Parses the request body as a `Blob`.
|
|
1286
|
+
* @example
|
|
1287
|
+
* ```ts
|
|
1288
|
+
* app.post('/entry', async (c) => {
|
|
1289
|
+
* const body = await c.req.blob();
|
|
1290
|
+
* });
|
|
1291
|
+
* ```
|
|
1292
|
+
* @see https://hono.dev/docs/api/request#blob
|
|
1293
|
+
*/
|
|
1294
|
+
blob() {
|
|
1295
|
+
return this.#cachedBody("blob");
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Parses the request body as `FormData`.
|
|
1299
|
+
* @example
|
|
1300
|
+
* ```ts
|
|
1301
|
+
* app.post('/entry', async (c) => {
|
|
1302
|
+
* const body = await c.req.formData();
|
|
1303
|
+
* });
|
|
1304
|
+
* ```
|
|
1305
|
+
* @see https://hono.dev/docs/api/request#formdata
|
|
1306
|
+
*/
|
|
1307
|
+
formData() {
|
|
1308
|
+
return this.#cachedBody("formData");
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Adds validated data to the request.
|
|
1312
|
+
*
|
|
1313
|
+
* @param target - The target of the validation.
|
|
1314
|
+
* @param data - The validated data to add.
|
|
1315
|
+
*/
|
|
1316
|
+
addValidatedData(target, data) {
|
|
1317
|
+
this.#validatedData[target] = data;
|
|
1318
|
+
}
|
|
1319
|
+
valid(target) {
|
|
1320
|
+
return this.#validatedData[target];
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* `.url()` can get the request url strings.
|
|
1324
|
+
*
|
|
1325
|
+
* @see {@link https://hono.dev/docs/api/request#url}
|
|
1326
|
+
*
|
|
1327
|
+
* @example
|
|
1328
|
+
* ```ts
|
|
1329
|
+
* app.get('/about/me', (c) => {
|
|
1330
|
+
* const url = c.req.url // `http://localhost:8787/about/me`
|
|
1331
|
+
* ...
|
|
1332
|
+
* })
|
|
1333
|
+
* ```
|
|
1334
|
+
*/
|
|
1335
|
+
get url() {
|
|
1336
|
+
return this.raw.url;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* `.method()` can get the method name of the request.
|
|
1340
|
+
*
|
|
1341
|
+
* @see {@link https://hono.dev/docs/api/request#method}
|
|
1342
|
+
*
|
|
1343
|
+
* @example
|
|
1344
|
+
* ```ts
|
|
1345
|
+
* app.get('/about/me', (c) => {
|
|
1346
|
+
* const method = c.req.method // `GET`
|
|
1347
|
+
* })
|
|
1348
|
+
* ```
|
|
1349
|
+
*/
|
|
1350
|
+
get method() {
|
|
1351
|
+
return this.raw.method;
|
|
1352
|
+
}
|
|
1353
|
+
get [GET_MATCH_RESULT]() {
|
|
1354
|
+
return this.#matchResult;
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* `.matchedRoutes()` can return a matched route in the handler
|
|
1358
|
+
*
|
|
1359
|
+
* @deprecated
|
|
1360
|
+
*
|
|
1361
|
+
* Use matchedRoutes helper defined in "hono/route" instead.
|
|
1362
|
+
*
|
|
1363
|
+
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
|
|
1364
|
+
*
|
|
1365
|
+
* @example
|
|
1366
|
+
* ```ts
|
|
1367
|
+
* app.use('*', async function logger(c, next) {
|
|
1368
|
+
* await next()
|
|
1369
|
+
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
|
|
1370
|
+
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
|
|
1371
|
+
* console.log(
|
|
1372
|
+
* method,
|
|
1373
|
+
* ' ',
|
|
1374
|
+
* path,
|
|
1375
|
+
* ' '.repeat(Math.max(10 - path.length, 0)),
|
|
1376
|
+
* name,
|
|
1377
|
+
* i === c.req.routeIndex ? '<- respond from here' : ''
|
|
1378
|
+
* )
|
|
1379
|
+
* })
|
|
1380
|
+
* })
|
|
1381
|
+
* ```
|
|
1382
|
+
*/
|
|
1383
|
+
get matchedRoutes() {
|
|
1384
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* `routePath()` can retrieve the path registered within the handler
|
|
1388
|
+
*
|
|
1389
|
+
* @deprecated
|
|
1390
|
+
*
|
|
1391
|
+
* Use routePath helper defined in "hono/route" instead.
|
|
1392
|
+
*
|
|
1393
|
+
* @see {@link https://hono.dev/docs/api/request#routepath}
|
|
1394
|
+
*
|
|
1395
|
+
* @example
|
|
1396
|
+
* ```ts
|
|
1397
|
+
* app.get('/posts/:id', (c) => {
|
|
1398
|
+
* return c.json({ path: c.req.routePath })
|
|
1399
|
+
* })
|
|
1400
|
+
* ```
|
|
1401
|
+
*/
|
|
1402
|
+
get routePath() {
|
|
1403
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1404
|
+
}
|
|
1405
|
+
};
|
|
1406
|
+
|
|
1407
|
+
// node_modules/hono/dist/utils/html.js
|
|
1408
|
+
var HtmlEscapedCallbackPhase = {
|
|
1409
|
+
Stringify: 1,
|
|
1410
|
+
BeforeStream: 2,
|
|
1411
|
+
Stream: 3
|
|
1412
|
+
};
|
|
1413
|
+
var raw = (value, callbacks) => {
|
|
1414
|
+
const escapedString = new String(value);
|
|
1415
|
+
escapedString.isEscaped = true;
|
|
1416
|
+
escapedString.callbacks = callbacks;
|
|
1417
|
+
return escapedString;
|
|
1418
|
+
};
|
|
1419
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1420
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1421
|
+
if (!(str instanceof Promise)) {
|
|
1422
|
+
str = str.toString();
|
|
1423
|
+
}
|
|
1424
|
+
if (str instanceof Promise) {
|
|
1425
|
+
str = await str;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
const callbacks = str.callbacks;
|
|
1429
|
+
if (!callbacks?.length) {
|
|
1430
|
+
return Promise.resolve(str);
|
|
1431
|
+
}
|
|
1432
|
+
if (buffer) {
|
|
1433
|
+
buffer[0] += str;
|
|
1434
|
+
} else {
|
|
1435
|
+
buffer = [str];
|
|
1436
|
+
}
|
|
1437
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
1438
|
+
(res) => Promise.all(
|
|
1439
|
+
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
1440
|
+
).then(() => buffer[0])
|
|
1441
|
+
);
|
|
1442
|
+
if (preserveCallbacks) {
|
|
1443
|
+
return raw(await resStr, callbacks);
|
|
1444
|
+
} else {
|
|
1445
|
+
return resStr;
|
|
1446
|
+
}
|
|
1447
|
+
};
|
|
1448
|
+
|
|
1449
|
+
// node_modules/hono/dist/context.js
|
|
1450
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1451
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1452
|
+
return {
|
|
1453
|
+
"Content-Type": contentType,
|
|
1454
|
+
...headers
|
|
1455
|
+
};
|
|
1456
|
+
};
|
|
1457
|
+
var createResponseInstance = (body, init) => new Response(body, init);
|
|
1458
|
+
var Context = class {
|
|
1459
|
+
#rawRequest;
|
|
1460
|
+
#req;
|
|
1461
|
+
/**
|
|
1462
|
+
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
|
|
1463
|
+
*
|
|
1464
|
+
* @see {@link https://hono.dev/docs/api/context#env}
|
|
1465
|
+
*
|
|
1466
|
+
* @example
|
|
1467
|
+
* ```ts
|
|
1468
|
+
* // Environment object for Cloudflare Workers
|
|
1469
|
+
* app.get('*', async c => {
|
|
1470
|
+
* const counter = c.env.COUNTER
|
|
1471
|
+
* })
|
|
1472
|
+
* ```
|
|
1473
|
+
*/
|
|
1474
|
+
env = {};
|
|
1475
|
+
#var;
|
|
1476
|
+
finalized = false;
|
|
1477
|
+
/**
|
|
1478
|
+
* `.error` can get the error object from the middleware if the Handler throws an error.
|
|
1479
|
+
*
|
|
1480
|
+
* @see {@link https://hono.dev/docs/api/context#error}
|
|
1481
|
+
*
|
|
1482
|
+
* @example
|
|
1483
|
+
* ```ts
|
|
1484
|
+
* app.use('*', async (c, next) => {
|
|
1485
|
+
* await next()
|
|
1486
|
+
* if (c.error) {
|
|
1487
|
+
* // do something...
|
|
1488
|
+
* }
|
|
1489
|
+
* })
|
|
1490
|
+
* ```
|
|
1491
|
+
*/
|
|
1492
|
+
error;
|
|
1493
|
+
#status;
|
|
1494
|
+
#executionCtx;
|
|
1495
|
+
#res;
|
|
1496
|
+
#layout;
|
|
1497
|
+
#renderer;
|
|
1498
|
+
#notFoundHandler;
|
|
1499
|
+
#preparedHeaders;
|
|
1500
|
+
#matchResult;
|
|
1501
|
+
#path;
|
|
1502
|
+
/**
|
|
1503
|
+
* Creates an instance of the Context class.
|
|
1504
|
+
*
|
|
1505
|
+
* @param req - The Request object.
|
|
1506
|
+
* @param options - Optional configuration options for the context.
|
|
1507
|
+
*/
|
|
1508
|
+
constructor(req, options) {
|
|
1509
|
+
this.#rawRequest = req;
|
|
1510
|
+
if (options) {
|
|
1511
|
+
this.#executionCtx = options.executionCtx;
|
|
1512
|
+
this.env = options.env;
|
|
1513
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1514
|
+
this.#path = options.path;
|
|
1515
|
+
this.#matchResult = options.matchResult;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* `.req` is the instance of {@link HonoRequest}.
|
|
1520
|
+
*/
|
|
1521
|
+
get req() {
|
|
1522
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1523
|
+
return this.#req;
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* @see {@link https://hono.dev/docs/api/context#event}
|
|
1527
|
+
* The FetchEvent associated with the current request.
|
|
1528
|
+
*
|
|
1529
|
+
* @throws Will throw an error if the context does not have a FetchEvent.
|
|
1530
|
+
*/
|
|
1531
|
+
get event() {
|
|
1532
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1533
|
+
return this.#executionCtx;
|
|
1534
|
+
} else {
|
|
1535
|
+
throw Error("This context has no FetchEvent");
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* @see {@link https://hono.dev/docs/api/context#executionctx}
|
|
1540
|
+
* The ExecutionContext associated with the current request.
|
|
1541
|
+
*
|
|
1542
|
+
* @throws Will throw an error if the context does not have an ExecutionContext.
|
|
1543
|
+
*/
|
|
1544
|
+
get executionCtx() {
|
|
1545
|
+
if (this.#executionCtx) {
|
|
1546
|
+
return this.#executionCtx;
|
|
1547
|
+
} else {
|
|
1548
|
+
throw Error("This context has no ExecutionContext");
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* @see {@link https://hono.dev/docs/api/context#res}
|
|
1553
|
+
* The Response object for the current request.
|
|
1554
|
+
*/
|
|
1555
|
+
get res() {
|
|
1556
|
+
return this.#res ||= createResponseInstance(null, {
|
|
1557
|
+
headers: this.#preparedHeaders ??= new Headers()
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* Sets the Response object for the current request.
|
|
1562
|
+
*
|
|
1563
|
+
* @param _res - The Response object to set.
|
|
1564
|
+
*/
|
|
1565
|
+
set res(_res) {
|
|
1566
|
+
if (this.#res && _res) {
|
|
1567
|
+
_res = createResponseInstance(_res.body, _res);
|
|
1568
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1569
|
+
if (k === "content-type") {
|
|
1570
|
+
continue;
|
|
1571
|
+
}
|
|
1572
|
+
if (k === "set-cookie") {
|
|
1573
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1574
|
+
_res.headers.delete("set-cookie");
|
|
1575
|
+
for (const cookie of cookies) {
|
|
1576
|
+
_res.headers.append("set-cookie", cookie);
|
|
1577
|
+
}
|
|
1578
|
+
} else {
|
|
1579
|
+
_res.headers.set(k, v);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
this.#res = _res;
|
|
1584
|
+
this.finalized = true;
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* `.render()` can create a response within a layout.
|
|
1588
|
+
*
|
|
1589
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1590
|
+
*
|
|
1591
|
+
* @example
|
|
1592
|
+
* ```ts
|
|
1593
|
+
* app.get('/', (c) => {
|
|
1594
|
+
* return c.render('Hello!')
|
|
1595
|
+
* })
|
|
1596
|
+
* ```
|
|
1597
|
+
*/
|
|
1598
|
+
render = (...args) => {
|
|
1599
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1600
|
+
return this.#renderer(...args);
|
|
1601
|
+
};
|
|
1602
|
+
/**
|
|
1603
|
+
* Sets the layout for the response.
|
|
1604
|
+
*
|
|
1605
|
+
* @param layout - The layout to set.
|
|
1606
|
+
* @returns The layout function.
|
|
1607
|
+
*/
|
|
1608
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1609
|
+
/**
|
|
1610
|
+
* Gets the current layout for the response.
|
|
1611
|
+
*
|
|
1612
|
+
* @returns The current layout function.
|
|
1613
|
+
*/
|
|
1614
|
+
getLayout = () => this.#layout;
|
|
1615
|
+
/**
|
|
1616
|
+
* `.setRenderer()` can set the layout in the custom middleware.
|
|
1617
|
+
*
|
|
1618
|
+
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
|
|
1619
|
+
*
|
|
1620
|
+
* @example
|
|
1621
|
+
* ```tsx
|
|
1622
|
+
* app.use('*', async (c, next) => {
|
|
1623
|
+
* c.setRenderer((content) => {
|
|
1624
|
+
* return c.html(
|
|
1625
|
+
* <html>
|
|
1626
|
+
* <body>
|
|
1627
|
+
* <p>{content}</p>
|
|
1628
|
+
* </body>
|
|
1629
|
+
* </html>
|
|
1630
|
+
* )
|
|
1631
|
+
* })
|
|
1632
|
+
* await next()
|
|
1633
|
+
* })
|
|
1634
|
+
* ```
|
|
1635
|
+
*/
|
|
1636
|
+
setRenderer = (renderer) => {
|
|
1637
|
+
this.#renderer = renderer;
|
|
1638
|
+
};
|
|
1639
|
+
/**
|
|
1640
|
+
* `.header()` can set headers.
|
|
1641
|
+
*
|
|
1642
|
+
* @see {@link https://hono.dev/docs/api/context#header}
|
|
1643
|
+
*
|
|
1644
|
+
* @example
|
|
1645
|
+
* ```ts
|
|
1646
|
+
* app.get('/welcome', (c) => {
|
|
1647
|
+
* // Set headers
|
|
1648
|
+
* c.header('X-Message', 'Hello!')
|
|
1649
|
+
* c.header('Content-Type', 'text/plain')
|
|
1650
|
+
*
|
|
1651
|
+
* return c.body('Thank you for coming')
|
|
1652
|
+
* })
|
|
1653
|
+
* ```
|
|
1654
|
+
*/
|
|
1655
|
+
header = (name, value, options) => {
|
|
1656
|
+
if (this.finalized) {
|
|
1657
|
+
this.#res = createResponseInstance(this.#res.body, this.#res);
|
|
1658
|
+
}
|
|
1659
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
1660
|
+
if (value === void 0) {
|
|
1661
|
+
headers.delete(name);
|
|
1662
|
+
} else if (options?.append) {
|
|
1663
|
+
headers.append(name, value);
|
|
1664
|
+
} else {
|
|
1665
|
+
headers.set(name, value);
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
status = (status) => {
|
|
1669
|
+
this.#status = status;
|
|
1670
|
+
};
|
|
1671
|
+
/**
|
|
1672
|
+
* `.set()` can set the value specified by the key.
|
|
1673
|
+
*
|
|
1674
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1675
|
+
*
|
|
1676
|
+
* @example
|
|
1677
|
+
* ```ts
|
|
1678
|
+
* app.use('*', async (c, next) => {
|
|
1679
|
+
* c.set('message', 'Hono is hot!!')
|
|
1680
|
+
* await next()
|
|
1681
|
+
* })
|
|
1682
|
+
* ```
|
|
1683
|
+
*/
|
|
1684
|
+
set = (key, value) => {
|
|
1685
|
+
this.#var ??= /* @__PURE__ */ new Map();
|
|
1686
|
+
this.#var.set(key, value);
|
|
1687
|
+
};
|
|
1688
|
+
/**
|
|
1689
|
+
* `.get()` can use the value specified by the key.
|
|
1690
|
+
*
|
|
1691
|
+
* @see {@link https://hono.dev/docs/api/context#set-get}
|
|
1692
|
+
*
|
|
1693
|
+
* @example
|
|
1694
|
+
* ```ts
|
|
1695
|
+
* app.get('/', (c) => {
|
|
1696
|
+
* const message = c.get('message')
|
|
1697
|
+
* return c.text(`The message is "${message}"`)
|
|
1698
|
+
* })
|
|
1699
|
+
* ```
|
|
1700
|
+
*/
|
|
1701
|
+
get = (key) => {
|
|
1702
|
+
return this.#var ? this.#var.get(key) : void 0;
|
|
1703
|
+
};
|
|
1704
|
+
/**
|
|
1705
|
+
* `.var` can access the value of a variable.
|
|
1706
|
+
*
|
|
1707
|
+
* @see {@link https://hono.dev/docs/api/context#var}
|
|
1708
|
+
*
|
|
1709
|
+
* @example
|
|
1710
|
+
* ```ts
|
|
1711
|
+
* const result = c.var.client.oneMethod()
|
|
1712
|
+
* ```
|
|
1713
|
+
*/
|
|
1714
|
+
// c.var.propName is a read-only
|
|
1715
|
+
get var() {
|
|
1716
|
+
if (!this.#var) {
|
|
1717
|
+
return {};
|
|
1718
|
+
}
|
|
1719
|
+
return Object.fromEntries(this.#var);
|
|
1720
|
+
}
|
|
1721
|
+
#newResponse(data, arg, headers) {
|
|
1722
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
1723
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
1724
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
1725
|
+
for (const [key, value] of argHeaders) {
|
|
1726
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1727
|
+
responseHeaders.append(key, value);
|
|
1728
|
+
} else {
|
|
1729
|
+
responseHeaders.set(key, value);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
if (headers) {
|
|
1734
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1735
|
+
if (typeof v === "string") {
|
|
1736
|
+
responseHeaders.set(k, v);
|
|
1737
|
+
} else {
|
|
1738
|
+
responseHeaders.delete(k);
|
|
1739
|
+
for (const v2 of v) {
|
|
1740
|
+
responseHeaders.append(k, v2);
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1746
|
+
return createResponseInstance(data, { status, headers: responseHeaders });
|
|
1747
|
+
}
|
|
1748
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1749
|
+
/**
|
|
1750
|
+
* `.body()` can return the HTTP response.
|
|
1751
|
+
* You can set headers with `.header()` and set HTTP status code with `.status`.
|
|
1752
|
+
* This can also be set in `.text()`, `.json()` and so on.
|
|
1753
|
+
*
|
|
1754
|
+
* @see {@link https://hono.dev/docs/api/context#body}
|
|
1755
|
+
*
|
|
1756
|
+
* @example
|
|
1757
|
+
* ```ts
|
|
1758
|
+
* app.get('/welcome', (c) => {
|
|
1759
|
+
* // Set headers
|
|
1760
|
+
* c.header('X-Message', 'Hello!')
|
|
1761
|
+
* c.header('Content-Type', 'text/plain')
|
|
1762
|
+
* // Set HTTP status code
|
|
1763
|
+
* c.status(201)
|
|
1764
|
+
*
|
|
1765
|
+
* // Return the response body
|
|
1766
|
+
* return c.body('Thank you for coming')
|
|
1767
|
+
* })
|
|
1768
|
+
* ```
|
|
1769
|
+
*/
|
|
1770
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1771
|
+
/**
|
|
1772
|
+
* `.text()` can render text as `Content-Type:text/plain`.
|
|
1773
|
+
*
|
|
1774
|
+
* @see {@link https://hono.dev/docs/api/context#text}
|
|
1775
|
+
*
|
|
1776
|
+
* @example
|
|
1777
|
+
* ```ts
|
|
1778
|
+
* app.get('/say', (c) => {
|
|
1779
|
+
* return c.text('Hello!')
|
|
1780
|
+
* })
|
|
1781
|
+
* ```
|
|
1782
|
+
*/
|
|
1783
|
+
text = (text, arg, headers) => {
|
|
1784
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
1785
|
+
text,
|
|
1786
|
+
arg,
|
|
1787
|
+
setDefaultContentType(TEXT_PLAIN, headers)
|
|
1788
|
+
);
|
|
1789
|
+
};
|
|
1790
|
+
/**
|
|
1791
|
+
* `.json()` can render JSON as `Content-Type:application/json`.
|
|
1792
|
+
*
|
|
1793
|
+
* @see {@link https://hono.dev/docs/api/context#json}
|
|
1794
|
+
*
|
|
1795
|
+
* @example
|
|
1796
|
+
* ```ts
|
|
1797
|
+
* app.get('/api', (c) => {
|
|
1798
|
+
* return c.json({ message: 'Hello!' })
|
|
1799
|
+
* })
|
|
1800
|
+
* ```
|
|
1801
|
+
*/
|
|
1802
|
+
json = (object, arg, headers) => {
|
|
1803
|
+
return this.#newResponse(
|
|
1804
|
+
JSON.stringify(object),
|
|
1805
|
+
arg,
|
|
1806
|
+
setDefaultContentType("application/json", headers)
|
|
1807
|
+
);
|
|
1808
|
+
};
|
|
1809
|
+
html = (html, arg, headers) => {
|
|
1810
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1811
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1812
|
+
};
|
|
1813
|
+
/**
|
|
1814
|
+
* `.redirect()` can Redirect, default status code is 302.
|
|
1815
|
+
*
|
|
1816
|
+
* @see {@link https://hono.dev/docs/api/context#redirect}
|
|
1817
|
+
*
|
|
1818
|
+
* @example
|
|
1819
|
+
* ```ts
|
|
1820
|
+
* app.get('/redirect', (c) => {
|
|
1821
|
+
* return c.redirect('/')
|
|
1822
|
+
* })
|
|
1823
|
+
* app.get('/redirect-permanently', (c) => {
|
|
1824
|
+
* return c.redirect('/', 301)
|
|
1825
|
+
* })
|
|
1826
|
+
* ```
|
|
1827
|
+
*/
|
|
1828
|
+
redirect = (location, status) => {
|
|
1829
|
+
const locationString = String(location);
|
|
1830
|
+
this.header(
|
|
1831
|
+
"Location",
|
|
1832
|
+
// Multibyes should be encoded
|
|
1833
|
+
// eslint-disable-next-line no-control-regex
|
|
1834
|
+
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
1835
|
+
);
|
|
1836
|
+
return this.newResponse(null, status ?? 302);
|
|
1837
|
+
};
|
|
1838
|
+
/**
|
|
1839
|
+
* `.notFound()` can return the Not Found Response.
|
|
1840
|
+
*
|
|
1841
|
+
* @see {@link https://hono.dev/docs/api/context#notfound}
|
|
1842
|
+
*
|
|
1843
|
+
* @example
|
|
1844
|
+
* ```ts
|
|
1845
|
+
* app.get('/notfound', (c) => {
|
|
1846
|
+
* return c.notFound()
|
|
1847
|
+
* })
|
|
1848
|
+
* ```
|
|
1849
|
+
*/
|
|
1850
|
+
notFound = () => {
|
|
1851
|
+
this.#notFoundHandler ??= () => createResponseInstance();
|
|
1852
|
+
return this.#notFoundHandler(this);
|
|
1853
|
+
};
|
|
1854
|
+
};
|
|
1855
|
+
|
|
1856
|
+
// node_modules/hono/dist/router.js
|
|
1857
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1858
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1859
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1860
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1861
|
+
var UnsupportedPathError = class extends Error {
|
|
1862
|
+
};
|
|
1863
|
+
|
|
1864
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1865
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1866
|
+
|
|
1867
|
+
// node_modules/hono/dist/hono-base.js
|
|
1868
|
+
var notFoundHandler = (c) => {
|
|
1869
|
+
return c.text("404 Not Found", 404);
|
|
1870
|
+
};
|
|
1871
|
+
var errorHandler = (err, c) => {
|
|
1872
|
+
if ("getResponse" in err) {
|
|
1873
|
+
const res = err.getResponse();
|
|
1874
|
+
return c.newResponse(res.body, res);
|
|
1875
|
+
}
|
|
1876
|
+
console.error(err);
|
|
1877
|
+
return c.text("Internal Server Error", 500);
|
|
1878
|
+
};
|
|
1879
|
+
var Hono = class _Hono {
|
|
1880
|
+
get;
|
|
1881
|
+
post;
|
|
1882
|
+
put;
|
|
1883
|
+
delete;
|
|
1884
|
+
options;
|
|
1885
|
+
patch;
|
|
1886
|
+
all;
|
|
1887
|
+
on;
|
|
1888
|
+
use;
|
|
1889
|
+
/*
|
|
1890
|
+
This class is like an abstract class and does not have a router.
|
|
1891
|
+
To use it, inherit the class and implement router in the constructor.
|
|
1892
|
+
*/
|
|
1893
|
+
router;
|
|
1894
|
+
getPath;
|
|
1895
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1896
|
+
_basePath = "/";
|
|
1897
|
+
#path = "/";
|
|
1898
|
+
routes = [];
|
|
1899
|
+
constructor(options = {}) {
|
|
1900
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1901
|
+
allMethods.forEach((method) => {
|
|
1902
|
+
this[method] = (args1, ...args) => {
|
|
1903
|
+
if (typeof args1 === "string") {
|
|
1904
|
+
this.#path = args1;
|
|
1905
|
+
} else {
|
|
1906
|
+
this.#addRoute(method, this.#path, args1);
|
|
1907
|
+
}
|
|
1908
|
+
args.forEach((handler) => {
|
|
1909
|
+
this.#addRoute(method, this.#path, handler);
|
|
1910
|
+
});
|
|
1911
|
+
return this;
|
|
1912
|
+
};
|
|
1913
|
+
});
|
|
1914
|
+
this.on = (method, path, ...handlers) => {
|
|
1915
|
+
for (const p of [path].flat()) {
|
|
1916
|
+
this.#path = p;
|
|
1917
|
+
for (const m of [method].flat()) {
|
|
1918
|
+
handlers.map((handler) => {
|
|
1919
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1920
|
+
});
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
return this;
|
|
1924
|
+
};
|
|
1925
|
+
this.use = (arg1, ...handlers) => {
|
|
1926
|
+
if (typeof arg1 === "string") {
|
|
1927
|
+
this.#path = arg1;
|
|
1928
|
+
} else {
|
|
1929
|
+
this.#path = "*";
|
|
1930
|
+
handlers.unshift(arg1);
|
|
1931
|
+
}
|
|
1932
|
+
handlers.forEach((handler) => {
|
|
1933
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1934
|
+
});
|
|
1935
|
+
return this;
|
|
1936
|
+
};
|
|
1937
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1938
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1939
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1940
|
+
}
|
|
1941
|
+
#clone() {
|
|
1942
|
+
const clone = new _Hono({
|
|
1943
|
+
router: this.router,
|
|
1944
|
+
getPath: this.getPath
|
|
1945
|
+
});
|
|
1946
|
+
clone.errorHandler = this.errorHandler;
|
|
1947
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1948
|
+
clone.routes = this.routes;
|
|
1949
|
+
return clone;
|
|
1950
|
+
}
|
|
1951
|
+
#notFoundHandler = notFoundHandler;
|
|
1952
|
+
// Cannot use `#` because it requires visibility at JavaScript runtime.
|
|
1953
|
+
errorHandler = errorHandler;
|
|
1954
|
+
/**
|
|
1955
|
+
* `.route()` allows grouping other Hono instance in routes.
|
|
1956
|
+
*
|
|
1957
|
+
* @see {@link https://hono.dev/docs/api/routing#grouping}
|
|
1958
|
+
*
|
|
1959
|
+
* @param {string} path - base Path
|
|
1960
|
+
* @param {Hono} app - other Hono instance
|
|
1961
|
+
* @returns {Hono} routed Hono instance
|
|
1962
|
+
*
|
|
1963
|
+
* @example
|
|
1964
|
+
* ```ts
|
|
1965
|
+
* const app = new Hono()
|
|
1966
|
+
* const app2 = new Hono()
|
|
1967
|
+
*
|
|
1968
|
+
* app2.get("/user", (c) => c.text("user"))
|
|
1969
|
+
* app.route("/api", app2) // GET /api/user
|
|
1970
|
+
* ```
|
|
1971
|
+
*/
|
|
1972
|
+
route(path, app) {
|
|
1973
|
+
const subApp = this.basePath(path);
|
|
1974
|
+
app.routes.map((r) => {
|
|
1975
|
+
let handler;
|
|
1976
|
+
if (app.errorHandler === errorHandler) {
|
|
1977
|
+
handler = r.handler;
|
|
1978
|
+
} else {
|
|
1979
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1980
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1981
|
+
}
|
|
1982
|
+
subApp.#addRoute(r.method, r.path, handler, r.basePath);
|
|
1983
|
+
});
|
|
1984
|
+
return this;
|
|
1985
|
+
}
|
|
1986
|
+
/**
|
|
1987
|
+
* `.basePath()` allows base paths to be specified.
|
|
1988
|
+
*
|
|
1989
|
+
* @see {@link https://hono.dev/docs/api/routing#base-path}
|
|
1990
|
+
*
|
|
1991
|
+
* @param {string} path - base Path
|
|
1992
|
+
* @returns {Hono} changed Hono instance
|
|
1993
|
+
*
|
|
1994
|
+
* @example
|
|
1995
|
+
* ```ts
|
|
1996
|
+
* const api = new Hono().basePath('/api')
|
|
1997
|
+
* ```
|
|
1998
|
+
*/
|
|
1999
|
+
basePath(path) {
|
|
2000
|
+
const subApp = this.#clone();
|
|
2001
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
2002
|
+
return subApp;
|
|
2003
|
+
}
|
|
2004
|
+
/**
|
|
2005
|
+
* `.onError()` handles an error and returns a customized Response.
|
|
2006
|
+
*
|
|
2007
|
+
* @see {@link https://hono.dev/docs/api/hono#error-handling}
|
|
2008
|
+
*
|
|
2009
|
+
* @param {ErrorHandler} handler - request Handler for error
|
|
2010
|
+
* @returns {Hono} changed Hono instance
|
|
2011
|
+
*
|
|
2012
|
+
* @example
|
|
2013
|
+
* ```ts
|
|
2014
|
+
* app.onError((err, c) => {
|
|
2015
|
+
* console.error(`${err}`)
|
|
2016
|
+
* return c.text('Custom Error Message', 500)
|
|
2017
|
+
* })
|
|
2018
|
+
* ```
|
|
2019
|
+
*/
|
|
2020
|
+
onError = (handler) => {
|
|
2021
|
+
this.errorHandler = handler;
|
|
2022
|
+
return this;
|
|
2023
|
+
};
|
|
2024
|
+
/**
|
|
2025
|
+
* `.notFound()` allows you to customize a Not Found Response.
|
|
2026
|
+
*
|
|
2027
|
+
* @see {@link https://hono.dev/docs/api/hono#not-found}
|
|
2028
|
+
*
|
|
2029
|
+
* @param {NotFoundHandler} handler - request handler for not-found
|
|
2030
|
+
* @returns {Hono} changed Hono instance
|
|
2031
|
+
*
|
|
2032
|
+
* @example
|
|
2033
|
+
* ```ts
|
|
2034
|
+
* app.notFound((c) => {
|
|
2035
|
+
* return c.text('Custom 404 Message', 404)
|
|
2036
|
+
* })
|
|
2037
|
+
* ```
|
|
2038
|
+
*/
|
|
2039
|
+
notFound = (handler) => {
|
|
2040
|
+
this.#notFoundHandler = handler;
|
|
2041
|
+
return this;
|
|
2042
|
+
};
|
|
2043
|
+
/**
|
|
2044
|
+
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
|
|
2045
|
+
*
|
|
2046
|
+
* @see {@link https://hono.dev/docs/api/hono#mount}
|
|
2047
|
+
*
|
|
2048
|
+
* @param {string} path - base Path
|
|
2049
|
+
* @param {Function} applicationHandler - other Request Handler
|
|
2050
|
+
* @param {MountOptions} [options] - options of `.mount()`
|
|
2051
|
+
* @returns {Hono} mounted Hono instance
|
|
2052
|
+
*
|
|
2053
|
+
* @example
|
|
2054
|
+
* ```ts
|
|
2055
|
+
* import { Router as IttyRouter } from 'itty-router'
|
|
2056
|
+
* import { Hono } from 'hono'
|
|
2057
|
+
* // Create itty-router application
|
|
2058
|
+
* const ittyRouter = IttyRouter()
|
|
2059
|
+
* // GET /itty-router/hello
|
|
2060
|
+
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
|
|
2061
|
+
*
|
|
2062
|
+
* const app = new Hono()
|
|
2063
|
+
* app.mount('/itty-router', ittyRouter.handle)
|
|
2064
|
+
* ```
|
|
2065
|
+
*
|
|
2066
|
+
* @example
|
|
2067
|
+
* ```ts
|
|
2068
|
+
* const app = new Hono()
|
|
2069
|
+
* // Send the request to another application without modification.
|
|
2070
|
+
* app.mount('/app', anotherApp, {
|
|
2071
|
+
* replaceRequest: (req) => req,
|
|
2072
|
+
* })
|
|
2073
|
+
* ```
|
|
2074
|
+
*/
|
|
2075
|
+
mount(path, applicationHandler, options) {
|
|
2076
|
+
let replaceRequest;
|
|
2077
|
+
let optionHandler;
|
|
2078
|
+
if (options) {
|
|
2079
|
+
if (typeof options === "function") {
|
|
2080
|
+
optionHandler = options;
|
|
2081
|
+
} else {
|
|
2082
|
+
optionHandler = options.optionHandler;
|
|
2083
|
+
if (options.replaceRequest === false) {
|
|
2084
|
+
replaceRequest = (request) => request;
|
|
2085
|
+
} else {
|
|
2086
|
+
replaceRequest = options.replaceRequest;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
const getOptions = optionHandler ? (c) => {
|
|
2091
|
+
const options2 = optionHandler(c);
|
|
2092
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
2093
|
+
} : (c) => {
|
|
2094
|
+
let executionContext = void 0;
|
|
2095
|
+
try {
|
|
2096
|
+
executionContext = c.executionCtx;
|
|
2097
|
+
} catch {
|
|
2098
|
+
}
|
|
2099
|
+
return [c.env, executionContext];
|
|
2100
|
+
};
|
|
2101
|
+
replaceRequest ||= (() => {
|
|
2102
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
2103
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
2104
|
+
return (request) => {
|
|
2105
|
+
const url = new URL(request.url);
|
|
2106
|
+
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
|
|
2107
|
+
return new Request(url, request);
|
|
2108
|
+
};
|
|
2109
|
+
})();
|
|
2110
|
+
const handler = async (c, next) => {
|
|
2111
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
2112
|
+
if (res) {
|
|
2113
|
+
return res;
|
|
2114
|
+
}
|
|
2115
|
+
await next();
|
|
2116
|
+
};
|
|
2117
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
2118
|
+
return this;
|
|
2119
|
+
}
|
|
2120
|
+
#addRoute(method, path, handler, baseRoutePath) {
|
|
2121
|
+
method = method.toUpperCase();
|
|
2122
|
+
path = mergePath(this._basePath, path);
|
|
2123
|
+
const r = {
|
|
2124
|
+
basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
|
|
2125
|
+
path,
|
|
2126
|
+
method,
|
|
2127
|
+
handler
|
|
2128
|
+
};
|
|
2129
|
+
this.router.add(method, path, [handler, r]);
|
|
2130
|
+
this.routes.push(r);
|
|
2131
|
+
}
|
|
2132
|
+
#handleError(err, c) {
|
|
2133
|
+
if (err instanceof Error) {
|
|
2134
|
+
return this.errorHandler(err, c);
|
|
2135
|
+
}
|
|
2136
|
+
throw err;
|
|
2137
|
+
}
|
|
2138
|
+
#dispatch(request, executionCtx, env, method) {
|
|
2139
|
+
if (method === "HEAD") {
|
|
2140
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
2141
|
+
}
|
|
2142
|
+
const path = this.getPath(request, { env });
|
|
2143
|
+
const matchResult = this.router.match(method, path);
|
|
2144
|
+
const c = new Context(request, {
|
|
2145
|
+
path,
|
|
2146
|
+
matchResult,
|
|
2147
|
+
env,
|
|
2148
|
+
executionCtx,
|
|
2149
|
+
notFoundHandler: this.#notFoundHandler
|
|
2150
|
+
});
|
|
2151
|
+
if (matchResult[0].length === 1) {
|
|
2152
|
+
let res;
|
|
2153
|
+
try {
|
|
2154
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
2155
|
+
c.res = await this.#notFoundHandler(c);
|
|
2156
|
+
});
|
|
2157
|
+
} catch (err) {
|
|
2158
|
+
return this.#handleError(err, c);
|
|
2159
|
+
}
|
|
2160
|
+
return res instanceof Promise ? res.then(
|
|
2161
|
+
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
2162
|
+
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
2163
|
+
}
|
|
2164
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
2165
|
+
return (async () => {
|
|
2166
|
+
try {
|
|
2167
|
+
const context = await composed(c);
|
|
2168
|
+
if (!context.finalized) {
|
|
2169
|
+
throw new Error(
|
|
2170
|
+
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
2171
|
+
);
|
|
2172
|
+
}
|
|
2173
|
+
return context.res;
|
|
2174
|
+
} catch (err) {
|
|
2175
|
+
return this.#handleError(err, c);
|
|
2176
|
+
}
|
|
2177
|
+
})();
|
|
2178
|
+
}
|
|
2179
|
+
/**
|
|
2180
|
+
* `.fetch()` will be entry point of your app.
|
|
2181
|
+
*
|
|
2182
|
+
* @see {@link https://hono.dev/docs/api/hono#fetch}
|
|
2183
|
+
*
|
|
2184
|
+
* @param {Request} request - request Object of request
|
|
2185
|
+
* @param {Env} Env - env Object
|
|
2186
|
+
* @param {ExecutionContext} - context of execution
|
|
2187
|
+
* @returns {Response | Promise<Response>} response of request
|
|
2188
|
+
*
|
|
2189
|
+
*/
|
|
2190
|
+
fetch = (request, ...rest) => {
|
|
2191
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
2192
|
+
};
|
|
2193
|
+
/**
|
|
2194
|
+
* `.request()` is a useful method for testing.
|
|
2195
|
+
* You can pass a URL or pathname to send a GET request.
|
|
2196
|
+
* app will return a Response object.
|
|
2197
|
+
* ```ts
|
|
2198
|
+
* test('GET /hello is ok', async () => {
|
|
2199
|
+
* const res = await app.request('/hello')
|
|
2200
|
+
* expect(res.status).toBe(200)
|
|
2201
|
+
* })
|
|
2202
|
+
* ```
|
|
2203
|
+
* @see https://hono.dev/docs/api/hono#request
|
|
2204
|
+
*/
|
|
2205
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
2206
|
+
if (input instanceof Request) {
|
|
2207
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
2208
|
+
}
|
|
2209
|
+
input = input.toString();
|
|
2210
|
+
return this.fetch(
|
|
2211
|
+
new Request(
|
|
2212
|
+
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
2213
|
+
requestInit
|
|
2214
|
+
),
|
|
2215
|
+
Env,
|
|
2216
|
+
executionCtx
|
|
2217
|
+
);
|
|
2218
|
+
};
|
|
2219
|
+
/**
|
|
2220
|
+
* `.fire()` automatically adds a global fetch event listener.
|
|
2221
|
+
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
|
|
2222
|
+
* @deprecated
|
|
2223
|
+
* Use `fire` from `hono/service-worker` instead.
|
|
2224
|
+
* ```ts
|
|
2225
|
+
* import { Hono } from 'hono'
|
|
2226
|
+
* import { fire } from 'hono/service-worker'
|
|
2227
|
+
*
|
|
2228
|
+
* const app = new Hono()
|
|
2229
|
+
* // ...
|
|
2230
|
+
* fire(app)
|
|
2231
|
+
* ```
|
|
2232
|
+
* @see https://hono.dev/docs/api/hono#fire
|
|
2233
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
|
|
2234
|
+
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
|
|
2235
|
+
*/
|
|
2236
|
+
fire = () => {
|
|
2237
|
+
addEventListener("fetch", (event) => {
|
|
2238
|
+
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
2239
|
+
});
|
|
2240
|
+
};
|
|
2241
|
+
};
|
|
2242
|
+
|
|
2243
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
2244
|
+
var emptyParam = [];
|
|
2245
|
+
function match(method, path) {
|
|
2246
|
+
const matchers = this.buildAllMatchers();
|
|
2247
|
+
const match2 = ((method2, path2) => {
|
|
2248
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
2249
|
+
const staticMatch = matcher[2][path2];
|
|
2250
|
+
if (staticMatch) {
|
|
2251
|
+
return staticMatch;
|
|
2252
|
+
}
|
|
2253
|
+
const match3 = path2.match(matcher[0]);
|
|
2254
|
+
if (!match3) {
|
|
2255
|
+
return [[], emptyParam];
|
|
2256
|
+
}
|
|
2257
|
+
const index = match3.indexOf("", 1);
|
|
2258
|
+
return [matcher[1][index], match3];
|
|
2259
|
+
});
|
|
2260
|
+
this.match = match2;
|
|
2261
|
+
return match2(method, path);
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
2265
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
2266
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
2267
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
2268
|
+
var PATH_ERROR = /* @__PURE__ */ Symbol();
|
|
2269
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
2270
|
+
function compareKey(a, b) {
|
|
2271
|
+
if (a.length === 1) {
|
|
2272
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
2273
|
+
}
|
|
2274
|
+
if (b.length === 1) {
|
|
2275
|
+
return 1;
|
|
2276
|
+
}
|
|
2277
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2278
|
+
return 1;
|
|
2279
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
2280
|
+
return -1;
|
|
2281
|
+
}
|
|
2282
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
2283
|
+
return 1;
|
|
2284
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
2285
|
+
return -1;
|
|
2286
|
+
}
|
|
2287
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
2288
|
+
}
|
|
2289
|
+
var Node = class _Node {
|
|
2290
|
+
#index;
|
|
2291
|
+
#varIndex;
|
|
2292
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
2293
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
2294
|
+
if (tokens.length === 0) {
|
|
2295
|
+
if (this.#index !== void 0) {
|
|
2296
|
+
throw PATH_ERROR;
|
|
2297
|
+
}
|
|
2298
|
+
if (pathErrorCheckOnly) {
|
|
2299
|
+
return;
|
|
2300
|
+
}
|
|
2301
|
+
this.#index = index;
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2304
|
+
const [token, ...restTokens] = tokens;
|
|
2305
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2306
|
+
let node;
|
|
2307
|
+
if (pattern) {
|
|
2308
|
+
const name = pattern[1];
|
|
2309
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
2310
|
+
if (name && pattern[2]) {
|
|
2311
|
+
if (regexpStr === ".*") {
|
|
2312
|
+
throw PATH_ERROR;
|
|
2313
|
+
}
|
|
2314
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
2315
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
2316
|
+
throw PATH_ERROR;
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
node = this.#children[regexpStr];
|
|
2320
|
+
if (!node) {
|
|
2321
|
+
if (Object.keys(this.#children).some(
|
|
2322
|
+
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2323
|
+
)) {
|
|
2324
|
+
throw PATH_ERROR;
|
|
2325
|
+
}
|
|
2326
|
+
if (pathErrorCheckOnly) {
|
|
2327
|
+
return;
|
|
2328
|
+
}
|
|
2329
|
+
node = this.#children[regexpStr] = new _Node();
|
|
2330
|
+
if (name !== "") {
|
|
2331
|
+
node.#varIndex = context.varIndex++;
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
2335
|
+
paramMap.push([name, node.#varIndex]);
|
|
2336
|
+
}
|
|
2337
|
+
} else {
|
|
2338
|
+
node = this.#children[token];
|
|
2339
|
+
if (!node) {
|
|
2340
|
+
if (Object.keys(this.#children).some(
|
|
2341
|
+
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
2342
|
+
)) {
|
|
2343
|
+
throw PATH_ERROR;
|
|
2344
|
+
}
|
|
2345
|
+
if (pathErrorCheckOnly) {
|
|
2346
|
+
return;
|
|
2347
|
+
}
|
|
2348
|
+
node = this.#children[token] = new _Node();
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
2352
|
+
}
|
|
2353
|
+
buildRegExpStr() {
|
|
2354
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
2355
|
+
const strList = childKeys.map((k) => {
|
|
2356
|
+
const c = this.#children[k];
|
|
2357
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
2358
|
+
});
|
|
2359
|
+
if (typeof this.#index === "number") {
|
|
2360
|
+
strList.unshift(`#${this.#index}`);
|
|
2361
|
+
}
|
|
2362
|
+
if (strList.length === 0) {
|
|
2363
|
+
return "";
|
|
2364
|
+
}
|
|
2365
|
+
if (strList.length === 1) {
|
|
2366
|
+
return strList[0];
|
|
2367
|
+
}
|
|
2368
|
+
return "(?:" + strList.join("|") + ")";
|
|
2369
|
+
}
|
|
2370
|
+
};
|
|
2371
|
+
|
|
2372
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
2373
|
+
var Trie = class {
|
|
2374
|
+
#context = { varIndex: 0 };
|
|
2375
|
+
#root = new Node();
|
|
2376
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
2377
|
+
const paramAssoc = [];
|
|
2378
|
+
const groups = [];
|
|
2379
|
+
for (let i = 0; ; ) {
|
|
2380
|
+
let replaced = false;
|
|
2381
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
2382
|
+
const mark = `@\\${i}`;
|
|
2383
|
+
groups[i] = [mark, m];
|
|
2384
|
+
i++;
|
|
2385
|
+
replaced = true;
|
|
2386
|
+
return mark;
|
|
2387
|
+
});
|
|
2388
|
+
if (!replaced) {
|
|
2389
|
+
break;
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
2393
|
+
for (let i = groups.length - 1; i >= 0; i--) {
|
|
2394
|
+
const [mark] = groups[i];
|
|
2395
|
+
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
2396
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
2397
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
2398
|
+
break;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
2403
|
+
return paramAssoc;
|
|
2404
|
+
}
|
|
2405
|
+
buildRegExp() {
|
|
2406
|
+
let regexp = this.#root.buildRegExpStr();
|
|
2407
|
+
if (regexp === "") {
|
|
2408
|
+
return [/^$/, [], []];
|
|
2409
|
+
}
|
|
2410
|
+
let captureIndex = 0;
|
|
2411
|
+
const indexReplacementMap = [];
|
|
2412
|
+
const paramReplacementMap = [];
|
|
2413
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
2414
|
+
if (handlerIndex !== void 0) {
|
|
2415
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
2416
|
+
return "$()";
|
|
2417
|
+
}
|
|
2418
|
+
if (paramIndex !== void 0) {
|
|
2419
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
2420
|
+
return "";
|
|
2421
|
+
}
|
|
2422
|
+
return "";
|
|
2423
|
+
});
|
|
2424
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
2425
|
+
}
|
|
2426
|
+
};
|
|
2427
|
+
|
|
2428
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
2429
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
2430
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2431
|
+
function buildWildcardRegExp(path) {
|
|
2432
|
+
return wildcardRegExpCache[path] ??= new RegExp(
|
|
2433
|
+
path === "*" ? "" : `^${path.replace(
|
|
2434
|
+
/\/\*$|([.\\+*[^\]$()])/g,
|
|
2435
|
+
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
2436
|
+
)}$`
|
|
2437
|
+
);
|
|
2438
|
+
}
|
|
2439
|
+
function clearWildcardRegExpCache() {
|
|
2440
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
2441
|
+
}
|
|
2442
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
2443
|
+
const trie = new Trie();
|
|
2444
|
+
const handlerData = [];
|
|
2445
|
+
if (routes.length === 0) {
|
|
2446
|
+
return nullMatcher;
|
|
2447
|
+
}
|
|
2448
|
+
const routesWithStaticPathFlag = routes.map(
|
|
2449
|
+
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
2450
|
+
).sort(
|
|
2451
|
+
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
2452
|
+
);
|
|
2453
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
2454
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
2455
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
2456
|
+
if (pathErrorCheckOnly) {
|
|
2457
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
2458
|
+
} else {
|
|
2459
|
+
j++;
|
|
2460
|
+
}
|
|
2461
|
+
let paramAssoc;
|
|
2462
|
+
try {
|
|
2463
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
2464
|
+
} catch (e) {
|
|
2465
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
2466
|
+
}
|
|
2467
|
+
if (pathErrorCheckOnly) {
|
|
2468
|
+
continue;
|
|
2469
|
+
}
|
|
2470
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
2471
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
2472
|
+
paramCount -= 1;
|
|
2473
|
+
for (; paramCount >= 0; paramCount--) {
|
|
2474
|
+
const [key, value] = paramAssoc[paramCount];
|
|
2475
|
+
paramIndexMap[key] = value;
|
|
2476
|
+
}
|
|
2477
|
+
return [h, paramIndexMap];
|
|
2478
|
+
});
|
|
2479
|
+
}
|
|
2480
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
2481
|
+
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
2482
|
+
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
2483
|
+
const map = handlerData[i][j]?.[1];
|
|
2484
|
+
if (!map) {
|
|
2485
|
+
continue;
|
|
2486
|
+
}
|
|
2487
|
+
const keys = Object.keys(map);
|
|
2488
|
+
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
2489
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
const handlerMap = [];
|
|
2494
|
+
for (const i in indexReplacementMap) {
|
|
2495
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
2496
|
+
}
|
|
2497
|
+
return [regexp, handlerMap, staticMap];
|
|
2498
|
+
}
|
|
2499
|
+
function findMiddleware(middleware, path) {
|
|
2500
|
+
if (!middleware) {
|
|
2501
|
+
return void 0;
|
|
2502
|
+
}
|
|
2503
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
2504
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
2505
|
+
return [...middleware[k]];
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
return void 0;
|
|
2509
|
+
}
|
|
2510
|
+
var RegExpRouter = class {
|
|
2511
|
+
name = "RegExpRouter";
|
|
2512
|
+
#middleware;
|
|
2513
|
+
#routes;
|
|
2514
|
+
constructor() {
|
|
2515
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2516
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
2517
|
+
}
|
|
2518
|
+
add(method, path, handler) {
|
|
2519
|
+
const middleware = this.#middleware;
|
|
2520
|
+
const routes = this.#routes;
|
|
2521
|
+
if (!middleware || !routes) {
|
|
2522
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2523
|
+
}
|
|
2524
|
+
if (!middleware[method]) {
|
|
2525
|
+
;
|
|
2526
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
2527
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
2528
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
2529
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
2530
|
+
});
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
if (path === "/*") {
|
|
2534
|
+
path = "*";
|
|
2535
|
+
}
|
|
2536
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
2537
|
+
if (/\*$/.test(path)) {
|
|
2538
|
+
const re = buildWildcardRegExp(path);
|
|
2539
|
+
if (method === METHOD_NAME_ALL) {
|
|
2540
|
+
Object.keys(middleware).forEach((m) => {
|
|
2541
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2542
|
+
});
|
|
2543
|
+
} else {
|
|
2544
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
2545
|
+
}
|
|
2546
|
+
Object.keys(middleware).forEach((m) => {
|
|
2547
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2548
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
2549
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
2550
|
+
});
|
|
2551
|
+
}
|
|
2552
|
+
});
|
|
2553
|
+
Object.keys(routes).forEach((m) => {
|
|
2554
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2555
|
+
Object.keys(routes[m]).forEach(
|
|
2556
|
+
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
2557
|
+
);
|
|
2558
|
+
}
|
|
2559
|
+
});
|
|
2560
|
+
return;
|
|
2561
|
+
}
|
|
2562
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
2563
|
+
for (let i = 0, len = paths.length; i < len; i++) {
|
|
2564
|
+
const path2 = paths[i];
|
|
2565
|
+
Object.keys(routes).forEach((m) => {
|
|
2566
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
2567
|
+
routes[m][path2] ||= [
|
|
2568
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
2569
|
+
];
|
|
2570
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
2571
|
+
}
|
|
2572
|
+
});
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
match = match;
|
|
2576
|
+
buildAllMatchers() {
|
|
2577
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
2578
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
2579
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
2580
|
+
});
|
|
2581
|
+
this.#middleware = this.#routes = void 0;
|
|
2582
|
+
clearWildcardRegExpCache();
|
|
2583
|
+
return matchers;
|
|
2584
|
+
}
|
|
2585
|
+
#buildMatcher(method) {
|
|
2586
|
+
const routes = [];
|
|
2587
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
2588
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
2589
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
2590
|
+
if (ownRoute.length !== 0) {
|
|
2591
|
+
hasOwnRoute ||= true;
|
|
2592
|
+
routes.push(...ownRoute);
|
|
2593
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
2594
|
+
routes.push(
|
|
2595
|
+
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
});
|
|
2599
|
+
if (!hasOwnRoute) {
|
|
2600
|
+
return null;
|
|
2601
|
+
} else {
|
|
2602
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
};
|
|
2606
|
+
|
|
2607
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
2608
|
+
var SmartRouter = class {
|
|
2609
|
+
name = "SmartRouter";
|
|
2610
|
+
#routers = [];
|
|
2611
|
+
#routes = [];
|
|
2612
|
+
constructor(init) {
|
|
2613
|
+
this.#routers = init.routers;
|
|
2614
|
+
}
|
|
2615
|
+
add(method, path, handler) {
|
|
2616
|
+
if (!this.#routes) {
|
|
2617
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
2618
|
+
}
|
|
2619
|
+
this.#routes.push([method, path, handler]);
|
|
2620
|
+
}
|
|
2621
|
+
match(method, path) {
|
|
2622
|
+
if (!this.#routes) {
|
|
2623
|
+
throw new Error("Fatal error");
|
|
2624
|
+
}
|
|
2625
|
+
const routers = this.#routers;
|
|
2626
|
+
const routes = this.#routes;
|
|
2627
|
+
const len = routers.length;
|
|
2628
|
+
let i = 0;
|
|
2629
|
+
let res;
|
|
2630
|
+
for (; i < len; i++) {
|
|
2631
|
+
const router = routers[i];
|
|
2632
|
+
try {
|
|
2633
|
+
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
2634
|
+
router.add(...routes[i2]);
|
|
2635
|
+
}
|
|
2636
|
+
res = router.match(method, path);
|
|
2637
|
+
} catch (e) {
|
|
2638
|
+
if (e instanceof UnsupportedPathError) {
|
|
2639
|
+
continue;
|
|
2640
|
+
}
|
|
2641
|
+
throw e;
|
|
2642
|
+
}
|
|
2643
|
+
this.match = router.match.bind(router);
|
|
2644
|
+
this.#routers = [router];
|
|
2645
|
+
this.#routes = void 0;
|
|
2646
|
+
break;
|
|
2647
|
+
}
|
|
2648
|
+
if (i === len) {
|
|
2649
|
+
throw new Error("Fatal error");
|
|
2650
|
+
}
|
|
2651
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2652
|
+
return res;
|
|
2653
|
+
}
|
|
2654
|
+
get activeRouter() {
|
|
2655
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2656
|
+
throw new Error("No active router has been determined yet.");
|
|
2657
|
+
}
|
|
2658
|
+
return this.#routers[0];
|
|
2659
|
+
}
|
|
2660
|
+
};
|
|
2661
|
+
|
|
2662
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
2663
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
2664
|
+
var hasChildren = (children) => {
|
|
2665
|
+
for (const _ in children) {
|
|
2666
|
+
return true;
|
|
2667
|
+
}
|
|
2668
|
+
return false;
|
|
2669
|
+
};
|
|
2670
|
+
var Node2 = class _Node2 {
|
|
2671
|
+
#methods;
|
|
2672
|
+
#children;
|
|
2673
|
+
#patterns;
|
|
2674
|
+
#order = 0;
|
|
2675
|
+
#params = emptyParams;
|
|
2676
|
+
constructor(method, handler, children) {
|
|
2677
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
2678
|
+
this.#methods = [];
|
|
2679
|
+
if (method && handler) {
|
|
2680
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
2681
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
2682
|
+
this.#methods = [m];
|
|
2683
|
+
}
|
|
2684
|
+
this.#patterns = [];
|
|
2685
|
+
}
|
|
2686
|
+
insert(method, path, handler) {
|
|
2687
|
+
this.#order = ++this.#order;
|
|
2688
|
+
let curNode = this;
|
|
2689
|
+
const parts = splitRoutingPath(path);
|
|
2690
|
+
const possibleKeys = [];
|
|
2691
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
2692
|
+
const p = parts[i];
|
|
2693
|
+
const nextP = parts[i + 1];
|
|
2694
|
+
const pattern = getPattern(p, nextP);
|
|
2695
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
2696
|
+
if (key in curNode.#children) {
|
|
2697
|
+
curNode = curNode.#children[key];
|
|
2698
|
+
if (pattern) {
|
|
2699
|
+
possibleKeys.push(pattern[1]);
|
|
2700
|
+
}
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
curNode.#children[key] = new _Node2();
|
|
2704
|
+
if (pattern) {
|
|
2705
|
+
curNode.#patterns.push(pattern);
|
|
2706
|
+
possibleKeys.push(pattern[1]);
|
|
2707
|
+
}
|
|
2708
|
+
curNode = curNode.#children[key];
|
|
2709
|
+
}
|
|
2710
|
+
curNode.#methods.push({
|
|
2711
|
+
[method]: {
|
|
2712
|
+
handler,
|
|
2713
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
2714
|
+
score: this.#order
|
|
2715
|
+
}
|
|
2716
|
+
});
|
|
2717
|
+
return curNode;
|
|
2718
|
+
}
|
|
2719
|
+
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
|
|
2720
|
+
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
2721
|
+
const m = node.#methods[i];
|
|
2722
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2723
|
+
const processedSet = {};
|
|
2724
|
+
if (handlerSet !== void 0) {
|
|
2725
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
2726
|
+
handlerSets.push(handlerSet);
|
|
2727
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
2728
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
2729
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2730
|
+
const processed = processedSet[handlerSet.score];
|
|
2731
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2732
|
+
processedSet[handlerSet.score] = true;
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
search(method, path) {
|
|
2739
|
+
const handlerSets = [];
|
|
2740
|
+
this.#params = emptyParams;
|
|
2741
|
+
const curNode = this;
|
|
2742
|
+
let curNodes = [curNode];
|
|
2743
|
+
const parts = splitPath(path);
|
|
2744
|
+
const curNodesQueue = [];
|
|
2745
|
+
const len = parts.length;
|
|
2746
|
+
let partOffsets = null;
|
|
2747
|
+
for (let i = 0; i < len; i++) {
|
|
2748
|
+
const part = parts[i];
|
|
2749
|
+
const isLast = i === len - 1;
|
|
2750
|
+
const tempNodes = [];
|
|
2751
|
+
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
2752
|
+
const node = curNodes[j];
|
|
2753
|
+
const nextNode = node.#children[part];
|
|
2754
|
+
if (nextNode) {
|
|
2755
|
+
nextNode.#params = node.#params;
|
|
2756
|
+
if (isLast) {
|
|
2757
|
+
if (nextNode.#children["*"]) {
|
|
2758
|
+
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
|
|
2759
|
+
}
|
|
2760
|
+
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
|
|
2761
|
+
} else {
|
|
2762
|
+
tempNodes.push(nextNode);
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
2766
|
+
const pattern = node.#patterns[k];
|
|
2767
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2768
|
+
if (pattern === "*") {
|
|
2769
|
+
const astNode = node.#children["*"];
|
|
2770
|
+
if (astNode) {
|
|
2771
|
+
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
|
|
2772
|
+
astNode.#params = params;
|
|
2773
|
+
tempNodes.push(astNode);
|
|
2774
|
+
}
|
|
2775
|
+
continue;
|
|
2776
|
+
}
|
|
2777
|
+
const [key, name, matcher] = pattern;
|
|
2778
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
2779
|
+
continue;
|
|
2780
|
+
}
|
|
2781
|
+
const child = node.#children[key];
|
|
2782
|
+
if (matcher instanceof RegExp) {
|
|
2783
|
+
if (partOffsets === null) {
|
|
2784
|
+
partOffsets = new Array(len);
|
|
2785
|
+
let offset = path[0] === "/" ? 1 : 0;
|
|
2786
|
+
for (let p = 0; p < len; p++) {
|
|
2787
|
+
partOffsets[p] = offset;
|
|
2788
|
+
offset += parts[p].length + 1;
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
const restPathString = path.substring(partOffsets[i]);
|
|
2792
|
+
const m = matcher.exec(restPathString);
|
|
2793
|
+
if (m) {
|
|
2794
|
+
params[name] = m[0];
|
|
2795
|
+
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
|
|
2796
|
+
if (hasChildren(child.#children)) {
|
|
2797
|
+
child.#params = params;
|
|
2798
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2799
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2800
|
+
targetCurNodes.push(child);
|
|
2801
|
+
}
|
|
2802
|
+
continue;
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
if (matcher === true || matcher.test(part)) {
|
|
2806
|
+
params[name] = part;
|
|
2807
|
+
if (isLast) {
|
|
2808
|
+
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
|
|
2809
|
+
if (child.#children["*"]) {
|
|
2810
|
+
this.#pushHandlerSets(
|
|
2811
|
+
handlerSets,
|
|
2812
|
+
child.#children["*"],
|
|
2813
|
+
method,
|
|
2814
|
+
params,
|
|
2815
|
+
node.#params
|
|
2816
|
+
);
|
|
2817
|
+
}
|
|
2818
|
+
} else {
|
|
2819
|
+
child.#params = params;
|
|
2820
|
+
tempNodes.push(child);
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
const shifted = curNodesQueue.shift();
|
|
2826
|
+
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
|
|
2827
|
+
}
|
|
2828
|
+
if (handlerSets.length > 1) {
|
|
2829
|
+
handlerSets.sort((a, b) => {
|
|
2830
|
+
return a.score - b.score;
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2834
|
+
}
|
|
2835
|
+
};
|
|
2836
|
+
|
|
2837
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2838
|
+
var TrieRouter = class {
|
|
2839
|
+
name = "TrieRouter";
|
|
2840
|
+
#node;
|
|
2841
|
+
constructor() {
|
|
2842
|
+
this.#node = new Node2();
|
|
2843
|
+
}
|
|
2844
|
+
add(method, path, handler) {
|
|
2845
|
+
const results = checkOptionalParameter(path);
|
|
2846
|
+
if (results) {
|
|
2847
|
+
for (let i = 0, len = results.length; i < len; i++) {
|
|
2848
|
+
this.#node.insert(method, results[i], handler);
|
|
2849
|
+
}
|
|
2850
|
+
return;
|
|
2851
|
+
}
|
|
2852
|
+
this.#node.insert(method, path, handler);
|
|
2853
|
+
}
|
|
2854
|
+
match(method, path) {
|
|
2855
|
+
return this.#node.search(method, path);
|
|
2856
|
+
}
|
|
2857
|
+
};
|
|
2858
|
+
|
|
2859
|
+
// node_modules/hono/dist/hono.js
|
|
2860
|
+
var Hono2 = class extends Hono {
|
|
2861
|
+
/**
|
|
2862
|
+
* Creates an instance of the Hono class.
|
|
2863
|
+
*
|
|
2864
|
+
* @param options - Optional configuration options for the Hono instance.
|
|
2865
|
+
*/
|
|
2866
|
+
constructor(options = {}) {
|
|
2867
|
+
super(options);
|
|
2868
|
+
this.router = options.router ?? new SmartRouter({
|
|
2869
|
+
routers: [new RegExpRouter(), new TrieRouter()]
|
|
2870
|
+
});
|
|
2871
|
+
}
|
|
2872
|
+
};
|
|
2873
|
+
|
|
2874
|
+
// node_modules/@hono/node-server/dist/index.mjs
|
|
2875
|
+
import { createServer as createServerHTTP } from "http";
|
|
2876
|
+
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
2877
|
+
import { Http2ServerRequest } from "http2";
|
|
2878
|
+
import { Readable } from "stream";
|
|
2879
|
+
import crypto from "crypto";
|
|
2880
|
+
var RequestError = class extends Error {
|
|
2881
|
+
constructor(message, options) {
|
|
2882
|
+
super(message, options);
|
|
2883
|
+
this.name = "RequestError";
|
|
2884
|
+
}
|
|
2885
|
+
};
|
|
2886
|
+
var toRequestError = (e) => {
|
|
2887
|
+
if (e instanceof RequestError) {
|
|
2888
|
+
return e;
|
|
2889
|
+
}
|
|
2890
|
+
return new RequestError(e.message, { cause: e });
|
|
2891
|
+
};
|
|
2892
|
+
var GlobalRequest = global.Request;
|
|
2893
|
+
var Request2 = class extends GlobalRequest {
|
|
2894
|
+
constructor(input, options) {
|
|
2895
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
2896
|
+
input = input[getRequestCache]();
|
|
2897
|
+
}
|
|
2898
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
2899
|
+
;
|
|
2900
|
+
options.duplex ??= "half";
|
|
2901
|
+
}
|
|
2902
|
+
super(input, options);
|
|
2903
|
+
}
|
|
2904
|
+
};
|
|
2905
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
2906
|
+
const headerRecord = [];
|
|
2907
|
+
const rawHeaders = incoming.rawHeaders;
|
|
2908
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
2909
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
2910
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
2911
|
+
58) {
|
|
2912
|
+
headerRecord.push([key, value]);
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
return new Headers(headerRecord);
|
|
2916
|
+
};
|
|
2917
|
+
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
2918
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
2919
|
+
const init = {
|
|
2920
|
+
method,
|
|
2921
|
+
headers,
|
|
2922
|
+
signal: abortController.signal
|
|
2923
|
+
};
|
|
2924
|
+
if (method === "TRACE") {
|
|
2925
|
+
init.method = "GET";
|
|
2926
|
+
const req = new Request2(url, init);
|
|
2927
|
+
Object.defineProperty(req, "method", {
|
|
2928
|
+
get() {
|
|
2929
|
+
return "TRACE";
|
|
2930
|
+
}
|
|
2931
|
+
});
|
|
2932
|
+
return req;
|
|
2933
|
+
}
|
|
2934
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
2935
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
2936
|
+
init.body = new ReadableStream({
|
|
2937
|
+
start(controller) {
|
|
2938
|
+
controller.enqueue(incoming.rawBody);
|
|
2939
|
+
controller.close();
|
|
2940
|
+
}
|
|
2941
|
+
});
|
|
2942
|
+
} else if (incoming[wrapBodyStream]) {
|
|
2943
|
+
let reader;
|
|
2944
|
+
init.body = new ReadableStream({
|
|
2945
|
+
async pull(controller) {
|
|
2946
|
+
try {
|
|
2947
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
2948
|
+
const { done, value } = await reader.read();
|
|
2949
|
+
if (done) {
|
|
2950
|
+
controller.close();
|
|
2951
|
+
} else {
|
|
2952
|
+
controller.enqueue(value);
|
|
2953
|
+
}
|
|
2954
|
+
} catch (error) {
|
|
2955
|
+
controller.error(error);
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
});
|
|
2959
|
+
} else {
|
|
2960
|
+
init.body = Readable.toWeb(incoming);
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
return new Request2(url, init);
|
|
2964
|
+
};
|
|
2965
|
+
var getRequestCache = Symbol("getRequestCache");
|
|
2966
|
+
var requestCache = Symbol("requestCache");
|
|
2967
|
+
var incomingKey = Symbol("incomingKey");
|
|
2968
|
+
var urlKey = Symbol("urlKey");
|
|
2969
|
+
var headersKey = Symbol("headersKey");
|
|
2970
|
+
var abortControllerKey = Symbol("abortControllerKey");
|
|
2971
|
+
var getAbortController = Symbol("getAbortController");
|
|
2972
|
+
var requestPrototype = {
|
|
2973
|
+
get method() {
|
|
2974
|
+
return this[incomingKey].method || "GET";
|
|
2975
|
+
},
|
|
2976
|
+
get url() {
|
|
2977
|
+
return this[urlKey];
|
|
2978
|
+
},
|
|
2979
|
+
get headers() {
|
|
2980
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
2981
|
+
},
|
|
2982
|
+
[getAbortController]() {
|
|
2983
|
+
this[getRequestCache]();
|
|
2984
|
+
return this[abortControllerKey];
|
|
2985
|
+
},
|
|
2986
|
+
[getRequestCache]() {
|
|
2987
|
+
this[abortControllerKey] ||= new AbortController();
|
|
2988
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
2989
|
+
this.method,
|
|
2990
|
+
this[urlKey],
|
|
2991
|
+
this.headers,
|
|
2992
|
+
this[incomingKey],
|
|
2993
|
+
this[abortControllerKey]
|
|
2994
|
+
);
|
|
2995
|
+
}
|
|
2996
|
+
};
|
|
2997
|
+
[
|
|
2998
|
+
"body",
|
|
2999
|
+
"bodyUsed",
|
|
3000
|
+
"cache",
|
|
3001
|
+
"credentials",
|
|
3002
|
+
"destination",
|
|
3003
|
+
"integrity",
|
|
3004
|
+
"mode",
|
|
3005
|
+
"redirect",
|
|
3006
|
+
"referrer",
|
|
3007
|
+
"referrerPolicy",
|
|
3008
|
+
"signal",
|
|
3009
|
+
"keepalive"
|
|
3010
|
+
].forEach((k) => {
|
|
3011
|
+
Object.defineProperty(requestPrototype, k, {
|
|
3012
|
+
get() {
|
|
3013
|
+
return this[getRequestCache]()[k];
|
|
3014
|
+
}
|
|
3015
|
+
});
|
|
3016
|
+
});
|
|
3017
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
3018
|
+
Object.defineProperty(requestPrototype, k, {
|
|
3019
|
+
value: function() {
|
|
3020
|
+
return this[getRequestCache]()[k]();
|
|
3021
|
+
}
|
|
3022
|
+
});
|
|
3023
|
+
});
|
|
3024
|
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
|
3025
|
+
value: function(depth, options, inspectFn) {
|
|
3026
|
+
const props = {
|
|
3027
|
+
method: this.method,
|
|
3028
|
+
url: this.url,
|
|
3029
|
+
headers: this.headers,
|
|
3030
|
+
nativeRequest: this[requestCache]
|
|
3031
|
+
};
|
|
3032
|
+
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
3033
|
+
}
|
|
3034
|
+
});
|
|
3035
|
+
Object.setPrototypeOf(requestPrototype, Request2.prototype);
|
|
3036
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
3037
|
+
const req = Object.create(requestPrototype);
|
|
3038
|
+
req[incomingKey] = incoming;
|
|
3039
|
+
const incomingUrl = incoming.url || "";
|
|
3040
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
3041
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
3042
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
3043
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
3044
|
+
}
|
|
3045
|
+
try {
|
|
3046
|
+
const url2 = new URL(incomingUrl);
|
|
3047
|
+
req[urlKey] = url2.href;
|
|
3048
|
+
} catch (e) {
|
|
3049
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
3050
|
+
}
|
|
3051
|
+
return req;
|
|
3052
|
+
}
|
|
3053
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
3054
|
+
if (!host) {
|
|
3055
|
+
throw new RequestError("Missing host header");
|
|
3056
|
+
}
|
|
3057
|
+
let scheme;
|
|
3058
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
3059
|
+
scheme = incoming.scheme;
|
|
3060
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
3061
|
+
throw new RequestError("Unsupported scheme");
|
|
3062
|
+
}
|
|
3063
|
+
} else {
|
|
3064
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
3065
|
+
}
|
|
3066
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
3067
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
3068
|
+
throw new RequestError("Invalid host header");
|
|
3069
|
+
}
|
|
3070
|
+
req[urlKey] = url.href;
|
|
3071
|
+
return req;
|
|
3072
|
+
};
|
|
3073
|
+
var responseCache = Symbol("responseCache");
|
|
3074
|
+
var getResponseCache = Symbol("getResponseCache");
|
|
3075
|
+
var cacheKey = Symbol("cache");
|
|
3076
|
+
var GlobalResponse = global.Response;
|
|
3077
|
+
var Response2 = class _Response {
|
|
3078
|
+
#body;
|
|
3079
|
+
#init;
|
|
3080
|
+
[getResponseCache]() {
|
|
3081
|
+
delete this[cacheKey];
|
|
3082
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
3083
|
+
}
|
|
3084
|
+
constructor(body, init) {
|
|
3085
|
+
let headers;
|
|
3086
|
+
this.#body = body;
|
|
3087
|
+
if (init instanceof _Response) {
|
|
3088
|
+
const cachedGlobalResponse = init[responseCache];
|
|
3089
|
+
if (cachedGlobalResponse) {
|
|
3090
|
+
this.#init = cachedGlobalResponse;
|
|
3091
|
+
this[getResponseCache]();
|
|
3092
|
+
return;
|
|
3093
|
+
} else {
|
|
3094
|
+
this.#init = init.#init;
|
|
3095
|
+
headers = new Headers(init.#init.headers);
|
|
3096
|
+
}
|
|
3097
|
+
} else {
|
|
3098
|
+
this.#init = init;
|
|
3099
|
+
}
|
|
3100
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
3101
|
+
;
|
|
3102
|
+
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
get headers() {
|
|
3106
|
+
const cache = this[cacheKey];
|
|
3107
|
+
if (cache) {
|
|
3108
|
+
if (!(cache[2] instanceof Headers)) {
|
|
3109
|
+
cache[2] = new Headers(
|
|
3110
|
+
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
|
3111
|
+
);
|
|
3112
|
+
}
|
|
3113
|
+
return cache[2];
|
|
3114
|
+
}
|
|
3115
|
+
return this[getResponseCache]().headers;
|
|
3116
|
+
}
|
|
3117
|
+
get status() {
|
|
3118
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
3119
|
+
}
|
|
3120
|
+
get ok() {
|
|
3121
|
+
const status = this.status;
|
|
3122
|
+
return status >= 200 && status < 300;
|
|
3123
|
+
}
|
|
3124
|
+
};
|
|
3125
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
3126
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
3127
|
+
get() {
|
|
3128
|
+
return this[getResponseCache]()[k];
|
|
3129
|
+
}
|
|
3130
|
+
});
|
|
3131
|
+
});
|
|
3132
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
3133
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
3134
|
+
value: function() {
|
|
3135
|
+
return this[getResponseCache]()[k]();
|
|
3136
|
+
}
|
|
3137
|
+
});
|
|
3138
|
+
});
|
|
3139
|
+
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
|
3140
|
+
value: function(depth, options, inspectFn) {
|
|
3141
|
+
const props = {
|
|
3142
|
+
status: this.status,
|
|
3143
|
+
headers: this.headers,
|
|
3144
|
+
ok: this.ok,
|
|
3145
|
+
nativeResponse: this[responseCache]
|
|
3146
|
+
};
|
|
3147
|
+
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
|
3148
|
+
}
|
|
3149
|
+
});
|
|
3150
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
3151
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
3152
|
+
async function readWithoutBlocking(readPromise) {
|
|
3153
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
3154
|
+
}
|
|
3155
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
3156
|
+
const cancel = (error) => {
|
|
3157
|
+
reader.cancel(error).catch(() => {
|
|
3158
|
+
});
|
|
3159
|
+
};
|
|
3160
|
+
writable.on("close", cancel);
|
|
3161
|
+
writable.on("error", cancel);
|
|
3162
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
3163
|
+
return reader.closed.finally(() => {
|
|
3164
|
+
writable.off("close", cancel);
|
|
3165
|
+
writable.off("error", cancel);
|
|
3166
|
+
});
|
|
3167
|
+
function handleStreamError(error) {
|
|
3168
|
+
if (error) {
|
|
3169
|
+
writable.destroy(error);
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
function onDrain() {
|
|
3173
|
+
reader.read().then(flow, handleStreamError);
|
|
3174
|
+
}
|
|
3175
|
+
function flow({ done, value }) {
|
|
3176
|
+
try {
|
|
3177
|
+
if (done) {
|
|
3178
|
+
writable.end();
|
|
3179
|
+
} else if (!writable.write(value)) {
|
|
3180
|
+
writable.once("drain", onDrain);
|
|
3181
|
+
} else {
|
|
3182
|
+
return reader.read().then(flow, handleStreamError);
|
|
3183
|
+
}
|
|
3184
|
+
} catch (e) {
|
|
3185
|
+
handleStreamError(e);
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
function writeFromReadableStream(stream, writable) {
|
|
3190
|
+
if (stream.locked) {
|
|
3191
|
+
throw new TypeError("ReadableStream is locked.");
|
|
3192
|
+
} else if (writable.destroyed) {
|
|
3193
|
+
return;
|
|
3194
|
+
}
|
|
3195
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
3196
|
+
}
|
|
3197
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
3198
|
+
const res = {};
|
|
3199
|
+
if (!(headers instanceof Headers)) {
|
|
3200
|
+
headers = new Headers(headers ?? void 0);
|
|
3201
|
+
}
|
|
3202
|
+
const cookies = [];
|
|
3203
|
+
for (const [k, v] of headers) {
|
|
3204
|
+
if (k === "set-cookie") {
|
|
3205
|
+
cookies.push(v);
|
|
3206
|
+
} else {
|
|
3207
|
+
res[k] = v;
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
if (cookies.length > 0) {
|
|
3211
|
+
res["set-cookie"] = cookies;
|
|
3212
|
+
}
|
|
3213
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
3214
|
+
return res;
|
|
3215
|
+
};
|
|
3216
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
3217
|
+
if (typeof global.crypto === "undefined") {
|
|
3218
|
+
global.crypto = crypto;
|
|
3219
|
+
}
|
|
3220
|
+
var outgoingEnded = Symbol("outgoingEnded");
|
|
3221
|
+
var incomingDraining = Symbol("incomingDraining");
|
|
3222
|
+
var DRAIN_TIMEOUT_MS = 500;
|
|
3223
|
+
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
3224
|
+
var drainIncoming = (incoming) => {
|
|
3225
|
+
const incomingWithDrainState = incoming;
|
|
3226
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
|
3227
|
+
return;
|
|
3228
|
+
}
|
|
3229
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
3230
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
3231
|
+
try {
|
|
3232
|
+
;
|
|
3233
|
+
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
|
3234
|
+
} catch {
|
|
3235
|
+
}
|
|
3236
|
+
return;
|
|
3237
|
+
}
|
|
3238
|
+
let bytesRead = 0;
|
|
3239
|
+
const cleanup = () => {
|
|
3240
|
+
clearTimeout(timer);
|
|
3241
|
+
incoming.off("data", onData);
|
|
3242
|
+
incoming.off("end", cleanup);
|
|
3243
|
+
incoming.off("error", cleanup);
|
|
3244
|
+
};
|
|
3245
|
+
const forceClose = () => {
|
|
3246
|
+
cleanup();
|
|
3247
|
+
const socket = incoming.socket;
|
|
3248
|
+
if (socket && !socket.destroyed) {
|
|
3249
|
+
socket.destroySoon();
|
|
3250
|
+
}
|
|
3251
|
+
};
|
|
3252
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
3253
|
+
timer.unref?.();
|
|
3254
|
+
const onData = (chunk) => {
|
|
3255
|
+
bytesRead += chunk.length;
|
|
3256
|
+
if (bytesRead > MAX_DRAIN_BYTES) {
|
|
3257
|
+
forceClose();
|
|
3258
|
+
}
|
|
3259
|
+
};
|
|
3260
|
+
incoming.on("data", onData);
|
|
3261
|
+
incoming.on("end", cleanup);
|
|
3262
|
+
incoming.on("error", cleanup);
|
|
3263
|
+
incoming.resume();
|
|
3264
|
+
};
|
|
3265
|
+
var handleRequestError = () => new Response(null, {
|
|
3266
|
+
status: 400
|
|
3267
|
+
});
|
|
3268
|
+
var handleFetchError = (e) => new Response(null, {
|
|
3269
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
3270
|
+
});
|
|
3271
|
+
var handleResponseError = (e, outgoing) => {
|
|
3272
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
3273
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
3274
|
+
console.info("The user aborted a request.");
|
|
3275
|
+
} else {
|
|
3276
|
+
console.error(e);
|
|
3277
|
+
if (!outgoing.headersSent) {
|
|
3278
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
3279
|
+
}
|
|
3280
|
+
outgoing.end(`Error: ${err.message}`);
|
|
3281
|
+
outgoing.destroy(err);
|
|
3282
|
+
}
|
|
3283
|
+
};
|
|
3284
|
+
var flushHeaders = (outgoing) => {
|
|
3285
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
3286
|
+
outgoing.flushHeaders();
|
|
3287
|
+
}
|
|
3288
|
+
};
|
|
3289
|
+
var responseViaCache = async (res, outgoing) => {
|
|
3290
|
+
let [status, body, header] = res[cacheKey];
|
|
3291
|
+
let hasContentLength = false;
|
|
3292
|
+
if (!header) {
|
|
3293
|
+
header = { "content-type": "text/plain; charset=UTF-8" };
|
|
3294
|
+
} else if (header instanceof Headers) {
|
|
3295
|
+
hasContentLength = header.has("content-length");
|
|
3296
|
+
header = buildOutgoingHttpHeaders(header);
|
|
3297
|
+
} else if (Array.isArray(header)) {
|
|
3298
|
+
const headerObj = new Headers(header);
|
|
3299
|
+
hasContentLength = headerObj.has("content-length");
|
|
3300
|
+
header = buildOutgoingHttpHeaders(headerObj);
|
|
3301
|
+
} else {
|
|
3302
|
+
for (const key in header) {
|
|
3303
|
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
3304
|
+
hasContentLength = true;
|
|
3305
|
+
break;
|
|
3306
|
+
}
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
if (!hasContentLength) {
|
|
3310
|
+
if (typeof body === "string") {
|
|
3311
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
3312
|
+
} else if (body instanceof Uint8Array) {
|
|
3313
|
+
header["Content-Length"] = body.byteLength;
|
|
3314
|
+
} else if (body instanceof Blob) {
|
|
3315
|
+
header["Content-Length"] = body.size;
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
outgoing.writeHead(status, header);
|
|
3319
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
3320
|
+
outgoing.end(body);
|
|
3321
|
+
} else if (body instanceof Blob) {
|
|
3322
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
3323
|
+
} else {
|
|
3324
|
+
flushHeaders(outgoing);
|
|
3325
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
3326
|
+
(e) => handleResponseError(e, outgoing)
|
|
3327
|
+
);
|
|
3328
|
+
}
|
|
3329
|
+
;
|
|
3330
|
+
outgoing[outgoingEnded]?.();
|
|
3331
|
+
};
|
|
3332
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
3333
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
3334
|
+
if (isPromise(res)) {
|
|
3335
|
+
if (options.errorHandler) {
|
|
3336
|
+
try {
|
|
3337
|
+
res = await res;
|
|
3338
|
+
} catch (err) {
|
|
3339
|
+
const errRes = await options.errorHandler(err);
|
|
3340
|
+
if (!errRes) {
|
|
3341
|
+
return;
|
|
3342
|
+
}
|
|
3343
|
+
res = errRes;
|
|
3344
|
+
}
|
|
3345
|
+
} else {
|
|
3346
|
+
res = await res.catch(handleFetchError);
|
|
3347
|
+
}
|
|
3348
|
+
}
|
|
3349
|
+
if (cacheKey in res) {
|
|
3350
|
+
return responseViaCache(res, outgoing);
|
|
3351
|
+
}
|
|
3352
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
3353
|
+
if (res.body) {
|
|
3354
|
+
const reader = res.body.getReader();
|
|
3355
|
+
const values = [];
|
|
3356
|
+
let done = false;
|
|
3357
|
+
let currentReadPromise = void 0;
|
|
3358
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
3359
|
+
let maxReadCount = 2;
|
|
3360
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
3361
|
+
currentReadPromise ||= reader.read();
|
|
3362
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
3363
|
+
console.error(e);
|
|
3364
|
+
done = true;
|
|
3365
|
+
});
|
|
3366
|
+
if (!chunk) {
|
|
3367
|
+
if (i === 1) {
|
|
3368
|
+
await new Promise((resolve2) => setTimeout(resolve2));
|
|
3369
|
+
maxReadCount = 3;
|
|
3370
|
+
continue;
|
|
3371
|
+
}
|
|
3372
|
+
break;
|
|
3373
|
+
}
|
|
3374
|
+
currentReadPromise = void 0;
|
|
3375
|
+
if (chunk.value) {
|
|
3376
|
+
values.push(chunk.value);
|
|
3377
|
+
}
|
|
3378
|
+
if (chunk.done) {
|
|
3379
|
+
done = true;
|
|
3380
|
+
break;
|
|
3381
|
+
}
|
|
3382
|
+
}
|
|
3383
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
3384
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
3388
|
+
values.forEach((value) => {
|
|
3389
|
+
;
|
|
3390
|
+
outgoing.write(value);
|
|
3391
|
+
});
|
|
3392
|
+
if (done) {
|
|
3393
|
+
outgoing.end();
|
|
3394
|
+
} else {
|
|
3395
|
+
if (values.length === 0) {
|
|
3396
|
+
flushHeaders(outgoing);
|
|
3397
|
+
}
|
|
3398
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
3399
|
+
}
|
|
3400
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
3401
|
+
} else {
|
|
3402
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
3403
|
+
outgoing.end();
|
|
3404
|
+
}
|
|
3405
|
+
;
|
|
3406
|
+
outgoing[outgoingEnded]?.();
|
|
3407
|
+
};
|
|
3408
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
3409
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
3410
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
|
|
3411
|
+
Object.defineProperty(global, "Request", {
|
|
3412
|
+
value: Request2
|
|
3413
|
+
});
|
|
3414
|
+
Object.defineProperty(global, "Response", {
|
|
3415
|
+
value: Response2
|
|
3416
|
+
});
|
|
3417
|
+
}
|
|
3418
|
+
return async (incoming, outgoing) => {
|
|
3419
|
+
let res, req;
|
|
3420
|
+
try {
|
|
3421
|
+
req = newRequest(incoming, options.hostname);
|
|
3422
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
3423
|
+
if (!incomingEnded) {
|
|
3424
|
+
;
|
|
3425
|
+
incoming[wrapBodyStream] = true;
|
|
3426
|
+
incoming.on("end", () => {
|
|
3427
|
+
incomingEnded = true;
|
|
3428
|
+
});
|
|
3429
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
3430
|
+
;
|
|
3431
|
+
outgoing[outgoingEnded] = () => {
|
|
3432
|
+
if (!incomingEnded) {
|
|
3433
|
+
setTimeout(() => {
|
|
3434
|
+
if (!incomingEnded) {
|
|
3435
|
+
setTimeout(() => {
|
|
3436
|
+
drainIncoming(incoming);
|
|
3437
|
+
});
|
|
3438
|
+
}
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
}
|
|
3443
|
+
outgoing.on("finish", () => {
|
|
3444
|
+
if (!incomingEnded) {
|
|
3445
|
+
drainIncoming(incoming);
|
|
3446
|
+
}
|
|
3447
|
+
});
|
|
3448
|
+
}
|
|
3449
|
+
outgoing.on("close", () => {
|
|
3450
|
+
const abortController = req[abortControllerKey];
|
|
3451
|
+
if (abortController) {
|
|
3452
|
+
if (incoming.errored) {
|
|
3453
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
3454
|
+
} else if (!outgoing.writableFinished) {
|
|
3455
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
if (!incomingEnded) {
|
|
3459
|
+
setTimeout(() => {
|
|
3460
|
+
if (!incomingEnded) {
|
|
3461
|
+
setTimeout(() => {
|
|
3462
|
+
drainIncoming(incoming);
|
|
3463
|
+
});
|
|
3464
|
+
}
|
|
3465
|
+
});
|
|
3466
|
+
}
|
|
3467
|
+
});
|
|
3468
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
3469
|
+
if (cacheKey in res) {
|
|
3470
|
+
return responseViaCache(res, outgoing);
|
|
3471
|
+
}
|
|
3472
|
+
} catch (e) {
|
|
3473
|
+
if (!res) {
|
|
3474
|
+
if (options.errorHandler) {
|
|
3475
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
3476
|
+
if (!res) {
|
|
3477
|
+
return;
|
|
3478
|
+
}
|
|
3479
|
+
} else if (!req) {
|
|
3480
|
+
res = handleRequestError();
|
|
3481
|
+
} else {
|
|
3482
|
+
res = handleFetchError(e);
|
|
3483
|
+
}
|
|
3484
|
+
} else {
|
|
3485
|
+
return handleResponseError(e, outgoing);
|
|
3486
|
+
}
|
|
3487
|
+
}
|
|
3488
|
+
try {
|
|
3489
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
3490
|
+
} catch (e) {
|
|
3491
|
+
return handleResponseError(e, outgoing);
|
|
3492
|
+
}
|
|
3493
|
+
};
|
|
3494
|
+
};
|
|
3495
|
+
var createAdaptorServer = (options) => {
|
|
3496
|
+
const fetchCallback = options.fetch;
|
|
3497
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
3498
|
+
hostname: options.hostname,
|
|
3499
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
3500
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
3501
|
+
});
|
|
3502
|
+
const createServer = options.createServer || createServerHTTP;
|
|
3503
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
3504
|
+
return server;
|
|
3505
|
+
};
|
|
3506
|
+
var serve = (options, listeningListener) => {
|
|
3507
|
+
const server = createAdaptorServer(options);
|
|
3508
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
3509
|
+
const serverInfo = server.address();
|
|
3510
|
+
listeningListener && listeningListener(serverInfo);
|
|
3511
|
+
});
|
|
3512
|
+
return server;
|
|
3513
|
+
};
|
|
3514
|
+
|
|
3515
|
+
// bridge/ipc_server.ts
|
|
3516
|
+
function createIpcApp(deps) {
|
|
3517
|
+
const app = new Hono2();
|
|
3518
|
+
app.get("/health", (c) => {
|
|
3519
|
+
const state = deps.getDeviceState();
|
|
3520
|
+
const status = {
|
|
3521
|
+
ok: true,
|
|
3522
|
+
deviceId: state?.deviceId,
|
|
3523
|
+
backendConnected: !deps.backend.isDegraded(),
|
|
3524
|
+
degraded: deps.backend.isDegraded(),
|
|
3525
|
+
activeSessions: deps.registry.size(),
|
|
3526
|
+
pendingEvents: deps.eventSender.pendingEventsCount(),
|
|
3527
|
+
ipcPort: deps.ipcPort
|
|
3528
|
+
};
|
|
3529
|
+
return c.json({ ...status, version: PACKAGE_VERSION });
|
|
3530
|
+
});
|
|
3531
|
+
app.get("/connection-status", async (c) => {
|
|
3532
|
+
const state = deps.getDeviceState();
|
|
3533
|
+
const base = {
|
|
3534
|
+
ok: true,
|
|
3535
|
+
deviceId: state?.deviceId,
|
|
3536
|
+
backendConnected: !deps.backend.isDegraded(),
|
|
3537
|
+
degraded: deps.backend.isDegraded(),
|
|
3538
|
+
activeSessions: deps.registry.size(),
|
|
3539
|
+
pendingEvents: deps.eventSender.pendingEventsCount(),
|
|
3540
|
+
ipcPort: deps.ipcPort,
|
|
3541
|
+
version: PACKAGE_VERSION,
|
|
3542
|
+
telegram: { linked: false },
|
|
3543
|
+
bot: {}
|
|
3544
|
+
};
|
|
3545
|
+
if (!state) {
|
|
3546
|
+
return c.json(base);
|
|
3547
|
+
}
|
|
3548
|
+
if (state.telegramLinked) {
|
|
3549
|
+
void deps.syncPendingSessions();
|
|
3550
|
+
try {
|
|
3551
|
+
const connection = await deps.backend.getConnectionInfo(state.deviceToken);
|
|
3552
|
+
return c.json({
|
|
3553
|
+
...base,
|
|
3554
|
+
deviceId: connection.deviceId ?? base.deviceId,
|
|
3555
|
+
telegram: connection.telegram,
|
|
3556
|
+
bot: connection.bot
|
|
3557
|
+
});
|
|
3558
|
+
} catch (error) {
|
|
3559
|
+
if (error instanceof BackendAuthError) {
|
|
3560
|
+
return c.json({
|
|
3561
|
+
...base,
|
|
3562
|
+
deviceId: state.deviceId ?? base.deviceId,
|
|
3563
|
+
telegram: { linked: true },
|
|
3564
|
+
bot: {},
|
|
3565
|
+
degraded: true
|
|
3566
|
+
});
|
|
3567
|
+
}
|
|
3568
|
+
deps.logger.warn("Connection status request failed", { error: String(error) });
|
|
3569
|
+
return c.json({ ...base, degraded: true }, 502);
|
|
3570
|
+
}
|
|
3571
|
+
}
|
|
3572
|
+
if (!shouldProbeTelegramLink(state)) {
|
|
3573
|
+
return c.json({
|
|
3574
|
+
...base,
|
|
3575
|
+
deviceId: state.deviceId ?? base.deviceId,
|
|
3576
|
+
telegram: { linked: false },
|
|
3577
|
+
bot: {}
|
|
3578
|
+
});
|
|
3579
|
+
}
|
|
3580
|
+
try {
|
|
3581
|
+
const linked = await deps.backend.isTelegramLinked(state.deviceToken, 0);
|
|
3582
|
+
if (!linked) {
|
|
3583
|
+
return c.json({
|
|
3584
|
+
...base,
|
|
3585
|
+
deviceId: state.deviceId ?? base.deviceId,
|
|
3586
|
+
telegram: { linked: false },
|
|
3587
|
+
bot: {}
|
|
3588
|
+
});
|
|
3589
|
+
}
|
|
3590
|
+
void deps.syncPendingSessions();
|
|
3591
|
+
const connection = await deps.backend.getConnectionInfo(state.deviceToken);
|
|
3592
|
+
return c.json({
|
|
3593
|
+
...base,
|
|
3594
|
+
deviceId: connection.deviceId ?? base.deviceId,
|
|
3595
|
+
telegram: connection.telegram,
|
|
3596
|
+
bot: connection.bot
|
|
3597
|
+
});
|
|
3598
|
+
} catch (error) {
|
|
3599
|
+
if (error instanceof BackendAuthError) {
|
|
3600
|
+
return c.json({
|
|
3601
|
+
...base,
|
|
3602
|
+
deviceId: state.deviceId ?? base.deviceId,
|
|
3603
|
+
telegram: { linked: false },
|
|
3604
|
+
bot: {},
|
|
3605
|
+
degraded: true
|
|
3606
|
+
});
|
|
3607
|
+
}
|
|
3608
|
+
deps.logger.warn("Connection status request failed", { error: String(error) });
|
|
3609
|
+
return c.json({ ...base, degraded: true }, 502);
|
|
3610
|
+
}
|
|
3611
|
+
});
|
|
3612
|
+
app.post("/telegram/link-token", async (c) => {
|
|
3613
|
+
try {
|
|
3614
|
+
const state = await deps.ensureHubDeviceRegistered();
|
|
3615
|
+
try {
|
|
3616
|
+
const connection = await deps.backend.getConnectionInfo(state.deviceToken);
|
|
3617
|
+
if (connection.telegram.linked) {
|
|
3618
|
+
deps.markTelegramLinked?.(true);
|
|
3619
|
+
return c.json(buildAlreadyLinkedTelegramResponse(connection));
|
|
3620
|
+
}
|
|
3621
|
+
} catch (error) {
|
|
3622
|
+
if (error instanceof BackendAuthError) {
|
|
3623
|
+
deps.logger.error("Telegram link token request failed", { error: String(error) });
|
|
3624
|
+
return c.json({ error: String(error) }, 502);
|
|
3625
|
+
}
|
|
3626
|
+
throw error;
|
|
3627
|
+
}
|
|
3628
|
+
deps.markTelegramBindPending?.();
|
|
3629
|
+
const result = await deps.backend.createLinkToken(state.deviceToken);
|
|
3630
|
+
return c.json(result);
|
|
3631
|
+
} catch (error) {
|
|
3632
|
+
deps.logger.error("Telegram link token request failed", { error: String(error) });
|
|
3633
|
+
return c.json({ error: String(error) }, 502);
|
|
3634
|
+
}
|
|
3635
|
+
});
|
|
3636
|
+
app.get("/sessions", (c) => c.json({ items: deps.registry.list() }));
|
|
3637
|
+
app.post("/sessions/register", async (c) => {
|
|
3638
|
+
const body = await c.req.json();
|
|
3639
|
+
const state = deps.getDeviceState();
|
|
3640
|
+
let linked = state?.telegramLinked === true;
|
|
3641
|
+
if (!linked && state && shouldProbeTelegramLink(state)) {
|
|
3642
|
+
try {
|
|
3643
|
+
linked = await deps.backend.isTelegramLinked(state.deviceToken, 0);
|
|
3644
|
+
} catch (error) {
|
|
3645
|
+
if (error instanceof BackendAuthError) {
|
|
3646
|
+
linked = false;
|
|
3647
|
+
} else {
|
|
3648
|
+
throw error;
|
|
3649
|
+
}
|
|
3650
|
+
}
|
|
3651
|
+
}
|
|
3652
|
+
if (!linked) {
|
|
3653
|
+
const record = {
|
|
3654
|
+
localId: body.localId,
|
|
3655
|
+
externalSessionId: body.externalSessionId,
|
|
3656
|
+
hubSessionId: body.localId,
|
|
3657
|
+
cwd: body.cwd,
|
|
3658
|
+
projectPath: body.projectPath,
|
|
3659
|
+
title: body.title,
|
|
3660
|
+
pid: body.pid,
|
|
3661
|
+
mode: body.mode,
|
|
3662
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3663
|
+
hubPending: true,
|
|
3664
|
+
status: body.status ?? "running"
|
|
3665
|
+
};
|
|
3666
|
+
deps.registry.register(record);
|
|
3667
|
+
deps.onSessionRegistered?.();
|
|
3668
|
+
deps.logger.info("Session registered locally (hub sync deferred)", {
|
|
3669
|
+
externalSessionId: body.externalSessionId
|
|
3670
|
+
});
|
|
3671
|
+
return c.json({ hubSessionId: record.localId, status: "pending" });
|
|
3672
|
+
}
|
|
3673
|
+
try {
|
|
3674
|
+
const hubState = await deps.ensureHubDeviceRegistered();
|
|
3675
|
+
const result = await deps.backend.registerSession(hubState.deviceToken, {
|
|
3676
|
+
external_session_id: body.externalSessionId,
|
|
3677
|
+
title: body.title,
|
|
3678
|
+
project_path: body.projectPath,
|
|
3679
|
+
cwd: body.cwd,
|
|
3680
|
+
status: body.status ?? "running"
|
|
3681
|
+
});
|
|
3682
|
+
const record = {
|
|
3683
|
+
localId: body.localId,
|
|
3684
|
+
externalSessionId: body.externalSessionId,
|
|
3685
|
+
hubSessionId: result.sessionId,
|
|
3686
|
+
cwd: body.cwd,
|
|
3687
|
+
projectPath: body.projectPath,
|
|
3688
|
+
title: body.title,
|
|
3689
|
+
pid: body.pid,
|
|
3690
|
+
mode: body.mode,
|
|
3691
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3692
|
+
status: body.status ?? result.status
|
|
3693
|
+
};
|
|
3694
|
+
deps.registry.register(record);
|
|
3695
|
+
deps.onSessionRegistered?.();
|
|
3696
|
+
deps.logger.info("Session registered", {
|
|
3697
|
+
deviceId: hubState.deviceId,
|
|
3698
|
+
externalSessionId: body.externalSessionId,
|
|
3699
|
+
hubSessionId: record.hubSessionId
|
|
3700
|
+
});
|
|
3701
|
+
return c.json({ hubSessionId: record.hubSessionId, status: result.status });
|
|
3702
|
+
} catch (error) {
|
|
3703
|
+
deps.logger.error("Session register failed", { error: String(error) });
|
|
3704
|
+
return c.json({ error: String(error) }, 502);
|
|
3705
|
+
}
|
|
3706
|
+
});
|
|
3707
|
+
app.post("/shutdown-if-idle", (c) => {
|
|
3708
|
+
const scheduled = deps.scheduleShutdownIfIdle?.() ?? false;
|
|
3709
|
+
return c.json({ scheduled, activeSessions: deps.registry.size() });
|
|
3710
|
+
});
|
|
3711
|
+
app.post("/shutdown", (c) => {
|
|
3712
|
+
deps.onShutdown?.();
|
|
3713
|
+
return c.json({ ok: true, activeSessions: deps.registry.size() });
|
|
3714
|
+
});
|
|
3715
|
+
app.delete("/sessions/:localId", async (c) => {
|
|
3716
|
+
const localId = c.req.param("localId");
|
|
3717
|
+
const session = deps.registry.getByLocalId(localId);
|
|
3718
|
+
if (!session) {
|
|
3719
|
+
return c.json({ ok: true });
|
|
3720
|
+
}
|
|
3721
|
+
await deps.eventSender.send(session.externalSessionId, {
|
|
3722
|
+
eventType: "session_shutdown",
|
|
3723
|
+
status: "offline",
|
|
3724
|
+
eventId: randomUUID()
|
|
3725
|
+
});
|
|
3726
|
+
deps.registry.unregister(localId);
|
|
3727
|
+
deps.logger.info("Session unregistered", { externalSessionId: localId });
|
|
3728
|
+
if (deps.registry.size() === 0) {
|
|
3729
|
+
deps.onEmptyRegistry?.();
|
|
3730
|
+
}
|
|
3731
|
+
return c.json({ ok: true });
|
|
3732
|
+
});
|
|
3733
|
+
app.post("/sessions/:localId/events", async (c) => {
|
|
3734
|
+
const localId = c.req.param("localId");
|
|
3735
|
+
const session = deps.registry.getByLocalId(localId);
|
|
3736
|
+
if (!session) {
|
|
3737
|
+
return c.json({ error: "Session not found" }, 404);
|
|
3738
|
+
}
|
|
3739
|
+
const event = await c.req.json();
|
|
3740
|
+
if (event.status) {
|
|
3741
|
+
deps.registry.updateStatus(localId, event.status);
|
|
3742
|
+
}
|
|
3743
|
+
if (session.hubPending) {
|
|
3744
|
+
await deps.eventSender.enqueue(session.externalSessionId, event);
|
|
3745
|
+
return c.json({ ok: true });
|
|
3746
|
+
}
|
|
3747
|
+
await deps.eventSender.send(session.externalSessionId, event);
|
|
3748
|
+
return c.json({ ok: true });
|
|
3749
|
+
});
|
|
3750
|
+
app.get("/sessions/:localId/commands/wait", async (c) => {
|
|
3751
|
+
const localId = c.req.param("localId");
|
|
3752
|
+
const command = await deps.registry.waitForCommand(
|
|
3753
|
+
localId,
|
|
3754
|
+
IPC_COMMAND_WAIT_TIMEOUT_MS
|
|
3755
|
+
);
|
|
3756
|
+
if (!command) {
|
|
3757
|
+
return c.body(null, 204);
|
|
3758
|
+
}
|
|
3759
|
+
return c.json(command);
|
|
3760
|
+
});
|
|
3761
|
+
return app;
|
|
3762
|
+
}
|
|
3763
|
+
function startIpcServer(deps) {
|
|
3764
|
+
const app = createIpcApp(deps);
|
|
3765
|
+
const listener = serve({
|
|
3766
|
+
fetch: app.fetch,
|
|
3767
|
+
hostname: "127.0.0.1",
|
|
3768
|
+
port: deps.ipcPort
|
|
3769
|
+
});
|
|
3770
|
+
deps.logger.info("IPC server listening", { ipcPort: deps.ipcPort });
|
|
3771
|
+
return {
|
|
3772
|
+
close: () => listener.close()
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
|
|
3776
|
+
// bridge/retry_queue.ts
|
|
3777
|
+
import { appendFileSync, existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
|
|
3778
|
+
var RetryQueue = class {
|
|
3779
|
+
filePath;
|
|
3780
|
+
constructor(dataDir) {
|
|
3781
|
+
this.filePath = eventsQueuePath(dataDir);
|
|
3782
|
+
}
|
|
3783
|
+
load() {
|
|
3784
|
+
if (!existsSync4(this.filePath)) return [];
|
|
3785
|
+
const lines = readFileSync4(this.filePath, "utf-8").split("\n").filter(Boolean);
|
|
3786
|
+
return lines.map((line) => JSON.parse(line));
|
|
3787
|
+
}
|
|
3788
|
+
persist(events) {
|
|
3789
|
+
if (events.length === 0) {
|
|
3790
|
+
writeFileSync2(this.filePath, "", "utf-8");
|
|
3791
|
+
return;
|
|
3792
|
+
}
|
|
3793
|
+
writeFileSync2(
|
|
3794
|
+
this.filePath,
|
|
3795
|
+
events.map((event) => JSON.stringify(event)).join("\n") + "\n",
|
|
3796
|
+
"utf-8"
|
|
3797
|
+
);
|
|
3798
|
+
}
|
|
3799
|
+
enqueue(event) {
|
|
3800
|
+
appendFileSync(this.filePath, `${JSON.stringify(event)}
|
|
3801
|
+
`, "utf-8");
|
|
3802
|
+
}
|
|
3803
|
+
};
|
|
3804
|
+
|
|
3805
|
+
// bridge/registry.ts
|
|
3806
|
+
var SessionRegistry = class {
|
|
3807
|
+
sessions = /* @__PURE__ */ new Map();
|
|
3808
|
+
hubToLocal = /* @__PURE__ */ new Map();
|
|
3809
|
+
commandQueues = /* @__PURE__ */ new Map();
|
|
3810
|
+
commandWaiters = /* @__PURE__ */ new Map();
|
|
3811
|
+
register(session) {
|
|
3812
|
+
this.sessions.set(session.localId, session);
|
|
3813
|
+
if (!session.hubPending) {
|
|
3814
|
+
this.hubToLocal.set(session.hubSessionId, session.localId);
|
|
3815
|
+
}
|
|
3816
|
+
if (!this.commandQueues.has(session.localId)) {
|
|
3817
|
+
this.commandQueues.set(session.localId, []);
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
markHubSynced(localId, hubSessionId) {
|
|
3821
|
+
const session = this.sessions.get(localId);
|
|
3822
|
+
if (!session) return;
|
|
3823
|
+
if (!session.hubPending) {
|
|
3824
|
+
this.hubToLocal.delete(session.hubSessionId);
|
|
3825
|
+
}
|
|
3826
|
+
session.hubSessionId = hubSessionId;
|
|
3827
|
+
session.hubPending = false;
|
|
3828
|
+
this.hubToLocal.set(hubSessionId, localId);
|
|
3829
|
+
}
|
|
3830
|
+
updateStatus(localId, status) {
|
|
3831
|
+
const session = this.sessions.get(localId);
|
|
3832
|
+
if (!session) return;
|
|
3833
|
+
session.status = status;
|
|
3834
|
+
}
|
|
3835
|
+
listPendingHubSync() {
|
|
3836
|
+
return this.list().filter((session) => session.hubPending);
|
|
3837
|
+
}
|
|
3838
|
+
unregister(localId) {
|
|
3839
|
+
const session = this.sessions.get(localId);
|
|
3840
|
+
if (session) {
|
|
3841
|
+
this.hubToLocal.delete(session.hubSessionId);
|
|
3842
|
+
}
|
|
3843
|
+
this.sessions.delete(localId);
|
|
3844
|
+
this.commandQueues.delete(localId);
|
|
3845
|
+
this.resolveWaiters(localId, null);
|
|
3846
|
+
}
|
|
3847
|
+
getByLocalId(localId) {
|
|
3848
|
+
return this.sessions.get(localId);
|
|
3849
|
+
}
|
|
3850
|
+
getLocalIdByHubSessionId(hubSessionId) {
|
|
3851
|
+
return this.hubToLocal.get(hubSessionId);
|
|
3852
|
+
}
|
|
3853
|
+
list() {
|
|
3854
|
+
return [...this.sessions.values()];
|
|
3855
|
+
}
|
|
3856
|
+
size() {
|
|
3857
|
+
return this.sessions.size;
|
|
3858
|
+
}
|
|
3859
|
+
enqueueCommand(localId, command) {
|
|
3860
|
+
const queue = this.commandQueues.get(localId);
|
|
3861
|
+
if (!queue) return false;
|
|
3862
|
+
queue.push(command);
|
|
3863
|
+
this.resolveWaiters(localId, command);
|
|
3864
|
+
return true;
|
|
3865
|
+
}
|
|
3866
|
+
async waitForCommand(localId, timeoutMs) {
|
|
3867
|
+
const queue = this.commandQueues.get(localId);
|
|
3868
|
+
if (!queue) return null;
|
|
3869
|
+
const existing = queue.shift();
|
|
3870
|
+
if (existing) return existing;
|
|
3871
|
+
return new Promise((resolve2) => {
|
|
3872
|
+
const waiters = this.commandWaiters.get(localId) ?? [];
|
|
3873
|
+
waiters.push(resolve2);
|
|
3874
|
+
this.commandWaiters.set(localId, waiters);
|
|
3875
|
+
setTimeout(() => {
|
|
3876
|
+
const current = this.commandWaiters.get(localId);
|
|
3877
|
+
if (!current) return;
|
|
3878
|
+
const index = current.indexOf(resolve2);
|
|
3879
|
+
if (index >= 0) {
|
|
3880
|
+
current.splice(index, 1);
|
|
3881
|
+
resolve2(null);
|
|
3882
|
+
}
|
|
3883
|
+
}, timeoutMs);
|
|
3884
|
+
});
|
|
3885
|
+
}
|
|
3886
|
+
resolveWaiters(localId, command) {
|
|
3887
|
+
const waiters = this.commandWaiters.get(localId);
|
|
3888
|
+
if (!waiters?.length) return;
|
|
3889
|
+
this.commandWaiters.set(localId, []);
|
|
3890
|
+
for (const resolve2 of waiters) {
|
|
3891
|
+
resolve2(command);
|
|
3892
|
+
}
|
|
3893
|
+
}
|
|
3894
|
+
};
|
|
3895
|
+
|
|
3896
|
+
// bridge/main.ts
|
|
3897
|
+
var BridgeRuntime = class {
|
|
3898
|
+
deviceState = null;
|
|
3899
|
+
eventSender;
|
|
3900
|
+
stopHeartbeat;
|
|
3901
|
+
stopPoller;
|
|
3902
|
+
ipcClose;
|
|
3903
|
+
shutdownTimer;
|
|
3904
|
+
config = loadBridgeConfig();
|
|
3905
|
+
logger = new Logger(this.config.bridgeLogLevel);
|
|
3906
|
+
stateStore = new DeviceStateStore(this.config.bridgeDataDir);
|
|
3907
|
+
registry = new SessionRegistry();
|
|
3908
|
+
retryQueue = new RetryQueue(this.config.bridgeDataDir);
|
|
3909
|
+
backend = new BackendClient(this.config, this.logger);
|
|
3910
|
+
async start() {
|
|
3911
|
+
await this.initOnStart();
|
|
3912
|
+
const eventSender = new EventSender(
|
|
3913
|
+
this.backend,
|
|
3914
|
+
this.retryQueue,
|
|
3915
|
+
this.logger,
|
|
3916
|
+
() => this.deviceState
|
|
3917
|
+
);
|
|
3918
|
+
this.eventSender = eventSender;
|
|
3919
|
+
const dispatcher = new CommandDispatcher(
|
|
3920
|
+
this.registry,
|
|
3921
|
+
this.backend,
|
|
3922
|
+
this.logger,
|
|
3923
|
+
() => this.deviceState?.deviceToken
|
|
3924
|
+
);
|
|
3925
|
+
const ipc = startIpcServer({
|
|
3926
|
+
registry: this.registry,
|
|
3927
|
+
backend: this.backend,
|
|
3928
|
+
eventSender,
|
|
3929
|
+
logger: this.logger,
|
|
3930
|
+
ipcPort: this.config.ipcPort,
|
|
3931
|
+
getDeviceState: () => this.deviceState,
|
|
3932
|
+
ensureHubDeviceRegistered: () => this.ensureHubDeviceRegistered(),
|
|
3933
|
+
syncPendingSessions: () => this.syncPendingSessions(),
|
|
3934
|
+
onEmptyRegistry: () => this.scheduleShutdownIfIdle(),
|
|
3935
|
+
onSessionRegistered: () => this.cancelScheduledShutdown(),
|
|
3936
|
+
scheduleShutdownIfIdle: () => this.scheduleShutdownIfIdle(),
|
|
3937
|
+
markTelegramBindPending: () => this.markTelegramBindPending(),
|
|
3938
|
+
markTelegramLinked: (linked) => this.markTelegramLinked(linked),
|
|
3939
|
+
onShutdown: () => {
|
|
3940
|
+
setImmediate(() => {
|
|
3941
|
+
this.logger.info("Shutdown requested");
|
|
3942
|
+
this.stop();
|
|
3943
|
+
process.exit(0);
|
|
3944
|
+
});
|
|
3945
|
+
}
|
|
3946
|
+
});
|
|
3947
|
+
this.ipcClose = ipc.close;
|
|
3948
|
+
const hasActiveSessions = () => this.registry.size() > 0;
|
|
3949
|
+
const shouldProbeTelegram = (state) => shouldProbeTelegramLink(state);
|
|
3950
|
+
const onAuthFailure = () => this.handleInvalidDeviceToken();
|
|
3951
|
+
this.stopHeartbeat = startHeartbeatLoop(
|
|
3952
|
+
this.config,
|
|
3953
|
+
this.backend,
|
|
3954
|
+
this.logger,
|
|
3955
|
+
() => this.deviceState,
|
|
3956
|
+
(state) => {
|
|
3957
|
+
this.deviceState = state;
|
|
3958
|
+
this.stateStore.save(state);
|
|
3959
|
+
},
|
|
3960
|
+
hasActiveSessions,
|
|
3961
|
+
shouldProbeTelegram,
|
|
3962
|
+
onAuthFailure
|
|
3963
|
+
);
|
|
3964
|
+
this.stopPoller = startPollerLoop(
|
|
3965
|
+
this.config,
|
|
3966
|
+
this.backend,
|
|
3967
|
+
dispatcher,
|
|
3968
|
+
eventSender,
|
|
3969
|
+
this.logger,
|
|
3970
|
+
() => this.deviceState,
|
|
3971
|
+
hasActiveSessions,
|
|
3972
|
+
shouldProbeTelegram,
|
|
3973
|
+
async () => {
|
|
3974
|
+
this.markTelegramLinked(true);
|
|
3975
|
+
await this.ensureHubDeviceRegistered();
|
|
3976
|
+
await this.syncPendingSessions();
|
|
3977
|
+
},
|
|
3978
|
+
onAuthFailure
|
|
3979
|
+
);
|
|
3980
|
+
this.logger.info("Bridge runtime started", {
|
|
3981
|
+
deviceId: this.deviceState?.deviceId,
|
|
3982
|
+
ipcPort: this.config.ipcPort
|
|
3983
|
+
});
|
|
3984
|
+
}
|
|
3985
|
+
async initOnStart() {
|
|
3986
|
+
const saved = this.stateStore.load();
|
|
3987
|
+
if (!saved?.deviceToken) {
|
|
3988
|
+
this.deviceState = null;
|
|
3989
|
+
this.logger.info("Bridge started idle: hub registration deferred until Telegram is linked");
|
|
3990
|
+
return;
|
|
3991
|
+
}
|
|
3992
|
+
const fingerprint = computeDeviceFingerprint();
|
|
3993
|
+
this.deviceState = {
|
|
3994
|
+
...saved,
|
|
3995
|
+
fingerprint,
|
|
3996
|
+
hubUrl: this.config.hubUrl
|
|
3997
|
+
};
|
|
3998
|
+
if (!shouldProbeTelegramLink(saved)) {
|
|
3999
|
+
this.logger.info("Telegram not linked \u2014 deferring hub probes until connect-telegram");
|
|
4000
|
+
return;
|
|
4001
|
+
}
|
|
4002
|
+
try {
|
|
4003
|
+
const linked = await this.backend.isTelegramLinked(saved.deviceToken);
|
|
4004
|
+
if (linked) {
|
|
4005
|
+
this.markTelegramLinked(true);
|
|
4006
|
+
await this.ensureHubDeviceRegistered();
|
|
4007
|
+
await this.syncPendingSessions();
|
|
4008
|
+
return;
|
|
4009
|
+
}
|
|
4010
|
+
if (saved.telegramBindPending) {
|
|
4011
|
+
this.logger.info("Telegram bind pending \u2014 waiting for user to complete /start in bot");
|
|
4012
|
+
return;
|
|
4013
|
+
}
|
|
4014
|
+
this.logger.info("Telegram not linked \u2014 deferring hub device/session sync");
|
|
4015
|
+
} catch (error) {
|
|
4016
|
+
if (error instanceof BackendAuthError) {
|
|
4017
|
+
this.handleInvalidDeviceToken();
|
|
4018
|
+
return;
|
|
4019
|
+
}
|
|
4020
|
+
throw error;
|
|
4021
|
+
}
|
|
4022
|
+
}
|
|
4023
|
+
markTelegramLinked(linked, bindPending = false) {
|
|
4024
|
+
if (!this.deviceState) return;
|
|
4025
|
+
this.deviceState = {
|
|
4026
|
+
...this.deviceState,
|
|
4027
|
+
telegramLinked: linked,
|
|
4028
|
+
telegramBindPending: bindPending
|
|
4029
|
+
};
|
|
4030
|
+
this.stateStore.save(this.deviceState);
|
|
4031
|
+
}
|
|
4032
|
+
markTelegramBindPending() {
|
|
4033
|
+
if (!this.deviceState) return;
|
|
4034
|
+
this.markTelegramLinked(this.deviceState.telegramLinked === true, true);
|
|
4035
|
+
}
|
|
4036
|
+
handleInvalidDeviceToken() {
|
|
4037
|
+
this.logger.warn("Device token rejected by hub \u2014 clearing stored credentials");
|
|
4038
|
+
this.backend.invalidateTelegramLinkedCache();
|
|
4039
|
+
const saved = this.stateStore.load();
|
|
4040
|
+
if (saved) {
|
|
4041
|
+
this.stateStore.save(clearDeviceCredentials(saved));
|
|
4042
|
+
}
|
|
4043
|
+
this.deviceState = null;
|
|
4044
|
+
}
|
|
4045
|
+
async ensureHubDeviceRegistered() {
|
|
4046
|
+
const fingerprint = computeDeviceFingerprint();
|
|
4047
|
+
const saved = this.stateStore.load();
|
|
4048
|
+
const existingToken = this.deviceState?.deviceToken ?? saved?.deviceToken;
|
|
4049
|
+
let result;
|
|
4050
|
+
if (existingToken) {
|
|
4051
|
+
try {
|
|
4052
|
+
result = await this.backend.registerDevice(fingerprint, existingToken);
|
|
4053
|
+
} catch {
|
|
4054
|
+
result = await this.backend.registerDevice(fingerprint);
|
|
4055
|
+
}
|
|
4056
|
+
} else {
|
|
4057
|
+
result = await this.backend.registerDevice(fingerprint);
|
|
4058
|
+
}
|
|
4059
|
+
this.deviceState = this.backend.toDeviceState(result, fingerprint, this.deviceState ?? saved ?? void 0);
|
|
4060
|
+
this.stateStore.save(this.deviceState);
|
|
4061
|
+
this.backend.invalidateTelegramLinkedCache();
|
|
4062
|
+
this.logger.info("Device registered on hub", { deviceId: this.deviceState.deviceId });
|
|
4063
|
+
return this.deviceState;
|
|
4064
|
+
}
|
|
4065
|
+
async syncPendingSessions() {
|
|
4066
|
+
const state = this.deviceState;
|
|
4067
|
+
if (!state) return;
|
|
4068
|
+
if (!state.telegramLinked && !shouldProbeTelegramLink(state)) return;
|
|
4069
|
+
let linked = state.telegramLinked === true;
|
|
4070
|
+
if (!linked) {
|
|
4071
|
+
try {
|
|
4072
|
+
linked = await this.backend.isTelegramLinked(state.deviceToken);
|
|
4073
|
+
} catch (error) {
|
|
4074
|
+
if (error instanceof BackendAuthError) {
|
|
4075
|
+
this.handleInvalidDeviceToken();
|
|
4076
|
+
return;
|
|
4077
|
+
}
|
|
4078
|
+
return;
|
|
4079
|
+
}
|
|
4080
|
+
if (!linked) return;
|
|
4081
|
+
this.markTelegramLinked(true);
|
|
4082
|
+
}
|
|
4083
|
+
for (const session of this.registry.listPendingHubSync()) {
|
|
4084
|
+
try {
|
|
4085
|
+
const result = await this.backend.registerSession(state.deviceToken, {
|
|
4086
|
+
external_session_id: session.externalSessionId,
|
|
4087
|
+
title: session.title,
|
|
4088
|
+
project_path: session.projectPath,
|
|
4089
|
+
cwd: session.cwd,
|
|
4090
|
+
status: session.status ?? "running"
|
|
4091
|
+
});
|
|
4092
|
+
this.registry.markHubSynced(session.localId, result.sessionId);
|
|
4093
|
+
this.logger.info("Pending session synced to hub", {
|
|
4094
|
+
localId: session.localId,
|
|
4095
|
+
hubSessionId: result.sessionId,
|
|
4096
|
+
status: session.status ?? "running"
|
|
4097
|
+
});
|
|
4098
|
+
} catch (error) {
|
|
4099
|
+
this.logger.warn("Pending session sync failed", {
|
|
4100
|
+
localId: session.localId,
|
|
4101
|
+
error: String(error)
|
|
4102
|
+
});
|
|
4103
|
+
}
|
|
4104
|
+
}
|
|
4105
|
+
await this.eventSender?.flushRetryQueue();
|
|
4106
|
+
}
|
|
4107
|
+
scheduleShutdownIfIdle() {
|
|
4108
|
+
if (this.registry.size() > 0) return false;
|
|
4109
|
+
if (this.shutdownTimer) clearTimeout(this.shutdownTimer);
|
|
4110
|
+
this.shutdownTimer = setTimeout(() => {
|
|
4111
|
+
if (this.registry.size() === 0) {
|
|
4112
|
+
this.logger.info("No active sessions, shutting down bridge");
|
|
4113
|
+
this.stop();
|
|
4114
|
+
process.exit(0);
|
|
4115
|
+
}
|
|
4116
|
+
}, 3e4);
|
|
4117
|
+
return true;
|
|
4118
|
+
}
|
|
4119
|
+
cancelScheduledShutdown() {
|
|
4120
|
+
if (this.shutdownTimer) clearTimeout(this.shutdownTimer);
|
|
4121
|
+
this.shutdownTimer = void 0;
|
|
4122
|
+
}
|
|
4123
|
+
stop() {
|
|
4124
|
+
this.stopHeartbeat?.();
|
|
4125
|
+
this.stopPoller?.();
|
|
4126
|
+
this.ipcClose?.();
|
|
4127
|
+
if (this.shutdownTimer) clearTimeout(this.shutdownTimer);
|
|
4128
|
+
}
|
|
4129
|
+
};
|
|
4130
|
+
async function stopBridge() {
|
|
4131
|
+
const config = loadBridgeConfig();
|
|
4132
|
+
try {
|
|
4133
|
+
const response = await fetch(`${ipcBaseUrl(config.ipcPort)}/shutdown`, {
|
|
4134
|
+
method: "POST",
|
|
4135
|
+
signal: AbortSignal.timeout(2e3)
|
|
4136
|
+
});
|
|
4137
|
+
if (!response.ok) {
|
|
4138
|
+
console.error(`Bridge shutdown failed: HTTP ${response.status}`);
|
|
4139
|
+
process.exit(1);
|
|
4140
|
+
}
|
|
4141
|
+
console.log("Bridge stopped");
|
|
4142
|
+
} catch {
|
|
4143
|
+
console.log("Bridge is not running");
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
async function main() {
|
|
4147
|
+
const command = process.argv[2] ?? "start";
|
|
4148
|
+
if (command === "stop") {
|
|
4149
|
+
await stopBridge();
|
|
4150
|
+
return;
|
|
4151
|
+
}
|
|
4152
|
+
if (command !== "start") {
|
|
4153
|
+
console.error(`Unknown command: ${command}`);
|
|
4154
|
+
process.exit(1);
|
|
4155
|
+
}
|
|
4156
|
+
const runtime = new BridgeRuntime();
|
|
4157
|
+
process.on("SIGINT", () => {
|
|
4158
|
+
runtime.stop();
|
|
4159
|
+
process.exit(0);
|
|
4160
|
+
});
|
|
4161
|
+
process.on("SIGTERM", () => {
|
|
4162
|
+
runtime.stop();
|
|
4163
|
+
process.exit(0);
|
|
4164
|
+
});
|
|
4165
|
+
await runtime.start();
|
|
4166
|
+
}
|
|
4167
|
+
main().catch((error) => {
|
|
4168
|
+
console.error(JSON.stringify({ level: "ERROR", message: "Bridge failed to start", error: String(error) }));
|
|
4169
|
+
process.exit(1);
|
|
4170
|
+
});
|
|
4171
|
+
export {
|
|
4172
|
+
BridgeRuntime
|
|
4173
|
+
};
|