base64.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.toFloat32Array = exports.fromBase64 = exports.toBase64 = void 0;
  5. const error_1 = require("../../core/error.js");
  6. const bytes_1 = require("./bytes.js");
  7. const toBase64 = (data) => {
  8. if (!data)
  9. return '';
  10. if (typeof globalThis.Buffer !== 'undefined') {
  11. return globalThis.Buffer.from(data).toString('base64');
  12. }
  13. if (typeof data === 'string') {
  14. data = (0, bytes_1.encodeUTF8)(data);
  15. }
  16. if (typeof btoa !== 'undefined') {
  17. return btoa(String.fromCharCode.apply(null, data));
  18. }
  19. throw new error_1.OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined');
  20. };
  21. exports.toBase64 = toBase64;
  22. const fromBase64 = (str) => {
  23. if (typeof globalThis.Buffer !== 'undefined') {
  24. const buf = globalThis.Buffer.from(str, 'base64');
  25. return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
  26. }
  27. if (typeof atob !== 'undefined') {
  28. const bstr = atob(str);
  29. const buf = new Uint8Array(bstr.length);
  30. for (let i = 0; i < bstr.length; i++) {
  31. buf[i] = bstr.charCodeAt(i);
  32. }
  33. return buf;
  34. }
  35. throw new error_1.OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined');
  36. };
  37. exports.fromBase64 = fromBase64;
  38. /**
  39. * Converts a Base64 encoded string to a Float32Array.
  40. * @param base64Str - The Base64 encoded string.
  41. * @returns An Array of numbers interpreted as Float32 values.
  42. */
  43. const toFloat32Array = (base64Str) => {
  44. if (typeof Buffer !== 'undefined') {
  45. // for Node.js environment
  46. const buf = Buffer.from(base64Str, 'base64');
  47. return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
  48. }
  49. else {
  50. // for legacy web platform APIs
  51. const binaryStr = atob(base64Str);
  52. const len = binaryStr.length;
  53. const bytes = new Uint8Array(len);
  54. for (let i = 0; i < len; i++) {
  55. bytes[i] = binaryStr.charCodeAt(i);
  56. }
  57. return Array.from(new Float32Array(bytes.buffer));
  58. }
  59. };
  60. exports.toFloat32Array = toFloat32Array;
  61. //# sourceMappingURL=base64.js.map