UNPKG

@malagu/core

Version:
95 lines 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkCancelled = exports.isCancelled = exports.cancelled = exports.CancellationTokenSource = exports.CancellationToken = exports.CancellationError = void 0; const event_1 = require("./event"); const emitter_1 = require("./emitter"); class CancellationError extends Error { constructor() { super('Canceled'); this.name = this.message; } } exports.CancellationError = CancellationError; // eslint-disable-next-line @typescript-eslint/no-explicit-any const shortcutEvent = Object.freeze(Object.assign(function (callback, context) { const handle = setTimeout(callback.bind(context), 0); return { dispose() { clearTimeout(handle); } }; }, { maxListeners: 0 })); var CancellationToken; (function (CancellationToken) { CancellationToken.None = Object.freeze({ isCancellationRequested: false, onCancellationRequested: event_1.Event.None }); CancellationToken.Cancelled = Object.freeze({ isCancellationRequested: true, onCancellationRequested: shortcutEvent }); })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {})); class MutableToken { constructor() { this._isCancelled = false; } cancel() { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(undefined); this._emitter = undefined; } } } get isCancellationRequested() { return this._isCancelled; } get onCancellationRequested() { if (this._isCancelled) { return shortcutEvent; } if (!this._emitter) { this._emitter = new emitter_1.Emitter(); } return this._emitter.event; } } class CancellationTokenSource { get token() { if (!this._token) { // be lazy and create the token only when // actually needed this._token = new MutableToken(); } return this._token; } cancel() { if (!this._token) { // save an object by returning the default // cancelled token when cancellation happens // before someone asks for the token this._token = CancellationToken.Cancelled; } else if (this._token !== CancellationToken.Cancelled) { this._token.cancel(); } } dispose() { this.cancel(); } } exports.CancellationTokenSource = CancellationTokenSource; const cancelledMessage = 'Cancelled'; function cancelled() { return new Error(cancelledMessage); } exports.cancelled = cancelled; function isCancelled(err) { return !!err && err.message === cancelledMessage; } exports.isCancelled = isCancelled; function checkCancelled(token) { if (!!token && token.isCancellationRequested) { throw cancelled(); } } exports.checkCancelled = checkCancelled; //# sourceMappingURL=cancellation.js.map