Skip to content

Commit

Permalink
Fixed compatibility with esoteric Mini Program environment (#3133)
Browse files Browse the repository at this point in the history
* fix: global is undefined

* fix: remove unneeded optional chaining

* fix: type error

* Tweak the fix and add changeset

* Fixed CodeSandbox build

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
  • Loading branch information
fw6 and Andarist committed Mar 10, 2022
1 parent 502ffe9 commit 4feef9d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/giant-suns-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'xstate': patch
---

Fixed compatibility with esoteric [Mini Program](https://developers.weixin.qq.com/miniprogram/en/dev/framework/app-service/) environment where `global` object was available but `global.console` wasn't.
10 changes: 7 additions & 3 deletions packages/core/src/devTools.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { IS_PRODUCTION } from './environment';
import { AnyInterpreter } from './types';

type ServiceListener = (service: AnyInterpreter) => void;
Expand All @@ -14,7 +15,7 @@ export interface XStateDevInterface {
}

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
export function getGlobal() {
export function getGlobal(): typeof globalThis | undefined {
if (typeof globalThis !== 'undefined') {
return globalThis;
}
Expand All @@ -27,8 +28,11 @@ export function getGlobal() {
if (typeof global !== 'undefined') {
return global;
}

return undefined;
if (!IS_PRODUCTION) {
console.warn(
'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'
);
}
}

function getDevTools(): XStateDevInterface | undefined {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class Interpreter<
* - `clock` uses the global `setTimeout` and `clearTimeout` functions
* - `logger` uses the global `console.log()` method
*/
public static defaultOptions = ((global) => ({
public static defaultOptions = {
execute: true,
deferEvents: true,
clock: {
Expand All @@ -142,9 +142,9 @@ export class Interpreter<
return clearTimeout(id);
}
} as Clock,
logger: global.console.log.bind(console),
logger: console.log.bind(console),
devTools: false
}))(typeof self !== 'undefined' ? self : global);
};
/**
* The current state of the interpreted machine.
*/
Expand Down

0 comments on commit 4feef9d

Please sign in to comment.