85 lines
2.2 KiB
JavaScript
85 lines
2.2 KiB
JavaScript
/** Minimal AbortController for Bare/Pear when globalThis lacks it (drive-resident /bin preamble). */
|
|
|
|
function bareAgentEnsureAbortPolyfill() {
|
|
const g =
|
|
typeof globalThis !== 'undefined'
|
|
? globalThis
|
|
: typeof global !== 'undefined'
|
|
? global
|
|
: typeof self !== 'undefined'
|
|
? self
|
|
: /** @type {Record<string, unknown>} */ ({})
|
|
if (typeof g.AbortController === 'function') return
|
|
|
|
function BareAbortSignal() {
|
|
/** @type {boolean} */
|
|
this.aborted = false
|
|
/** @type {unknown} */
|
|
this.reason = undefined
|
|
/** @type {{ fn: () => void, once: boolean }[]} */
|
|
this._listeners = []
|
|
}
|
|
|
|
BareAbortSignal.prototype.addEventListener = function (type, fn, opts) {
|
|
if (type !== 'abort' || typeof fn !== 'function') return
|
|
const once = !!(opts && opts.once)
|
|
if (this.aborted) {
|
|
if (once) {
|
|
try {
|
|
fn.call(this)
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
return
|
|
}
|
|
this._listeners.push({ fn: /** @type {() => void} */ (fn), once })
|
|
}
|
|
|
|
BareAbortSignal.prototype.removeEventListener = function (type, fn) {
|
|
if (type !== 'abort' || typeof fn !== 'function') return
|
|
this._listeners = this._listeners.filter((x) => x.fn !== fn)
|
|
}
|
|
|
|
BareAbortSignal.prototype.throwIfAborted = function () {
|
|
if (!this.aborted) return
|
|
const DOMException = g.DOMException
|
|
if (typeof DOMException === 'function') {
|
|
throw new DOMException('Aborted', 'AbortError')
|
|
}
|
|
const e = new Error('Aborted')
|
|
e.name = 'AbortError'
|
|
throw e
|
|
}
|
|
|
|
function BareAbortController() {
|
|
this.signal = new BareAbortSignal()
|
|
}
|
|
|
|
BareAbortController.prototype.abort = function (reason) {
|
|
const s = this.signal
|
|
if (s.aborted) return
|
|
s.aborted = true
|
|
s.reason = reason
|
|
const list = s._listeners.slice()
|
|
s._listeners.length = 0
|
|
for (const x of list) {
|
|
try {
|
|
x.fn.call(s)
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
}
|
|
|
|
if (typeof globalThis !== 'undefined') {
|
|
globalThis.AbortController = BareAbortController
|
|
globalThis.AbortSignal = BareAbortSignal
|
|
} else {
|
|
g.AbortController = BareAbortController
|
|
g.AbortSignal = BareAbortSignal
|
|
}
|
|
}
|
|
|
|
bareAgentEnsureAbortPolyfill()
|