github.com/hernad/nomad@v1.6.112/ui/app/utils/stream-frames.js (about)

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