DetachArrayBuffer.js 1.2 KB

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