DetachArrayBuffer.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var $SyntaxError = require('es-errors/syntax');
  3. var $TypeError = require('es-errors/type');
  4. var IsDetachedBuffer = require('./IsDetachedBuffer');
  5. var isArrayBuffer = require('is-array-buffer');
  6. var isSharedArrayBuffer = require('is-shared-array-buffer');
  7. var MessageChannel;
  8. try {
  9. // eslint-disable-next-line global-require
  10. MessageChannel = require('worker_threads').MessageChannel; // node 11.7+
  11. } catch (e) { /**/ }
  12. // https://262.ecma-international.org/8.0/#sec-detacharraybuffer
  13. /* globals postMessage */
  14. module.exports = function DetachArrayBuffer(arrayBuffer) {
  15. if (!isArrayBuffer(arrayBuffer) || isSharedArrayBuffer(arrayBuffer)) {
  16. throw new $TypeError('Assertion failed: `arrayBuffer` must be an Object with an [[ArrayBufferData]] internal slot, and not a Shared Array Buffer');
  17. }
  18. if (!IsDetachedBuffer(arrayBuffer)) { // node v21.0.0+ throws when you structuredClone a detached buffer
  19. if (typeof structuredClone === 'function') {
  20. structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  21. } else if (typeof postMessage === 'function') {
  22. postMessage('', '/', [arrayBuffer]); // TODO: see if this might trigger listeners
  23. } else if (MessageChannel) {
  24. (new MessageChannel()).port1.postMessage(null, [arrayBuffer]);
  25. } else {
  26. throw new $SyntaxError('DetachArrayBuffer is not supported in this environment');
  27. }
  28. }
  29. return null;
  30. };