github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/ui/app/utils/stream-frames.js (about)

     1  import { TextDecoderLite } from 'text-encoder-lite';
     2  import base64js from 'base64-js';
     3  
     4  const decoder = new TextDecoderLite('utf-8');
     5  
     6  /**
     7   *
     8   * @param {string} chunk
     9   * Chunk is an undelimited string of valid JSON objects as returned by a streaming endpoint.
    10   * Each JSON object in a chunk contains two properties:
    11   *   Offset {number} The index from the beginning of the stream at which this JSON object starts
    12   *   Data {string} A base64 encoded string representing the contents of the stream this JSON
    13   *                 object represents.
    14   */
    15  export function decode(chunk) {
    16    const lines = chunk.replace(/\}\{/g, '}\n{').split('\n').without('');
    17    const frames = lines
    18      .map((line) => JSON.parse(line))
    19      .filter((frame) => frame.Data);
    20  
    21    if (frames.length) {
    22      frames.forEach((frame) => (frame.Data = b64decode(frame.Data)));
    23      return {
    24        offset: frames[frames.length - 1].Offset,
    25        message: frames.mapBy('Data').join(''),
    26      };
    27    }
    28  
    29    return {};
    30  }
    31  
    32  function b64decode(str) {
    33    return decoder.decode(base64js.toByteArray(str));
    34  }