Skip to content

Commit

Permalink
fix(root): find global context (window/self/global) in a more safe way
Browse files Browse the repository at this point in the history
Closes #1930
  • Loading branch information
jayphelps committed Sep 15, 2016
1 parent 6bd3423 commit a098132
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
9 changes: 9 additions & 0 deletions spec/util/root-spec.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
25 changes: 12 additions & 13 deletions src/util/root.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)');
}

0 comments on commit a098132

Please sign in to comment.