/*1* This file is part of CoCalc: Copyright © 2024 Sagemath, Inc.2* License: Distributed under the terms of the Modified BSD License (same as ipywidgets)3*/45// Inspiration: this is meant to be a more modern version of upstream ipywidget's6// packages/base-manager/src/utils.ts, which based on a non-maintained library.7// Hence the BSD license.89import { fromUint8Array, toUint8Array } from "js-base64";1011// Convert an ArrayBuffer to a base64 string.12// UNCLEAR: I put in ArrayBufferView also, since it's mentioned in all the typings13// in ipywidgets, and we can at least handle one case of it Uint8Array in14// one direction.15export function bufferToBase64(buffer: ArrayBuffer | ArrayBufferView): string {16if (buffer instanceof ArrayBuffer) {17return fromUint8Array(new Uint8Array(buffer));18} else if (buffer instanceof Uint8Array) {19return fromUint8Array(buffer);20}21throw new Error("buffer must be either ArrayBuffer or Uint8Array");22}2324// Convert a base64 string to an ArrayBuffer.25export function base64ToBuffer(base64: string): ArrayBuffer {26const buffer = toUint8Array(base64).buffer;27// @ts-ignore28return buffer;29}303132