github.com/aminovpavel/nomad@v0.11.8/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
    17      .replace(/\}\{/g, '}\n{')
    18      .split('\n')
    19      .without('');
    20    const frames = lines.map(line => JSON.parse(line)).filter(frame => frame.Data);
    21  
    22    if (frames.length) {
    23      frames.forEach(frame => (frame.Data = b64decode(frame.Data)));
    24      return {
    25        offset: frames[frames.length - 1].Offset,
    26        message: frames.mapBy('Data').join(''),
    27      };
    28    }
    29  
    30    return {};
    31  }
    32  
    33  function b64decode(str) {
    34    return decoder.decode(base64js.toByteArray(str));
    35  }