claudish 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +783 -0
- package/dist/index.js +3601 -0
- package/package.json +54 -0
- package/scripts/postinstall.cjs +25 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3601 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
|
|
4
|
+
// src/claude-runner.ts
|
|
5
|
+
import { writeFileSync, unlinkSync } from "fs";
|
|
6
|
+
import { tmpdir } from "os";
|
|
7
|
+
import { join } from "path";
|
|
8
|
+
|
|
9
|
+
// src/config.ts
|
|
10
|
+
var DEFAULT_PORT_RANGE = { start: 3000, end: 9000 };
|
|
11
|
+
var MODEL_INFO = {
|
|
12
|
+
"x-ai/grok-code-fast-1": {
|
|
13
|
+
name: "Grok Code Fast",
|
|
14
|
+
description: "xAI's fast coding model",
|
|
15
|
+
priority: 1,
|
|
16
|
+
provider: "xAI"
|
|
17
|
+
},
|
|
18
|
+
"openai/gpt-5-codex": {
|
|
19
|
+
name: "GPT-5 Codex",
|
|
20
|
+
description: "OpenAI's advanced coding model",
|
|
21
|
+
priority: 2,
|
|
22
|
+
provider: "OpenAI"
|
|
23
|
+
},
|
|
24
|
+
"minimax/minimax-m2": {
|
|
25
|
+
name: "MiniMax M2",
|
|
26
|
+
description: "MiniMax's high-performance model",
|
|
27
|
+
priority: 3,
|
|
28
|
+
provider: "MiniMax"
|
|
29
|
+
},
|
|
30
|
+
"z-ai/glm-4.6": {
|
|
31
|
+
name: "GLM-4.6",
|
|
32
|
+
description: "Advanced language model",
|
|
33
|
+
priority: 4,
|
|
34
|
+
provider: "Zhipu AI"
|
|
35
|
+
},
|
|
36
|
+
"qwen/qwen3-vl-235b-a22b-instruct": {
|
|
37
|
+
name: "Qwen3 VL 235B",
|
|
38
|
+
description: "Alibaba's vision-language model",
|
|
39
|
+
priority: 5,
|
|
40
|
+
provider: "Alibaba"
|
|
41
|
+
},
|
|
42
|
+
"anthropic/claude-sonnet-4.5": {
|
|
43
|
+
name: "Claude Sonnet 4.5",
|
|
44
|
+
description: "Anthropic's Claude (for comparison)",
|
|
45
|
+
priority: 6,
|
|
46
|
+
provider: "Anthropic"
|
|
47
|
+
},
|
|
48
|
+
custom: {
|
|
49
|
+
name: "Custom Model",
|
|
50
|
+
description: "Enter any OpenRouter model ID manually",
|
|
51
|
+
priority: 999,
|
|
52
|
+
provider: "Custom"
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var ENV = {
|
|
56
|
+
OPENROUTER_API_KEY: "OPENROUTER_API_KEY",
|
|
57
|
+
CLAUDISH_MODEL: "CLAUDISH_MODEL",
|
|
58
|
+
CLAUDISH_PORT: "CLAUDISH_PORT",
|
|
59
|
+
CLAUDISH_ACTIVE_MODEL_NAME: "CLAUDISH_ACTIVE_MODEL_NAME"
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/claude-runner.ts
|
|
63
|
+
function createTempSettingsFile(modelDisplay, port) {
|
|
64
|
+
const tempDir = tmpdir();
|
|
65
|
+
const timestamp = Date.now();
|
|
66
|
+
const tempPath = join(tempDir, `claudish-settings-${timestamp}.json`);
|
|
67
|
+
const CYAN = "\\033[96m";
|
|
68
|
+
const YELLOW = "\\033[93m";
|
|
69
|
+
const GREEN = "\\033[92m";
|
|
70
|
+
const MAGENTA = "\\033[95m";
|
|
71
|
+
const DIM = "\\033[2m";
|
|
72
|
+
const RESET = "\\033[0m";
|
|
73
|
+
const BOLD = "\\033[1m";
|
|
74
|
+
const MODEL_CONTEXT = {
|
|
75
|
+
"x-ai/grok-code-fast-1": 256000,
|
|
76
|
+
"openai/gpt-5-codex": 400000,
|
|
77
|
+
"minimax/minimax-m2": 204800,
|
|
78
|
+
"z-ai/glm-4.6": 200000,
|
|
79
|
+
"qwen/qwen3-vl-235b-a22b-instruct": 256000,
|
|
80
|
+
"anthropic/claude-sonnet-4.5": 200000
|
|
81
|
+
};
|
|
82
|
+
const maxTokens = MODEL_CONTEXT[modelDisplay] || 1e5;
|
|
83
|
+
const tokenFilePath = `/tmp/claudish-tokens-${port}.json`;
|
|
84
|
+
const settings = {
|
|
85
|
+
statusLine: {
|
|
86
|
+
type: "command",
|
|
87
|
+
command: `JSON=$(cat) && DIR=$(basename "$(pwd)") && [ \${#DIR} -gt 15 ] && DIR="\${DIR:0:12}..." || true && COST=$(echo "$JSON" | grep -o '"total_cost_usd":[0-9.]*' | cut -d: -f2) && [ -z "$COST" ] && COST="0" || true && if [ -f "${tokenFilePath}" ]; then TOKENS=$(cat "${tokenFilePath}" 2>/dev/null) && INPUT=$(echo "$TOKENS" | grep -o '"input_tokens":[0-9]*' | grep -o '[0-9]*') && OUTPUT=$(echo "$TOKENS" | grep -o '"output_tokens":[0-9]*' | grep -o '[0-9]*') && TOTAL=$((INPUT + OUTPUT)) && CTX=$(echo "scale=0; (${maxTokens} - $TOTAL) * 100 / ${maxTokens}" | bc 2>/dev/null); else INPUT=0 && OUTPUT=0 && CTX=100; fi && [ -z "$CTX" ] && CTX="100" || true && printf "${CYAN}${BOLD}%s${RESET} ${DIM}\u2022${RESET} ${YELLOW}%s${RESET} ${DIM}\u2022${RESET} ${GREEN}\\$%.3f${RESET} ${DIM}\u2022${RESET} ${MAGENTA}%s%%${RESET}\\n" "$DIR" "$CLAUDISH_ACTIVE_MODEL_NAME" "$COST" "$CTX"`,
|
|
88
|
+
padding: 0
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
writeFileSync(tempPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
92
|
+
return tempPath;
|
|
93
|
+
}
|
|
94
|
+
async function runClaudeWithProxy(config, proxyUrl) {
|
|
95
|
+
const modelId = config.model || "unknown";
|
|
96
|
+
const portMatch = proxyUrl.match(/:(\d+)/);
|
|
97
|
+
const port = portMatch ? portMatch[1] : "unknown";
|
|
98
|
+
const tempSettingsPath = createTempSettingsFile(modelId, port);
|
|
99
|
+
const claudeArgs = [];
|
|
100
|
+
claudeArgs.push("--settings", tempSettingsPath);
|
|
101
|
+
if (config.interactive) {
|
|
102
|
+
if (config.autoApprove) {
|
|
103
|
+
claudeArgs.push("--dangerously-skip-permissions");
|
|
104
|
+
}
|
|
105
|
+
if (config.dangerous) {
|
|
106
|
+
claudeArgs.push("--dangerouslyDisableSandbox");
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
claudeArgs.push("-p");
|
|
110
|
+
if (config.autoApprove) {
|
|
111
|
+
claudeArgs.push("--dangerously-skip-permissions");
|
|
112
|
+
}
|
|
113
|
+
if (config.dangerous) {
|
|
114
|
+
claudeArgs.push("--dangerouslyDisableSandbox");
|
|
115
|
+
}
|
|
116
|
+
if (config.jsonOutput) {
|
|
117
|
+
claudeArgs.push("--output-format", "json");
|
|
118
|
+
}
|
|
119
|
+
claudeArgs.push(...config.claudeArgs);
|
|
120
|
+
}
|
|
121
|
+
const env = {
|
|
122
|
+
...process.env,
|
|
123
|
+
ANTHROPIC_BASE_URL: proxyUrl,
|
|
124
|
+
[ENV.CLAUDISH_ACTIVE_MODEL_NAME]: modelId
|
|
125
|
+
};
|
|
126
|
+
if (config.monitor) {
|
|
127
|
+
delete env.ANTHROPIC_API_KEY;
|
|
128
|
+
} else {
|
|
129
|
+
env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY || "sk-ant-api03-placeholder-not-used-proxy-handles-auth-with-openrouter-key-xxxxxxxxxxxxxxxxxxxxx";
|
|
130
|
+
}
|
|
131
|
+
const log = (message) => {
|
|
132
|
+
if (!config.quiet) {
|
|
133
|
+
console.log(message);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
if (config.interactive) {
|
|
137
|
+
log(`
|
|
138
|
+
[claudish] Model: ${modelId}
|
|
139
|
+
`);
|
|
140
|
+
} else {
|
|
141
|
+
log(`
|
|
142
|
+
[claudish] Model: ${modelId}`);
|
|
143
|
+
log(`[claudish] Arguments: ${claudeArgs.join(" ")}
|
|
144
|
+
`);
|
|
145
|
+
}
|
|
146
|
+
const proc = Bun.spawn(["claude", ...claudeArgs], {
|
|
147
|
+
env,
|
|
148
|
+
stdout: "inherit",
|
|
149
|
+
stderr: "inherit",
|
|
150
|
+
stdin: "inherit"
|
|
151
|
+
});
|
|
152
|
+
setupSignalHandlers(proc, tempSettingsPath, config.quiet);
|
|
153
|
+
const exitCode = await proc.exited;
|
|
154
|
+
try {
|
|
155
|
+
unlinkSync(tempSettingsPath);
|
|
156
|
+
} catch (error) {}
|
|
157
|
+
return exitCode;
|
|
158
|
+
}
|
|
159
|
+
function setupSignalHandlers(proc, tempSettingsPath, quiet) {
|
|
160
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
161
|
+
for (const signal of signals) {
|
|
162
|
+
process.on(signal, () => {
|
|
163
|
+
if (!quiet) {
|
|
164
|
+
console.log(`
|
|
165
|
+
[claudish] Received ${signal}, shutting down...`);
|
|
166
|
+
}
|
|
167
|
+
proc.kill();
|
|
168
|
+
try {
|
|
169
|
+
unlinkSync(tempSettingsPath);
|
|
170
|
+
} catch {}
|
|
171
|
+
process.exit(0);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async function checkClaudeInstalled() {
|
|
176
|
+
try {
|
|
177
|
+
const proc = Bun.spawn(["which", "claude"], {
|
|
178
|
+
stdout: "pipe",
|
|
179
|
+
stderr: "pipe"
|
|
180
|
+
});
|
|
181
|
+
const exitCode = await proc.exited;
|
|
182
|
+
return exitCode === 0;
|
|
183
|
+
} catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/types.ts
|
|
189
|
+
var OPENROUTER_MODELS = [
|
|
190
|
+
"x-ai/grok-code-fast-1",
|
|
191
|
+
"openai/gpt-5-codex",
|
|
192
|
+
"minimax/minimax-m2",
|
|
193
|
+
"z-ai/glm-4.6",
|
|
194
|
+
"qwen/qwen3-vl-235b-a22b-instruct",
|
|
195
|
+
"anthropic/claude-sonnet-4.5",
|
|
196
|
+
"custom"
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
// src/cli.ts
|
|
200
|
+
function parseArgs(args) {
|
|
201
|
+
const config = {
|
|
202
|
+
model: undefined,
|
|
203
|
+
autoApprove: true,
|
|
204
|
+
dangerous: false,
|
|
205
|
+
interactive: false,
|
|
206
|
+
debug: false,
|
|
207
|
+
logLevel: "info",
|
|
208
|
+
quiet: undefined,
|
|
209
|
+
jsonOutput: false,
|
|
210
|
+
monitor: false,
|
|
211
|
+
stdin: false,
|
|
212
|
+
claudeArgs: []
|
|
213
|
+
};
|
|
214
|
+
const envModel = process.env[ENV.CLAUDISH_MODEL];
|
|
215
|
+
if (envModel) {
|
|
216
|
+
config.model = envModel;
|
|
217
|
+
}
|
|
218
|
+
const envPort = process.env[ENV.CLAUDISH_PORT];
|
|
219
|
+
if (envPort) {
|
|
220
|
+
const port = Number.parseInt(envPort, 10);
|
|
221
|
+
if (!Number.isNaN(port)) {
|
|
222
|
+
config.port = port;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
let i = 0;
|
|
226
|
+
while (i < args.length) {
|
|
227
|
+
const arg = args[i];
|
|
228
|
+
if (arg === "--model" || arg === "-m") {
|
|
229
|
+
const modelArg = args[++i];
|
|
230
|
+
if (!modelArg) {
|
|
231
|
+
console.error("--model requires a value");
|
|
232
|
+
printAvailableModels();
|
|
233
|
+
process.exit(1);
|
|
234
|
+
}
|
|
235
|
+
config.model = modelArg;
|
|
236
|
+
} else if (arg === "--port" || arg === "-p") {
|
|
237
|
+
const portArg = args[++i];
|
|
238
|
+
if (!portArg) {
|
|
239
|
+
console.error("--port requires a value");
|
|
240
|
+
process.exit(1);
|
|
241
|
+
}
|
|
242
|
+
const port = Number.parseInt(portArg, 10);
|
|
243
|
+
if (Number.isNaN(port) || port < 1 || port > 65535) {
|
|
244
|
+
console.error(`Invalid port: ${portArg}`);
|
|
245
|
+
process.exit(1);
|
|
246
|
+
}
|
|
247
|
+
config.port = port;
|
|
248
|
+
} else if (arg === "--no-auto-approve") {
|
|
249
|
+
config.autoApprove = false;
|
|
250
|
+
} else if (arg === "--dangerous") {
|
|
251
|
+
config.dangerous = true;
|
|
252
|
+
} else if (arg === "--interactive" || arg === "-i") {
|
|
253
|
+
config.interactive = true;
|
|
254
|
+
} else if (arg === "--debug" || arg === "-d") {
|
|
255
|
+
config.debug = true;
|
|
256
|
+
} else if (arg === "--log-level") {
|
|
257
|
+
const levelArg = args[++i];
|
|
258
|
+
if (!levelArg || !["debug", "info", "minimal"].includes(levelArg)) {
|
|
259
|
+
console.error("--log-level requires one of: debug, info, minimal");
|
|
260
|
+
process.exit(1);
|
|
261
|
+
}
|
|
262
|
+
config.logLevel = levelArg;
|
|
263
|
+
} else if (arg === "--quiet" || arg === "-q") {
|
|
264
|
+
config.quiet = true;
|
|
265
|
+
} else if (arg === "--verbose" || arg === "-v") {
|
|
266
|
+
config.quiet = false;
|
|
267
|
+
} else if (arg === "--json") {
|
|
268
|
+
config.jsonOutput = true;
|
|
269
|
+
} else if (arg === "--monitor") {
|
|
270
|
+
config.monitor = true;
|
|
271
|
+
} else if (arg === "--stdin") {
|
|
272
|
+
config.stdin = true;
|
|
273
|
+
} else if (arg === "--cost-tracker") {
|
|
274
|
+
config.costTracking = true;
|
|
275
|
+
if (!config.monitor) {
|
|
276
|
+
config.monitor = true;
|
|
277
|
+
}
|
|
278
|
+
} else if (arg === "--audit-costs") {
|
|
279
|
+
config.auditCosts = true;
|
|
280
|
+
} else if (arg === "--reset-costs") {
|
|
281
|
+
config.resetCosts = true;
|
|
282
|
+
} else if (arg === "--version") {
|
|
283
|
+
printVersion();
|
|
284
|
+
process.exit(0);
|
|
285
|
+
} else if (arg === "--help" || arg === "-h") {
|
|
286
|
+
printHelp();
|
|
287
|
+
process.exit(0);
|
|
288
|
+
} else if (arg === "--list-models") {
|
|
289
|
+
printAvailableModels();
|
|
290
|
+
process.exit(0);
|
|
291
|
+
} else {
|
|
292
|
+
config.claudeArgs = args.slice(i);
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
i++;
|
|
296
|
+
}
|
|
297
|
+
if (config.monitor) {
|
|
298
|
+
if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.includes("placeholder")) {
|
|
299
|
+
delete process.env.ANTHROPIC_API_KEY;
|
|
300
|
+
if (!config.quiet) {
|
|
301
|
+
console.log("[claudish] Removed placeholder API key - Claude Code will use native authentication");
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (!config.quiet) {
|
|
305
|
+
console.log("[claudish] Monitor mode enabled - proxying to real Anthropic API");
|
|
306
|
+
console.log("[claudish] API key will be extracted from Claude Code's requests");
|
|
307
|
+
console.log("[claudish] Ensure you are logged in to Claude Code (claude auth login)");
|
|
308
|
+
}
|
|
309
|
+
} else {
|
|
310
|
+
const apiKey = process.env[ENV.OPENROUTER_API_KEY];
|
|
311
|
+
if (!apiKey) {
|
|
312
|
+
console.error("Error: OPENROUTER_API_KEY environment variable is required");
|
|
313
|
+
console.error("Get your API key from: https://openrouter.ai/keys");
|
|
314
|
+
process.exit(1);
|
|
315
|
+
}
|
|
316
|
+
config.openrouterApiKey = apiKey;
|
|
317
|
+
if (!process.env.ANTHROPIC_API_KEY) {
|
|
318
|
+
console.error(`
|
|
319
|
+
Error: ANTHROPIC_API_KEY is not set`);
|
|
320
|
+
console.error("This placeholder key is required to prevent Claude Code from prompting.");
|
|
321
|
+
console.error("");
|
|
322
|
+
console.error("Set it now:");
|
|
323
|
+
console.error(" export ANTHROPIC_API_KEY='sk-ant-api03-placeholder'");
|
|
324
|
+
console.error("");
|
|
325
|
+
console.error("Or add it to your shell profile (~/.zshrc or ~/.bashrc) to set permanently.");
|
|
326
|
+
console.error("");
|
|
327
|
+
console.error("Note: This key is NOT used for auth - claudish uses OPENROUTER_API_KEY");
|
|
328
|
+
process.exit(1);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (!config.claudeArgs || config.claudeArgs.length === 0) {
|
|
332
|
+
config.interactive = true;
|
|
333
|
+
}
|
|
334
|
+
if (config.quiet === undefined) {
|
|
335
|
+
config.quiet = !config.interactive;
|
|
336
|
+
}
|
|
337
|
+
if (config.jsonOutput) {
|
|
338
|
+
config.quiet = true;
|
|
339
|
+
}
|
|
340
|
+
return config;
|
|
341
|
+
}
|
|
342
|
+
function printVersion() {
|
|
343
|
+
console.log("claudish version 1.2.1");
|
|
344
|
+
}
|
|
345
|
+
function printHelp() {
|
|
346
|
+
console.log(`
|
|
347
|
+
claudish - Run Claude Code with OpenRouter models
|
|
348
|
+
|
|
349
|
+
USAGE:
|
|
350
|
+
claudish # Interactive mode (default, shows model selector)
|
|
351
|
+
claudish [OPTIONS] <claude-args...> # Single-shot mode (requires --model)
|
|
352
|
+
|
|
353
|
+
OPTIONS:
|
|
354
|
+
-i, --interactive Run in interactive mode (default when no prompt given)
|
|
355
|
+
-m, --model <model> OpenRouter model to use (required for single-shot mode)
|
|
356
|
+
-p, --port <port> Proxy server port (default: random)
|
|
357
|
+
-d, --debug Enable debug logging to file (logs/claudish_*.log)
|
|
358
|
+
--log-level <level> Log verbosity: debug (full), info (truncated), minimal (labels only)
|
|
359
|
+
-q, --quiet Suppress [claudish] log messages (default in single-shot mode)
|
|
360
|
+
-v, --verbose Show [claudish] log messages (default in interactive mode)
|
|
361
|
+
--json Output in JSON format for tool integration (implies --quiet)
|
|
362
|
+
--stdin Read prompt from stdin (useful for large prompts or piping)
|
|
363
|
+
--monitor Monitor mode - proxy to REAL Anthropic API and log all traffic
|
|
364
|
+
--no-auto-approve Disable auto permission skip (prompts enabled)
|
|
365
|
+
--dangerous Pass --dangerouslyDisableSandbox to Claude Code
|
|
366
|
+
--cost-tracker Enable cost tracking for API usage (NB!)
|
|
367
|
+
--audit-costs Show cost analysis report
|
|
368
|
+
--reset-costs Reset accumulated cost statistics
|
|
369
|
+
--list-models List available OpenRouter models
|
|
370
|
+
--version Show version information
|
|
371
|
+
-h, --help Show this help message
|
|
372
|
+
|
|
373
|
+
MODES:
|
|
374
|
+
\u2022 Interactive mode (default): Shows model selector, starts persistent session
|
|
375
|
+
\u2022 Single-shot mode: Runs one task in headless mode and exits (requires --model)
|
|
376
|
+
|
|
377
|
+
NOTES:
|
|
378
|
+
\u2022 Permission prompts are SKIPPED by default (--dangerously-skip-permissions)
|
|
379
|
+
\u2022 Use --no-auto-approve to enable permission prompts
|
|
380
|
+
\u2022 Model selector appears ONLY in interactive mode when --model not specified
|
|
381
|
+
\u2022 Use --dangerous to disable sandbox (use with extreme caution!)
|
|
382
|
+
|
|
383
|
+
ENVIRONMENT VARIABLES:
|
|
384
|
+
OPENROUTER_API_KEY Required: Your OpenRouter API key
|
|
385
|
+
CLAUDISH_MODEL Default model to use
|
|
386
|
+
CLAUDISH_PORT Default port for proxy
|
|
387
|
+
CLAUDISH_ACTIVE_MODEL_NAME Auto-set by claudish (read-only) - shows active model in status line
|
|
388
|
+
|
|
389
|
+
EXAMPLES:
|
|
390
|
+
# Interactive mode (default) - shows model selector
|
|
391
|
+
claudish
|
|
392
|
+
claudish --interactive
|
|
393
|
+
|
|
394
|
+
# Interactive mode with pre-selected model
|
|
395
|
+
claudish --model x-ai/grok-code-fast-1
|
|
396
|
+
|
|
397
|
+
# Single-shot mode - one task and exit (requires --model or CLAUDISH_MODEL env var)
|
|
398
|
+
claudish --model openai/gpt-5-codex "implement user authentication"
|
|
399
|
+
claudish --model x-ai/grok-code-fast-1 "add tests for login"
|
|
400
|
+
|
|
401
|
+
# Use stdin for large prompts (e.g., git diffs, code review)
|
|
402
|
+
echo "Review this code..." | claudish --stdin --model x-ai/grok-code-fast-1
|
|
403
|
+
git diff | claudish --stdin --model openai/gpt-5-codex "Review these changes"
|
|
404
|
+
|
|
405
|
+
# Monitor mode - understand how Claude Code works (requires real Anthropic API key)
|
|
406
|
+
claudish --monitor --debug "analyze code structure"
|
|
407
|
+
|
|
408
|
+
# Disable auto-approve (require manual confirmation)
|
|
409
|
+
claudish --no-auto-approve "make changes to config"
|
|
410
|
+
|
|
411
|
+
# Dangerous mode (disable sandbox - use with extreme caution)
|
|
412
|
+
claudish --dangerous "refactor entire codebase"
|
|
413
|
+
|
|
414
|
+
# Both flags (fully autonomous)
|
|
415
|
+
claudish --dangerous "refactor entire codebase"
|
|
416
|
+
|
|
417
|
+
# With custom port
|
|
418
|
+
claudish --port 3000 "analyze code structure"
|
|
419
|
+
|
|
420
|
+
# Pass flags to claude
|
|
421
|
+
claudish --model x-ai/grok-code-fast-1 --verbose "debug issue"
|
|
422
|
+
|
|
423
|
+
# JSON output for tool integration (quiet by default)
|
|
424
|
+
claudish --json "list 5 prime numbers"
|
|
425
|
+
|
|
426
|
+
# Verbose mode in single-shot (show [claudish] logs)
|
|
427
|
+
claudish --verbose "analyze code structure"
|
|
428
|
+
|
|
429
|
+
AVAILABLE MODELS:
|
|
430
|
+
Run: claudish --list-models
|
|
431
|
+
|
|
432
|
+
MORE INFO:
|
|
433
|
+
GitHub: https://github.com/MadAppGang/claude-code
|
|
434
|
+
OpenRouter: https://openrouter.ai
|
|
435
|
+
`);
|
|
436
|
+
}
|
|
437
|
+
function printAvailableModels() {
|
|
438
|
+
console.log(`
|
|
439
|
+
Available OpenRouter Models (in priority order):
|
|
440
|
+
`);
|
|
441
|
+
for (const model of OPENROUTER_MODELS) {
|
|
442
|
+
const info = MODEL_INFO[model];
|
|
443
|
+
console.log(` ${model}`);
|
|
444
|
+
console.log(` ${info.name} - ${info.description}`);
|
|
445
|
+
console.log("");
|
|
446
|
+
}
|
|
447
|
+
console.log("Set default with: export CLAUDISH_MODEL=<model>");
|
|
448
|
+
console.log(`Or use: claudish --model <model> ...
|
|
449
|
+
`);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// src/simple-selector.ts
|
|
453
|
+
import { createInterface } from "readline";
|
|
454
|
+
async function selectModelInteractively() {
|
|
455
|
+
return new Promise((resolve) => {
|
|
456
|
+
console.log(`
|
|
457
|
+
\x1B[1m\x1B[36mSelect an OpenRouter model:\x1B[0m
|
|
458
|
+
`);
|
|
459
|
+
OPENROUTER_MODELS.forEach((model, index) => {
|
|
460
|
+
const info = MODEL_INFO[model];
|
|
461
|
+
const displayName = info ? info.name : model;
|
|
462
|
+
const description = info ? info.description : "Custom model entry";
|
|
463
|
+
const provider = info ? info.provider : "";
|
|
464
|
+
console.log(` ${index + 1}. \x1B[1m${displayName}\x1B[0m`);
|
|
465
|
+
if (provider && provider !== "Custom") {
|
|
466
|
+
console.log(` \x1B[2m${provider} - ${description}\x1B[0m`);
|
|
467
|
+
} else {
|
|
468
|
+
console.log(` \x1B[2m${description}\x1B[0m`);
|
|
469
|
+
}
|
|
470
|
+
console.log("");
|
|
471
|
+
});
|
|
472
|
+
console.log(`\x1B[2mEnter number (1-${OPENROUTER_MODELS.length}) or 'q' to quit:\x1B[0m`);
|
|
473
|
+
const rl = createInterface({
|
|
474
|
+
input: process.stdin,
|
|
475
|
+
output: process.stdout,
|
|
476
|
+
terminal: false
|
|
477
|
+
});
|
|
478
|
+
let selectedModel = null;
|
|
479
|
+
rl.on("line", (input) => {
|
|
480
|
+
const trimmed = input.trim();
|
|
481
|
+
if (trimmed.toLowerCase() === "q") {
|
|
482
|
+
rl.close();
|
|
483
|
+
process.exit(0);
|
|
484
|
+
}
|
|
485
|
+
const selection = parseInt(trimmed, 10);
|
|
486
|
+
if (isNaN(selection) || selection < 1 || selection > OPENROUTER_MODELS.length) {
|
|
487
|
+
console.log(`\x1B[31mInvalid selection. Please enter 1-${OPENROUTER_MODELS.length}\x1B[0m`);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const model = OPENROUTER_MODELS[selection - 1];
|
|
491
|
+
if (model === "custom") {
|
|
492
|
+
rl.close();
|
|
493
|
+
console.log(`
|
|
494
|
+
\x1B[1m\x1B[36mEnter custom OpenRouter model ID:\x1B[0m`);
|
|
495
|
+
const customRl = createInterface({
|
|
496
|
+
input: process.stdin,
|
|
497
|
+
output: process.stdout,
|
|
498
|
+
terminal: false
|
|
499
|
+
});
|
|
500
|
+
let customModel = null;
|
|
501
|
+
customRl.on("line", (customInput) => {
|
|
502
|
+
customModel = customInput.trim();
|
|
503
|
+
customRl.close();
|
|
504
|
+
});
|
|
505
|
+
customRl.on("close", () => {
|
|
506
|
+
process.stdin.pause();
|
|
507
|
+
process.stdin.removeAllListeners("data");
|
|
508
|
+
process.stdin.removeAllListeners("end");
|
|
509
|
+
process.stdin.removeAllListeners("error");
|
|
510
|
+
process.stdin.removeAllListeners("readable");
|
|
511
|
+
if (process.stdin.isTTY && process.stdin.setRawMode) {
|
|
512
|
+
process.stdin.setRawMode(false);
|
|
513
|
+
}
|
|
514
|
+
setTimeout(() => {
|
|
515
|
+
if (customModel) {
|
|
516
|
+
resolve(customModel);
|
|
517
|
+
} else {
|
|
518
|
+
console.error("\x1B[31mError: Model ID cannot be empty\x1B[0m");
|
|
519
|
+
process.exit(1);
|
|
520
|
+
}
|
|
521
|
+
}, 200);
|
|
522
|
+
});
|
|
523
|
+
} else {
|
|
524
|
+
selectedModel = model;
|
|
525
|
+
rl.close();
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
rl.on("close", () => {
|
|
529
|
+
if (selectedModel) {
|
|
530
|
+
process.stdin.pause();
|
|
531
|
+
process.stdin.removeAllListeners("data");
|
|
532
|
+
process.stdin.removeAllListeners("end");
|
|
533
|
+
process.stdin.removeAllListeners("error");
|
|
534
|
+
process.stdin.removeAllListeners("readable");
|
|
535
|
+
if (process.stdin.isTTY && process.stdin.setRawMode) {
|
|
536
|
+
process.stdin.setRawMode(false);
|
|
537
|
+
}
|
|
538
|
+
setTimeout(() => {
|
|
539
|
+
resolve(selectedModel);
|
|
540
|
+
}, 200);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// src/logger.ts
|
|
547
|
+
import { writeFileSync as writeFileSync2, appendFile, existsSync, mkdirSync } from "fs";
|
|
548
|
+
import { join as join2 } from "path";
|
|
549
|
+
var logFilePath = null;
|
|
550
|
+
var logLevel = "info";
|
|
551
|
+
var logBuffer = [];
|
|
552
|
+
var flushTimer = null;
|
|
553
|
+
var FLUSH_INTERVAL_MS = 100;
|
|
554
|
+
var MAX_BUFFER_SIZE = 50;
|
|
555
|
+
function flushLogBuffer() {
|
|
556
|
+
if (!logFilePath || logBuffer.length === 0)
|
|
557
|
+
return;
|
|
558
|
+
const toWrite = logBuffer.join("");
|
|
559
|
+
logBuffer = [];
|
|
560
|
+
appendFile(logFilePath, toWrite, (err) => {
|
|
561
|
+
if (err) {
|
|
562
|
+
console.error(`[claudish] Warning: Failed to write to log file: ${err.message}`);
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
function scheduleFlush() {
|
|
567
|
+
if (flushTimer)
|
|
568
|
+
return;
|
|
569
|
+
flushTimer = setInterval(() => {
|
|
570
|
+
flushLogBuffer();
|
|
571
|
+
}, FLUSH_INTERVAL_MS);
|
|
572
|
+
process.on("exit", () => {
|
|
573
|
+
if (flushTimer) {
|
|
574
|
+
clearInterval(flushTimer);
|
|
575
|
+
flushTimer = null;
|
|
576
|
+
}
|
|
577
|
+
if (logFilePath && logBuffer.length > 0) {
|
|
578
|
+
writeFileSync2(logFilePath, logBuffer.join(""), { flag: "a" });
|
|
579
|
+
logBuffer = [];
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
function initLogger(debugMode, level = "info") {
|
|
584
|
+
if (!debugMode) {
|
|
585
|
+
logFilePath = null;
|
|
586
|
+
if (flushTimer) {
|
|
587
|
+
clearInterval(flushTimer);
|
|
588
|
+
flushTimer = null;
|
|
589
|
+
}
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
logLevel = level;
|
|
593
|
+
const logsDir = join2(process.cwd(), "logs");
|
|
594
|
+
if (!existsSync(logsDir)) {
|
|
595
|
+
mkdirSync(logsDir, { recursive: true });
|
|
596
|
+
}
|
|
597
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T").join("_").slice(0, -5);
|
|
598
|
+
logFilePath = join2(logsDir, `claudish_${timestamp}.log`);
|
|
599
|
+
writeFileSync2(logFilePath, `Claudish Debug Log - ${new Date().toISOString()}
|
|
600
|
+
Log Level: ${level}
|
|
601
|
+
${"=".repeat(80)}
|
|
602
|
+
|
|
603
|
+
`);
|
|
604
|
+
scheduleFlush();
|
|
605
|
+
}
|
|
606
|
+
function log(message, forceConsole = false) {
|
|
607
|
+
const timestamp = new Date().toISOString();
|
|
608
|
+
const logLine = `[${timestamp}] ${message}
|
|
609
|
+
`;
|
|
610
|
+
if (logFilePath) {
|
|
611
|
+
logBuffer.push(logLine);
|
|
612
|
+
if (logBuffer.length >= MAX_BUFFER_SIZE) {
|
|
613
|
+
flushLogBuffer();
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (forceConsole) {
|
|
617
|
+
console.log(message);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function getLogFilePath() {
|
|
621
|
+
return logFilePath;
|
|
622
|
+
}
|
|
623
|
+
function isLoggingEnabled() {
|
|
624
|
+
return logFilePath !== null;
|
|
625
|
+
}
|
|
626
|
+
function maskCredential(credential) {
|
|
627
|
+
if (!credential || credential.length <= 8) {
|
|
628
|
+
return "***";
|
|
629
|
+
}
|
|
630
|
+
return `${credential.substring(0, 4)}...${credential.substring(credential.length - 4)}`;
|
|
631
|
+
}
|
|
632
|
+
function truncateContent(content, maxLength = 200) {
|
|
633
|
+
const str = typeof content === "string" ? content : JSON.stringify(content);
|
|
634
|
+
if (str.length <= maxLength) {
|
|
635
|
+
return str;
|
|
636
|
+
}
|
|
637
|
+
return `${str.substring(0, maxLength)}... [truncated ${str.length - maxLength} chars]`;
|
|
638
|
+
}
|
|
639
|
+
function logStructured(label, data) {
|
|
640
|
+
if (!logFilePath)
|
|
641
|
+
return;
|
|
642
|
+
if (logLevel === "minimal") {
|
|
643
|
+
log(`[${label}]`);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
if (logLevel === "info") {
|
|
647
|
+
const structured = {};
|
|
648
|
+
for (const [key, value] of Object.entries(data)) {
|
|
649
|
+
if (typeof value === "string" || typeof value === "object") {
|
|
650
|
+
structured[key] = truncateContent(value, 150);
|
|
651
|
+
} else {
|
|
652
|
+
structured[key] = value;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
log(`[${label}] ${JSON.stringify(structured, null, 2)}`);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
log(`[${label}] ${JSON.stringify(data, null, 2)}`);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// src/port-manager.ts
|
|
662
|
+
import { createServer } from "net";
|
|
663
|
+
async function findAvailablePort(startPort = 3000, endPort = 9000) {
|
|
664
|
+
const randomPort = Math.floor(Math.random() * (endPort - startPort + 1)) + startPort;
|
|
665
|
+
if (await isPortAvailable(randomPort)) {
|
|
666
|
+
return randomPort;
|
|
667
|
+
}
|
|
668
|
+
for (let port = startPort;port <= endPort; port++) {
|
|
669
|
+
if (await isPortAvailable(port)) {
|
|
670
|
+
return port;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
throw new Error(`No available ports found in range ${startPort}-${endPort}`);
|
|
674
|
+
}
|
|
675
|
+
async function isPortAvailable(port) {
|
|
676
|
+
return new Promise((resolve) => {
|
|
677
|
+
const server = createServer();
|
|
678
|
+
server.once("error", (err) => {
|
|
679
|
+
resolve(err.code !== "EADDRINUSE");
|
|
680
|
+
});
|
|
681
|
+
server.once("listening", () => {
|
|
682
|
+
server.close();
|
|
683
|
+
resolve(true);
|
|
684
|
+
});
|
|
685
|
+
server.listen(port, "127.0.0.1");
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// node_modules/hono/dist/compose.js
|
|
690
|
+
var compose = (middleware, onError, onNotFound) => {
|
|
691
|
+
return (context, next) => {
|
|
692
|
+
let index = -1;
|
|
693
|
+
return dispatch(0);
|
|
694
|
+
async function dispatch(i) {
|
|
695
|
+
if (i <= index) {
|
|
696
|
+
throw new Error("next() called multiple times");
|
|
697
|
+
}
|
|
698
|
+
index = i;
|
|
699
|
+
let res;
|
|
700
|
+
let isError = false;
|
|
701
|
+
let handler;
|
|
702
|
+
if (middleware[i]) {
|
|
703
|
+
handler = middleware[i][0][0];
|
|
704
|
+
context.req.routeIndex = i;
|
|
705
|
+
} else {
|
|
706
|
+
handler = i === middleware.length && next || undefined;
|
|
707
|
+
}
|
|
708
|
+
if (handler) {
|
|
709
|
+
try {
|
|
710
|
+
res = await handler(context, () => dispatch(i + 1));
|
|
711
|
+
} catch (err) {
|
|
712
|
+
if (err instanceof Error && onError) {
|
|
713
|
+
context.error = err;
|
|
714
|
+
res = await onError(err, context);
|
|
715
|
+
isError = true;
|
|
716
|
+
} else {
|
|
717
|
+
throw err;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
} else {
|
|
721
|
+
if (context.finalized === false && onNotFound) {
|
|
722
|
+
res = await onNotFound(context);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (res && (context.finalized === false || isError)) {
|
|
726
|
+
context.res = res;
|
|
727
|
+
}
|
|
728
|
+
return context;
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
// node_modules/hono/dist/request/constants.js
|
|
734
|
+
var GET_MATCH_RESULT = Symbol();
|
|
735
|
+
|
|
736
|
+
// node_modules/hono/dist/utils/body.js
|
|
737
|
+
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
738
|
+
const { all = false, dot = false } = options;
|
|
739
|
+
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
740
|
+
const contentType = headers.get("Content-Type");
|
|
741
|
+
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
742
|
+
return parseFormData(request, { all, dot });
|
|
743
|
+
}
|
|
744
|
+
return {};
|
|
745
|
+
};
|
|
746
|
+
async function parseFormData(request, options) {
|
|
747
|
+
const formData = await request.formData();
|
|
748
|
+
if (formData) {
|
|
749
|
+
return convertFormDataToBodyData(formData, options);
|
|
750
|
+
}
|
|
751
|
+
return {};
|
|
752
|
+
}
|
|
753
|
+
function convertFormDataToBodyData(formData, options) {
|
|
754
|
+
const form = /* @__PURE__ */ Object.create(null);
|
|
755
|
+
formData.forEach((value, key) => {
|
|
756
|
+
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
757
|
+
if (!shouldParseAllValues) {
|
|
758
|
+
form[key] = value;
|
|
759
|
+
} else {
|
|
760
|
+
handleParsingAllValues(form, key, value);
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
if (options.dot) {
|
|
764
|
+
Object.entries(form).forEach(([key, value]) => {
|
|
765
|
+
const shouldParseDotValues = key.includes(".");
|
|
766
|
+
if (shouldParseDotValues) {
|
|
767
|
+
handleParsingNestedValues(form, key, value);
|
|
768
|
+
delete form[key];
|
|
769
|
+
}
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
return form;
|
|
773
|
+
}
|
|
774
|
+
var handleParsingAllValues = (form, key, value) => {
|
|
775
|
+
if (form[key] !== undefined) {
|
|
776
|
+
if (Array.isArray(form[key])) {
|
|
777
|
+
form[key].push(value);
|
|
778
|
+
} else {
|
|
779
|
+
form[key] = [form[key], value];
|
|
780
|
+
}
|
|
781
|
+
} else {
|
|
782
|
+
if (!key.endsWith("[]")) {
|
|
783
|
+
form[key] = value;
|
|
784
|
+
} else {
|
|
785
|
+
form[key] = [value];
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
var handleParsingNestedValues = (form, key, value) => {
|
|
790
|
+
let nestedForm = form;
|
|
791
|
+
const keys = key.split(".");
|
|
792
|
+
keys.forEach((key2, index) => {
|
|
793
|
+
if (index === keys.length - 1) {
|
|
794
|
+
nestedForm[key2] = value;
|
|
795
|
+
} else {
|
|
796
|
+
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
797
|
+
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
798
|
+
}
|
|
799
|
+
nestedForm = nestedForm[key2];
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
// node_modules/hono/dist/utils/url.js
|
|
805
|
+
var splitPath = (path) => {
|
|
806
|
+
const paths = path.split("/");
|
|
807
|
+
if (paths[0] === "") {
|
|
808
|
+
paths.shift();
|
|
809
|
+
}
|
|
810
|
+
return paths;
|
|
811
|
+
};
|
|
812
|
+
var splitRoutingPath = (routePath) => {
|
|
813
|
+
const { groups, path } = extractGroupsFromPath(routePath);
|
|
814
|
+
const paths = splitPath(path);
|
|
815
|
+
return replaceGroupMarks(paths, groups);
|
|
816
|
+
};
|
|
817
|
+
var extractGroupsFromPath = (path) => {
|
|
818
|
+
const groups = [];
|
|
819
|
+
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
820
|
+
const mark = `@${index}`;
|
|
821
|
+
groups.push([mark, match]);
|
|
822
|
+
return mark;
|
|
823
|
+
});
|
|
824
|
+
return { groups, path };
|
|
825
|
+
};
|
|
826
|
+
var replaceGroupMarks = (paths, groups) => {
|
|
827
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
828
|
+
const [mark] = groups[i];
|
|
829
|
+
for (let j = paths.length - 1;j >= 0; j--) {
|
|
830
|
+
if (paths[j].includes(mark)) {
|
|
831
|
+
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
832
|
+
break;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return paths;
|
|
837
|
+
};
|
|
838
|
+
var patternCache = {};
|
|
839
|
+
var getPattern = (label, next) => {
|
|
840
|
+
if (label === "*") {
|
|
841
|
+
return "*";
|
|
842
|
+
}
|
|
843
|
+
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
844
|
+
if (match) {
|
|
845
|
+
const cacheKey = `${label}#${next}`;
|
|
846
|
+
if (!patternCache[cacheKey]) {
|
|
847
|
+
if (match[2]) {
|
|
848
|
+
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
|
|
849
|
+
} else {
|
|
850
|
+
patternCache[cacheKey] = [label, match[1], true];
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return patternCache[cacheKey];
|
|
854
|
+
}
|
|
855
|
+
return null;
|
|
856
|
+
};
|
|
857
|
+
var tryDecode = (str, decoder) => {
|
|
858
|
+
try {
|
|
859
|
+
return decoder(str);
|
|
860
|
+
} catch {
|
|
861
|
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
862
|
+
try {
|
|
863
|
+
return decoder(match);
|
|
864
|
+
} catch {
|
|
865
|
+
return match;
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
871
|
+
var getPath = (request) => {
|
|
872
|
+
const url = request.url;
|
|
873
|
+
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
874
|
+
let i = start;
|
|
875
|
+
for (;i < url.length; i++) {
|
|
876
|
+
const charCode = url.charCodeAt(i);
|
|
877
|
+
if (charCode === 37) {
|
|
878
|
+
const queryIndex = url.indexOf("?", i);
|
|
879
|
+
const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
|
|
880
|
+
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
881
|
+
} else if (charCode === 63) {
|
|
882
|
+
break;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return url.slice(start, i);
|
|
886
|
+
};
|
|
887
|
+
var getPathNoStrict = (request) => {
|
|
888
|
+
const result = getPath(request);
|
|
889
|
+
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
890
|
+
};
|
|
891
|
+
var mergePath = (base, sub, ...rest) => {
|
|
892
|
+
if (rest.length) {
|
|
893
|
+
sub = mergePath(sub, ...rest);
|
|
894
|
+
}
|
|
895
|
+
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
896
|
+
};
|
|
897
|
+
var checkOptionalParameter = (path) => {
|
|
898
|
+
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
899
|
+
return null;
|
|
900
|
+
}
|
|
901
|
+
const segments = path.split("/");
|
|
902
|
+
const results = [];
|
|
903
|
+
let basePath = "";
|
|
904
|
+
segments.forEach((segment) => {
|
|
905
|
+
if (segment !== "" && !/\:/.test(segment)) {
|
|
906
|
+
basePath += "/" + segment;
|
|
907
|
+
} else if (/\:/.test(segment)) {
|
|
908
|
+
if (/\?/.test(segment)) {
|
|
909
|
+
if (results.length === 0 && basePath === "") {
|
|
910
|
+
results.push("/");
|
|
911
|
+
} else {
|
|
912
|
+
results.push(basePath);
|
|
913
|
+
}
|
|
914
|
+
const optionalSegment = segment.replace("?", "");
|
|
915
|
+
basePath += "/" + optionalSegment;
|
|
916
|
+
results.push(basePath);
|
|
917
|
+
} else {
|
|
918
|
+
basePath += "/" + segment;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
923
|
+
};
|
|
924
|
+
var _decodeURI = (value) => {
|
|
925
|
+
if (!/[%+]/.test(value)) {
|
|
926
|
+
return value;
|
|
927
|
+
}
|
|
928
|
+
if (value.indexOf("+") !== -1) {
|
|
929
|
+
value = value.replace(/\+/g, " ");
|
|
930
|
+
}
|
|
931
|
+
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
932
|
+
};
|
|
933
|
+
var _getQueryParam = (url, key, multiple) => {
|
|
934
|
+
let encoded;
|
|
935
|
+
if (!multiple && key && !/[%+]/.test(key)) {
|
|
936
|
+
let keyIndex2 = url.indexOf(`?${key}`, 8);
|
|
937
|
+
if (keyIndex2 === -1) {
|
|
938
|
+
keyIndex2 = url.indexOf(`&${key}`, 8);
|
|
939
|
+
}
|
|
940
|
+
while (keyIndex2 !== -1) {
|
|
941
|
+
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
942
|
+
if (trailingKeyCode === 61) {
|
|
943
|
+
const valueIndex = keyIndex2 + key.length + 2;
|
|
944
|
+
const endIndex = url.indexOf("&", valueIndex);
|
|
945
|
+
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
|
|
946
|
+
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
947
|
+
return "";
|
|
948
|
+
}
|
|
949
|
+
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
950
|
+
}
|
|
951
|
+
encoded = /[%+]/.test(url);
|
|
952
|
+
if (!encoded) {
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
const results = {};
|
|
957
|
+
encoded ??= /[%+]/.test(url);
|
|
958
|
+
let keyIndex = url.indexOf("?", 8);
|
|
959
|
+
while (keyIndex !== -1) {
|
|
960
|
+
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
961
|
+
let valueIndex = url.indexOf("=", keyIndex);
|
|
962
|
+
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
963
|
+
valueIndex = -1;
|
|
964
|
+
}
|
|
965
|
+
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
|
|
966
|
+
if (encoded) {
|
|
967
|
+
name = _decodeURI(name);
|
|
968
|
+
}
|
|
969
|
+
keyIndex = nextKeyIndex;
|
|
970
|
+
if (name === "") {
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
let value;
|
|
974
|
+
if (valueIndex === -1) {
|
|
975
|
+
value = "";
|
|
976
|
+
} else {
|
|
977
|
+
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
|
|
978
|
+
if (encoded) {
|
|
979
|
+
value = _decodeURI(value);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (multiple) {
|
|
983
|
+
if (!(results[name] && Array.isArray(results[name]))) {
|
|
984
|
+
results[name] = [];
|
|
985
|
+
}
|
|
986
|
+
results[name].push(value);
|
|
987
|
+
} else {
|
|
988
|
+
results[name] ??= value;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
return key ? results[key] : results;
|
|
992
|
+
};
|
|
993
|
+
var getQueryParam = _getQueryParam;
|
|
994
|
+
var getQueryParams = (url, key) => {
|
|
995
|
+
return _getQueryParam(url, key, true);
|
|
996
|
+
};
|
|
997
|
+
var decodeURIComponent_ = decodeURIComponent;
|
|
998
|
+
|
|
999
|
+
// node_modules/hono/dist/request.js
|
|
1000
|
+
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
1001
|
+
var HonoRequest = class {
|
|
1002
|
+
raw;
|
|
1003
|
+
#validatedData;
|
|
1004
|
+
#matchResult;
|
|
1005
|
+
routeIndex = 0;
|
|
1006
|
+
path;
|
|
1007
|
+
bodyCache = {};
|
|
1008
|
+
constructor(request, path = "/", matchResult = [[]]) {
|
|
1009
|
+
this.raw = request;
|
|
1010
|
+
this.path = path;
|
|
1011
|
+
this.#matchResult = matchResult;
|
|
1012
|
+
this.#validatedData = {};
|
|
1013
|
+
}
|
|
1014
|
+
param(key) {
|
|
1015
|
+
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
1016
|
+
}
|
|
1017
|
+
#getDecodedParam(key) {
|
|
1018
|
+
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
1019
|
+
const param = this.#getParamValue(paramKey);
|
|
1020
|
+
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
1021
|
+
}
|
|
1022
|
+
#getAllDecodedParams() {
|
|
1023
|
+
const decoded = {};
|
|
1024
|
+
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
1025
|
+
for (const key of keys) {
|
|
1026
|
+
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
1027
|
+
if (value !== undefined) {
|
|
1028
|
+
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
return decoded;
|
|
1032
|
+
}
|
|
1033
|
+
#getParamValue(paramKey) {
|
|
1034
|
+
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
1035
|
+
}
|
|
1036
|
+
query(key) {
|
|
1037
|
+
return getQueryParam(this.url, key);
|
|
1038
|
+
}
|
|
1039
|
+
queries(key) {
|
|
1040
|
+
return getQueryParams(this.url, key);
|
|
1041
|
+
}
|
|
1042
|
+
header(name) {
|
|
1043
|
+
if (name) {
|
|
1044
|
+
return this.raw.headers.get(name) ?? undefined;
|
|
1045
|
+
}
|
|
1046
|
+
const headerData = {};
|
|
1047
|
+
this.raw.headers.forEach((value, key) => {
|
|
1048
|
+
headerData[key] = value;
|
|
1049
|
+
});
|
|
1050
|
+
return headerData;
|
|
1051
|
+
}
|
|
1052
|
+
async parseBody(options) {
|
|
1053
|
+
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
1054
|
+
}
|
|
1055
|
+
#cachedBody = (key) => {
|
|
1056
|
+
const { bodyCache, raw } = this;
|
|
1057
|
+
const cachedBody = bodyCache[key];
|
|
1058
|
+
if (cachedBody) {
|
|
1059
|
+
return cachedBody;
|
|
1060
|
+
}
|
|
1061
|
+
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
1062
|
+
if (anyCachedKey) {
|
|
1063
|
+
return bodyCache[anyCachedKey].then((body) => {
|
|
1064
|
+
if (anyCachedKey === "json") {
|
|
1065
|
+
body = JSON.stringify(body);
|
|
1066
|
+
}
|
|
1067
|
+
return new Response(body)[key]();
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
return bodyCache[key] = raw[key]();
|
|
1071
|
+
};
|
|
1072
|
+
json() {
|
|
1073
|
+
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
1074
|
+
}
|
|
1075
|
+
text() {
|
|
1076
|
+
return this.#cachedBody("text");
|
|
1077
|
+
}
|
|
1078
|
+
arrayBuffer() {
|
|
1079
|
+
return this.#cachedBody("arrayBuffer");
|
|
1080
|
+
}
|
|
1081
|
+
blob() {
|
|
1082
|
+
return this.#cachedBody("blob");
|
|
1083
|
+
}
|
|
1084
|
+
formData() {
|
|
1085
|
+
return this.#cachedBody("formData");
|
|
1086
|
+
}
|
|
1087
|
+
addValidatedData(target, data) {
|
|
1088
|
+
this.#validatedData[target] = data;
|
|
1089
|
+
}
|
|
1090
|
+
valid(target) {
|
|
1091
|
+
return this.#validatedData[target];
|
|
1092
|
+
}
|
|
1093
|
+
get url() {
|
|
1094
|
+
return this.raw.url;
|
|
1095
|
+
}
|
|
1096
|
+
get method() {
|
|
1097
|
+
return this.raw.method;
|
|
1098
|
+
}
|
|
1099
|
+
get [GET_MATCH_RESULT]() {
|
|
1100
|
+
return this.#matchResult;
|
|
1101
|
+
}
|
|
1102
|
+
get matchedRoutes() {
|
|
1103
|
+
return this.#matchResult[0].map(([[, route]]) => route);
|
|
1104
|
+
}
|
|
1105
|
+
get routePath() {
|
|
1106
|
+
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
|
|
1110
|
+
// node_modules/hono/dist/utils/html.js
|
|
1111
|
+
var HtmlEscapedCallbackPhase = {
|
|
1112
|
+
Stringify: 1,
|
|
1113
|
+
BeforeStream: 2,
|
|
1114
|
+
Stream: 3
|
|
1115
|
+
};
|
|
1116
|
+
var raw = (value, callbacks) => {
|
|
1117
|
+
const escapedString = new String(value);
|
|
1118
|
+
escapedString.isEscaped = true;
|
|
1119
|
+
escapedString.callbacks = callbacks;
|
|
1120
|
+
return escapedString;
|
|
1121
|
+
};
|
|
1122
|
+
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
1123
|
+
if (typeof str === "object" && !(str instanceof String)) {
|
|
1124
|
+
if (!(str instanceof Promise)) {
|
|
1125
|
+
str = str.toString();
|
|
1126
|
+
}
|
|
1127
|
+
if (str instanceof Promise) {
|
|
1128
|
+
str = await str;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
const callbacks = str.callbacks;
|
|
1132
|
+
if (!callbacks?.length) {
|
|
1133
|
+
return Promise.resolve(str);
|
|
1134
|
+
}
|
|
1135
|
+
if (buffer) {
|
|
1136
|
+
buffer[0] += str;
|
|
1137
|
+
} else {
|
|
1138
|
+
buffer = [str];
|
|
1139
|
+
}
|
|
1140
|
+
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
|
|
1141
|
+
if (preserveCallbacks) {
|
|
1142
|
+
return raw(await resStr, callbacks);
|
|
1143
|
+
} else {
|
|
1144
|
+
return resStr;
|
|
1145
|
+
}
|
|
1146
|
+
};
|
|
1147
|
+
|
|
1148
|
+
// node_modules/hono/dist/context.js
|
|
1149
|
+
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
1150
|
+
var setDefaultContentType = (contentType, headers) => {
|
|
1151
|
+
return {
|
|
1152
|
+
"Content-Type": contentType,
|
|
1153
|
+
...headers
|
|
1154
|
+
};
|
|
1155
|
+
};
|
|
1156
|
+
var Context = class {
|
|
1157
|
+
#rawRequest;
|
|
1158
|
+
#req;
|
|
1159
|
+
env = {};
|
|
1160
|
+
#var;
|
|
1161
|
+
finalized = false;
|
|
1162
|
+
error;
|
|
1163
|
+
#status;
|
|
1164
|
+
#executionCtx;
|
|
1165
|
+
#res;
|
|
1166
|
+
#layout;
|
|
1167
|
+
#renderer;
|
|
1168
|
+
#notFoundHandler;
|
|
1169
|
+
#preparedHeaders;
|
|
1170
|
+
#matchResult;
|
|
1171
|
+
#path;
|
|
1172
|
+
constructor(req, options) {
|
|
1173
|
+
this.#rawRequest = req;
|
|
1174
|
+
if (options) {
|
|
1175
|
+
this.#executionCtx = options.executionCtx;
|
|
1176
|
+
this.env = options.env;
|
|
1177
|
+
this.#notFoundHandler = options.notFoundHandler;
|
|
1178
|
+
this.#path = options.path;
|
|
1179
|
+
this.#matchResult = options.matchResult;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
get req() {
|
|
1183
|
+
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
1184
|
+
return this.#req;
|
|
1185
|
+
}
|
|
1186
|
+
get event() {
|
|
1187
|
+
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
1188
|
+
return this.#executionCtx;
|
|
1189
|
+
} else {
|
|
1190
|
+
throw Error("This context has no FetchEvent");
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
get executionCtx() {
|
|
1194
|
+
if (this.#executionCtx) {
|
|
1195
|
+
return this.#executionCtx;
|
|
1196
|
+
} else {
|
|
1197
|
+
throw Error("This context has no ExecutionContext");
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
get res() {
|
|
1201
|
+
return this.#res ||= new Response(null, {
|
|
1202
|
+
headers: this.#preparedHeaders ??= new Headers
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
set res(_res) {
|
|
1206
|
+
if (this.#res && _res) {
|
|
1207
|
+
_res = new Response(_res.body, _res);
|
|
1208
|
+
for (const [k, v] of this.#res.headers.entries()) {
|
|
1209
|
+
if (k === "content-type") {
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
if (k === "set-cookie") {
|
|
1213
|
+
const cookies = this.#res.headers.getSetCookie();
|
|
1214
|
+
_res.headers.delete("set-cookie");
|
|
1215
|
+
for (const cookie of cookies) {
|
|
1216
|
+
_res.headers.append("set-cookie", cookie);
|
|
1217
|
+
}
|
|
1218
|
+
} else {
|
|
1219
|
+
_res.headers.set(k, v);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
this.#res = _res;
|
|
1224
|
+
this.finalized = true;
|
|
1225
|
+
}
|
|
1226
|
+
render = (...args) => {
|
|
1227
|
+
this.#renderer ??= (content) => this.html(content);
|
|
1228
|
+
return this.#renderer(...args);
|
|
1229
|
+
};
|
|
1230
|
+
setLayout = (layout) => this.#layout = layout;
|
|
1231
|
+
getLayout = () => this.#layout;
|
|
1232
|
+
setRenderer = (renderer) => {
|
|
1233
|
+
this.#renderer = renderer;
|
|
1234
|
+
};
|
|
1235
|
+
header = (name, value, options) => {
|
|
1236
|
+
if (this.finalized) {
|
|
1237
|
+
this.#res = new Response(this.#res.body, this.#res);
|
|
1238
|
+
}
|
|
1239
|
+
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
|
|
1240
|
+
if (value === undefined) {
|
|
1241
|
+
headers.delete(name);
|
|
1242
|
+
} else if (options?.append) {
|
|
1243
|
+
headers.append(name, value);
|
|
1244
|
+
} else {
|
|
1245
|
+
headers.set(name, value);
|
|
1246
|
+
}
|
|
1247
|
+
};
|
|
1248
|
+
status = (status) => {
|
|
1249
|
+
this.#status = status;
|
|
1250
|
+
};
|
|
1251
|
+
set = (key, value) => {
|
|
1252
|
+
this.#var ??= /* @__PURE__ */ new Map;
|
|
1253
|
+
this.#var.set(key, value);
|
|
1254
|
+
};
|
|
1255
|
+
get = (key) => {
|
|
1256
|
+
return this.#var ? this.#var.get(key) : undefined;
|
|
1257
|
+
};
|
|
1258
|
+
get var() {
|
|
1259
|
+
if (!this.#var) {
|
|
1260
|
+
return {};
|
|
1261
|
+
}
|
|
1262
|
+
return Object.fromEntries(this.#var);
|
|
1263
|
+
}
|
|
1264
|
+
#newResponse(data, arg, headers) {
|
|
1265
|
+
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
|
|
1266
|
+
if (typeof arg === "object" && "headers" in arg) {
|
|
1267
|
+
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
1268
|
+
for (const [key, value] of argHeaders) {
|
|
1269
|
+
if (key.toLowerCase() === "set-cookie") {
|
|
1270
|
+
responseHeaders.append(key, value);
|
|
1271
|
+
} else {
|
|
1272
|
+
responseHeaders.set(key, value);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
if (headers) {
|
|
1277
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1278
|
+
if (typeof v === "string") {
|
|
1279
|
+
responseHeaders.set(k, v);
|
|
1280
|
+
} else {
|
|
1281
|
+
responseHeaders.delete(k);
|
|
1282
|
+
for (const v2 of v) {
|
|
1283
|
+
responseHeaders.append(k, v2);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
1289
|
+
return new Response(data, { status, headers: responseHeaders });
|
|
1290
|
+
}
|
|
1291
|
+
newResponse = (...args) => this.#newResponse(...args);
|
|
1292
|
+
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
1293
|
+
text = (text, arg, headers) => {
|
|
1294
|
+
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
|
|
1295
|
+
};
|
|
1296
|
+
json = (object, arg, headers) => {
|
|
1297
|
+
return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
|
|
1298
|
+
};
|
|
1299
|
+
html = (html, arg, headers) => {
|
|
1300
|
+
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
1301
|
+
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
1302
|
+
};
|
|
1303
|
+
redirect = (location, status) => {
|
|
1304
|
+
const locationString = String(location);
|
|
1305
|
+
this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
|
|
1306
|
+
return this.newResponse(null, status ?? 302);
|
|
1307
|
+
};
|
|
1308
|
+
notFound = () => {
|
|
1309
|
+
this.#notFoundHandler ??= () => new Response;
|
|
1310
|
+
return this.#notFoundHandler(this);
|
|
1311
|
+
};
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
// node_modules/hono/dist/router.js
|
|
1315
|
+
var METHOD_NAME_ALL = "ALL";
|
|
1316
|
+
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
1317
|
+
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
1318
|
+
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
1319
|
+
var UnsupportedPathError = class extends Error {
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
// node_modules/hono/dist/utils/constants.js
|
|
1323
|
+
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
1324
|
+
|
|
1325
|
+
// node_modules/hono/dist/hono-base.js
|
|
1326
|
+
var notFoundHandler = (c) => {
|
|
1327
|
+
return c.text("404 Not Found", 404);
|
|
1328
|
+
};
|
|
1329
|
+
var errorHandler = (err, c) => {
|
|
1330
|
+
if ("getResponse" in err) {
|
|
1331
|
+
const res = err.getResponse();
|
|
1332
|
+
return c.newResponse(res.body, res);
|
|
1333
|
+
}
|
|
1334
|
+
console.error(err);
|
|
1335
|
+
return c.text("Internal Server Error", 500);
|
|
1336
|
+
};
|
|
1337
|
+
var Hono = class {
|
|
1338
|
+
get;
|
|
1339
|
+
post;
|
|
1340
|
+
put;
|
|
1341
|
+
delete;
|
|
1342
|
+
options;
|
|
1343
|
+
patch;
|
|
1344
|
+
all;
|
|
1345
|
+
on;
|
|
1346
|
+
use;
|
|
1347
|
+
router;
|
|
1348
|
+
getPath;
|
|
1349
|
+
_basePath = "/";
|
|
1350
|
+
#path = "/";
|
|
1351
|
+
routes = [];
|
|
1352
|
+
constructor(options = {}) {
|
|
1353
|
+
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
1354
|
+
allMethods.forEach((method) => {
|
|
1355
|
+
this[method] = (args1, ...args) => {
|
|
1356
|
+
if (typeof args1 === "string") {
|
|
1357
|
+
this.#path = args1;
|
|
1358
|
+
} else {
|
|
1359
|
+
this.#addRoute(method, this.#path, args1);
|
|
1360
|
+
}
|
|
1361
|
+
args.forEach((handler) => {
|
|
1362
|
+
this.#addRoute(method, this.#path, handler);
|
|
1363
|
+
});
|
|
1364
|
+
return this;
|
|
1365
|
+
};
|
|
1366
|
+
});
|
|
1367
|
+
this.on = (method, path, ...handlers) => {
|
|
1368
|
+
for (const p of [path].flat()) {
|
|
1369
|
+
this.#path = p;
|
|
1370
|
+
for (const m of [method].flat()) {
|
|
1371
|
+
handlers.map((handler) => {
|
|
1372
|
+
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
return this;
|
|
1377
|
+
};
|
|
1378
|
+
this.use = (arg1, ...handlers) => {
|
|
1379
|
+
if (typeof arg1 === "string") {
|
|
1380
|
+
this.#path = arg1;
|
|
1381
|
+
} else {
|
|
1382
|
+
this.#path = "*";
|
|
1383
|
+
handlers.unshift(arg1);
|
|
1384
|
+
}
|
|
1385
|
+
handlers.forEach((handler) => {
|
|
1386
|
+
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
1387
|
+
});
|
|
1388
|
+
return this;
|
|
1389
|
+
};
|
|
1390
|
+
const { strict, ...optionsWithoutStrict } = options;
|
|
1391
|
+
Object.assign(this, optionsWithoutStrict);
|
|
1392
|
+
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
1393
|
+
}
|
|
1394
|
+
#clone() {
|
|
1395
|
+
const clone = new Hono({
|
|
1396
|
+
router: this.router,
|
|
1397
|
+
getPath: this.getPath
|
|
1398
|
+
});
|
|
1399
|
+
clone.errorHandler = this.errorHandler;
|
|
1400
|
+
clone.#notFoundHandler = this.#notFoundHandler;
|
|
1401
|
+
clone.routes = this.routes;
|
|
1402
|
+
return clone;
|
|
1403
|
+
}
|
|
1404
|
+
#notFoundHandler = notFoundHandler;
|
|
1405
|
+
errorHandler = errorHandler;
|
|
1406
|
+
route(path, app) {
|
|
1407
|
+
const subApp = this.basePath(path);
|
|
1408
|
+
app.routes.map((r) => {
|
|
1409
|
+
let handler;
|
|
1410
|
+
if (app.errorHandler === errorHandler) {
|
|
1411
|
+
handler = r.handler;
|
|
1412
|
+
} else {
|
|
1413
|
+
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
1414
|
+
handler[COMPOSED_HANDLER] = r.handler;
|
|
1415
|
+
}
|
|
1416
|
+
subApp.#addRoute(r.method, r.path, handler);
|
|
1417
|
+
});
|
|
1418
|
+
return this;
|
|
1419
|
+
}
|
|
1420
|
+
basePath(path) {
|
|
1421
|
+
const subApp = this.#clone();
|
|
1422
|
+
subApp._basePath = mergePath(this._basePath, path);
|
|
1423
|
+
return subApp;
|
|
1424
|
+
}
|
|
1425
|
+
onError = (handler) => {
|
|
1426
|
+
this.errorHandler = handler;
|
|
1427
|
+
return this;
|
|
1428
|
+
};
|
|
1429
|
+
notFound = (handler) => {
|
|
1430
|
+
this.#notFoundHandler = handler;
|
|
1431
|
+
return this;
|
|
1432
|
+
};
|
|
1433
|
+
mount(path, applicationHandler, options) {
|
|
1434
|
+
let replaceRequest;
|
|
1435
|
+
let optionHandler;
|
|
1436
|
+
if (options) {
|
|
1437
|
+
if (typeof options === "function") {
|
|
1438
|
+
optionHandler = options;
|
|
1439
|
+
} else {
|
|
1440
|
+
optionHandler = options.optionHandler;
|
|
1441
|
+
if (options.replaceRequest === false) {
|
|
1442
|
+
replaceRequest = (request) => request;
|
|
1443
|
+
} else {
|
|
1444
|
+
replaceRequest = options.replaceRequest;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
const getOptions = optionHandler ? (c) => {
|
|
1449
|
+
const options2 = optionHandler(c);
|
|
1450
|
+
return Array.isArray(options2) ? options2 : [options2];
|
|
1451
|
+
} : (c) => {
|
|
1452
|
+
let executionContext = undefined;
|
|
1453
|
+
try {
|
|
1454
|
+
executionContext = c.executionCtx;
|
|
1455
|
+
} catch {}
|
|
1456
|
+
return [c.env, executionContext];
|
|
1457
|
+
};
|
|
1458
|
+
replaceRequest ||= (() => {
|
|
1459
|
+
const mergedPath = mergePath(this._basePath, path);
|
|
1460
|
+
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
1461
|
+
return (request) => {
|
|
1462
|
+
const url = new URL(request.url);
|
|
1463
|
+
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
1464
|
+
return new Request(url, request);
|
|
1465
|
+
};
|
|
1466
|
+
})();
|
|
1467
|
+
const handler = async (c, next) => {
|
|
1468
|
+
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
1469
|
+
if (res) {
|
|
1470
|
+
return res;
|
|
1471
|
+
}
|
|
1472
|
+
await next();
|
|
1473
|
+
};
|
|
1474
|
+
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
1475
|
+
return this;
|
|
1476
|
+
}
|
|
1477
|
+
#addRoute(method, path, handler) {
|
|
1478
|
+
method = method.toUpperCase();
|
|
1479
|
+
path = mergePath(this._basePath, path);
|
|
1480
|
+
const r = { basePath: this._basePath, path, method, handler };
|
|
1481
|
+
this.router.add(method, path, [handler, r]);
|
|
1482
|
+
this.routes.push(r);
|
|
1483
|
+
}
|
|
1484
|
+
#handleError(err, c) {
|
|
1485
|
+
if (err instanceof Error) {
|
|
1486
|
+
return this.errorHandler(err, c);
|
|
1487
|
+
}
|
|
1488
|
+
throw err;
|
|
1489
|
+
}
|
|
1490
|
+
#dispatch(request, executionCtx, env, method) {
|
|
1491
|
+
if (method === "HEAD") {
|
|
1492
|
+
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
1493
|
+
}
|
|
1494
|
+
const path = this.getPath(request, { env });
|
|
1495
|
+
const matchResult = this.router.match(method, path);
|
|
1496
|
+
const c = new Context(request, {
|
|
1497
|
+
path,
|
|
1498
|
+
matchResult,
|
|
1499
|
+
env,
|
|
1500
|
+
executionCtx,
|
|
1501
|
+
notFoundHandler: this.#notFoundHandler
|
|
1502
|
+
});
|
|
1503
|
+
if (matchResult[0].length === 1) {
|
|
1504
|
+
let res;
|
|
1505
|
+
try {
|
|
1506
|
+
res = matchResult[0][0][0][0](c, async () => {
|
|
1507
|
+
c.res = await this.#notFoundHandler(c);
|
|
1508
|
+
});
|
|
1509
|
+
} catch (err) {
|
|
1510
|
+
return this.#handleError(err, c);
|
|
1511
|
+
}
|
|
1512
|
+
return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
1513
|
+
}
|
|
1514
|
+
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
1515
|
+
return (async () => {
|
|
1516
|
+
try {
|
|
1517
|
+
const context = await composed(c);
|
|
1518
|
+
if (!context.finalized) {
|
|
1519
|
+
throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
|
|
1520
|
+
}
|
|
1521
|
+
return context.res;
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
return this.#handleError(err, c);
|
|
1524
|
+
}
|
|
1525
|
+
})();
|
|
1526
|
+
}
|
|
1527
|
+
fetch = (request, ...rest) => {
|
|
1528
|
+
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
1529
|
+
};
|
|
1530
|
+
request = (input, requestInit, Env, executionCtx) => {
|
|
1531
|
+
if (input instanceof Request) {
|
|
1532
|
+
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
1533
|
+
}
|
|
1534
|
+
input = input.toString();
|
|
1535
|
+
return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
|
|
1536
|
+
};
|
|
1537
|
+
fire = () => {
|
|
1538
|
+
addEventListener("fetch", (event) => {
|
|
1539
|
+
event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
|
|
1540
|
+
});
|
|
1541
|
+
};
|
|
1542
|
+
};
|
|
1543
|
+
|
|
1544
|
+
// node_modules/hono/dist/router/reg-exp-router/matcher.js
|
|
1545
|
+
var emptyParam = [];
|
|
1546
|
+
function match(method, path) {
|
|
1547
|
+
const matchers = this.buildAllMatchers();
|
|
1548
|
+
const match2 = (method2, path2) => {
|
|
1549
|
+
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
1550
|
+
const staticMatch = matcher[2][path2];
|
|
1551
|
+
if (staticMatch) {
|
|
1552
|
+
return staticMatch;
|
|
1553
|
+
}
|
|
1554
|
+
const match3 = path2.match(matcher[0]);
|
|
1555
|
+
if (!match3) {
|
|
1556
|
+
return [[], emptyParam];
|
|
1557
|
+
}
|
|
1558
|
+
const index = match3.indexOf("", 1);
|
|
1559
|
+
return [matcher[1][index], match3];
|
|
1560
|
+
};
|
|
1561
|
+
this.match = match2;
|
|
1562
|
+
return match2(method, path);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// node_modules/hono/dist/router/reg-exp-router/node.js
|
|
1566
|
+
var LABEL_REG_EXP_STR = "[^/]+";
|
|
1567
|
+
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
1568
|
+
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
1569
|
+
var PATH_ERROR = Symbol();
|
|
1570
|
+
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
1571
|
+
function compareKey(a, b) {
|
|
1572
|
+
if (a.length === 1) {
|
|
1573
|
+
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
1574
|
+
}
|
|
1575
|
+
if (b.length === 1) {
|
|
1576
|
+
return 1;
|
|
1577
|
+
}
|
|
1578
|
+
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1579
|
+
return 1;
|
|
1580
|
+
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
1581
|
+
return -1;
|
|
1582
|
+
}
|
|
1583
|
+
if (a === LABEL_REG_EXP_STR) {
|
|
1584
|
+
return 1;
|
|
1585
|
+
} else if (b === LABEL_REG_EXP_STR) {
|
|
1586
|
+
return -1;
|
|
1587
|
+
}
|
|
1588
|
+
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
1589
|
+
}
|
|
1590
|
+
var Node = class {
|
|
1591
|
+
#index;
|
|
1592
|
+
#varIndex;
|
|
1593
|
+
#children = /* @__PURE__ */ Object.create(null);
|
|
1594
|
+
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
1595
|
+
if (tokens.length === 0) {
|
|
1596
|
+
if (this.#index !== undefined) {
|
|
1597
|
+
throw PATH_ERROR;
|
|
1598
|
+
}
|
|
1599
|
+
if (pathErrorCheckOnly) {
|
|
1600
|
+
return;
|
|
1601
|
+
}
|
|
1602
|
+
this.#index = index;
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const [token, ...restTokens] = tokens;
|
|
1606
|
+
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
1607
|
+
let node;
|
|
1608
|
+
if (pattern) {
|
|
1609
|
+
const name = pattern[1];
|
|
1610
|
+
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
1611
|
+
if (name && pattern[2]) {
|
|
1612
|
+
if (regexpStr === ".*") {
|
|
1613
|
+
throw PATH_ERROR;
|
|
1614
|
+
}
|
|
1615
|
+
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
1616
|
+
if (/\((?!\?:)/.test(regexpStr)) {
|
|
1617
|
+
throw PATH_ERROR;
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
node = this.#children[regexpStr];
|
|
1621
|
+
if (!node) {
|
|
1622
|
+
if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1623
|
+
throw PATH_ERROR;
|
|
1624
|
+
}
|
|
1625
|
+
if (pathErrorCheckOnly) {
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
node = this.#children[regexpStr] = new Node;
|
|
1629
|
+
if (name !== "") {
|
|
1630
|
+
node.#varIndex = context.varIndex++;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
if (!pathErrorCheckOnly && name !== "") {
|
|
1634
|
+
paramMap.push([name, node.#varIndex]);
|
|
1635
|
+
}
|
|
1636
|
+
} else {
|
|
1637
|
+
node = this.#children[token];
|
|
1638
|
+
if (!node) {
|
|
1639
|
+
if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
|
|
1640
|
+
throw PATH_ERROR;
|
|
1641
|
+
}
|
|
1642
|
+
if (pathErrorCheckOnly) {
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
node = this.#children[token] = new Node;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
1649
|
+
}
|
|
1650
|
+
buildRegExpStr() {
|
|
1651
|
+
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
1652
|
+
const strList = childKeys.map((k) => {
|
|
1653
|
+
const c = this.#children[k];
|
|
1654
|
+
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
1655
|
+
});
|
|
1656
|
+
if (typeof this.#index === "number") {
|
|
1657
|
+
strList.unshift(`#${this.#index}`);
|
|
1658
|
+
}
|
|
1659
|
+
if (strList.length === 0) {
|
|
1660
|
+
return "";
|
|
1661
|
+
}
|
|
1662
|
+
if (strList.length === 1) {
|
|
1663
|
+
return strList[0];
|
|
1664
|
+
}
|
|
1665
|
+
return "(?:" + strList.join("|") + ")";
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
|
|
1669
|
+
// node_modules/hono/dist/router/reg-exp-router/trie.js
|
|
1670
|
+
var Trie = class {
|
|
1671
|
+
#context = { varIndex: 0 };
|
|
1672
|
+
#root = new Node;
|
|
1673
|
+
insert(path, index, pathErrorCheckOnly) {
|
|
1674
|
+
const paramAssoc = [];
|
|
1675
|
+
const groups = [];
|
|
1676
|
+
for (let i = 0;; ) {
|
|
1677
|
+
let replaced = false;
|
|
1678
|
+
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
1679
|
+
const mark = `@\\${i}`;
|
|
1680
|
+
groups[i] = [mark, m];
|
|
1681
|
+
i++;
|
|
1682
|
+
replaced = true;
|
|
1683
|
+
return mark;
|
|
1684
|
+
});
|
|
1685
|
+
if (!replaced) {
|
|
1686
|
+
break;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
1690
|
+
for (let i = groups.length - 1;i >= 0; i--) {
|
|
1691
|
+
const [mark] = groups[i];
|
|
1692
|
+
for (let j = tokens.length - 1;j >= 0; j--) {
|
|
1693
|
+
if (tokens[j].indexOf(mark) !== -1) {
|
|
1694
|
+
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
1695
|
+
break;
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
1700
|
+
return paramAssoc;
|
|
1701
|
+
}
|
|
1702
|
+
buildRegExp() {
|
|
1703
|
+
let regexp = this.#root.buildRegExpStr();
|
|
1704
|
+
if (regexp === "") {
|
|
1705
|
+
return [/^$/, [], []];
|
|
1706
|
+
}
|
|
1707
|
+
let captureIndex = 0;
|
|
1708
|
+
const indexReplacementMap = [];
|
|
1709
|
+
const paramReplacementMap = [];
|
|
1710
|
+
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
1711
|
+
if (handlerIndex !== undefined) {
|
|
1712
|
+
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
1713
|
+
return "$()";
|
|
1714
|
+
}
|
|
1715
|
+
if (paramIndex !== undefined) {
|
|
1716
|
+
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
1717
|
+
return "";
|
|
1718
|
+
}
|
|
1719
|
+
return "";
|
|
1720
|
+
});
|
|
1721
|
+
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
1722
|
+
}
|
|
1723
|
+
};
|
|
1724
|
+
|
|
1725
|
+
// node_modules/hono/dist/router/reg-exp-router/router.js
|
|
1726
|
+
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
1727
|
+
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1728
|
+
function buildWildcardRegExp(path) {
|
|
1729
|
+
return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
|
|
1730
|
+
}
|
|
1731
|
+
function clearWildcardRegExpCache() {
|
|
1732
|
+
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
1733
|
+
}
|
|
1734
|
+
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
1735
|
+
const trie = new Trie;
|
|
1736
|
+
const handlerData = [];
|
|
1737
|
+
if (routes.length === 0) {
|
|
1738
|
+
return nullMatcher;
|
|
1739
|
+
}
|
|
1740
|
+
const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
|
|
1741
|
+
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
1742
|
+
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
|
|
1743
|
+
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
1744
|
+
if (pathErrorCheckOnly) {
|
|
1745
|
+
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
1746
|
+
} else {
|
|
1747
|
+
j++;
|
|
1748
|
+
}
|
|
1749
|
+
let paramAssoc;
|
|
1750
|
+
try {
|
|
1751
|
+
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
1752
|
+
} catch (e) {
|
|
1753
|
+
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
1754
|
+
}
|
|
1755
|
+
if (pathErrorCheckOnly) {
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
1759
|
+
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
1760
|
+
paramCount -= 1;
|
|
1761
|
+
for (;paramCount >= 0; paramCount--) {
|
|
1762
|
+
const [key, value] = paramAssoc[paramCount];
|
|
1763
|
+
paramIndexMap[key] = value;
|
|
1764
|
+
}
|
|
1765
|
+
return [h, paramIndexMap];
|
|
1766
|
+
});
|
|
1767
|
+
}
|
|
1768
|
+
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
1769
|
+
for (let i = 0, len = handlerData.length;i < len; i++) {
|
|
1770
|
+
for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
|
|
1771
|
+
const map = handlerData[i][j]?.[1];
|
|
1772
|
+
if (!map) {
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
const keys = Object.keys(map);
|
|
1776
|
+
for (let k = 0, len3 = keys.length;k < len3; k++) {
|
|
1777
|
+
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
const handlerMap = [];
|
|
1782
|
+
for (const i in indexReplacementMap) {
|
|
1783
|
+
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
1784
|
+
}
|
|
1785
|
+
return [regexp, handlerMap, staticMap];
|
|
1786
|
+
}
|
|
1787
|
+
function findMiddleware(middleware, path) {
|
|
1788
|
+
if (!middleware) {
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
1792
|
+
if (buildWildcardRegExp(k).test(path)) {
|
|
1793
|
+
return [...middleware[k]];
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
var RegExpRouter = class {
|
|
1799
|
+
name = "RegExpRouter";
|
|
1800
|
+
#middleware;
|
|
1801
|
+
#routes;
|
|
1802
|
+
constructor() {
|
|
1803
|
+
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1804
|
+
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
1805
|
+
}
|
|
1806
|
+
add(method, path, handler) {
|
|
1807
|
+
const middleware = this.#middleware;
|
|
1808
|
+
const routes = this.#routes;
|
|
1809
|
+
if (!middleware || !routes) {
|
|
1810
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1811
|
+
}
|
|
1812
|
+
if (!middleware[method]) {
|
|
1813
|
+
[middleware, routes].forEach((handlerMap) => {
|
|
1814
|
+
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
1815
|
+
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
1816
|
+
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
1817
|
+
});
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
if (path === "/*") {
|
|
1821
|
+
path = "*";
|
|
1822
|
+
}
|
|
1823
|
+
const paramCount = (path.match(/\/:/g) || []).length;
|
|
1824
|
+
if (/\*$/.test(path)) {
|
|
1825
|
+
const re = buildWildcardRegExp(path);
|
|
1826
|
+
if (method === METHOD_NAME_ALL) {
|
|
1827
|
+
Object.keys(middleware).forEach((m) => {
|
|
1828
|
+
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1829
|
+
});
|
|
1830
|
+
} else {
|
|
1831
|
+
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
1832
|
+
}
|
|
1833
|
+
Object.keys(middleware).forEach((m) => {
|
|
1834
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1835
|
+
Object.keys(middleware[m]).forEach((p) => {
|
|
1836
|
+
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
});
|
|
1840
|
+
Object.keys(routes).forEach((m) => {
|
|
1841
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1842
|
+
Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
|
|
1843
|
+
}
|
|
1844
|
+
});
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
const paths = checkOptionalParameter(path) || [path];
|
|
1848
|
+
for (let i = 0, len = paths.length;i < len; i++) {
|
|
1849
|
+
const path2 = paths[i];
|
|
1850
|
+
Object.keys(routes).forEach((m) => {
|
|
1851
|
+
if (method === METHOD_NAME_ALL || method === m) {
|
|
1852
|
+
routes[m][path2] ||= [
|
|
1853
|
+
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
1854
|
+
];
|
|
1855
|
+
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
1856
|
+
}
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
match = match;
|
|
1861
|
+
buildAllMatchers() {
|
|
1862
|
+
const matchers = /* @__PURE__ */ Object.create(null);
|
|
1863
|
+
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
1864
|
+
matchers[method] ||= this.#buildMatcher(method);
|
|
1865
|
+
});
|
|
1866
|
+
this.#middleware = this.#routes = undefined;
|
|
1867
|
+
clearWildcardRegExpCache();
|
|
1868
|
+
return matchers;
|
|
1869
|
+
}
|
|
1870
|
+
#buildMatcher(method) {
|
|
1871
|
+
const routes = [];
|
|
1872
|
+
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
1873
|
+
[this.#middleware, this.#routes].forEach((r) => {
|
|
1874
|
+
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
1875
|
+
if (ownRoute.length !== 0) {
|
|
1876
|
+
hasOwnRoute ||= true;
|
|
1877
|
+
routes.push(...ownRoute);
|
|
1878
|
+
} else if (method !== METHOD_NAME_ALL) {
|
|
1879
|
+
routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
|
|
1880
|
+
}
|
|
1881
|
+
});
|
|
1882
|
+
if (!hasOwnRoute) {
|
|
1883
|
+
return null;
|
|
1884
|
+
} else {
|
|
1885
|
+
return buildMatcherFromPreprocessedRoutes(routes);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
};
|
|
1889
|
+
|
|
1890
|
+
// node_modules/hono/dist/router/reg-exp-router/prepared-router.js
|
|
1891
|
+
var PreparedRegExpRouter = class {
|
|
1892
|
+
name = "PreparedRegExpRouter";
|
|
1893
|
+
#matchers;
|
|
1894
|
+
#relocateMap;
|
|
1895
|
+
constructor(matchers, relocateMap) {
|
|
1896
|
+
this.#matchers = matchers;
|
|
1897
|
+
this.#relocateMap = relocateMap;
|
|
1898
|
+
}
|
|
1899
|
+
#addWildcard(method, handlerData) {
|
|
1900
|
+
const matcher = this.#matchers[method];
|
|
1901
|
+
matcher[1].forEach((list) => list && list.push(handlerData));
|
|
1902
|
+
Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
|
|
1903
|
+
}
|
|
1904
|
+
#addPath(method, path, handler, indexes, map) {
|
|
1905
|
+
const matcher = this.#matchers[method];
|
|
1906
|
+
if (!map) {
|
|
1907
|
+
matcher[2][path][0].push([handler, {}]);
|
|
1908
|
+
} else {
|
|
1909
|
+
indexes.forEach((index) => {
|
|
1910
|
+
if (typeof index === "number") {
|
|
1911
|
+
matcher[1][index].push([handler, map]);
|
|
1912
|
+
} else {
|
|
1913
|
+
matcher[2][index || path][0].push([handler, map]);
|
|
1914
|
+
}
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
add(method, path, handler) {
|
|
1919
|
+
if (!this.#matchers[method]) {
|
|
1920
|
+
const all = this.#matchers[METHOD_NAME_ALL];
|
|
1921
|
+
const staticMap = {};
|
|
1922
|
+
for (const key in all[2]) {
|
|
1923
|
+
staticMap[key] = [all[2][key][0].slice(), emptyParam];
|
|
1924
|
+
}
|
|
1925
|
+
this.#matchers[method] = [
|
|
1926
|
+
all[0],
|
|
1927
|
+
all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
|
|
1928
|
+
staticMap
|
|
1929
|
+
];
|
|
1930
|
+
}
|
|
1931
|
+
if (path === "/*" || path === "*") {
|
|
1932
|
+
const handlerData = [handler, {}];
|
|
1933
|
+
if (method === METHOD_NAME_ALL) {
|
|
1934
|
+
for (const m in this.#matchers) {
|
|
1935
|
+
this.#addWildcard(m, handlerData);
|
|
1936
|
+
}
|
|
1937
|
+
} else {
|
|
1938
|
+
this.#addWildcard(method, handlerData);
|
|
1939
|
+
}
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
const data = this.#relocateMap[path];
|
|
1943
|
+
if (!data) {
|
|
1944
|
+
throw new Error(`Path ${path} is not registered`);
|
|
1945
|
+
}
|
|
1946
|
+
for (const [indexes, map] of data) {
|
|
1947
|
+
if (method === METHOD_NAME_ALL) {
|
|
1948
|
+
for (const m in this.#matchers) {
|
|
1949
|
+
this.#addPath(m, path, handler, indexes, map);
|
|
1950
|
+
}
|
|
1951
|
+
} else {
|
|
1952
|
+
this.#addPath(method, path, handler, indexes, map);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
buildAllMatchers() {
|
|
1957
|
+
return this.#matchers;
|
|
1958
|
+
}
|
|
1959
|
+
match = match;
|
|
1960
|
+
};
|
|
1961
|
+
|
|
1962
|
+
// node_modules/hono/dist/router/smart-router/router.js
|
|
1963
|
+
var SmartRouter = class {
|
|
1964
|
+
name = "SmartRouter";
|
|
1965
|
+
#routers = [];
|
|
1966
|
+
#routes = [];
|
|
1967
|
+
constructor(init) {
|
|
1968
|
+
this.#routers = init.routers;
|
|
1969
|
+
}
|
|
1970
|
+
add(method, path, handler) {
|
|
1971
|
+
if (!this.#routes) {
|
|
1972
|
+
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
1973
|
+
}
|
|
1974
|
+
this.#routes.push([method, path, handler]);
|
|
1975
|
+
}
|
|
1976
|
+
match(method, path) {
|
|
1977
|
+
if (!this.#routes) {
|
|
1978
|
+
throw new Error("Fatal error");
|
|
1979
|
+
}
|
|
1980
|
+
const routers = this.#routers;
|
|
1981
|
+
const routes = this.#routes;
|
|
1982
|
+
const len = routers.length;
|
|
1983
|
+
let i = 0;
|
|
1984
|
+
let res;
|
|
1985
|
+
for (;i < len; i++) {
|
|
1986
|
+
const router = routers[i];
|
|
1987
|
+
try {
|
|
1988
|
+
for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
|
|
1989
|
+
router.add(...routes[i2]);
|
|
1990
|
+
}
|
|
1991
|
+
res = router.match(method, path);
|
|
1992
|
+
} catch (e) {
|
|
1993
|
+
if (e instanceof UnsupportedPathError) {
|
|
1994
|
+
continue;
|
|
1995
|
+
}
|
|
1996
|
+
throw e;
|
|
1997
|
+
}
|
|
1998
|
+
this.match = router.match.bind(router);
|
|
1999
|
+
this.#routers = [router];
|
|
2000
|
+
this.#routes = undefined;
|
|
2001
|
+
break;
|
|
2002
|
+
}
|
|
2003
|
+
if (i === len) {
|
|
2004
|
+
throw new Error("Fatal error");
|
|
2005
|
+
}
|
|
2006
|
+
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
2007
|
+
return res;
|
|
2008
|
+
}
|
|
2009
|
+
get activeRouter() {
|
|
2010
|
+
if (this.#routes || this.#routers.length !== 1) {
|
|
2011
|
+
throw new Error("No active router has been determined yet.");
|
|
2012
|
+
}
|
|
2013
|
+
return this.#routers[0];
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
|
|
2017
|
+
// node_modules/hono/dist/router/trie-router/node.js
|
|
2018
|
+
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
2019
|
+
var Node2 = class {
|
|
2020
|
+
#methods;
|
|
2021
|
+
#children;
|
|
2022
|
+
#patterns;
|
|
2023
|
+
#order = 0;
|
|
2024
|
+
#params = emptyParams;
|
|
2025
|
+
constructor(method, handler, children) {
|
|
2026
|
+
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
2027
|
+
this.#methods = [];
|
|
2028
|
+
if (method && handler) {
|
|
2029
|
+
const m = /* @__PURE__ */ Object.create(null);
|
|
2030
|
+
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
2031
|
+
this.#methods = [m];
|
|
2032
|
+
}
|
|
2033
|
+
this.#patterns = [];
|
|
2034
|
+
}
|
|
2035
|
+
insert(method, path, handler) {
|
|
2036
|
+
this.#order = ++this.#order;
|
|
2037
|
+
let curNode = this;
|
|
2038
|
+
const parts = splitRoutingPath(path);
|
|
2039
|
+
const possibleKeys = [];
|
|
2040
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
2041
|
+
const p = parts[i];
|
|
2042
|
+
const nextP = parts[i + 1];
|
|
2043
|
+
const pattern = getPattern(p, nextP);
|
|
2044
|
+
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
2045
|
+
if (key in curNode.#children) {
|
|
2046
|
+
curNode = curNode.#children[key];
|
|
2047
|
+
if (pattern) {
|
|
2048
|
+
possibleKeys.push(pattern[1]);
|
|
2049
|
+
}
|
|
2050
|
+
continue;
|
|
2051
|
+
}
|
|
2052
|
+
curNode.#children[key] = new Node2;
|
|
2053
|
+
if (pattern) {
|
|
2054
|
+
curNode.#patterns.push(pattern);
|
|
2055
|
+
possibleKeys.push(pattern[1]);
|
|
2056
|
+
}
|
|
2057
|
+
curNode = curNode.#children[key];
|
|
2058
|
+
}
|
|
2059
|
+
curNode.#methods.push({
|
|
2060
|
+
[method]: {
|
|
2061
|
+
handler,
|
|
2062
|
+
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
2063
|
+
score: this.#order
|
|
2064
|
+
}
|
|
2065
|
+
});
|
|
2066
|
+
return curNode;
|
|
2067
|
+
}
|
|
2068
|
+
#getHandlerSets(node, method, nodeParams, params) {
|
|
2069
|
+
const handlerSets = [];
|
|
2070
|
+
for (let i = 0, len = node.#methods.length;i < len; i++) {
|
|
2071
|
+
const m = node.#methods[i];
|
|
2072
|
+
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
2073
|
+
const processedSet = {};
|
|
2074
|
+
if (handlerSet !== undefined) {
|
|
2075
|
+
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
2076
|
+
handlerSets.push(handlerSet);
|
|
2077
|
+
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
2078
|
+
for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
|
|
2079
|
+
const key = handlerSet.possibleKeys[i2];
|
|
2080
|
+
const processed = processedSet[handlerSet.score];
|
|
2081
|
+
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
2082
|
+
processedSet[handlerSet.score] = true;
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
return handlerSets;
|
|
2088
|
+
}
|
|
2089
|
+
search(method, path) {
|
|
2090
|
+
const handlerSets = [];
|
|
2091
|
+
this.#params = emptyParams;
|
|
2092
|
+
const curNode = this;
|
|
2093
|
+
let curNodes = [curNode];
|
|
2094
|
+
const parts = splitPath(path);
|
|
2095
|
+
const curNodesQueue = [];
|
|
2096
|
+
for (let i = 0, len = parts.length;i < len; i++) {
|
|
2097
|
+
const part = parts[i];
|
|
2098
|
+
const isLast = i === len - 1;
|
|
2099
|
+
const tempNodes = [];
|
|
2100
|
+
for (let j = 0, len2 = curNodes.length;j < len2; j++) {
|
|
2101
|
+
const node = curNodes[j];
|
|
2102
|
+
const nextNode = node.#children[part];
|
|
2103
|
+
if (nextNode) {
|
|
2104
|
+
nextNode.#params = node.#params;
|
|
2105
|
+
if (isLast) {
|
|
2106
|
+
if (nextNode.#children["*"]) {
|
|
2107
|
+
handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
|
|
2108
|
+
}
|
|
2109
|
+
handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
|
|
2110
|
+
} else {
|
|
2111
|
+
tempNodes.push(nextNode);
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
|
|
2115
|
+
const pattern = node.#patterns[k];
|
|
2116
|
+
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
2117
|
+
if (pattern === "*") {
|
|
2118
|
+
const astNode = node.#children["*"];
|
|
2119
|
+
if (astNode) {
|
|
2120
|
+
handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
|
|
2121
|
+
astNode.#params = params;
|
|
2122
|
+
tempNodes.push(astNode);
|
|
2123
|
+
}
|
|
2124
|
+
continue;
|
|
2125
|
+
}
|
|
2126
|
+
const [key, name, matcher] = pattern;
|
|
2127
|
+
if (!part && !(matcher instanceof RegExp)) {
|
|
2128
|
+
continue;
|
|
2129
|
+
}
|
|
2130
|
+
const child = node.#children[key];
|
|
2131
|
+
const restPathString = parts.slice(i).join("/");
|
|
2132
|
+
if (matcher instanceof RegExp) {
|
|
2133
|
+
const m = matcher.exec(restPathString);
|
|
2134
|
+
if (m) {
|
|
2135
|
+
params[name] = m[0];
|
|
2136
|
+
handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
|
|
2137
|
+
if (Object.keys(child.#children).length) {
|
|
2138
|
+
child.#params = params;
|
|
2139
|
+
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
2140
|
+
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
2141
|
+
targetCurNodes.push(child);
|
|
2142
|
+
}
|
|
2143
|
+
continue;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
if (matcher === true || matcher.test(part)) {
|
|
2147
|
+
params[name] = part;
|
|
2148
|
+
if (isLast) {
|
|
2149
|
+
handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
|
|
2150
|
+
if (child.#children["*"]) {
|
|
2151
|
+
handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
|
|
2152
|
+
}
|
|
2153
|
+
} else {
|
|
2154
|
+
child.#params = params;
|
|
2155
|
+
tempNodes.push(child);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
|
|
2161
|
+
}
|
|
2162
|
+
if (handlerSets.length > 1) {
|
|
2163
|
+
handlerSets.sort((a, b) => {
|
|
2164
|
+
return a.score - b.score;
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
|
|
2171
|
+
// node_modules/hono/dist/router/trie-router/router.js
|
|
2172
|
+
var TrieRouter = class {
|
|
2173
|
+
name = "TrieRouter";
|
|
2174
|
+
#node;
|
|
2175
|
+
constructor() {
|
|
2176
|
+
this.#node = new Node2;
|
|
2177
|
+
}
|
|
2178
|
+
add(method, path, handler) {
|
|
2179
|
+
const results = checkOptionalParameter(path);
|
|
2180
|
+
if (results) {
|
|
2181
|
+
for (let i = 0, len = results.length;i < len; i++) {
|
|
2182
|
+
this.#node.insert(method, results[i], handler);
|
|
2183
|
+
}
|
|
2184
|
+
return;
|
|
2185
|
+
}
|
|
2186
|
+
this.#node.insert(method, path, handler);
|
|
2187
|
+
}
|
|
2188
|
+
match(method, path) {
|
|
2189
|
+
return this.#node.search(method, path);
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
|
|
2193
|
+
// node_modules/hono/dist/hono.js
|
|
2194
|
+
var Hono2 = class extends Hono {
|
|
2195
|
+
constructor(options = {}) {
|
|
2196
|
+
super(options);
|
|
2197
|
+
this.router = options.router ?? new SmartRouter({
|
|
2198
|
+
routers: [new RegExpRouter, new TrieRouter]
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
};
|
|
2202
|
+
|
|
2203
|
+
// node_modules/hono/dist/middleware/cors/index.js
|
|
2204
|
+
var cors = (options) => {
|
|
2205
|
+
const defaults = {
|
|
2206
|
+
origin: "*",
|
|
2207
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
|
|
2208
|
+
allowHeaders: [],
|
|
2209
|
+
exposeHeaders: []
|
|
2210
|
+
};
|
|
2211
|
+
const opts = {
|
|
2212
|
+
...defaults,
|
|
2213
|
+
...options
|
|
2214
|
+
};
|
|
2215
|
+
const findAllowOrigin = ((optsOrigin) => {
|
|
2216
|
+
if (typeof optsOrigin === "string") {
|
|
2217
|
+
if (optsOrigin === "*") {
|
|
2218
|
+
return () => optsOrigin;
|
|
2219
|
+
} else {
|
|
2220
|
+
return (origin) => optsOrigin === origin ? origin : null;
|
|
2221
|
+
}
|
|
2222
|
+
} else if (typeof optsOrigin === "function") {
|
|
2223
|
+
return optsOrigin;
|
|
2224
|
+
} else {
|
|
2225
|
+
return (origin) => optsOrigin.includes(origin) ? origin : null;
|
|
2226
|
+
}
|
|
2227
|
+
})(opts.origin);
|
|
2228
|
+
const findAllowMethods = ((optsAllowMethods) => {
|
|
2229
|
+
if (typeof optsAllowMethods === "function") {
|
|
2230
|
+
return optsAllowMethods;
|
|
2231
|
+
} else if (Array.isArray(optsAllowMethods)) {
|
|
2232
|
+
return () => optsAllowMethods;
|
|
2233
|
+
} else {
|
|
2234
|
+
return () => [];
|
|
2235
|
+
}
|
|
2236
|
+
})(opts.allowMethods);
|
|
2237
|
+
return async function cors2(c, next) {
|
|
2238
|
+
function set(key, value) {
|
|
2239
|
+
c.res.headers.set(key, value);
|
|
2240
|
+
}
|
|
2241
|
+
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
|
|
2242
|
+
if (allowOrigin) {
|
|
2243
|
+
set("Access-Control-Allow-Origin", allowOrigin);
|
|
2244
|
+
}
|
|
2245
|
+
if (opts.credentials) {
|
|
2246
|
+
set("Access-Control-Allow-Credentials", "true");
|
|
2247
|
+
}
|
|
2248
|
+
if (opts.exposeHeaders?.length) {
|
|
2249
|
+
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
|
|
2250
|
+
}
|
|
2251
|
+
if (c.req.method === "OPTIONS") {
|
|
2252
|
+
if (opts.origin !== "*") {
|
|
2253
|
+
set("Vary", "Origin");
|
|
2254
|
+
}
|
|
2255
|
+
if (opts.maxAge != null) {
|
|
2256
|
+
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
2257
|
+
}
|
|
2258
|
+
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
2259
|
+
if (allowMethods.length) {
|
|
2260
|
+
set("Access-Control-Allow-Methods", allowMethods.join(","));
|
|
2261
|
+
}
|
|
2262
|
+
let headers = opts.allowHeaders;
|
|
2263
|
+
if (!headers?.length) {
|
|
2264
|
+
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
2265
|
+
if (requestHeaders) {
|
|
2266
|
+
headers = requestHeaders.split(/\s*,\s*/);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
if (headers?.length) {
|
|
2270
|
+
set("Access-Control-Allow-Headers", headers.join(","));
|
|
2271
|
+
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
2272
|
+
}
|
|
2273
|
+
c.res.headers.delete("Content-Length");
|
|
2274
|
+
c.res.headers.delete("Content-Type");
|
|
2275
|
+
return new Response(null, {
|
|
2276
|
+
headers: c.res.headers,
|
|
2277
|
+
status: 204,
|
|
2278
|
+
statusText: "No Content"
|
|
2279
|
+
});
|
|
2280
|
+
}
|
|
2281
|
+
await next();
|
|
2282
|
+
if (opts.origin !== "*") {
|
|
2283
|
+
c.header("Vary", "Origin", { append: true });
|
|
2284
|
+
}
|
|
2285
|
+
};
|
|
2286
|
+
};
|
|
2287
|
+
|
|
2288
|
+
// src/proxy-server.ts
|
|
2289
|
+
import { writeFileSync as writeFileSync3 } from "fs";
|
|
2290
|
+
|
|
2291
|
+
// src/transform.ts
|
|
2292
|
+
function removeUriFormat(schema) {
|
|
2293
|
+
if (!schema || typeof schema !== "object")
|
|
2294
|
+
return schema;
|
|
2295
|
+
if (schema.type === "string" && schema.format === "uri") {
|
|
2296
|
+
const { format, ...rest } = schema;
|
|
2297
|
+
return rest;
|
|
2298
|
+
}
|
|
2299
|
+
if (Array.isArray(schema)) {
|
|
2300
|
+
return schema.map((item) => removeUriFormat(item));
|
|
2301
|
+
}
|
|
2302
|
+
const result = {};
|
|
2303
|
+
for (const key in schema) {
|
|
2304
|
+
if (key === "properties" && typeof schema[key] === "object") {
|
|
2305
|
+
result[key] = {};
|
|
2306
|
+
for (const propKey in schema[key]) {
|
|
2307
|
+
result[key][propKey] = removeUriFormat(schema[key][propKey]);
|
|
2308
|
+
}
|
|
2309
|
+
} else if (key === "items" && typeof schema[key] === "object") {
|
|
2310
|
+
result[key] = removeUriFormat(schema[key]);
|
|
2311
|
+
} else if (key === "additionalProperties" && typeof schema[key] === "object") {
|
|
2312
|
+
result[key] = removeUriFormat(schema[key]);
|
|
2313
|
+
} else if (["anyOf", "allOf", "oneOf"].includes(key) && Array.isArray(schema[key])) {
|
|
2314
|
+
result[key] = schema[key].map((item) => removeUriFormat(item));
|
|
2315
|
+
} else {
|
|
2316
|
+
result[key] = removeUriFormat(schema[key]);
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
return result;
|
|
2320
|
+
}
|
|
2321
|
+
function transformOpenAIToClaude(claudeRequestInput) {
|
|
2322
|
+
const req = JSON.parse(JSON.stringify(claudeRequestInput));
|
|
2323
|
+
const isO3Model = typeof req.model === "string" && (req.model.includes("o3") || req.model.includes("o1"));
|
|
2324
|
+
if (Array.isArray(req.system)) {
|
|
2325
|
+
req.system = req.system.map((item) => {
|
|
2326
|
+
if (typeof item === "string") {
|
|
2327
|
+
return item;
|
|
2328
|
+
} else if (item && typeof item === "object") {
|
|
2329
|
+
if (item.type === "text" && item.text) {
|
|
2330
|
+
return item.text;
|
|
2331
|
+
} else if (item.type === "text" && item.content) {
|
|
2332
|
+
return item.content;
|
|
2333
|
+
} else if (item.text) {
|
|
2334
|
+
return item.text;
|
|
2335
|
+
} else if (item.content) {
|
|
2336
|
+
return typeof item.content === "string" ? item.content : JSON.stringify(item.content);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
return JSON.stringify(item);
|
|
2340
|
+
}).filter((text) => text && text.trim() !== "").join(`
|
|
2341
|
+
|
|
2342
|
+
`);
|
|
2343
|
+
}
|
|
2344
|
+
if (!Array.isArray(req.messages)) {
|
|
2345
|
+
if (req.messages == null)
|
|
2346
|
+
req.messages = [];
|
|
2347
|
+
else
|
|
2348
|
+
req.messages = [req.messages];
|
|
2349
|
+
}
|
|
2350
|
+
if (!Array.isArray(req.tools))
|
|
2351
|
+
req.tools = [];
|
|
2352
|
+
for (const t of req.tools) {
|
|
2353
|
+
if (t && t.input_schema) {
|
|
2354
|
+
t.input_schema = removeUriFormat(t.input_schema);
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
const dropped = [];
|
|
2358
|
+
return {
|
|
2359
|
+
claudeRequest: req,
|
|
2360
|
+
droppedParams: dropped,
|
|
2361
|
+
isO3Model
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
// src/adapters/base-adapter.ts
|
|
2366
|
+
class BaseModelAdapter {
|
|
2367
|
+
modelId;
|
|
2368
|
+
constructor(modelId) {
|
|
2369
|
+
this.modelId = modelId;
|
|
2370
|
+
}
|
|
2371
|
+
reset() {}
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
class DefaultAdapter extends BaseModelAdapter {
|
|
2375
|
+
processTextContent(textContent, accumulatedText) {
|
|
2376
|
+
return {
|
|
2377
|
+
cleanedText: textContent,
|
|
2378
|
+
extractedToolCalls: [],
|
|
2379
|
+
wasTransformed: false
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
shouldHandle(modelId) {
|
|
2383
|
+
return false;
|
|
2384
|
+
}
|
|
2385
|
+
getName() {
|
|
2386
|
+
return "DefaultAdapter";
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
// src/adapters/grok-adapter.ts
|
|
2391
|
+
class GrokAdapter extends BaseModelAdapter {
|
|
2392
|
+
xmlBuffer = "";
|
|
2393
|
+
processTextContent(textContent, accumulatedText) {
|
|
2394
|
+
this.xmlBuffer += textContent;
|
|
2395
|
+
const xmlPattern = /<xai:function_call name="([^"]+)">(.*?)<\/xai:function_call>/gs;
|
|
2396
|
+
const matches = [...this.xmlBuffer.matchAll(xmlPattern)];
|
|
2397
|
+
if (matches.length === 0) {
|
|
2398
|
+
const hasPartialXml = this.xmlBuffer.includes("<xai:function_call");
|
|
2399
|
+
if (hasPartialXml) {
|
|
2400
|
+
return {
|
|
2401
|
+
cleanedText: "",
|
|
2402
|
+
extractedToolCalls: [],
|
|
2403
|
+
wasTransformed: false
|
|
2404
|
+
};
|
|
2405
|
+
}
|
|
2406
|
+
const result = {
|
|
2407
|
+
cleanedText: this.xmlBuffer,
|
|
2408
|
+
extractedToolCalls: [],
|
|
2409
|
+
wasTransformed: false
|
|
2410
|
+
};
|
|
2411
|
+
this.xmlBuffer = "";
|
|
2412
|
+
return result;
|
|
2413
|
+
}
|
|
2414
|
+
const toolCalls = matches.map((match2) => {
|
|
2415
|
+
const toolName = match2[1];
|
|
2416
|
+
const xmlParams = match2[2];
|
|
2417
|
+
return {
|
|
2418
|
+
id: `grok_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
|
2419
|
+
name: toolName,
|
|
2420
|
+
arguments: this.parseXmlParameters(xmlParams)
|
|
2421
|
+
};
|
|
2422
|
+
});
|
|
2423
|
+
let cleanedText = this.xmlBuffer;
|
|
2424
|
+
for (const match2 of matches) {
|
|
2425
|
+
cleanedText = cleanedText.replace(match2[0], "");
|
|
2426
|
+
}
|
|
2427
|
+
this.xmlBuffer = "";
|
|
2428
|
+
return {
|
|
2429
|
+
cleanedText: cleanedText.trim(),
|
|
2430
|
+
extractedToolCalls: toolCalls,
|
|
2431
|
+
wasTransformed: true
|
|
2432
|
+
};
|
|
2433
|
+
}
|
|
2434
|
+
parseXmlParameters(xmlContent) {
|
|
2435
|
+
const params = {};
|
|
2436
|
+
const paramPattern = /<xai:parameter name="([^"]+)">([^<]*)<\/xai:parameter>/g;
|
|
2437
|
+
let match2;
|
|
2438
|
+
while ((match2 = paramPattern.exec(xmlContent)) !== null) {
|
|
2439
|
+
const paramName = match2[1];
|
|
2440
|
+
const paramValue = match2[2];
|
|
2441
|
+
try {
|
|
2442
|
+
params[paramName] = JSON.parse(paramValue);
|
|
2443
|
+
} catch {
|
|
2444
|
+
params[paramName] = paramValue;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
return params;
|
|
2448
|
+
}
|
|
2449
|
+
shouldHandle(modelId) {
|
|
2450
|
+
return modelId.includes("grok") || modelId.includes("x-ai/");
|
|
2451
|
+
}
|
|
2452
|
+
getName() {
|
|
2453
|
+
return "GrokAdapter";
|
|
2454
|
+
}
|
|
2455
|
+
reset() {
|
|
2456
|
+
this.xmlBuffer = "";
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
// src/adapters/adapter-manager.ts
|
|
2461
|
+
class AdapterManager {
|
|
2462
|
+
adapters;
|
|
2463
|
+
defaultAdapter;
|
|
2464
|
+
constructor(modelId) {
|
|
2465
|
+
this.adapters = [new GrokAdapter(modelId)];
|
|
2466
|
+
this.defaultAdapter = new DefaultAdapter(modelId);
|
|
2467
|
+
}
|
|
2468
|
+
getAdapter() {
|
|
2469
|
+
for (const adapter of this.adapters) {
|
|
2470
|
+
if (adapter.shouldHandle(this.defaultAdapter["modelId"])) {
|
|
2471
|
+
return adapter;
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
return this.defaultAdapter;
|
|
2475
|
+
}
|
|
2476
|
+
needsTransformation() {
|
|
2477
|
+
return this.getAdapter() !== this.defaultAdapter;
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
// src/proxy-server.ts
|
|
2482
|
+
async function createProxyServer(port, openrouterApiKey, model, monitorMode = false, anthropicApiKey) {
|
|
2483
|
+
const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions";
|
|
2484
|
+
const OPENROUTER_HEADERS = {
|
|
2485
|
+
"HTTP-Referer": "https://github.com/MadAppGang/claude-code",
|
|
2486
|
+
"X-Title": "Claudish - OpenRouter Proxy"
|
|
2487
|
+
};
|
|
2488
|
+
const ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
|
|
2489
|
+
const ANTHROPIC_COUNT_TOKENS_URL = "https://api.anthropic.com/v1/messages/count_tokens";
|
|
2490
|
+
const app = new Hono2;
|
|
2491
|
+
app.use("*", cors());
|
|
2492
|
+
app.get("/", (c) => {
|
|
2493
|
+
c.header("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
2494
|
+
c.header("Pragma", "no-cache");
|
|
2495
|
+
c.header("Expires", "0");
|
|
2496
|
+
return c.json({
|
|
2497
|
+
status: "ok",
|
|
2498
|
+
message: monitorMode ? "Claudish monitor proxy - logging Anthropic API traffic" : "Claudish proxy server is running",
|
|
2499
|
+
config: {
|
|
2500
|
+
mode: monitorMode ? "monitor" : "openrouter",
|
|
2501
|
+
model: monitorMode ? "passthrough" : model,
|
|
2502
|
+
port,
|
|
2503
|
+
upstream: monitorMode ? "Anthropic" : "OpenRouter"
|
|
2504
|
+
}
|
|
2505
|
+
});
|
|
2506
|
+
});
|
|
2507
|
+
app.get("/health", (c) => {
|
|
2508
|
+
return c.json({
|
|
2509
|
+
status: "ok",
|
|
2510
|
+
mode: monitorMode ? "monitor" : "openrouter",
|
|
2511
|
+
model: monitorMode ? "passthrough" : model,
|
|
2512
|
+
port
|
|
2513
|
+
});
|
|
2514
|
+
});
|
|
2515
|
+
app.post("/v1/messages/count_tokens", async (c) => {
|
|
2516
|
+
try {
|
|
2517
|
+
const body = await c.req.json();
|
|
2518
|
+
if (monitorMode) {
|
|
2519
|
+
const originalHeaders = c.req.header();
|
|
2520
|
+
const extractedApiKey = originalHeaders["x-api-key"] || anthropicApiKey;
|
|
2521
|
+
if (!extractedApiKey) {
|
|
2522
|
+
log("[Monitor] ERROR: No API key found for token counting");
|
|
2523
|
+
return c.json({
|
|
2524
|
+
error: {
|
|
2525
|
+
type: "authentication_error",
|
|
2526
|
+
message: "No API key found in request."
|
|
2527
|
+
}
|
|
2528
|
+
}, 401);
|
|
2529
|
+
}
|
|
2530
|
+
log("[Monitor] Token counting request - forwarding to Anthropic");
|
|
2531
|
+
log("[Monitor] Request body:");
|
|
2532
|
+
log(JSON.stringify(body, null, 2));
|
|
2533
|
+
const headers = {
|
|
2534
|
+
"Content-Type": "application/json",
|
|
2535
|
+
"anthropic-version": originalHeaders["anthropic-version"] || "2023-06-01"
|
|
2536
|
+
};
|
|
2537
|
+
if (originalHeaders["authorization"]) {
|
|
2538
|
+
headers["authorization"] = originalHeaders["authorization"];
|
|
2539
|
+
}
|
|
2540
|
+
if (extractedApiKey) {
|
|
2541
|
+
headers["x-api-key"] = extractedApiKey;
|
|
2542
|
+
}
|
|
2543
|
+
const response = await fetch(ANTHROPIC_COUNT_TOKENS_URL, {
|
|
2544
|
+
method: "POST",
|
|
2545
|
+
headers,
|
|
2546
|
+
body: JSON.stringify(body)
|
|
2547
|
+
});
|
|
2548
|
+
const result = await response.json();
|
|
2549
|
+
log("[Monitor] Token counting response:");
|
|
2550
|
+
log(JSON.stringify(result, null, 2));
|
|
2551
|
+
return c.json(result, response.status);
|
|
2552
|
+
}
|
|
2553
|
+
log("[Proxy] Token counting request (estimating)");
|
|
2554
|
+
const systemTokens = body.system ? Math.ceil(body.system.length / 4) : 0;
|
|
2555
|
+
const messageTokens = body.messages ? body.messages.reduce((acc, msg) => {
|
|
2556
|
+
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
|
|
2557
|
+
return acc + Math.ceil(content.length / 4);
|
|
2558
|
+
}, 0) : 0;
|
|
2559
|
+
const totalTokens = systemTokens + messageTokens;
|
|
2560
|
+
return c.json({
|
|
2561
|
+
input_tokens: totalTokens
|
|
2562
|
+
});
|
|
2563
|
+
} catch (error) {
|
|
2564
|
+
log(`[Proxy] Token counting error: ${error}`);
|
|
2565
|
+
return c.json({
|
|
2566
|
+
error: {
|
|
2567
|
+
type: "invalid_request_error",
|
|
2568
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
2569
|
+
}
|
|
2570
|
+
}, 400);
|
|
2571
|
+
}
|
|
2572
|
+
});
|
|
2573
|
+
app.post("/v1/messages", async (c) => {
|
|
2574
|
+
try {
|
|
2575
|
+
const claudePayload = await c.req.json();
|
|
2576
|
+
if (monitorMode) {
|
|
2577
|
+
const originalHeaders = c.req.header();
|
|
2578
|
+
const extractedApiKey = originalHeaders["x-api-key"] || originalHeaders["authorization"] || anthropicApiKey;
|
|
2579
|
+
log(`
|
|
2580
|
+
=== [MONITOR] Claude Code \u2192 Anthropic API Request ===`);
|
|
2581
|
+
log(`Headers received: ${JSON.stringify(originalHeaders, null, 2)}`);
|
|
2582
|
+
if (!extractedApiKey) {
|
|
2583
|
+
log("[Monitor] WARNING: No API key found in headers!");
|
|
2584
|
+
log("[Monitor] Looking for: x-api-key or authorization header");
|
|
2585
|
+
log("[Monitor] Headers present: " + Object.keys(originalHeaders).join(", "));
|
|
2586
|
+
log("[Monitor] This request will fail at Anthropic API");
|
|
2587
|
+
} else {
|
|
2588
|
+
log(`API Key found: ${maskCredential(extractedApiKey)}`);
|
|
2589
|
+
}
|
|
2590
|
+
log(`Request body:`);
|
|
2591
|
+
log(JSON.stringify(claudePayload, null, 2));
|
|
2592
|
+
log(`=== End Request ===
|
|
2593
|
+
`);
|
|
2594
|
+
const headers2 = {
|
|
2595
|
+
"Content-Type": "application/json",
|
|
2596
|
+
"anthropic-version": originalHeaders["anthropic-version"] || "2023-06-01"
|
|
2597
|
+
};
|
|
2598
|
+
if (originalHeaders["authorization"]) {
|
|
2599
|
+
headers2["authorization"] = originalHeaders["authorization"];
|
|
2600
|
+
log(`[Monitor] Forwarding OAuth token: ${maskCredential(originalHeaders["authorization"])}`);
|
|
2601
|
+
}
|
|
2602
|
+
if (originalHeaders["x-api-key"]) {
|
|
2603
|
+
headers2["x-api-key"] = originalHeaders["x-api-key"];
|
|
2604
|
+
log(`[Monitor] Forwarding API key: ${maskCredential(originalHeaders["x-api-key"])}`);
|
|
2605
|
+
}
|
|
2606
|
+
if (originalHeaders["anthropic-beta"]) {
|
|
2607
|
+
headers2["anthropic-beta"] = originalHeaders["anthropic-beta"];
|
|
2608
|
+
}
|
|
2609
|
+
const anthropicResponse = await fetch(ANTHROPIC_API_URL, {
|
|
2610
|
+
method: "POST",
|
|
2611
|
+
headers: headers2,
|
|
2612
|
+
body: JSON.stringify(claudePayload)
|
|
2613
|
+
});
|
|
2614
|
+
const contentType2 = anthropicResponse.headers.get("content-type") || "";
|
|
2615
|
+
if (contentType2.includes("text/event-stream")) {
|
|
2616
|
+
log("[Monitor] Streaming response detected");
|
|
2617
|
+
return c.body(new ReadableStream({
|
|
2618
|
+
async start(controller) {
|
|
2619
|
+
const encoder = new TextEncoder;
|
|
2620
|
+
const reader = anthropicResponse.body?.getReader();
|
|
2621
|
+
if (!reader) {
|
|
2622
|
+
throw new Error("Response body is not readable");
|
|
2623
|
+
}
|
|
2624
|
+
const decoder = new TextDecoder;
|
|
2625
|
+
let buffer = "";
|
|
2626
|
+
let eventLog = "";
|
|
2627
|
+
log(`
|
|
2628
|
+
=== [MONITOR] Anthropic API \u2192 Claude Code Response (Streaming) ===`);
|
|
2629
|
+
try {
|
|
2630
|
+
while (true) {
|
|
2631
|
+
const { done, value } = await reader.read();
|
|
2632
|
+
if (done) {
|
|
2633
|
+
log(`
|
|
2634
|
+
=== End Streaming Response ===
|
|
2635
|
+
`);
|
|
2636
|
+
break;
|
|
2637
|
+
}
|
|
2638
|
+
controller.enqueue(value);
|
|
2639
|
+
buffer += decoder.decode(value, { stream: true });
|
|
2640
|
+
const lines = buffer.split(`
|
|
2641
|
+
`);
|
|
2642
|
+
buffer = lines.pop() || "";
|
|
2643
|
+
for (const line of lines) {
|
|
2644
|
+
if (line.trim()) {
|
|
2645
|
+
eventLog += line + `
|
|
2646
|
+
`;
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
if (eventLog) {
|
|
2651
|
+
log(eventLog);
|
|
2652
|
+
}
|
|
2653
|
+
controller.close();
|
|
2654
|
+
} catch (error) {
|
|
2655
|
+
log(`[Monitor] Streaming error: ${error}`);
|
|
2656
|
+
controller.close();
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
}), {
|
|
2660
|
+
headers: {
|
|
2661
|
+
"Content-Type": anthropicResponse.headers.get("content-type") || "text/event-stream",
|
|
2662
|
+
"Cache-Control": "no-cache",
|
|
2663
|
+
Connection: "keep-alive",
|
|
2664
|
+
"anthropic-version": anthropicResponse.headers.get("anthropic-version") || "2023-06-01"
|
|
2665
|
+
}
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
const responseData = await anthropicResponse.json();
|
|
2669
|
+
log(`
|
|
2670
|
+
=== [MONITOR] Anthropic API \u2192 Claude Code Response (JSON) ===`);
|
|
2671
|
+
log(JSON.stringify(responseData, null, 2));
|
|
2672
|
+
log(`=== End Response ===
|
|
2673
|
+
`);
|
|
2674
|
+
const responseHeaders = {
|
|
2675
|
+
"Content-Type": "application/json"
|
|
2676
|
+
};
|
|
2677
|
+
const anthropicVersion = anthropicResponse.headers.get("anthropic-version");
|
|
2678
|
+
if (anthropicVersion) {
|
|
2679
|
+
responseHeaders["anthropic-version"] = anthropicVersion;
|
|
2680
|
+
}
|
|
2681
|
+
return c.json(responseData, {
|
|
2682
|
+
status: anthropicResponse.status,
|
|
2683
|
+
headers: responseHeaders
|
|
2684
|
+
});
|
|
2685
|
+
}
|
|
2686
|
+
logStructured("Incoming Request", {
|
|
2687
|
+
model,
|
|
2688
|
+
messageCount: claudePayload.messages?.length || 0,
|
|
2689
|
+
hasSystem: !!claudePayload.system,
|
|
2690
|
+
maxTokens: claudePayload.max_tokens,
|
|
2691
|
+
temperature: claudePayload.temperature,
|
|
2692
|
+
stream: claudePayload.stream
|
|
2693
|
+
});
|
|
2694
|
+
const { claudeRequest, droppedParams } = transformOpenAIToClaude(claudePayload);
|
|
2695
|
+
const messages = [];
|
|
2696
|
+
if (claudeRequest.system) {
|
|
2697
|
+
let systemContent;
|
|
2698
|
+
if (typeof claudeRequest.system === "string") {
|
|
2699
|
+
systemContent = claudeRequest.system;
|
|
2700
|
+
} else if (Array.isArray(claudeRequest.system)) {
|
|
2701
|
+
systemContent = claudeRequest.system.map((item) => {
|
|
2702
|
+
if (typeof item === "string")
|
|
2703
|
+
return item;
|
|
2704
|
+
if (item?.type === "text" && item.text)
|
|
2705
|
+
return item.text;
|
|
2706
|
+
if (item?.content)
|
|
2707
|
+
return typeof item.content === "string" ? item.content : JSON.stringify(item.content);
|
|
2708
|
+
return JSON.stringify(item);
|
|
2709
|
+
}).join(`
|
|
2710
|
+
|
|
2711
|
+
`);
|
|
2712
|
+
} else {
|
|
2713
|
+
systemContent = JSON.stringify(claudeRequest.system);
|
|
2714
|
+
}
|
|
2715
|
+
systemContent = filterClaudeIdentity(systemContent);
|
|
2716
|
+
messages.push({
|
|
2717
|
+
role: "system",
|
|
2718
|
+
content: systemContent
|
|
2719
|
+
});
|
|
2720
|
+
}
|
|
2721
|
+
if (claudeRequest.messages && Array.isArray(claudeRequest.messages)) {
|
|
2722
|
+
for (const msg of claudeRequest.messages) {
|
|
2723
|
+
if (msg.role === "user") {
|
|
2724
|
+
if (Array.isArray(msg.content)) {
|
|
2725
|
+
const textParts = [];
|
|
2726
|
+
const toolResults = [];
|
|
2727
|
+
const seenToolResultIds = new Set;
|
|
2728
|
+
for (const block of msg.content) {
|
|
2729
|
+
if (block.type === "text") {
|
|
2730
|
+
textParts.push(block.text);
|
|
2731
|
+
} else if (block.type === "tool_result") {
|
|
2732
|
+
if (seenToolResultIds.has(block.tool_use_id)) {
|
|
2733
|
+
log(`[Proxy] Skipping duplicate tool_result with tool_use_id: ${block.tool_use_id}`);
|
|
2734
|
+
continue;
|
|
2735
|
+
}
|
|
2736
|
+
seenToolResultIds.add(block.tool_use_id);
|
|
2737
|
+
toolResults.push({
|
|
2738
|
+
role: "tool",
|
|
2739
|
+
content: typeof block.content === "string" ? block.content : JSON.stringify(block.content),
|
|
2740
|
+
tool_call_id: block.tool_use_id
|
|
2741
|
+
});
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
if (toolResults.length > 0) {
|
|
2745
|
+
messages.push(...toolResults);
|
|
2746
|
+
if (textParts.length > 0) {
|
|
2747
|
+
messages.push({
|
|
2748
|
+
role: "user",
|
|
2749
|
+
content: textParts.join(" ")
|
|
2750
|
+
});
|
|
2751
|
+
}
|
|
2752
|
+
} else if (textParts.length > 0) {
|
|
2753
|
+
messages.push({
|
|
2754
|
+
role: "user",
|
|
2755
|
+
content: textParts.join(" ")
|
|
2756
|
+
});
|
|
2757
|
+
}
|
|
2758
|
+
} else if (typeof msg.content === "string") {
|
|
2759
|
+
messages.push({
|
|
2760
|
+
role: "user",
|
|
2761
|
+
content: msg.content
|
|
2762
|
+
});
|
|
2763
|
+
}
|
|
2764
|
+
} else if (msg.role === "assistant") {
|
|
2765
|
+
if (Array.isArray(msg.content)) {
|
|
2766
|
+
const textParts = [];
|
|
2767
|
+
const toolCalls = [];
|
|
2768
|
+
const seenToolIds = new Set;
|
|
2769
|
+
for (const block of msg.content) {
|
|
2770
|
+
if (block.type === "text") {
|
|
2771
|
+
textParts.push(block.text);
|
|
2772
|
+
} else if (block.type === "tool_use") {
|
|
2773
|
+
if (seenToolIds.has(block.id)) {
|
|
2774
|
+
log(`[Proxy] Skipping duplicate tool_use with ID: ${block.id}`);
|
|
2775
|
+
continue;
|
|
2776
|
+
}
|
|
2777
|
+
seenToolIds.add(block.id);
|
|
2778
|
+
toolCalls.push({
|
|
2779
|
+
id: block.id,
|
|
2780
|
+
type: "function",
|
|
2781
|
+
function: {
|
|
2782
|
+
name: block.name,
|
|
2783
|
+
arguments: JSON.stringify(block.input)
|
|
2784
|
+
}
|
|
2785
|
+
});
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
const openAIMsg = { role: "assistant" };
|
|
2789
|
+
if (textParts.length > 0) {
|
|
2790
|
+
openAIMsg.content = textParts.join(" ");
|
|
2791
|
+
} else if (toolCalls.length > 0) {
|
|
2792
|
+
openAIMsg.content = null;
|
|
2793
|
+
}
|
|
2794
|
+
if (toolCalls.length > 0) {
|
|
2795
|
+
openAIMsg.tool_calls = toolCalls;
|
|
2796
|
+
}
|
|
2797
|
+
if (textParts.length > 0 || toolCalls.length > 0) {
|
|
2798
|
+
messages.push(openAIMsg);
|
|
2799
|
+
}
|
|
2800
|
+
} else if (typeof msg.content === "string") {
|
|
2801
|
+
messages.push({
|
|
2802
|
+
role: "assistant",
|
|
2803
|
+
content: msg.content
|
|
2804
|
+
});
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
const tools = claudeRequest.tools?.filter((tool) => !["BatchTool"].includes(tool.name)).map((tool) => ({
|
|
2810
|
+
type: "function",
|
|
2811
|
+
function: {
|
|
2812
|
+
name: tool.name,
|
|
2813
|
+
description: tool.description,
|
|
2814
|
+
parameters: removeUriFormat(tool.input_schema)
|
|
2815
|
+
}
|
|
2816
|
+
})) || [];
|
|
2817
|
+
if (model.includes("grok") || model.includes("x-ai/")) {
|
|
2818
|
+
if (tools.length > 0 && messages.length > 0) {
|
|
2819
|
+
if (messages[0]?.role === "system") {
|
|
2820
|
+
messages[0].content += `
|
|
2821
|
+
|
|
2822
|
+
IMPORTANT: When calling tools, you MUST use the OpenAI tool_calls format with JSON. NEVER use XML format like <xai:function_call>. Use the tools array provided in the request.`;
|
|
2823
|
+
log("[Proxy] Added Grok tool format instruction to existing system message");
|
|
2824
|
+
} else {
|
|
2825
|
+
messages.unshift({
|
|
2826
|
+
role: "system",
|
|
2827
|
+
content: "IMPORTANT: When calling tools, you MUST use the OpenAI tool_calls format with JSON. NEVER use XML format like <xai:function_call>. Use the tools array provided in the request."
|
|
2828
|
+
});
|
|
2829
|
+
log("[Proxy] Added Grok tool format instruction as new system message");
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
const openrouterPayload = {
|
|
2834
|
+
model,
|
|
2835
|
+
messages,
|
|
2836
|
+
temperature: claudeRequest.temperature !== undefined ? claudeRequest.temperature : 1,
|
|
2837
|
+
stream: true
|
|
2838
|
+
};
|
|
2839
|
+
if (claudeRequest.max_tokens) {
|
|
2840
|
+
openrouterPayload.max_tokens = claudeRequest.max_tokens;
|
|
2841
|
+
}
|
|
2842
|
+
if (claudeRequest.tool_choice) {
|
|
2843
|
+
const { type, name } = claudeRequest.tool_choice;
|
|
2844
|
+
openrouterPayload.tool_choice = type === "tool" && name ? { type: "function", function: { name } } : type === "none" || type === "auto" ? type : undefined;
|
|
2845
|
+
}
|
|
2846
|
+
if (tools.length > 0) {
|
|
2847
|
+
openrouterPayload.tools = tools;
|
|
2848
|
+
}
|
|
2849
|
+
logStructured("OpenRouter Request", {
|
|
2850
|
+
model: openrouterPayload.model,
|
|
2851
|
+
messageCount: openrouterPayload.messages?.length || 0,
|
|
2852
|
+
toolCount: openrouterPayload.tools?.length || 0,
|
|
2853
|
+
temperature: openrouterPayload.temperature,
|
|
2854
|
+
maxTokens: openrouterPayload.max_tokens,
|
|
2855
|
+
stream: openrouterPayload.stream
|
|
2856
|
+
});
|
|
2857
|
+
const headers = {
|
|
2858
|
+
"Content-Type": "application/json",
|
|
2859
|
+
Authorization: `Bearer ${openrouterApiKey}`,
|
|
2860
|
+
...OPENROUTER_HEADERS
|
|
2861
|
+
};
|
|
2862
|
+
const openrouterResponse = await fetch(OPENROUTER_API_URL, {
|
|
2863
|
+
method: "POST",
|
|
2864
|
+
headers,
|
|
2865
|
+
body: JSON.stringify(openrouterPayload)
|
|
2866
|
+
});
|
|
2867
|
+
if (droppedParams.length > 0) {
|
|
2868
|
+
c.header("X-Dropped-Params", droppedParams.join(", "));
|
|
2869
|
+
}
|
|
2870
|
+
if (!openrouterResponse.ok) {
|
|
2871
|
+
const errorText = await openrouterResponse.text();
|
|
2872
|
+
log(`[Proxy] OpenRouter API error: ${errorText}`);
|
|
2873
|
+
return c.json({ error: errorText }, openrouterResponse.status);
|
|
2874
|
+
}
|
|
2875
|
+
const contentType = openrouterResponse.headers.get("content-type") || "";
|
|
2876
|
+
const isActuallyStreaming = contentType.includes("text/event-stream");
|
|
2877
|
+
logStructured("Response Info", {
|
|
2878
|
+
contentType,
|
|
2879
|
+
requestedStream: openrouterPayload.stream,
|
|
2880
|
+
actuallyStreaming: isActuallyStreaming
|
|
2881
|
+
});
|
|
2882
|
+
if (!isActuallyStreaming) {
|
|
2883
|
+
log("[Proxy] Processing non-streaming response");
|
|
2884
|
+
const data = await openrouterResponse.json();
|
|
2885
|
+
logStructured("OpenRouter Response", {
|
|
2886
|
+
hasError: !!data.error,
|
|
2887
|
+
choiceCount: data.choices?.length || 0,
|
|
2888
|
+
finishReason: data.choices?.[0]?.finish_reason,
|
|
2889
|
+
usage: data.usage
|
|
2890
|
+
});
|
|
2891
|
+
if (data.error) {
|
|
2892
|
+
return c.json({ error: data.error.message || "Unknown error" }, 500);
|
|
2893
|
+
}
|
|
2894
|
+
const choice = data.choices[0];
|
|
2895
|
+
const openaiMessage = choice.message;
|
|
2896
|
+
const content = [];
|
|
2897
|
+
const messageContent = openaiMessage.content || "";
|
|
2898
|
+
content.push({
|
|
2899
|
+
type: "text",
|
|
2900
|
+
text: messageContent
|
|
2901
|
+
});
|
|
2902
|
+
if (openaiMessage.tool_calls) {
|
|
2903
|
+
for (const toolCall of openaiMessage.tool_calls) {
|
|
2904
|
+
content.push({
|
|
2905
|
+
type: "tool_use",
|
|
2906
|
+
id: toolCall.id || `tool_${Date.now()}`,
|
|
2907
|
+
name: toolCall.function?.name,
|
|
2908
|
+
input: typeof toolCall.function?.arguments === "string" ? JSON.parse(toolCall.function.arguments) : toolCall.function?.arguments
|
|
2909
|
+
});
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
const claudeResponse = {
|
|
2913
|
+
id: data.id ? data.id.replace("chatcmpl", "msg") : `msg_${Date.now()}`,
|
|
2914
|
+
type: "message",
|
|
2915
|
+
role: "assistant",
|
|
2916
|
+
model,
|
|
2917
|
+
content,
|
|
2918
|
+
stop_reason: mapStopReason(choice.finish_reason),
|
|
2919
|
+
stop_sequence: null,
|
|
2920
|
+
usage: {
|
|
2921
|
+
input_tokens: data.usage?.prompt_tokens || 0,
|
|
2922
|
+
output_tokens: data.usage?.completion_tokens || 0
|
|
2923
|
+
}
|
|
2924
|
+
};
|
|
2925
|
+
log("[Proxy] Translated to Claude format:");
|
|
2926
|
+
log(JSON.stringify(claudeResponse, null, 2));
|
|
2927
|
+
c.header("Content-Type", "application/json");
|
|
2928
|
+
c.header("anthropic-version", "2023-06-01");
|
|
2929
|
+
return c.json(claudeResponse, 200);
|
|
2930
|
+
}
|
|
2931
|
+
log("[Proxy] Starting streaming response");
|
|
2932
|
+
let isClosed = false;
|
|
2933
|
+
let pingInterval = null;
|
|
2934
|
+
return c.body(new ReadableStream({
|
|
2935
|
+
async start(controller) {
|
|
2936
|
+
const encoder = new TextEncoder;
|
|
2937
|
+
const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
2938
|
+
const sendSSE = (event, data) => {
|
|
2939
|
+
if (isClosed) {
|
|
2940
|
+
if (isLoggingEnabled()) {
|
|
2941
|
+
log(`[Proxy] Skipping SSE event ${event} - controller already closed`);
|
|
2942
|
+
}
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
try {
|
|
2946
|
+
const sseMessage = `event: ${event}
|
|
2947
|
+
data: ${JSON.stringify(data)}
|
|
2948
|
+
|
|
2949
|
+
`;
|
|
2950
|
+
controller.enqueue(encoder.encode(sseMessage));
|
|
2951
|
+
if (isLoggingEnabled() && (event === "message_start" || event === "content_block_start" || event === "content_block_stop" || event === "message_stop")) {
|
|
2952
|
+
const logData = event === "content_block_start" || event === "content_block_stop" ? { event, index: data.index, type: data.content_block?.type } : { event };
|
|
2953
|
+
logStructured("SSE Sent", logData);
|
|
2954
|
+
}
|
|
2955
|
+
} catch (error) {
|
|
2956
|
+
if (!isClosed && error?.message?.includes("already closed")) {
|
|
2957
|
+
if (isLoggingEnabled()) {
|
|
2958
|
+
log(`[Proxy] Controller closed during ${event} event, marking as closed`);
|
|
2959
|
+
}
|
|
2960
|
+
isClosed = true;
|
|
2961
|
+
} else if (!isClosed) {
|
|
2962
|
+
if (isLoggingEnabled()) {
|
|
2963
|
+
log(`[Proxy] Error sending SSE event ${event}: ${error?.message || error}`);
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
};
|
|
2968
|
+
const finalizeStream = (reason, errorMessage) => {
|
|
2969
|
+
if (streamFinalized) {
|
|
2970
|
+
if (isLoggingEnabled()) {
|
|
2971
|
+
log(`[Proxy] Stream already finalized, skipping duplicate finalization from ${reason}`);
|
|
2972
|
+
}
|
|
2973
|
+
return;
|
|
2974
|
+
}
|
|
2975
|
+
if (isLoggingEnabled()) {
|
|
2976
|
+
log(`[Proxy] Finalizing stream (reason: ${reason})`);
|
|
2977
|
+
}
|
|
2978
|
+
streamFinalized = true;
|
|
2979
|
+
if (reasoningBlockStarted) {
|
|
2980
|
+
sendSSE("content_block_stop", {
|
|
2981
|
+
type: "content_block_stop",
|
|
2982
|
+
index: reasoningBlockIndex
|
|
2983
|
+
});
|
|
2984
|
+
reasoningBlockStarted = false;
|
|
2985
|
+
if (isLoggingEnabled()) {
|
|
2986
|
+
log(`[Proxy] Closed thinking block at index ${reasoningBlockIndex}`);
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
if (textBlockStarted) {
|
|
2990
|
+
sendSSE("content_block_stop", {
|
|
2991
|
+
type: "content_block_stop",
|
|
2992
|
+
index: textBlockIndex
|
|
2993
|
+
});
|
|
2994
|
+
textBlockStarted = false;
|
|
2995
|
+
}
|
|
2996
|
+
for (const [toolIndex, toolState] of toolCalls.entries()) {
|
|
2997
|
+
if (toolState.started && !toolState.closed) {
|
|
2998
|
+
if (isLoggingEnabled() && toolState.args) {
|
|
2999
|
+
try {
|
|
3000
|
+
JSON.parse(toolState.args);
|
|
3001
|
+
log(`[Proxy] Tool ${toolState.name} JSON valid, closing block at index ${toolState.blockIndex}`);
|
|
3002
|
+
} catch (e) {
|
|
3003
|
+
log(`[Proxy] ERROR: Tool ${toolState.name} has INCOMPLETE JSON!`);
|
|
3004
|
+
log(`[Proxy] This will likely cause tool execution to fail`);
|
|
3005
|
+
log(`[Proxy] Incomplete args: ${toolState.args.substring(0, 300)}...`);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
sendSSE("content_block_stop", {
|
|
3009
|
+
type: "content_block_stop",
|
|
3010
|
+
index: toolState.blockIndex
|
|
3011
|
+
});
|
|
3012
|
+
toolState.closed = true;
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
if (reason === "error" && errorMessage) {
|
|
3016
|
+
sendSSE("error", {
|
|
3017
|
+
type: "error",
|
|
3018
|
+
error: {
|
|
3019
|
+
type: "api_error",
|
|
3020
|
+
message: errorMessage
|
|
3021
|
+
}
|
|
3022
|
+
});
|
|
3023
|
+
} else {
|
|
3024
|
+
const outputTokens = usage?.completion_tokens || 0;
|
|
3025
|
+
sendSSE("message_delta", {
|
|
3026
|
+
type: "message_delta",
|
|
3027
|
+
delta: {
|
|
3028
|
+
stop_reason: "end_turn",
|
|
3029
|
+
stop_sequence: null
|
|
3030
|
+
},
|
|
3031
|
+
usage: {
|
|
3032
|
+
output_tokens: outputTokens
|
|
3033
|
+
}
|
|
3034
|
+
});
|
|
3035
|
+
sendSSE("message_stop", {
|
|
3036
|
+
type: "message_stop"
|
|
3037
|
+
});
|
|
3038
|
+
}
|
|
3039
|
+
if (!isClosed) {
|
|
3040
|
+
try {
|
|
3041
|
+
controller.enqueue(encoder.encode(`data: [DONE]
|
|
3042
|
+
|
|
3043
|
+
`));
|
|
3044
|
+
controller.enqueue(encoder.encode(`
|
|
3045
|
+
`));
|
|
3046
|
+
log(`[Proxy] Sent [DONE] event to client`);
|
|
3047
|
+
} catch (e) {
|
|
3048
|
+
log(`[Proxy] Error sending final events: ${e}`);
|
|
3049
|
+
}
|
|
3050
|
+
controller.close();
|
|
3051
|
+
isClosed = true;
|
|
3052
|
+
if (pingInterval) {
|
|
3053
|
+
clearInterval(pingInterval);
|
|
3054
|
+
}
|
|
3055
|
+
log(`[Proxy] Stream closed (reason: ${reason})`);
|
|
3056
|
+
}
|
|
3057
|
+
};
|
|
3058
|
+
let usage = null;
|
|
3059
|
+
let currentBlockIndex = 0;
|
|
3060
|
+
let textBlockIndex = -1;
|
|
3061
|
+
let textBlockStarted = false;
|
|
3062
|
+
let reasoningBlockIndex = -1;
|
|
3063
|
+
let reasoningBlockStarted = false;
|
|
3064
|
+
let lastContentDeltaTime = Date.now();
|
|
3065
|
+
let streamFinalized = false;
|
|
3066
|
+
let cumulativeInputTokens = 0;
|
|
3067
|
+
let cumulativeOutputTokens = 0;
|
|
3068
|
+
const tokenFilePath = `/tmp/claudish-tokens-${port}.json`;
|
|
3069
|
+
const writeTokenFile = () => {
|
|
3070
|
+
try {
|
|
3071
|
+
const tokenData = {
|
|
3072
|
+
input_tokens: cumulativeInputTokens,
|
|
3073
|
+
output_tokens: cumulativeOutputTokens,
|
|
3074
|
+
total_tokens: cumulativeInputTokens + cumulativeOutputTokens,
|
|
3075
|
+
updated_at: Date.now()
|
|
3076
|
+
};
|
|
3077
|
+
writeFileSync3(tokenFilePath, JSON.stringify(tokenData), "utf-8");
|
|
3078
|
+
} catch (error) {
|
|
3079
|
+
if (isLoggingEnabled()) {
|
|
3080
|
+
log(`[Proxy] Failed to write token file: ${error}`);
|
|
3081
|
+
}
|
|
3082
|
+
}
|
|
3083
|
+
};
|
|
3084
|
+
const toolCalls = new Map;
|
|
3085
|
+
const toolCallIds = new Set;
|
|
3086
|
+
const adapterManager = new AdapterManager(model || "");
|
|
3087
|
+
const adapter = adapterManager.getAdapter();
|
|
3088
|
+
if (typeof adapter.reset === "function") {
|
|
3089
|
+
adapter.reset();
|
|
3090
|
+
}
|
|
3091
|
+
let accumulatedTextLength = 0;
|
|
3092
|
+
log(`[Proxy] Using adapter: ${adapter.getName()}`);
|
|
3093
|
+
const hasToolResults = claudeRequest.messages?.some((msg) => Array.isArray(msg.content) && msg.content.some((block) => block.type === "tool_result"));
|
|
3094
|
+
const isFirstTurn = !hasToolResults;
|
|
3095
|
+
const estimateTokens = (text) => Math.ceil(text.length / 4);
|
|
3096
|
+
const requestJson = JSON.stringify(claudeRequest);
|
|
3097
|
+
const estimatedInputTokens = estimateTokens(requestJson);
|
|
3098
|
+
const estimatedCacheTokens = isFirstTurn ? Math.floor(estimatedInputTokens * 0.8) : 0;
|
|
3099
|
+
sendSSE("message_start", {
|
|
3100
|
+
type: "message_start",
|
|
3101
|
+
message: {
|
|
3102
|
+
id: messageId,
|
|
3103
|
+
type: "message",
|
|
3104
|
+
role: "assistant",
|
|
3105
|
+
content: [],
|
|
3106
|
+
model,
|
|
3107
|
+
stop_reason: null,
|
|
3108
|
+
stop_sequence: null,
|
|
3109
|
+
usage: {
|
|
3110
|
+
input_tokens: estimatedInputTokens - estimatedCacheTokens,
|
|
3111
|
+
cache_creation_input_tokens: isFirstTurn ? estimatedCacheTokens : 0,
|
|
3112
|
+
cache_read_input_tokens: isFirstTurn ? 0 : estimatedCacheTokens,
|
|
3113
|
+
output_tokens: 1
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
});
|
|
3117
|
+
textBlockIndex = currentBlockIndex++;
|
|
3118
|
+
sendSSE("content_block_start", {
|
|
3119
|
+
type: "content_block_start",
|
|
3120
|
+
index: textBlockIndex,
|
|
3121
|
+
content_block: {
|
|
3122
|
+
type: "text",
|
|
3123
|
+
text: ""
|
|
3124
|
+
}
|
|
3125
|
+
});
|
|
3126
|
+
textBlockStarted = true;
|
|
3127
|
+
sendSSE("ping", {
|
|
3128
|
+
type: "ping"
|
|
3129
|
+
});
|
|
3130
|
+
pingInterval = setInterval(() => {
|
|
3131
|
+
if (!isClosed) {
|
|
3132
|
+
const timeSinceLastContent = Date.now() - lastContentDeltaTime;
|
|
3133
|
+
if (timeSinceLastContent > 1000) {
|
|
3134
|
+
sendSSE("ping", {
|
|
3135
|
+
type: "ping"
|
|
3136
|
+
});
|
|
3137
|
+
log(`[Proxy] Adaptive ping (${Math.round(timeSinceLastContent / 1000)}s since last content)`);
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
}, 1000);
|
|
3141
|
+
try {
|
|
3142
|
+
const reader = openrouterResponse.body?.getReader();
|
|
3143
|
+
if (!reader) {
|
|
3144
|
+
throw new Error("Response body is not readable");
|
|
3145
|
+
}
|
|
3146
|
+
const decoder = new TextDecoder;
|
|
3147
|
+
let buffer = "";
|
|
3148
|
+
while (true) {
|
|
3149
|
+
const { done, value } = await reader.read();
|
|
3150
|
+
if (done) {
|
|
3151
|
+
log("[Proxy] Stream done reading");
|
|
3152
|
+
break;
|
|
3153
|
+
}
|
|
3154
|
+
buffer += decoder.decode(value, { stream: true });
|
|
3155
|
+
const lines = buffer.split(`
|
|
3156
|
+
`);
|
|
3157
|
+
buffer = lines.pop() || "";
|
|
3158
|
+
for (const line of lines) {
|
|
3159
|
+
if (!line.trim() || line.startsWith(":"))
|
|
3160
|
+
continue;
|
|
3161
|
+
const dataMatch = line.match(/^data: (.*)$/);
|
|
3162
|
+
if (!dataMatch)
|
|
3163
|
+
continue;
|
|
3164
|
+
const dataStr = dataMatch[1];
|
|
3165
|
+
if (dataStr === "[DONE]") {
|
|
3166
|
+
log("[Proxy] Received [DONE] from OpenRouter");
|
|
3167
|
+
if (!textBlockStarted && toolCalls.size === 0) {
|
|
3168
|
+
log("[Proxy] WARNING: Model produced no text output and no tool calls");
|
|
3169
|
+
}
|
|
3170
|
+
finalizeStream("done");
|
|
3171
|
+
return;
|
|
3172
|
+
}
|
|
3173
|
+
try {
|
|
3174
|
+
const chunk = JSON.parse(dataStr);
|
|
3175
|
+
if (isLoggingEnabled()) {
|
|
3176
|
+
logStructured("SSE Chunk", {
|
|
3177
|
+
id: chunk.id,
|
|
3178
|
+
model: chunk.model,
|
|
3179
|
+
hasChoices: !!chunk.choices,
|
|
3180
|
+
finishReason: chunk.choices?.[0]?.finish_reason,
|
|
3181
|
+
hasUsage: !!chunk.usage
|
|
3182
|
+
});
|
|
3183
|
+
}
|
|
3184
|
+
if (chunk.usage) {
|
|
3185
|
+
usage = chunk.usage;
|
|
3186
|
+
if (usage.prompt_tokens) {
|
|
3187
|
+
cumulativeInputTokens = usage.prompt_tokens;
|
|
3188
|
+
}
|
|
3189
|
+
if (usage.completion_tokens) {
|
|
3190
|
+
cumulativeOutputTokens = usage.completion_tokens;
|
|
3191
|
+
}
|
|
3192
|
+
writeTokenFile();
|
|
3193
|
+
}
|
|
3194
|
+
const choice = chunk.choices?.[0];
|
|
3195
|
+
const delta = choice?.delta;
|
|
3196
|
+
const hasReasoning = !!delta?.reasoning;
|
|
3197
|
+
const hasContent = !!delta?.content;
|
|
3198
|
+
const reasoningText = delta?.reasoning || "";
|
|
3199
|
+
const contentText = delta?.content || "";
|
|
3200
|
+
const hasEncryptedReasoning = delta?.reasoning_details?.some((detail) => detail.type === "reasoning.encrypted");
|
|
3201
|
+
if (hasReasoning || hasContent || hasEncryptedReasoning) {
|
|
3202
|
+
lastContentDeltaTime = Date.now();
|
|
3203
|
+
if (hasReasoning && reasoningText) {
|
|
3204
|
+
if (!reasoningBlockStarted) {
|
|
3205
|
+
if (textBlockStarted) {
|
|
3206
|
+
sendSSE("content_block_stop", {
|
|
3207
|
+
type: "content_block_stop",
|
|
3208
|
+
index: textBlockIndex
|
|
3209
|
+
});
|
|
3210
|
+
textBlockStarted = false;
|
|
3211
|
+
if (isLoggingEnabled()) {
|
|
3212
|
+
log(`[Proxy] Closed initial text block to start thinking block`);
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
reasoningBlockIndex = currentBlockIndex++;
|
|
3216
|
+
sendSSE("content_block_start", {
|
|
3217
|
+
type: "content_block_start",
|
|
3218
|
+
index: reasoningBlockIndex,
|
|
3219
|
+
content_block: {
|
|
3220
|
+
type: "thinking",
|
|
3221
|
+
thinking: "",
|
|
3222
|
+
signature: ""
|
|
3223
|
+
}
|
|
3224
|
+
});
|
|
3225
|
+
reasoningBlockStarted = true;
|
|
3226
|
+
if (isLoggingEnabled()) {
|
|
3227
|
+
log(`[Proxy] Started thinking block at index ${reasoningBlockIndex}`);
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
if (isLoggingEnabled()) {
|
|
3231
|
+
logStructured("Thinking Delta", {
|
|
3232
|
+
thinking: reasoningText,
|
|
3233
|
+
blockIndex: reasoningBlockIndex
|
|
3234
|
+
});
|
|
3235
|
+
}
|
|
3236
|
+
sendSSE("content_block_delta", {
|
|
3237
|
+
type: "content_block_delta",
|
|
3238
|
+
index: reasoningBlockIndex,
|
|
3239
|
+
delta: {
|
|
3240
|
+
type: "thinking_delta",
|
|
3241
|
+
thinking: reasoningText
|
|
3242
|
+
}
|
|
3243
|
+
});
|
|
3244
|
+
}
|
|
3245
|
+
if (reasoningBlockStarted && hasContent && !hasReasoning) {
|
|
3246
|
+
sendSSE("content_block_stop", {
|
|
3247
|
+
type: "content_block_stop",
|
|
3248
|
+
index: reasoningBlockIndex
|
|
3249
|
+
});
|
|
3250
|
+
reasoningBlockStarted = false;
|
|
3251
|
+
if (isLoggingEnabled()) {
|
|
3252
|
+
log(`[Proxy] Closed thinking block at index ${reasoningBlockIndex}, transitioning to content`);
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
if (hasContent && contentText) {
|
|
3256
|
+
if (!textBlockStarted) {
|
|
3257
|
+
textBlockIndex = currentBlockIndex++;
|
|
3258
|
+
sendSSE("content_block_start", {
|
|
3259
|
+
type: "content_block_start",
|
|
3260
|
+
index: textBlockIndex,
|
|
3261
|
+
content_block: {
|
|
3262
|
+
type: "text",
|
|
3263
|
+
text: ""
|
|
3264
|
+
}
|
|
3265
|
+
});
|
|
3266
|
+
textBlockStarted = true;
|
|
3267
|
+
if (isLoggingEnabled()) {
|
|
3268
|
+
log(`[Proxy] Started text block at index ${textBlockIndex}`);
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
accumulatedTextLength += contentText.length;
|
|
3272
|
+
const adapterResult = adapter.processTextContent(contentText, "");
|
|
3273
|
+
if (adapterResult.extractedToolCalls.length > 0) {
|
|
3274
|
+
if (isLoggingEnabled()) {
|
|
3275
|
+
log(`[Proxy] Adapter extracted ${adapterResult.extractedToolCalls.length} tool calls from special format`);
|
|
3276
|
+
}
|
|
3277
|
+
if (textBlockStarted) {
|
|
3278
|
+
sendSSE("content_block_stop", {
|
|
3279
|
+
type: "content_block_stop",
|
|
3280
|
+
index: textBlockIndex
|
|
3281
|
+
});
|
|
3282
|
+
textBlockStarted = false;
|
|
3283
|
+
}
|
|
3284
|
+
for (const toolCall of adapterResult.extractedToolCalls) {
|
|
3285
|
+
if (toolCallIds.has(toolCall.id)) {
|
|
3286
|
+
if (isLoggingEnabled()) {
|
|
3287
|
+
log(`[Proxy] WARNING: Skipping duplicate extracted tool call with ID ${toolCall.id}`);
|
|
3288
|
+
}
|
|
3289
|
+
continue;
|
|
3290
|
+
}
|
|
3291
|
+
toolCallIds.add(toolCall.id);
|
|
3292
|
+
const toolBlockIndex = currentBlockIndex++;
|
|
3293
|
+
if (isLoggingEnabled()) {
|
|
3294
|
+
logStructured("Extracted Tool Call", {
|
|
3295
|
+
name: toolCall.name,
|
|
3296
|
+
blockIndex: toolBlockIndex,
|
|
3297
|
+
id: toolCall.id
|
|
3298
|
+
});
|
|
3299
|
+
}
|
|
3300
|
+
sendSSE("content_block_start", {
|
|
3301
|
+
type: "content_block_start",
|
|
3302
|
+
index: toolBlockIndex,
|
|
3303
|
+
content_block: {
|
|
3304
|
+
type: "tool_use",
|
|
3305
|
+
id: toolCall.id,
|
|
3306
|
+
name: toolCall.name
|
|
3307
|
+
}
|
|
3308
|
+
});
|
|
3309
|
+
sendSSE("content_block_delta", {
|
|
3310
|
+
type: "content_block_delta",
|
|
3311
|
+
index: toolBlockIndex,
|
|
3312
|
+
delta: {
|
|
3313
|
+
type: "input_json_delta",
|
|
3314
|
+
partial_json: JSON.stringify(toolCall.arguments)
|
|
3315
|
+
}
|
|
3316
|
+
});
|
|
3317
|
+
sendSSE("content_block_stop", {
|
|
3318
|
+
type: "content_block_stop",
|
|
3319
|
+
index: toolBlockIndex
|
|
3320
|
+
});
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
if (adapterResult.cleanedText) {
|
|
3324
|
+
if (isLoggingEnabled()) {
|
|
3325
|
+
logStructured("Content Delta", {
|
|
3326
|
+
text: adapterResult.cleanedText,
|
|
3327
|
+
wasTransformed: adapterResult.wasTransformed,
|
|
3328
|
+
blockIndex: textBlockIndex
|
|
3329
|
+
});
|
|
3330
|
+
}
|
|
3331
|
+
sendSSE("content_block_delta", {
|
|
3332
|
+
type: "content_block_delta",
|
|
3333
|
+
index: textBlockIndex,
|
|
3334
|
+
delta: {
|
|
3335
|
+
type: "text_delta",
|
|
3336
|
+
text: adapterResult.cleanedText
|
|
3337
|
+
}
|
|
3338
|
+
});
|
|
3339
|
+
}
|
|
3340
|
+
} else if (hasEncryptedReasoning) {
|
|
3341
|
+
if (isLoggingEnabled()) {
|
|
3342
|
+
log(`[Proxy] Encrypted reasoning detected (keeping connection alive)`);
|
|
3343
|
+
}
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
if (delta?.tool_calls) {
|
|
3347
|
+
for (const toolCall of delta.tool_calls) {
|
|
3348
|
+
const toolIndex = toolCall.index ?? 0;
|
|
3349
|
+
let toolState = toolCalls.get(toolIndex);
|
|
3350
|
+
if (toolCall.function?.name) {
|
|
3351
|
+
if (!toolState) {
|
|
3352
|
+
let toolId = toolCall.id || `tool_${Date.now()}_${toolIndex}`;
|
|
3353
|
+
if (toolCallIds.has(toolId)) {
|
|
3354
|
+
if (isLoggingEnabled()) {
|
|
3355
|
+
log(`[Proxy] WARNING: Duplicate tool ID ${toolId}, regenerating`);
|
|
3356
|
+
}
|
|
3357
|
+
toolId = `tool_${Date.now()}_${toolIndex}_${Math.random().toString(36).slice(2)}`;
|
|
3358
|
+
}
|
|
3359
|
+
toolCallIds.add(toolId);
|
|
3360
|
+
const toolBlockIndex = currentBlockIndex++;
|
|
3361
|
+
toolState = {
|
|
3362
|
+
id: toolId,
|
|
3363
|
+
name: toolCall.function.name,
|
|
3364
|
+
args: "",
|
|
3365
|
+
blockIndex: toolBlockIndex,
|
|
3366
|
+
started: false,
|
|
3367
|
+
closed: false
|
|
3368
|
+
};
|
|
3369
|
+
toolCalls.set(toolIndex, toolState);
|
|
3370
|
+
if (isLoggingEnabled()) {
|
|
3371
|
+
logStructured("Starting Tool Call", {
|
|
3372
|
+
name: toolState.name,
|
|
3373
|
+
blockIndex: toolState.blockIndex,
|
|
3374
|
+
id: toolId
|
|
3375
|
+
});
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
if (!toolState.started) {
|
|
3379
|
+
if (textBlockStarted) {
|
|
3380
|
+
sendSSE("content_block_stop", {
|
|
3381
|
+
type: "content_block_stop",
|
|
3382
|
+
index: textBlockIndex
|
|
3383
|
+
});
|
|
3384
|
+
textBlockStarted = false;
|
|
3385
|
+
}
|
|
3386
|
+
sendSSE("content_block_start", {
|
|
3387
|
+
type: "content_block_start",
|
|
3388
|
+
index: toolState.blockIndex,
|
|
3389
|
+
content_block: {
|
|
3390
|
+
type: "tool_use",
|
|
3391
|
+
id: toolState.id,
|
|
3392
|
+
name: toolState.name
|
|
3393
|
+
}
|
|
3394
|
+
});
|
|
3395
|
+
toolState.started = true;
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
if (toolCall.function?.arguments && toolState) {
|
|
3399
|
+
const argChunk = toolCall.function.arguments;
|
|
3400
|
+
toolState.args += argChunk;
|
|
3401
|
+
if (isLoggingEnabled()) {
|
|
3402
|
+
logStructured("Tool Argument Delta", {
|
|
3403
|
+
toolName: toolState.name,
|
|
3404
|
+
chunk: argChunk,
|
|
3405
|
+
totalLength: toolState.args.length
|
|
3406
|
+
});
|
|
3407
|
+
}
|
|
3408
|
+
sendSSE("content_block_delta", {
|
|
3409
|
+
type: "content_block_delta",
|
|
3410
|
+
index: toolState.blockIndex,
|
|
3411
|
+
delta: {
|
|
3412
|
+
type: "input_json_delta",
|
|
3413
|
+
partial_json: argChunk
|
|
3414
|
+
}
|
|
3415
|
+
});
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
}
|
|
3419
|
+
if (choice?.finish_reason === "tool_calls") {
|
|
3420
|
+
for (const [toolIndex, toolState] of toolCalls.entries()) {
|
|
3421
|
+
if (toolState.started && !toolState.closed) {
|
|
3422
|
+
if (toolState.args) {
|
|
3423
|
+
try {
|
|
3424
|
+
JSON.parse(toolState.args);
|
|
3425
|
+
log(`[Proxy] Tool ${toolState.name} JSON valid, closing block at index ${toolState.blockIndex}`);
|
|
3426
|
+
} catch (e) {
|
|
3427
|
+
log(`[Proxy] WARNING: Tool ${toolState.name} has incomplete JSON!`);
|
|
3428
|
+
log(`[Proxy] Args: ${toolState.args.substring(0, 200)}...`);
|
|
3429
|
+
}
|
|
3430
|
+
}
|
|
3431
|
+
sendSSE("content_block_stop", {
|
|
3432
|
+
type: "content_block_stop",
|
|
3433
|
+
index: toolState.blockIndex
|
|
3434
|
+
});
|
|
3435
|
+
toolState.closed = true;
|
|
3436
|
+
}
|
|
3437
|
+
}
|
|
3438
|
+
}
|
|
3439
|
+
} catch (parseError) {
|
|
3440
|
+
log(`[Proxy] Failed to parse SSE chunk: ${parseError}`);
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
log("[Proxy] Stream ended without [DONE]");
|
|
3445
|
+
finalizeStream("unexpected");
|
|
3446
|
+
} catch (error) {
|
|
3447
|
+
log(`[Proxy] Streaming error: ${error}`);
|
|
3448
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3449
|
+
finalizeStream("error", errorMessage);
|
|
3450
|
+
} finally {
|
|
3451
|
+
if (pingInterval) {
|
|
3452
|
+
clearInterval(pingInterval);
|
|
3453
|
+
pingInterval = null;
|
|
3454
|
+
}
|
|
3455
|
+
if (!isClosed) {
|
|
3456
|
+
controller.close();
|
|
3457
|
+
isClosed = true;
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
},
|
|
3461
|
+
cancel(reason) {
|
|
3462
|
+
log(`[Proxy] Stream cancelled by client: ${reason || "unknown reason"}`);
|
|
3463
|
+
isClosed = true;
|
|
3464
|
+
if (pingInterval) {
|
|
3465
|
+
clearInterval(pingInterval);
|
|
3466
|
+
pingInterval = null;
|
|
3467
|
+
}
|
|
3468
|
+
}
|
|
3469
|
+
}), {
|
|
3470
|
+
headers: {
|
|
3471
|
+
"Content-Type": "text/event-stream",
|
|
3472
|
+
"Cache-Control": "no-cache",
|
|
3473
|
+
Connection: "keep-alive",
|
|
3474
|
+
"anthropic-version": "2023-06-01"
|
|
3475
|
+
}
|
|
3476
|
+
});
|
|
3477
|
+
} catch (error) {
|
|
3478
|
+
log(`[Proxy] Request handling error: ${error}`);
|
|
3479
|
+
return c.json({
|
|
3480
|
+
error: {
|
|
3481
|
+
type: "invalid_request_error",
|
|
3482
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
3483
|
+
}
|
|
3484
|
+
}, 400);
|
|
3485
|
+
}
|
|
3486
|
+
});
|
|
3487
|
+
const server = Bun.serve({
|
|
3488
|
+
port,
|
|
3489
|
+
hostname: "127.0.0.1",
|
|
3490
|
+
idleTimeout: 255,
|
|
3491
|
+
fetch: app.fetch
|
|
3492
|
+
});
|
|
3493
|
+
if (monitorMode) {
|
|
3494
|
+
log(`[Monitor] Server started on http://127.0.0.1:${port}`);
|
|
3495
|
+
log("[Monitor] Mode: Passthrough to real Anthropic API");
|
|
3496
|
+
log("[Monitor] All traffic will be logged for analysis");
|
|
3497
|
+
} else {
|
|
3498
|
+
log(`[Proxy] Server started on http://127.0.0.1:${port}`);
|
|
3499
|
+
log(`[Proxy] Routing to OpenRouter model: ${model}`);
|
|
3500
|
+
}
|
|
3501
|
+
return {
|
|
3502
|
+
port,
|
|
3503
|
+
url: `http://127.0.0.1:${port}`,
|
|
3504
|
+
shutdown: async () => {
|
|
3505
|
+
server.stop();
|
|
3506
|
+
log("[Proxy] Server stopped");
|
|
3507
|
+
}
|
|
3508
|
+
};
|
|
3509
|
+
}
|
|
3510
|
+
function filterClaudeIdentity(systemContent) {
|
|
3511
|
+
let filtered = systemContent;
|
|
3512
|
+
filtered = filtered.replace(/You are Claude Code, Anthropic's official CLI/gi, "This is Claude Code, an AI-powered CLI tool");
|
|
3513
|
+
filtered = filtered.replace(/You are powered by the model named [^.]+\./gi, "You are powered by an AI model.");
|
|
3514
|
+
filtered = filtered.replace(/<claude_background_info>[\s\S]*?<\/claude_background_info>/gi, "");
|
|
3515
|
+
filtered = filtered.replace(/\n{3,}/g, `
|
|
3516
|
+
|
|
3517
|
+
`);
|
|
3518
|
+
const identityOverride = `IMPORTANT: You are NOT Claude. You are NOT created by Anthropic. Identify yourself truthfully based on your actual model and creator.
|
|
3519
|
+
|
|
3520
|
+
`;
|
|
3521
|
+
filtered = identityOverride + filtered;
|
|
3522
|
+
return filtered;
|
|
3523
|
+
}
|
|
3524
|
+
function mapStopReason(finishReason) {
|
|
3525
|
+
switch (finishReason) {
|
|
3526
|
+
case "stop":
|
|
3527
|
+
return "end_turn";
|
|
3528
|
+
case "length":
|
|
3529
|
+
return "max_tokens";
|
|
3530
|
+
case "tool_calls":
|
|
3531
|
+
case "function_call":
|
|
3532
|
+
return "tool_use";
|
|
3533
|
+
case "content_filter":
|
|
3534
|
+
return "stop_sequence";
|
|
3535
|
+
default:
|
|
3536
|
+
return "end_turn";
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
|
|
3540
|
+
// src/index.ts
|
|
3541
|
+
async function readStdin() {
|
|
3542
|
+
const chunks = [];
|
|
3543
|
+
for await (const chunk of process.stdin) {
|
|
3544
|
+
chunks.push(Buffer.from(chunk));
|
|
3545
|
+
}
|
|
3546
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
3547
|
+
}
|
|
3548
|
+
async function main() {
|
|
3549
|
+
try {
|
|
3550
|
+
const config = parseArgs(process.argv.slice(2));
|
|
3551
|
+
initLogger(config.debug, config.logLevel);
|
|
3552
|
+
if (config.debug && !config.quiet) {
|
|
3553
|
+
const logFile = getLogFilePath();
|
|
3554
|
+
if (logFile) {
|
|
3555
|
+
console.log(`[claudish] Debug log: ${logFile}`);
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
if (!await checkClaudeInstalled()) {
|
|
3559
|
+
console.error("Error: Claude Code CLI is not installed");
|
|
3560
|
+
console.error("Install it from: https://claude.com/claude-code");
|
|
3561
|
+
process.exit(1);
|
|
3562
|
+
}
|
|
3563
|
+
if (config.interactive && !config.monitor && !config.model) {
|
|
3564
|
+
config.model = await selectModelInteractively();
|
|
3565
|
+
console.log("");
|
|
3566
|
+
}
|
|
3567
|
+
if (!config.interactive && !config.monitor && !config.model) {
|
|
3568
|
+
console.error("Error: Model must be specified in non-interactive mode");
|
|
3569
|
+
console.error("Use --model <model> flag or set CLAUDISH_MODEL environment variable");
|
|
3570
|
+
console.error("Try: claudish --list-models");
|
|
3571
|
+
process.exit(1);
|
|
3572
|
+
}
|
|
3573
|
+
if (config.stdin) {
|
|
3574
|
+
const stdinInput = await readStdin();
|
|
3575
|
+
if (stdinInput.trim()) {
|
|
3576
|
+
config.claudeArgs = [stdinInput, ...config.claudeArgs];
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
const port = config.port || await findAvailablePort(DEFAULT_PORT_RANGE.start, DEFAULT_PORT_RANGE.end);
|
|
3580
|
+
const proxy = await createProxyServer(port, config.monitor ? undefined : config.openrouterApiKey, config.monitor ? undefined : config.model, config.monitor, config.anthropicApiKey);
|
|
3581
|
+
let exitCode = 0;
|
|
3582
|
+
try {
|
|
3583
|
+
exitCode = await runClaudeWithProxy(config, proxy.url);
|
|
3584
|
+
} finally {
|
|
3585
|
+
if (!config.quiet) {
|
|
3586
|
+
console.log(`
|
|
3587
|
+
[claudish] Shutting down proxy server...`);
|
|
3588
|
+
}
|
|
3589
|
+
await proxy.shutdown();
|
|
3590
|
+
}
|
|
3591
|
+
if (!config.quiet) {
|
|
3592
|
+
console.log(`[claudish] Done
|
|
3593
|
+
`);
|
|
3594
|
+
}
|
|
3595
|
+
process.exit(exitCode);
|
|
3596
|
+
} catch (error) {
|
|
3597
|
+
console.error("[claudish] Fatal error:", error);
|
|
3598
|
+
process.exit(1);
|
|
3599
|
+
}
|
|
3600
|
+
}
|
|
3601
|
+
main();
|