diff --git a/lib/internal/locks.js b/lib/internal/locks.js index 817159c06e28..d394d78fb0a9 100644 --- a/lib/internal/locks.js +++ b/lib/internal/locks.js @@ -13,7 +13,7 @@ const { const { ERR_ILLEGAL_CONSTRUCTOR, ERR_INVALID_THIS, -} = require('internal/errors'); +} = require('internal/errors').codes; const { kEmptyObject, lazyDOMException, @@ -165,6 +165,10 @@ class LockManager { */ // https://w3c.github.io/web-locks/#api-lock-manager-request async request(name, options, callback = undefined) { + if (!(this instanceof LockManager)) { + throw new ERR_INVALID_THIS('LockManager'); + } + if (callback === undefined) { callback = options; options = undefined; diff --git a/test/parallel/test-web-locks.js b/test/parallel/test-web-locks.js index 9b0ab92e7c40..da4687e8cc49 100644 --- a/test/parallel/test-web-locks.js +++ b/test/parallel/test-web-locks.js @@ -190,6 +190,38 @@ describe('Web Locks with worker threads', () => { })); }); + it('should throw proper errors on illegal constructor and invalid receiver', async () => { + const LockManager = navigator.locks.constructor; + assert.throws( + () => new LockManager(), + { code: 'ERR_ILLEGAL_CONSTRUCTOR' }, + ); + await assert.rejects( + LockManager.prototype.request.call({}, 'test', common.mustNotCall()), + { code: 'ERR_INVALID_THIS' }, + ); + await assert.rejects( + LockManager.prototype.query.call({}), + { code: 'ERR_INVALID_THIS' }, + ); + + await navigator.locks.request('receiver-test', common.mustCall((lock) => { + const Lock = lock.constructor; + assert.throws( + () => new Lock(), + { code: 'ERR_ILLEGAL_CONSTRUCTOR' }, + ); + assert.throws( + () => Reflect.get(Lock.prototype, 'name', {}), + { code: 'ERR_INVALID_THIS' }, + ); + assert.throws( + () => Reflect.get(Lock.prototype, 'mode', {}), + { code: 'ERR_INVALID_THIS' }, + ); + })); + }); + it('should clean up when worker is terminated with a pending lock', async () => { // Acquire the lock in the main thread so that the worker's request will be pending await navigator.locks.request('cleanup-test', common.mustCall(async () => {