mirror of
https://github.com/langgenius/dify.git
synced 2026-06-08 00:41:55 +08:00
Co-authored-by: GareArc <garethcxy@dify.ai> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: L1nSn0w <l1nsn0w@qq.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: gigglewang <gigglewang@dify.ai> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Co-authored-by: Xiyuan Chen <52963600+GareArc@users.noreply.github.com>
37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import type { SseEvent } from './sse.js'
|
|
|
|
const dec = new TextDecoder()
|
|
|
|
export function eventNameFromDifyData(data: Uint8Array): string {
|
|
if (data.byteLength === 0)
|
|
return ''
|
|
try {
|
|
const obj = JSON.parse(dec.decode(data)) as unknown
|
|
if (obj === null || typeof obj !== 'object')
|
|
return ''
|
|
const evt = (obj as { event?: unknown }).event
|
|
return typeof evt === 'string' ? evt : ''
|
|
}
|
|
catch {
|
|
return ''
|
|
}
|
|
}
|
|
|
|
// Dify always sends JSON-encoded SSE data. Most endpoints embed the event
|
|
// name in the JSON `event` field rather than emitting a transport-level
|
|
// `event:` line. This adapter promotes the embedded name into `ev.name`
|
|
// so consumers can dispatch uniformly. Transport-level `event:` lines win
|
|
// when both are present, preserving compatibility with `event: ping`.
|
|
export async function* normalizeDifyStream(
|
|
iter: AsyncIterable<SseEvent>,
|
|
): AsyncGenerator<SseEvent, void, void> {
|
|
for await (const ev of iter) {
|
|
if (ev.name !== '') {
|
|
yield ev
|
|
continue
|
|
}
|
|
const name = eventNameFromDifyData(ev.data)
|
|
yield name === '' ? ev : { ...ev, name }
|
|
}
|
|
}
|