jsonl.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { AnthropicError } from "../../core/error.mjs";
  2. import { ReadableStreamToAsyncIterable } from "../shims.mjs";
  3. import { LineDecoder } from "./line.mjs";
  4. export class JSONLDecoder {
  5. constructor(iterator, controller) {
  6. this.iterator = iterator;
  7. this.controller = controller;
  8. }
  9. async *decoder() {
  10. const lineDecoder = new LineDecoder();
  11. for await (const chunk of this.iterator) {
  12. for (const line of lineDecoder.decode(chunk)) {
  13. yield JSON.parse(line);
  14. }
  15. }
  16. for (const line of lineDecoder.flush()) {
  17. yield JSON.parse(line);
  18. }
  19. }
  20. [Symbol.asyncIterator]() {
  21. return this.decoder();
  22. }
  23. static fromResponse(response, controller) {
  24. if (!response.body) {
  25. controller.abort();
  26. if (typeof globalThis.navigator !== 'undefined' &&
  27. globalThis.navigator.product === 'ReactNative') {
  28. throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
  29. }
  30. throw new AnthropicError(`Attempted to iterate over a response with no body`);
  31. }
  32. return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
  33. }
  34. }
  35. //# sourceMappingURL=jsonl.mjs.map