env-util.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // we create this local-only type, which has assertions made to indicate
  2. // that we do not know and cannot guarantee which JS environment we are in
  3. const g = globalThis as Partial<{
  4. self: typeof globalThis.self;
  5. window: typeof globalThis.window;
  6. }>;
  7. /**
  8. * Detects if this code is running within any Service or WebWorker context.
  9. * @returns true if in a worker of some kind, false if otherwise
  10. */
  11. export function envIsServiceOrWebWorker() {
  12. return (
  13. typeof WorkerGlobalScope !== "undefined" &&
  14. g.self instanceof WorkerGlobalScope
  15. );
  16. }
  17. /**
  18. * Detects if the code is running in a regular DOM or Web Worker context.
  19. * @returns true if running in a DOM or Web Worker context, false if running in Node.js
  20. */
  21. export function envIsBrowser() {
  22. return g.window !== undefined;
  23. }
  24. /**
  25. * a convenience method that returns whether or not
  26. * this code is executing in some type of browser-centric environment
  27. *
  28. * @returns true if in the browser's main UI thread or in a worker, false if otherwise
  29. */
  30. export function envIsBrowserOrWorker() {
  31. return envIsServiceOrWebWorker() || envIsBrowser();
  32. }