diff --git a/lib/index.js b/lib/index.js index 549a363a..d8d6eb04 100644 --- a/lib/index.js +++ b/lib/index.js @@ -18,43 +18,68 @@ 'use strict'; -function node_require(module) { +// Prevent React Native packager from seeing modules required with this +function nodeRequire(module) { return require(module); } -// If process is defined, we're running in node. -function isNode() { - return typeof process == 'object' && (('' + process) == '[object process]' || typeof jest == 'object') + +function getContext() { + if (typeof process === 'object' && process + '' === '[object process]') { + return process.type === 'renderer' ? 'electron' : 'nodejs'; + } + + if (typeof navigator !== 'undefined') { + if (navigator.product === 'ReactNative') { + return 'reactnative'; + } + + if (/Chrome/.test(navigator.userAgent)) { + return 'chromedebugger'; + } + } + + if (typeof global !== 'undefined') { + if (global.__debug__) { + return 'vscodedebugger'; + } + } + + if (typeof Realm !== 'undefined') { + return 'jscore'; + } + + throw Error("Unknown execution context"); } -// function isElectronRenderer() { -// return isNode() && process.type === 'renderer' -// } - var realmConstructor; -if (isNode()) { - node_require('./submit-analytics')('Run'); - // Prevent React Native packager from seeing this module. - var binary = node_require('node-pre-gyp'); - var path = node_require('path'); - var pkg = path.resolve(path.join(__dirname,'../package.json')); - var binding_path = binary.find(pkg); - realmConstructor = require(binding_path).Realm; -} else { - if (typeof Realm != 'undefined') { - // The global Realm constructor should be available on device (using JavaScriptCore). +switch(getContext()) { + case 'nodejs': + case 'electron': + nodeRequire('./submit-analytics')('Run'); + + var binary = nodeRequire('node-pre-gyp'); + var path = nodeRequire('path'); + var pkg = path.resolve(path.join(__dirname,'../package.json')); + var binding_path = binary.find(pkg); + + realmConstructor = require(binding_path).Realm; + break; + + case 'reactnative': + case 'jscore': realmConstructor = Realm; // eslint-disable-line no-undef - // eslint-disable-next-line - } else if (typeof window != 'undefined') { - // The userAgent will be defined when running in a browser (such as Chrome debugging mode). + break; + + case 'chromedebugger': + case 'vscodedebugger': realmConstructor = require('./browser').default; // (exported as ES6 module) - // eslint-disable-next-line - } + break; } if (!realmConstructor) { - throw new Error('Missing Realm constructor - please ensure RealmReact framework is included!'); + throw new Error('Missing Realm constructor. Did you run "react-native link realm"? Please see https://realm.io/docs/react-native/latest/#missing-realm-constructor for troubleshooting'); } require('./extensions')(realmConstructor);