testFlags.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { Mutex } from 'async-mutex'
  3. class TestFlags {
  4. // @ts-expect-error this is not called in production
  5. private mutex: Mutex
  6. // @ts-expect-error this is not called in production
  7. private flags: Map<string, boolean>
  8. constructor() {
  9. if (VITE_TEST_MODE) {
  10. this.mutex = new Mutex()
  11. this.flags = new Map()
  12. }
  13. }
  14. get(flag: string, skipClearing = false): boolean {
  15. if (!VITE_TEST_MODE) return false
  16. const flagValue = !!this.flags.get(flag)
  17. if (!skipClearing) this.clear(flag)
  18. return flagValue
  19. }
  20. async set(flag: string): Promise<void> {
  21. if (!VITE_TEST_MODE) return
  22. await this.mutex.runExclusive(() => {
  23. this.flags.set(flag, true)
  24. if (import.meta.env.VITE_DEBUG_TEST_FLAGS) {
  25. console.log('[testFlags] set flag "%s"', flag)
  26. }
  27. })
  28. }
  29. async clear(flag: string): Promise<void> {
  30. if (!VITE_TEST_MODE) return
  31. await this.mutex.runExclusive(() => {
  32. this.flags.delete(flag)
  33. })
  34. }
  35. }
  36. const testFlags = new TestFlags()
  37. declare global {
  38. interface Window {
  39. testFlags: TestFlags
  40. }
  41. }
  42. if (VITE_TEST_MODE) {
  43. // Register globally for access from Capybara/Selenium.
  44. window.testFlags = testFlags
  45. }
  46. export default testFlags