Path: blob/main/extensions/copilot/src/platform/nesFetch/node/streamTransformer.ts
13401 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { Completion } from '../common/completionsAPI';67/**8* @throws if data line cannot be parsed as JSON or if it contains an error field.9*/10export async function* jsonlStreamToCompletions(jsonlStream: AsyncIterable<string>): AsyncGenerator<Completion> {11for await (const line of jsonlStream) {12if (line.trim() === 'data: [DONE]') {13continue;14}1516if (line.startsWith('data: ')) {17const message: Completion & { error?: { message: string } } = JSON.parse(line.substring('data: '.length));1819if (message.error) {20throw new Error(message.error.message);21}2223yield message;24}25}26}2728// function replaceBytes(s: string): string {29// if (!s.startsWith('bytes:')) {30// return s;31// }32// const bytes: number[] = [];33// let i = 'bytes:'.length;34// const textEncoder = new TextEncoder();35// while (i < s.length) {36// if (s.slice(i, i + 3) === '\\\\x') {37// bytes.push(parseInt(s.slice(i + 3, i + 5), 16));38// i += 5;39// } else if (s.slice(i, i + 2) === '\\x') {40// bytes.push(parseInt(s.slice(i + 2, i + 4), 16));41// i += 4;42// } else {43// const encoded = textEncoder.encode(s.slice(i, i + 1));44// for (const b of encoded) {45// bytes.push(b);46// }47// i += 1;48// }49// }50// return new TextDecoder('utf8', { fatal: false }).decode(51// new Uint8Array(bytes)52// );53// }545556