mirror of
https://github.com/denoland/deno.git
synced 2025-03-03 09:31:22 -05:00
Use globalThis to reference global scope (#3719)
Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
This commit is contained in:
parent
23e67eb515
commit
60b53fd6b6
19 changed files with 219 additions and 264 deletions
|
@ -32,9 +32,10 @@ import { fromTypeScriptDiagnostic } from "./diagnostics_util.ts";
|
|||
import * as os from "./os.ts";
|
||||
import { assert } from "./util.ts";
|
||||
import * as util from "./util.ts";
|
||||
import { window as self } from "./window.ts";
|
||||
import { postMessage, workerClose, workerMain } from "./workers.ts";
|
||||
|
||||
const self = globalThis;
|
||||
|
||||
interface CompilerRequestCompile {
|
||||
type: CompilerRequestType.Compile;
|
||||
rootNames: string[];
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
import { window } from "./window.ts";
|
||||
|
||||
// This allows us to access core in API even if we
|
||||
// dispose window.Deno
|
||||
export const core = window.Deno.core as DenoCore;
|
||||
export const core = globalThis.Deno.core as DenoCore;
|
||||
|
|
|
@ -10,7 +10,6 @@ import {
|
|||
isSlotable,
|
||||
retarget
|
||||
} from "./dom_util.ts";
|
||||
import { window } from "./window.ts";
|
||||
|
||||
// https://dom.spec.whatwg.org/#get-the-parent
|
||||
// Note: Nodes, shadow roots, and documents override this algorithm so we set it to null.
|
||||
|
@ -40,7 +39,7 @@ export class EventTarget implements domTypes.EventTarget {
|
|||
callback: (event: domTypes.Event) => void | null,
|
||||
options?: domTypes.AddEventListenerOptions | boolean
|
||||
): void {
|
||||
const this_ = this || window;
|
||||
const this_ = this || globalThis;
|
||||
|
||||
requiredArguments("EventTarget.addEventListener", arguments.length, 2);
|
||||
const normalizedOptions: domTypes.AddEventListenerOptions = eventTargetHelpers.normalizeAddEventHandlerOptions(
|
||||
|
@ -86,7 +85,7 @@ export class EventTarget implements domTypes.EventTarget {
|
|||
callback: (event: domTypes.Event) => void | null,
|
||||
options?: domTypes.EventListenerOptions | boolean
|
||||
): void {
|
||||
const this_ = this || window;
|
||||
const this_ = this || globalThis;
|
||||
|
||||
requiredArguments("EventTarget.removeEventListener", arguments.length, 2);
|
||||
const listeners = this_[domTypes.eventTargetListeners];
|
||||
|
@ -126,7 +125,7 @@ export class EventTarget implements domTypes.EventTarget {
|
|||
}
|
||||
|
||||
public dispatchEvent(event: domTypes.Event): boolean {
|
||||
const this_ = this || window;
|
||||
const this_ = this || globalThis;
|
||||
|
||||
requiredArguments("EventTarget.dispatchEvent", arguments.length, 1);
|
||||
const listeners = this_[domTypes.eventTargetListeners];
|
||||
|
|
|
@ -1,13 +1,10 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
|
||||
// This is a "special" module, in that it define the global runtime scope of
|
||||
// Deno, and therefore it defines a lot of the runtime environment that code
|
||||
// is evaluated in. We use this file to automatically build the runtime type
|
||||
// library.
|
||||
// is evaluated in.
|
||||
|
||||
// Modules which will make up part of the global public API surface should be
|
||||
// imported as namespaces, so when the runtime type library is generated they
|
||||
// can be expressed as a namespace in the type library.
|
||||
import { window } from "./window.ts";
|
||||
// By convention we import those items that are globally exposed as namespaces
|
||||
import * as blob from "./blob.ts";
|
||||
import * as consoleTypes from "./console.ts";
|
||||
import * as csprng from "./get_random_values.ts";
|
||||
|
@ -31,12 +28,10 @@ import * as request from "./request.ts";
|
|||
// These imports are not exposed and therefore are fine to just import the
|
||||
// symbols required.
|
||||
import { core } from "./core.ts";
|
||||
|
||||
import { internalObject } from "./internals.ts";
|
||||
|
||||
// During the build process, augmentations to the variable `window` in this
|
||||
// file are tracked and created as part of default library that is built into
|
||||
// Deno, we only need to declare the enough to compile Deno.
|
||||
// This global augmentation is just enough types to be able to build Deno,
|
||||
// the runtime types are fully defined in `lib.deno_runtime.d.ts`.
|
||||
declare global {
|
||||
interface CallSite {
|
||||
getThis(): unknown;
|
||||
|
@ -65,145 +60,177 @@ declare global {
|
|||
[consoleTypes.customInspect]?(): string;
|
||||
}
|
||||
|
||||
const console: consoleTypes.Console;
|
||||
}
|
||||
interface EvalErrorInfo {
|
||||
isNativeError: boolean;
|
||||
isCompileError: boolean;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
thrown: any;
|
||||
}
|
||||
|
||||
// A self reference to the global object.
|
||||
window.window = window;
|
||||
interface DenoCore {
|
||||
print(s: string, isErr?: boolean): void;
|
||||
dispatch(
|
||||
opId: number,
|
||||
control: Uint8Array,
|
||||
zeroCopy?: ArrayBufferView | null
|
||||
): Uint8Array | null;
|
||||
setAsyncHandler(opId: number, cb: (msg: Uint8Array) => void): void;
|
||||
sharedQueue: {
|
||||
head(): number;
|
||||
numRecords(): number;
|
||||
size(): number;
|
||||
push(buf: Uint8Array): boolean;
|
||||
reset(): void;
|
||||
shift(): Uint8Array | null;
|
||||
};
|
||||
|
||||
ops(): Record<string, number>;
|
||||
|
||||
recv(cb: (opId: number, msg: Uint8Array) => void): void;
|
||||
|
||||
send(
|
||||
opId: number,
|
||||
control: null | ArrayBufferView,
|
||||
data?: ArrayBufferView
|
||||
): null | Uint8Array;
|
||||
|
||||
shared: SharedArrayBuffer;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
evalContext(code: string): [any, EvalErrorInfo | null];
|
||||
|
||||
errorToJSON: (e: Error) => string;
|
||||
}
|
||||
|
||||
// Only `var` variables show up in the `globalThis` type when doing a global
|
||||
// scope augmentation.
|
||||
/* eslint-disable no-var */
|
||||
var addEventListener: (
|
||||
type: string,
|
||||
callback: (event: domTypes.Event) => void | null,
|
||||
options?: boolean | domTypes.AddEventListenerOptions | undefined
|
||||
) => void;
|
||||
var compilerMain: (() => void) | undefined;
|
||||
var console: consoleTypes.Console;
|
||||
var Deno: {
|
||||
core: DenoCore;
|
||||
};
|
||||
var denoMain: (() => void) | undefined;
|
||||
var location: domTypes.Location;
|
||||
var onerror:
|
||||
| ((
|
||||
msg: string,
|
||||
source: string,
|
||||
lineno: number,
|
||||
colno: number,
|
||||
e: domTypes.Event
|
||||
) => boolean | void)
|
||||
| undefined;
|
||||
var onload: ((e: domTypes.Event) => void) | undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
var onmessage: ((e: { data: any }) => Promise<void> | void) | undefined;
|
||||
var onunload: ((e: domTypes.Event) => void) | undefined;
|
||||
var queueMicrotask: (callback: () => void) => void;
|
||||
var wasmCompilerMain: (() => void) | undefined;
|
||||
var workerMain: (() => Promise<void> | void) | undefined;
|
||||
/* eslint-enable */
|
||||
}
|
||||
|
||||
// Add internal object to Deno object.
|
||||
// This is not exposed as part of the Deno types.
|
||||
// @ts-ignore
|
||||
Deno[Deno.symbols.internal] = internalObject;
|
||||
// This is the Deno namespace, it is handled differently from other window
|
||||
// properties when building the runtime type library, as the whole module
|
||||
// is flattened into a single namespace.
|
||||
window.Deno = Deno;
|
||||
|
||||
// Globally available functions and object instances.
|
||||
window.atob = textEncoding.atob;
|
||||
window.btoa = textEncoding.btoa;
|
||||
window.fetch = fetchTypes.fetch;
|
||||
window.clearTimeout = timers.clearTimeout;
|
||||
window.clearInterval = timers.clearInterval;
|
||||
window.console = new consoleTypes.Console(core.print);
|
||||
window.setTimeout = timers.setTimeout;
|
||||
window.setInterval = timers.setInterval;
|
||||
window.location = (undefined as unknown) as domTypes.Location;
|
||||
window.onload = undefined as undefined | Function;
|
||||
window.onunload = undefined as undefined | Function;
|
||||
// The following Crypto interface implementation is not up to par with the
|
||||
// standard https://www.w3.org/TR/WebCryptoAPI/#crypto-interface as it does not
|
||||
// yet incorporate the SubtleCrypto interface as its "subtle" property.
|
||||
window.crypto = (csprng as unknown) as Crypto;
|
||||
// window.queueMicrotask added by hand to self-maintained lib.deno_runtime.d.ts
|
||||
function writable(value: unknown): PropertyDescriptor {
|
||||
return {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
}
|
||||
|
||||
// When creating the runtime type library, we use modifications to `window` to
|
||||
// determine what is in the global namespace. When we put a class in the
|
||||
// namespace, we also need its global instance type as well, otherwise users
|
||||
// won't be able to refer to instances.
|
||||
// We have to export the type aliases, so that TypeScript _knows_ they are
|
||||
// being used, which it cannot statically determine within this module.
|
||||
window.Blob = blob.DenoBlob;
|
||||
export type Blob = domTypes.Blob;
|
||||
function nonEnumerable(value: unknown): PropertyDescriptor {
|
||||
return {
|
||||
value,
|
||||
writable: true,
|
||||
configurable: true
|
||||
};
|
||||
}
|
||||
|
||||
export type Body = domTypes.Body;
|
||||
function readOnly(value: unknown): PropertyDescriptor {
|
||||
return {
|
||||
value,
|
||||
enumerable: true
|
||||
};
|
||||
}
|
||||
|
||||
window.File = domFile.DomFileImpl as domTypes.DomFileConstructor;
|
||||
export type File = domTypes.DomFile;
|
||||
const globalProperties = {
|
||||
window: readOnly(globalThis),
|
||||
Deno: readOnly(Deno),
|
||||
atob: writable(textEncoding.atob),
|
||||
btoa: writable(textEncoding.btoa),
|
||||
fetch: writable(fetchTypes.fetch),
|
||||
clearTimeout: writable(timers.clearTimeout),
|
||||
clearInterval: writable(timers.clearInterval),
|
||||
console: writable(new consoleTypes.Console(core.print)),
|
||||
setTimeout: writable(timers.setTimeout),
|
||||
setInterval: writable(timers.setInterval),
|
||||
onload: writable(undefined),
|
||||
onunload: writable(undefined),
|
||||
crypto: readOnly(csprng),
|
||||
Blob: nonEnumerable(blob.DenoBlob),
|
||||
File: nonEnumerable(domFile.DomFileImpl),
|
||||
CustomEvent: nonEnumerable(customEvent.CustomEvent),
|
||||
Event: nonEnumerable(event.Event),
|
||||
EventTarget: nonEnumerable(eventTarget.EventTarget),
|
||||
URL: nonEnumerable(url.URL),
|
||||
URLSearchParams: nonEnumerable(urlSearchParams.URLSearchParams),
|
||||
Headers: nonEnumerable(headers.Headers),
|
||||
FormData: nonEnumerable(formData.FormData),
|
||||
TextEncoder: nonEnumerable(textEncoding.TextEncoder),
|
||||
TextDecoder: nonEnumerable(textEncoding.TextDecoder),
|
||||
Request: nonEnumerable(request.Request),
|
||||
Response: nonEnumerable(fetchTypes.Response),
|
||||
performance: writable(new performanceUtil.Performance()),
|
||||
|
||||
export type CustomEventInit = domTypes.CustomEventInit;
|
||||
window.CustomEvent = customEvent.CustomEvent;
|
||||
export type CustomEvent = domTypes.CustomEvent;
|
||||
export type EventInit = domTypes.EventInit;
|
||||
window.Event = event.Event;
|
||||
export type Event = domTypes.Event;
|
||||
export type EventListener = domTypes.EventListener;
|
||||
window.EventTarget = eventTarget.EventTarget;
|
||||
export type EventTarget = domTypes.EventTarget;
|
||||
window.URL = url.URL;
|
||||
export type URL = url.URL;
|
||||
window.URLSearchParams = urlSearchParams.URLSearchParams;
|
||||
export type URLSearchParams = domTypes.URLSearchParams;
|
||||
onmessage: writable(workers.onmessage),
|
||||
onerror: writable(workers.onerror),
|
||||
|
||||
// Using the `as` keyword to use standard compliant interfaces as the Deno
|
||||
// implementations contain some implementation details we wouldn't want to
|
||||
// expose in the runtime type library.
|
||||
window.Headers = headers.Headers as domTypes.HeadersConstructor;
|
||||
export type Headers = domTypes.Headers;
|
||||
window.FormData = formData.FormData as domTypes.FormDataConstructor;
|
||||
export type FormData = domTypes.FormData;
|
||||
workerMain: nonEnumerable(workers.workerMain),
|
||||
workerClose: nonEnumerable(workers.workerClose),
|
||||
postMessage: writable(workers.postMessage),
|
||||
Worker: nonEnumerable(workers.WorkerImpl),
|
||||
|
||||
window.TextEncoder = textEncoding.TextEncoder;
|
||||
export type TextEncoder = textEncoding.TextEncoder;
|
||||
window.TextDecoder = textEncoding.TextDecoder;
|
||||
export type TextDecoder = textEncoding.TextDecoder;
|
||||
[domTypes.eventTargetHost]: nonEnumerable(null),
|
||||
[domTypes.eventTargetListeners]: nonEnumerable({}),
|
||||
[domTypes.eventTargetMode]: nonEnumerable(""),
|
||||
[domTypes.eventTargetNodeType]: nonEnumerable(0),
|
||||
[eventTarget.eventTargetAssignedSlot]: nonEnumerable(false),
|
||||
[eventTarget.eventTargetHasActivationBehavior]: nonEnumerable(false),
|
||||
|
||||
window.Request = request.Request as domTypes.RequestConstructor;
|
||||
export type Request = domTypes.Request;
|
||||
addEventListener: readOnly(
|
||||
eventTarget.EventTarget.prototype.addEventListener
|
||||
),
|
||||
dispatchEvent: readOnly(eventTarget.EventTarget.prototype.dispatchEvent),
|
||||
removeEventListener: readOnly(
|
||||
eventTarget.EventTarget.prototype.removeEventListener
|
||||
)
|
||||
};
|
||||
|
||||
window.Response = fetchTypes.Response;
|
||||
export type Response = domTypes.Response;
|
||||
|
||||
window.performance = new performanceUtil.Performance();
|
||||
|
||||
// This variable functioning correctly depends on `declareAsLet`
|
||||
// in //tools/ts_library_builder/main.ts
|
||||
window.onmessage = workers.onmessage;
|
||||
window.onerror = workers.onerror;
|
||||
|
||||
window.workerMain = workers.workerMain;
|
||||
window.workerClose = workers.workerClose;
|
||||
window.postMessage = workers.postMessage;
|
||||
|
||||
window.Worker = workers.WorkerImpl;
|
||||
export type Worker = workers.Worker;
|
||||
|
||||
window[domTypes.eventTargetHost] = null;
|
||||
window[domTypes.eventTargetListeners] = {};
|
||||
window[domTypes.eventTargetMode] = "";
|
||||
window[domTypes.eventTargetNodeType] = 0;
|
||||
window[eventTarget.eventTargetAssignedSlot] = false;
|
||||
window[eventTarget.eventTargetHasActivationBehavior] = false;
|
||||
window.addEventListener = eventTarget.EventTarget.prototype.addEventListener;
|
||||
window.dispatchEvent = eventTarget.EventTarget.prototype.dispatchEvent;
|
||||
window.removeEventListener =
|
||||
eventTarget.EventTarget.prototype.removeEventListener;
|
||||
Object.defineProperties(globalThis, globalProperties);
|
||||
|
||||
// Registers the handler for window.onload function.
|
||||
window.addEventListener("load", (e: domTypes.Event): void => {
|
||||
const onload = window.onload;
|
||||
globalThis.addEventListener("load", (e: domTypes.Event): void => {
|
||||
const { onload } = globalThis;
|
||||
if (typeof onload === "function") {
|
||||
onload(e);
|
||||
}
|
||||
});
|
||||
// Registers the handler for window.onunload function.
|
||||
window.addEventListener("unload", (e: domTypes.Event): void => {
|
||||
const onunload = window.onunload;
|
||||
globalThis.addEventListener("unload", (e: domTypes.Event): void => {
|
||||
const { onunload } = globalThis;
|
||||
if (typeof onunload === "function") {
|
||||
onunload(e);
|
||||
}
|
||||
});
|
||||
|
||||
// below are interfaces that are available in TypeScript but
|
||||
// have different signatures
|
||||
export interface ImportMeta {
|
||||
url: string;
|
||||
main: boolean;
|
||||
}
|
||||
|
||||
export interface Crypto {
|
||||
readonly subtle: null;
|
||||
getRandomValues: <
|
||||
T extends
|
||||
| Int8Array
|
||||
| Uint8Array
|
||||
| Uint8ClampedArray
|
||||
| Int16Array
|
||||
| Uint16Array
|
||||
| Int32Array
|
||||
| Uint32Array
|
||||
>(
|
||||
typedArray: T
|
||||
) => T;
|
||||
}
|
||||
|
|
12
cli/js/lib.deno_runtime.d.ts
vendored
12
cli/js/lib.deno_runtime.d.ts
vendored
|
@ -2200,8 +2200,16 @@ declare const TextDecoder: typeof __textEncoding.TextDecoder;
|
|||
declare const Request: __domTypes.RequestConstructor;
|
||||
declare const Response: typeof __fetch.Response;
|
||||
declare const performance: __performanceUtil.Performance;
|
||||
declare let onmessage: (e: { data: any }) => void;
|
||||
declare let onerror: (e: Event) => void;
|
||||
declare let onmessage: ((e: { data: any }) => Promise<void> | void) | undefined;
|
||||
declare let onerror:
|
||||
| ((
|
||||
msg: string,
|
||||
source: string,
|
||||
lineno: number,
|
||||
colno: number,
|
||||
e: Event
|
||||
) => boolean | void)
|
||||
| undefined;
|
||||
declare const workerMain: typeof __workers.workerMain;
|
||||
declare const workerClose: typeof __workers.workerClose;
|
||||
declare const postMessage: typeof __workers.postMessage;
|
||||
|
|
|
@ -2,7 +2,6 @@
|
|||
import { URL } from "./url.ts";
|
||||
import { notImplemented } from "./util.ts";
|
||||
import { Location } from "./dom_types.ts";
|
||||
import { window } from "./window.ts";
|
||||
|
||||
export class LocationImpl implements Location {
|
||||
constructor(url: string) {
|
||||
|
@ -47,6 +46,6 @@ export class LocationImpl implements Location {
|
|||
}
|
||||
|
||||
export function setLocation(url: string): void {
|
||||
window.location = new LocationImpl(url);
|
||||
Object.freeze(window.location);
|
||||
globalThis.location = new LocationImpl(url);
|
||||
Object.freeze(globalThis.location);
|
||||
}
|
||||
|
|
|
@ -7,7 +7,6 @@ import { args } from "./deno.ts";
|
|||
import { setPrepareStackTrace } from "./error_stack.ts";
|
||||
import { replLoop } from "./repl.ts";
|
||||
import { setVersions } from "./version.ts";
|
||||
import { window } from "./window.ts";
|
||||
import { setLocation } from "./location.ts";
|
||||
import { setBuildInfo } from "./build.ts";
|
||||
import { setSignals } from "./process.ts";
|
||||
|
@ -36,4 +35,4 @@ function denoMain(preserveDenoNamespace = true, name?: string): void {
|
|||
replLoop();
|
||||
}
|
||||
}
|
||||
window["denoMain"] = denoMain;
|
||||
globalThis["denoMain"] = denoMain;
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
import { DomIterable } from "../dom_types.ts";
|
||||
import { window } from "../window.ts";
|
||||
import { requiredArguments } from "../util.ts";
|
||||
import { exposeForTest } from "../internals.ts";
|
||||
|
||||
|
@ -57,7 +56,9 @@ export function DomIterableMixin<K, V, TBase extends Constructor>(
|
|||
arguments.length,
|
||||
1
|
||||
);
|
||||
callbackfn = callbackfn.bind(thisArg == null ? window : Object(thisArg));
|
||||
callbackfn = callbackfn.bind(
|
||||
thisArg == null ? globalThis : Object(thisArg)
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
for (const [key, value] of (this as any)[dataSymbol]) {
|
||||
callbackfn(value, key, this);
|
||||
|
|
19
cli/js/os.ts
19
cli/js/os.ts
|
@ -5,7 +5,6 @@ import { sendSync } from "./dispatch_json.ts";
|
|||
import { ErrorKind } from "./errors.ts";
|
||||
import { assert } from "./util.ts";
|
||||
import * as util from "./util.ts";
|
||||
import { window } from "./window.ts";
|
||||
import { OperatingSystem, Arch } from "./build.ts";
|
||||
|
||||
/** Check if running in terminal.
|
||||
|
@ -109,21 +108,21 @@ export function start(preserveDenoNamespace = true, source?: string): Start {
|
|||
|
||||
// pid and noColor need to be set in the Deno module before it's set to be
|
||||
// frozen.
|
||||
util.immutableDefine(window.Deno, "pid", pid);
|
||||
util.immutableDefine(window.Deno, "noColor", noColor);
|
||||
Object.freeze(window.Deno);
|
||||
util.immutableDefine(globalThis.Deno, "pid", pid);
|
||||
util.immutableDefine(globalThis.Deno, "noColor", noColor);
|
||||
Object.freeze(globalThis.Deno);
|
||||
|
||||
if (preserveDenoNamespace) {
|
||||
util.immutableDefine(window, "Deno", window.Deno);
|
||||
util.immutableDefine(globalThis, "Deno", globalThis.Deno);
|
||||
// Deno.core could ONLY be safely frozen here (not in globals.ts)
|
||||
// since shared_queue.js will modify core properties.
|
||||
Object.freeze(window.Deno.core);
|
||||
Object.freeze(globalThis.Deno.core);
|
||||
// core.sharedQueue is an object so we should also freeze it.
|
||||
Object.freeze(window.Deno.core.sharedQueue);
|
||||
Object.freeze(globalThis.Deno.core.sharedQueue);
|
||||
} else {
|
||||
// Remove window.Deno
|
||||
delete window.Deno;
|
||||
assert(window.Deno === undefined);
|
||||
// Remove globalThis.Deno
|
||||
delete globalThis.Deno;
|
||||
assert(globalThis.Deno === undefined);
|
||||
}
|
||||
|
||||
return startResponse;
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
import { close } from "./files.ts";
|
||||
import { exit } from "./os.ts";
|
||||
import { window } from "./window.ts";
|
||||
import { core } from "./core.ts";
|
||||
import { formatError } from "./format_error.ts";
|
||||
import { stringifyArgs } from "./console.ts";
|
||||
|
@ -104,8 +103,8 @@ function evaluate(code: string): boolean {
|
|||
|
||||
// @internal
|
||||
export async function replLoop(): Promise<void> {
|
||||
const { console } = window;
|
||||
Object.defineProperties(window, replCommands);
|
||||
const { console } = globalThis;
|
||||
Object.defineProperties(globalThis, replCommands);
|
||||
|
||||
const historyFile = "deno_history.txt";
|
||||
const rid = startRepl(historyFile);
|
||||
|
@ -118,12 +117,12 @@ export async function replLoop(): Promise<void> {
|
|||
exit(exitCode);
|
||||
};
|
||||
|
||||
// Configure window._ to give the last evaluation result.
|
||||
Object.defineProperty(window, "_", {
|
||||
// Configure globalThis._ to give the last evaluation result.
|
||||
Object.defineProperty(globalThis, "_", {
|
||||
configurable: true,
|
||||
get: (): Value => lastEvalResult,
|
||||
set: (value: Value): Value => {
|
||||
Object.defineProperty(window, "_", {
|
||||
Object.defineProperty(globalThis, "_", {
|
||||
value: value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
|
@ -133,12 +132,12 @@ export async function replLoop(): Promise<void> {
|
|||
}
|
||||
});
|
||||
|
||||
// Configure window._error to give the last thrown error.
|
||||
Object.defineProperty(window, "_error", {
|
||||
// Configure globalThis._error to give the last thrown error.
|
||||
Object.defineProperty(globalThis, "_error", {
|
||||
configurable: true,
|
||||
get: (): Value => lastThrownError,
|
||||
set: (value: Value): Value => {
|
||||
Object.defineProperty(window, "_error", {
|
||||
Object.defineProperty(globalThis, "_error", {
|
||||
value: value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
import { assert } from "./util.ts";
|
||||
import { window } from "./window.ts";
|
||||
import * as dispatch from "./dispatch.ts";
|
||||
import { sendSync, sendAsync } from "./dispatch_json.ts";
|
||||
import { RBTree } from "./rbtree.ts";
|
||||
|
||||
const { console } = window;
|
||||
const { console } = globalThis;
|
||||
|
||||
interface Timer {
|
||||
id: number;
|
||||
|
@ -173,7 +172,7 @@ function fireTimers(): void {
|
|||
if (pendingFireTimers.length > 0) {
|
||||
hasPendingFireTimers = true;
|
||||
// Fire the list of pending timers as a chain of microtasks.
|
||||
window.queueMicrotask(firePendingTimers);
|
||||
globalThis.queueMicrotask(firePendingTimers);
|
||||
} else {
|
||||
setOrClearGlobalTimeout(nextDueNode && nextDueNode.due, now);
|
||||
}
|
||||
|
@ -198,14 +197,14 @@ function firePendingTimers(): void {
|
|||
// Fire a single timer and allow its children microtasks scheduled first.
|
||||
fire(pendingFireTimers.shift()!);
|
||||
// ...and we schedule next timer after this.
|
||||
window.queueMicrotask(firePendingTimers);
|
||||
globalThis.queueMicrotask(firePendingTimers);
|
||||
}
|
||||
}
|
||||
|
||||
export type Args = unknown[];
|
||||
|
||||
function checkThis(thisArg: unknown): void {
|
||||
if (thisArg !== null && thisArg !== undefined && thisArg !== window) {
|
||||
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis) {
|
||||
throw new TypeError("Illegal invocation");
|
||||
}
|
||||
}
|
||||
|
@ -222,8 +221,8 @@ function setTimer(
|
|||
args: Args,
|
||||
repeat: boolean
|
||||
): number {
|
||||
// Bind `args` to the callback and bind `this` to window(global).
|
||||
const callback: () => void = cb.bind(window, ...args);
|
||||
// Bind `args` to the callback and bind `this` to globalThis(global).
|
||||
const callback: () => void = cb.bind(globalThis, ...args);
|
||||
// In the browser, the delay value must be coercible to an integer between 0
|
||||
// and INT32_MAX. Any other value will cause the timer to fire immediately.
|
||||
// We emulate this behavior.
|
||||
|
|
|
@ -2,7 +2,6 @@
|
|||
import * as urlSearchParams from "./url_search_params.ts";
|
||||
import * as domTypes from "./dom_types.ts";
|
||||
import { getRandomValues } from "./get_random_values.ts";
|
||||
import { window } from "./window.ts";
|
||||
import { customInspect } from "./console.ts";
|
||||
|
||||
interface URLParts {
|
||||
|
@ -374,7 +373,7 @@ export class URL {
|
|||
|
||||
// TODO(kevinkassimo): implement MediaSource version in the future.
|
||||
static createObjectURL(b: domTypes.Blob): string {
|
||||
const origin = window.location.origin || "http://deno-opaque-origin";
|
||||
const origin = globalThis.location.origin || "http://deno-opaque-origin";
|
||||
const key = `blob:${origin}/${generateUUID()}`;
|
||||
blobURLMap.set(key, b);
|
||||
return key;
|
||||
|
@ -391,7 +390,7 @@ export class URL {
|
|||
return;
|
||||
}
|
||||
// Origin match check seems irrelevant for now, unless we implement
|
||||
// persisten storage for per window.location.origin at some point.
|
||||
// persisten storage for per globalThis.location.origin at some point.
|
||||
blobURLMap.delete(url);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
import { atob } from "./text_encoding.ts";
|
||||
import { TypedArray } from "./types.ts";
|
||||
import { window } from "./window.ts";
|
||||
|
||||
let logDebug = false;
|
||||
let logSource = "JS";
|
||||
|
@ -19,9 +19,9 @@ export function setLogDebug(debug: boolean, source?: string): void {
|
|||
*/
|
||||
export function log(...args: unknown[]): void {
|
||||
if (logDebug) {
|
||||
// if we destructure `console` off `window` too early, we don't bind to
|
||||
// if we destructure `console` off `globalThis` too early, we don't bind to
|
||||
// the right console, therefore we don't log anything out.
|
||||
window.console.log(`DEBUG ${logSource} -`, ...args);
|
||||
globalThis.console.log(`DEBUG ${logSource} -`, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -345,7 +345,7 @@ export function humanFileSize(bytes: number): string {
|
|||
|
||||
// @internal
|
||||
export function base64ToUint8Array(data: string): Uint8Array {
|
||||
const binString = window.atob(data);
|
||||
const binString = atob(data);
|
||||
const size = binString.length;
|
||||
const bytes = new Uint8Array(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
// (0, eval) is indirect eval.
|
||||
// See the links below for details:
|
||||
// - https://stackoverflow.com/a/14120023
|
||||
// - https://tc39.github.io/ecma262/#sec-performeval (spec)
|
||||
export const window = (0, eval)("this");
|
||||
// TODO: The above should be replaced with globalThis
|
||||
// when the globalThis proposal goes to stage 4
|
||||
// See https://github.com/tc39/proposal-global
|
|
@ -4,9 +4,9 @@ import * as dispatch from "./dispatch.ts";
|
|||
import { sendAsync, sendSync } from "./dispatch_json.ts";
|
||||
import { log, createResolvable, Resolvable } from "./util.ts";
|
||||
import { TextDecoder, TextEncoder } from "./text_encoding.ts";
|
||||
import { window } from "./window.ts";
|
||||
import { blobURLMap } from "./url.ts";
|
||||
import { blobBytesWeakMap } from "./blob.ts";
|
||||
import { Event } from "./event.ts";
|
||||
import { EventTarget } from "./event_target.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
@ -106,16 +106,19 @@ export async function workerMain(): Promise<void> {
|
|||
const event = { data };
|
||||
|
||||
try {
|
||||
result = window.onmessage(event);
|
||||
if (!globalThis["onmessage"]) {
|
||||
break;
|
||||
}
|
||||
result = globalThis.onmessage!(event);
|
||||
if (result && "then" in result) {
|
||||
await result;
|
||||
}
|
||||
if (!window["onmessage"]) {
|
||||
if (!globalThis["onmessage"]) {
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
if (window["onerror"]) {
|
||||
const result = window.onerror(
|
||||
if (globalThis["onerror"]) {
|
||||
const result = globalThis.onerror(
|
||||
e.message,
|
||||
e.fileName,
|
||||
e.lineNumber,
|
||||
|
@ -145,7 +148,7 @@ export interface Worker {
|
|||
export interface WorkerOptions {}
|
||||
|
||||
/** Extended Deno Worker initialization options.
|
||||
* `noDenoNamespace` hides global `window.Deno` namespace for
|
||||
* `noDenoNamespace` hides global `globalThis.Deno` namespace for
|
||||
* spawned worker and nested workers spawned by it (default: false).
|
||||
*/
|
||||
export interface DenoWorkerOptions extends WorkerOptions {
|
||||
|
@ -202,7 +205,9 @@ export class WorkerImpl extends EventTarget implements Worker {
|
|||
}
|
||||
|
||||
private handleError(e: any): boolean {
|
||||
const event = new window.Event("error", { cancelable: true });
|
||||
// TODO: this is being handled in a type unsafe way, it should be type safe
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const event = new Event("error", { cancelable: true }) as any;
|
||||
event.message = e.message;
|
||||
event.lineNumber = e.lineNumber ? e.lineNumber + 1 : null;
|
||||
event.columnNumber = e.columnNumber ? e.columnNumber + 1 : null;
|
||||
|
|
|
@ -412,7 +412,7 @@ mod tests {
|
|||
assert_eq!(actual.message, "TypeError: baz");
|
||||
// Because this is accessing the live bundle, this test might be more fragile
|
||||
assert_eq!(actual.frames.len(), 1);
|
||||
assert!(actual.frames[0].script_name.ends_with("/window.ts"));
|
||||
assert!(actual.frames[0].script_name.ends_with("/dom_types.ts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -144,7 +144,7 @@ class Host {
|
|||
* @param {ts.CompilerOptions} _options
|
||||
*/
|
||||
getDefaultLibFileName(_options) {
|
||||
return "lib.deno_core.d.ts";
|
||||
return "lib.esnext.d.ts";
|
||||
}
|
||||
|
||||
getDefaultLibLocation() {
|
||||
|
|
66
deno_typescript/lib.deno_core.d.ts
vendored
66
deno_typescript/lib.deno_core.d.ts
vendored
|
@ -1,66 +0,0 @@
|
|||
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
||||
|
||||
// This file contains APIs that are introduced into the global namespace by
|
||||
// Deno core. These are not intended to be used directly by runtime users of
|
||||
// Deno and therefore do not flow through to the runtime type library.
|
||||
|
||||
declare interface MessageCallback {
|
||||
(msg: Uint8Array): void;
|
||||
}
|
||||
|
||||
interface EvalErrorInfo {
|
||||
// Is the object thrown a native Error?
|
||||
isNativeError: boolean;
|
||||
// Was the error happened during compilation?
|
||||
isCompileError: boolean;
|
||||
// The actual thrown entity
|
||||
// (might be an Error or anything else thrown by the user)
|
||||
// If isNativeError is true, this is an Error
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
thrown: any;
|
||||
}
|
||||
|
||||
declare interface DenoCore {
|
||||
print(s: string, isErr?: boolean): void;
|
||||
dispatch(
|
||||
opId: number,
|
||||
control: Uint8Array,
|
||||
zeroCopy?: ArrayBufferView | null
|
||||
): Uint8Array | null;
|
||||
setAsyncHandler(opId: number, cb: MessageCallback): void;
|
||||
sharedQueue: {
|
||||
head(): number;
|
||||
numRecords(): number;
|
||||
size(): number;
|
||||
push(buf: Uint8Array): boolean;
|
||||
reset(): void;
|
||||
shift(): Uint8Array | null;
|
||||
};
|
||||
|
||||
ops(): Record<string, number>;
|
||||
|
||||
recv(cb: (opId: number, msg: Uint8Array) => void): void;
|
||||
|
||||
send(
|
||||
opId: number,
|
||||
control: null | ArrayBufferView,
|
||||
data?: ArrayBufferView
|
||||
): null | Uint8Array;
|
||||
|
||||
shared: SharedArrayBuffer;
|
||||
|
||||
/** Evaluate provided code in the current context.
|
||||
* It differs from eval(...) in that it does not create a new context.
|
||||
* Returns an array: [output, errInfo].
|
||||
* If an error occurs, `output` becomes null and `errInfo` is non-null.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
evalContext(code: string): [any, EvalErrorInfo | null];
|
||||
|
||||
errorToJSON: (e: Error) => string;
|
||||
}
|
||||
|
||||
declare interface DenoInterface {
|
||||
core: DenoCore;
|
||||
}
|
||||
declare let Deno: DenoInterface;
|
|
@ -146,7 +146,7 @@ pub fn compile_bundle(
|
|||
},
|
||||
});
|
||||
|
||||
let mut root_names_str: Vec<String> = root_names
|
||||
let root_names_str: Vec<String> = root_names
|
||||
.iter()
|
||||
.map(|p| {
|
||||
if !p.exists() {
|
||||
|
@ -158,7 +158,6 @@ pub fn compile_bundle(
|
|||
module_specifier.as_str().to_string()
|
||||
})
|
||||
.collect();
|
||||
root_names_str.push("$asset$/lib.deno_core.d.ts".to_string());
|
||||
|
||||
// TODO lift js_check to caller?
|
||||
let state = js_check(ts_isolate.compile(&config_json, root_names_str));
|
||||
|
@ -267,9 +266,6 @@ pub fn get_asset(name: &str) -> Option<String> {
|
|||
"bundle_loader.js" => {
|
||||
Some(read_file("../deno_typescript/bundle_loader.js"))
|
||||
}
|
||||
"lib.deno_core.d.ts" => {
|
||||
Some(read_file("../deno_typescript/lib.deno_core.d.ts"))
|
||||
}
|
||||
"lib.deno_runtime.d.ts" => Some(read_file("js/lib.deno_runtime.d.ts")),
|
||||
"bootstrap.ts" => Some("console.log(\"hello deno\");".to_string()),
|
||||
"typescript.d.ts" => inc!("typescript.d.ts"),
|
||||
|
|
Loading…
Add table
Reference in a new issue