From 7d3dd707ae8d916b6bea98d37a9cb0467b665124 Mon Sep 17 00:00:00 2001 From: Jay Phelps Date: Fri, 9 Sep 2016 13:15:19 -0700 Subject: [PATCH] fix(root): find global context (window/self/global) in a more safe way Closes #1930 --- spec/util/root-spec.ts | 9 +++++++++ src/util/root.ts | 25 ++++++++++++------------- 2 files changed, 21 insertions(+), 13 deletions(-) create mode 100644 spec/util/root-spec.ts diff --git a/spec/util/root-spec.ts b/spec/util/root-spec.ts new file mode 100644 index 0000000000..70f83c6905 --- /dev/null +++ b/spec/util/root-spec.ts @@ -0,0 +1,9 @@ +import { expect } from 'chai'; +import { root } from '../../dist/cjs/util/root'; + +/** @test {root} */ +describe('root', () => { + it('should exist', () => { + expect(typeof root).to.equal('object'); + }); +}); diff --git a/src/util/root.ts b/src/util/root.ts index a08c0507ad..0c0a3c3951 100644 --- a/src/util/root.ts +++ b/src/util/root.ts @@ -1,12 +1,3 @@ -let objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false -}; - declare let global: NodeJS.Global; declare let module: any; declare let exports: any; @@ -18,9 +9,17 @@ declare module NodeJS { } } -export let root: any = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); +/** + * window: browser in DOM main thread + * self: browser in WebWorker + * global: Node.js/other + */ +export const root: any = ( + typeof window == 'object' && window.window === window && window + || typeof self == 'object' && self.self === self && self + || typeof global == 'object' && global.global === global && global +); -let freeGlobal = objectTypes[typeof global] && global; -if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; +if (!root) { + throw new Error('RxJS could not find any global context (window, self, global)'); }