fix(core): try to use symbol for platform

This commit is contained in:
alina 🌸 2024-03-05 01:31:02 +03:00
parent d87a11b52e
commit b9f8fd58db
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI

View file

@ -16,24 +16,16 @@ export interface ICorePlatform extends ITlPlatform {
} | null> } | null>
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line
let globalObject: any const globalObject = (0, eval)('this')
if (typeof globalThis !== 'undefined') {
globalObject = globalThis
} else if (typeof global !== 'undefined') {
globalObject = global
} else if (typeof self !== 'undefined') {
globalObject = self
} else if (typeof window !== 'undefined') {
globalObject = window
}
// NB: when using with some bundlers (e.g. vite) re-importing this module will not return the same object // NB: when using with some bundlers (e.g. vite) re-importing this module will not return the same object
// so we need to store the platform in a global object to be able to survive hot-reloads etc. // so we need to store the platform in a global object to be able to survive hot-reloads etc.
// try to use Symbol if available, otherwise fallback to a string
const platformKey = typeof Symbol !== 'undefined' ? Symbol.for('mtcute.platform') : '__MTCUTE_PLATFORM__'
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
let _platform: ICorePlatform | null = globalObject?.__MTCUTE_PLATFORM__ ?? null let _platform: ICorePlatform | null = globalObject?.[platformKey] ?? null
export function setPlatform(platform: ICorePlatform): void { export function setPlatform(platform: ICorePlatform): void {
if (_platform) { if (_platform) {
@ -49,7 +41,7 @@ export function setPlatform(platform: ICorePlatform): void {
TlBinaryWriter.platform = platform TlBinaryWriter.platform = platform
if (globalObject) { if (globalObject) {
globalObject.__MTCUTE_PLATFORM__ = platform globalObject[platformKey] = platform
} }
} }