import { core, primordials } from "ext:core/mod.js";
import { op_defer, op_now } from "ext:core/ops";
const {
Uint8Array,
Uint32Array,
PromisePrototypeThen,
TypedArrayPrototypeGetBuffer,
TypeError,
indirectEval,
ReflectApply,
} = primordials;
import * as webidl from "ext:deno_webidl/00_webidl.js";
const hrU8 = new Uint8Array(8);
const hr = new Uint32Array(TypedArrayPrototypeGetBuffer(hrU8));
function opNow() {
op_now(hrU8);
return (hr[0] * 1000 + hr[1] / 1e6);
}
function checkThis(thisArg) {
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis) {
throw new TypeError("Illegal invocation");
}
}
function setImmediate(callback, ...args) {
if (args.length > 0) {
const unboundCallback = callback;
callback = () => ReflectApply(unboundCallback, window, args);
}
return core.queueImmediate(
callback,
);
}
function setTimeout(callback, timeout = 0, ...args) {
checkThis(this);
if (typeof callback !== "function") {
const unboundCallback = webidl.converters.DOMString(callback);
callback = () => indirectEval(unboundCallback);
}
if (args.length > 0) {
const unboundCallback = callback;
callback = () => ReflectApply(unboundCallback, window, args);
}
timeout = webidl.converters.long(timeout);
return core.queueUserTimer(
core.getTimerDepth() + 1,
false,
timeout,
callback,
);
}
function setInterval(callback, timeout = 0, ...args) {
checkThis(this);
if (typeof callback !== "function") {
const unboundCallback = webidl.converters.DOMString(callback);
callback = () => indirectEval(unboundCallback);
}
if (args.length > 0) {
const unboundCallback = callback;
callback = () => ReflectApply(unboundCallback, window, args);
}
timeout = webidl.converters.long(timeout);
return core.queueUserTimer(
core.getTimerDepth() + 1,
true,
timeout,
callback,
);
}
function clearTimeout(id = 0) {
checkThis(this);
id = webidl.converters.long(id);
core.cancelTimer(id);
}
function clearInterval(id = 0) {
checkThis(this);
id = webidl.converters.long(id);
core.cancelTimer(id);
}
function unrefTimer(id) {
core.unrefTimer(id);
}
function refTimer(id) {
core.refTimer(id);
}
function defer(go) {
PromisePrototypeThen(op_defer(), () => go());
}
export {
clearInterval,
clearTimeout,
defer,
opNow,
refTimer,
setImmediate,
setInterval,
setTimeout,
unrefTimer,
};