summaryrefslogtreecommitdiff
path: root/SPECS/platform/global-object.js
blob: 96239d911b2157bda0423620cb7258aea8ab71ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/**
 * Cross-Platform Global Object Access
 *
 * Provides unified access to global objects across different JavaScript environments:
 * - Browser (window)
 * - Node.js (global)
 * - Web Workers (self)
 * - Modern environments (globalThis)
 * - Fallback for edge cases
 */

/**
 * Safely test if an object could be a global object
 * @param {any} obj - Object to test
 * @returns {any} The object if it has Math, undefined otherwise
 */
function testGlobalCandidate(obj) {
  return obj && obj.Math === Math ? obj : undefined;
}

/**
 * Cached reference to the global object
 * Uses a cascade of checks to find the appropriate global object:
 * 1. globalThis (ES2020 standard)
 * 2. window (browser)
 * 3. self (web workers, service workers)
 * 4. global (Node.js)
 * 5. Function constructor fallback
 * 6. Empty object fallback
 */
const GLOBAL_OBJ =
  (typeof globalThis === "object" && testGlobalCandidate(globalThis)) ||
  (typeof window === "object" && testGlobalCandidate(window)) ||
  (typeof self === "object" && testGlobalCandidate(self)) ||
  (typeof global === "object" && testGlobalCandidate(global)) ||
  (() => {
    try {
      // Use Function constructor to access global in strict mode
      return Function("return this")();
    } catch (error) {
      // In case Function constructor is disabled (CSP, etc.)
      return {};
    }
  })();

/**
 * Get the global object for the current environment
 * @returns {Object} Global object (window, global, self, etc.)
 */
function getGlobalObject() {
  return GLOBAL_OBJ;
}

/**
 * Get or create a singleton on the global object
 * Useful for ensuring single instances across different modules
 * @param {string} key - Key to store singleton under
 * @param {Function} factory - Factory function to create the singleton
 * @param {Object} target - Target object (defaults to global)
 * @returns {any} The singleton instance
 */
function getGlobalSingleton(key, factory, target) {
  const globalTarget = target || GLOBAL_OBJ;
  const sentryGlobals = (globalTarget.__SENTRY__ =
    globalTarget.__SENTRY__ || {});

  return sentryGlobals[key] || (sentryGlobals[key] = factory());
}

/**
 * Detect the current JavaScript environment
 * @returns {Object} Environment information
 */
function detectEnvironment() {
  const global = getGlobalObject();

  return {
    // Environment types
    isBrowser:
      typeof window !== "undefined" && typeof window.document !== "undefined",
    isNode:
      typeof global !== "undefined" &&
      global.process &&
      global.process.versions &&
      global.process.versions.node,
    isWebWorker: typeof self !== "undefined" && typeof window === "undefined",
    isServiceWorker:
      typeof self !== "undefined" && typeof self.serviceWorker !== "undefined",
    isDeno: typeof Deno !== "undefined",
    isBun: typeof Bun !== "undefined",

    // Browser specifics
    isElectron:
      typeof global !== "undefined" &&
      global.process &&
      global.process.type === "renderer",
    isWebView:
      typeof window !== "undefined" &&
      (window.ReactNativeWebView ||
        window.webkit?.messageHandlers ||
        window.Android),

    // Runtime capabilities
    hasGlobalThis: typeof globalThis !== "undefined",
    hasWindow: typeof window !== "undefined",
    hasGlobal: typeof global !== "undefined",
    hasSelf: typeof self !== "undefined",
    hasDocument: typeof document !== "undefined",
    hasProcess: typeof process !== "undefined",

    // Console availability
    hasConsole: typeof console !== "undefined",

    // Global object used
    globalObjectName:
      typeof globalThis !== "undefined"
        ? "globalThis"
        : typeof window !== "undefined"
          ? "window"
          : typeof global !== "undefined"
            ? "global"
            : typeof self !== "undefined"
              ? "self"
              : "unknown",
  };
}

/**
 * Get environment-specific information
 * @returns {Object} Detailed environment information
 */
function getEnvironmentInfo() {
  const env = detectEnvironment();
  const global = getGlobalObject();
  const info = { ...env };

  // Add version information where available
  if (env.isNode) {
    info.nodeVersion = global.process?.versions?.node;
    info.v8Version = global.process?.versions?.v8;
  }

  if (env.isBrowser) {
    info.userAgent =
      typeof navigator !== "undefined" ? navigator.userAgent : undefined;
    info.language =
      typeof navigator !== "undefined" ? navigator.language : undefined;
  }

  if (env.isDeno) {
    info.denoVersion = Deno?.version?.deno;
  }

  if (env.isBun) {
    info.bunVersion = Bun?.version;
  }

  return info;
}

/**
 * Safely access nested properties on global object
 * @param {string} path - Dot-separated path to property
 * @returns {any} Property value or undefined
 */
function getGlobalProperty(path) {
  const parts = path.split(".");
  let current = getGlobalObject();

  for (const part of parts) {
    if (current == null || typeof current !== "object") {
      return undefined;
    }
    current = current[part];
  }

  return current;
}

/**
 * Safely set nested properties on global object
 * @param {string} path - Dot-separated path to property
 * @param {any} value - Value to set
 * @returns {boolean} True if successful
 */
function setGlobalProperty(path, value) {
  try {
    const parts = path.split(".");
    const propertyName = parts.pop();
    let current = getGlobalObject();

    for (const part of parts) {
      if (current[part] == null) {
        current[part] = {};
      }
      current = current[part];
    }

    current[propertyName] = value;
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Check if running in a sandboxed environment
 * @returns {boolean} True if environment appears sandboxed
 */
function isSandboxed() {
  const global = getGlobalObject();

  // Check for common sandbox restrictions
  const restrictions = [
    // No eval
    () => {
      try {
        eval("1");
        return false;
      } catch (e) {
        return true;
      }
    },

    // No Function constructor
    () => {
      try {
        new Function("return 1")();
        return false;
      } catch (e) {
        return true;
      }
    },

    // Limited global properties
    () => {
      const expectedProps = ["Object", "Array", "String", "Number", "Boolean"];
      return !expectedProps.every((prop) => typeof global[prop] === "function");
    },
  ];

  return restrictions.some((check) => {
    try {
      return check();
    } catch (e) {
      return true;
    }
  });
}

/**
 * Get safe globals that should be available in most environments
 * @returns {Object} Safe global references
 */
function getSafeGlobals() {
  const global = getGlobalObject();

  return {
    Object: global.Object,
    Array: global.Array,
    String: global.String,
    Number: global.Number,
    Boolean: global.Boolean,
    Date: global.Date,
    RegExp: global.RegExp,
    JSON: global.JSON,
    Math: global.Math,
    parseInt: global.parseInt,
    parseFloat: global.parseFloat,
    isNaN: global.isNaN,
    isFinite: global.isFinite,
    console: global.console,
    setTimeout: global.setTimeout,
    clearTimeout: global.clearTimeout,
    setInterval: global.setInterval,
    clearInterval: global.clearInterval,
  };
}

module.exports = {
  GLOBAL_OBJ,
  getGlobalObject,
  getGlobalSingleton,
  detectEnvironment,
  getEnvironmentInfo,
  getGlobalProperty,
  setGlobalProperty,
  isSandboxed,
  getSafeGlobals,
};