self-media-james/articles/008/claude-code-source-code/src/cli/transports/transportUtils.ts
邓文兵 11b0bd6b86 chore(008): 纳入 Claude Code / claw-code 源码素材并忽略缓存文件
- 收录 008 文章分析用的两份源码(claude-code-source-code、claw-code),
  已移除其内嵌 .git,作为普通素材文件入库
- .gitignore 增加 .DS_Store、__pycache__/、*.pyc,屏蔽系统与缓存噪音

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 13:13:22 +08:00

46 lines
1.7 KiB
TypeScript

import { URL } from 'url'
import { isEnvTruthy } from '../../utils/envUtils.js'
import { HybridTransport } from './HybridTransport.js'
import { SSETransport } from './SSETransport.js'
import type { Transport } from './Transport.js'
import { WebSocketTransport } from './WebSocketTransport.js'
/**
* Helper function to get the appropriate transport for a URL.
*
* Transport selection priority:
* 1. SSETransport (SSE reads + POST writes) when CLAUDE_CODE_USE_CCR_V2 is set
* 2. HybridTransport (WS reads + POST writes) when CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2 is set
* 3. WebSocketTransport (WS reads + WS writes) — default
*/
export function getTransportForUrl(
url: URL,
headers: Record<string, string> = {},
sessionId?: string,
refreshHeaders?: () => Record<string, string>,
): Transport {
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
// v2: SSE for reads, HTTP POST for writes
// --sdk-url is the session URL (.../sessions/{id});
// derive the SSE stream URL by appending /worker/events/stream
const sseUrl = new URL(url.href)
if (sseUrl.protocol === 'wss:') {
sseUrl.protocol = 'https:'
} else if (sseUrl.protocol === 'ws:') {
sseUrl.protocol = 'http:'
}
sseUrl.pathname =
sseUrl.pathname.replace(/\/$/, '') + '/worker/events/stream'
return new SSETransport(sseUrl, headers, sessionId, refreshHeaders)
}
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
if (isEnvTruthy(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)) {
return new HybridTransport(url, headers, sessionId, refreshHeaders)
}
return new WebSocketTransport(url, headers, sessionId, refreshHeaders)
} else {
throw new Error(`Unsupported protocol: ${url.protocol}`)
}
}