base.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """Base file for constants that don't fit any other categories."""
  2. from __future__ import annotations
  3. import platform
  4. from enum import Enum
  5. from importlib import metadata
  6. from pathlib import Path
  7. from types import SimpleNamespace
  8. from typing import Literal
  9. from platformdirs import PlatformDirs
  10. from .utils import classproperty
  11. IS_WINDOWS = platform.system() == "Windows"
  12. IS_MACOS = platform.system() == "Darwin"
  13. IS_LINUX = platform.system() == "Linux"
  14. class Dirs(SimpleNamespace):
  15. """Various directories/paths used by Reflex."""
  16. # The frontend directories in a project.
  17. # The web folder where the NextJS app is compiled to.
  18. WEB = ".web"
  19. # The directory where uploaded files are stored.
  20. UPLOADED_FILES = "uploaded_files"
  21. # The name of the assets directory.
  22. APP_ASSETS = "assets"
  23. # The name of the assets directory for external resources (a subfolder of APP_ASSETS).
  24. EXTERNAL_APP_ASSETS = "external"
  25. # The name of the utils file.
  26. UTILS = "utils"
  27. # The name of the state file.
  28. STATE_PATH = "/".join([UTILS, "state"])
  29. # The name of the components file.
  30. COMPONENTS_PATH = "/".join([UTILS, "components"])
  31. # The name of the contexts file.
  32. CONTEXTS_PATH = "/".join([UTILS, "context"])
  33. # The name of the output static directory.
  34. STATIC = "build/client"
  35. # The name of the public html directory served at "/"
  36. PUBLIC = "public"
  37. # The directory where styles are located.
  38. STYLES = "styles"
  39. # The name of the pages directory.
  40. PAGES = "app"
  41. # The name of the routes directory.
  42. ROUTES = "routes"
  43. # The name of the env json file.
  44. ENV_JSON = "env.json"
  45. # The name of the reflex json file.
  46. REFLEX_JSON = "reflex.json"
  47. # The name of the postcss config file.
  48. POSTCSS_JS = "postcss.config.js"
  49. # The name of the states directory.
  50. STATES = ".states"
  51. # Where compilation artifacts for the backend are stored.
  52. BACKEND = "backend"
  53. # JSON-encoded list of page routes that need to be evaluated on the backend.
  54. STATEFUL_PAGES = "stateful_pages.json"
  55. # Marker file indicating that upload component was used in the frontend.
  56. UPLOAD_IS_USED = "upload_is_used"
  57. def _reflex_version() -> str:
  58. """Get the Reflex version.
  59. Returns:
  60. The Reflex version.
  61. """
  62. try:
  63. return metadata.version("reflex")
  64. except metadata.PackageNotFoundError:
  65. return "unknown"
  66. class Reflex(SimpleNamespace):
  67. """Base constants concerning Reflex."""
  68. # App names and versions.
  69. # The name of the Reflex package.
  70. MODULE_NAME = "reflex"
  71. # The current version of Reflex.
  72. VERSION = _reflex_version()
  73. # The reflex json file.
  74. JSON = "reflex.json"
  75. # Files and directories used to init a new project.
  76. # The directory to store reflex dependencies.
  77. # on windows, we use C:/Users/<username>/AppData/Local/reflex.
  78. # on macOS, we use ~/Library/Application Support/reflex.
  79. # on linux, we use ~/.local/share/reflex.
  80. # If user sets REFLEX_DIR envroment variable use that instead.
  81. DIR = PlatformDirs(MODULE_NAME, False).user_data_path
  82. LOGS_DIR = DIR / "logs"
  83. # The root directory of the reflex library.
  84. ROOT_DIR = Path(__file__).parents[2]
  85. RELEASES_URL = "https://api.github.com/repos/reflex-dev/templates/releases"
  86. # The reflex stylesheet language supported
  87. STYLESHEETS_SUPPORTED = ["css", "sass", "scss"]
  88. class ReflexHostingCLI(SimpleNamespace):
  89. """Base constants concerning Reflex Hosting CLI."""
  90. # The name of the Reflex Hosting CLI package.
  91. MODULE_NAME = "reflex-hosting-cli"
  92. class Templates(SimpleNamespace):
  93. """Constants related to Templates."""
  94. # The route on Reflex backend to query which templates are available and their URLs.
  95. APP_TEMPLATES_ROUTE = "/app-templates"
  96. # The default template
  97. DEFAULT = "blank"
  98. # The AI template
  99. AI = "ai"
  100. # The option for the user to choose a remote template.
  101. CHOOSE_TEMPLATES = "choose-templates"
  102. # The URL to find reflex templates.
  103. REFLEX_TEMPLATES_URL = "https://reflex.dev/templates"
  104. # Demo url for the default template.
  105. DEFAULT_TEMPLATE_URL = "https://blank-template.reflex.run"
  106. # The reflex.build frontend host
  107. REFLEX_BUILD_FRONTEND = "https://reflex.build"
  108. # The reflex.build backend host
  109. REFLEX_BUILD_BACKEND = "https://flexgen-prod-flexgen.fly.dev"
  110. @classproperty
  111. @classmethod
  112. def REFLEX_BUILD_URL(cls):
  113. """The URL to redirect to reflex.build.
  114. Returns:
  115. The URL to redirect to reflex.build.
  116. """
  117. from reflex.config import environment
  118. return (
  119. environment.REFLEX_BUILD_FRONTEND.get()
  120. + "/gen?reflex_init_token={reflex_init_token}"
  121. )
  122. @classproperty
  123. @classmethod
  124. def REFLEX_BUILD_POLL_URL(cls):
  125. """The URL to poll waiting for the user to select a generation.
  126. Returns:
  127. The URL to poll waiting for the user to select a generation.
  128. """
  129. from reflex.config import environment
  130. return environment.REFLEX_BUILD_BACKEND.get() + "/api/init/{reflex_init_token}"
  131. @classproperty
  132. @classmethod
  133. def REFLEX_BUILD_CODE_URL(cls):
  134. """The URL to fetch the generation's reflex code.
  135. Returns:
  136. The URL to fetch the generation's reflex code.
  137. """
  138. from reflex.config import environment
  139. return (
  140. environment.REFLEX_BUILD_BACKEND.get()
  141. + "/api/gen/{generation_hash}/refactored"
  142. )
  143. class Dirs(SimpleNamespace):
  144. """Folders used by the template system of Reflex."""
  145. # The template directory used during reflex init.
  146. BASE = Reflex.ROOT_DIR / Reflex.MODULE_NAME / ".templates"
  147. # The web subdirectory of the template directory.
  148. WEB_TEMPLATE = BASE / "web"
  149. # The jinja template directory.
  150. JINJA_TEMPLATE = BASE / "jinja"
  151. # Where the code for the templates is stored.
  152. CODE = "code"
  153. class Next(SimpleNamespace):
  154. """Constants related to NextJS."""
  155. # The NextJS config file
  156. CONFIG_FILE = "next.config.js"
  157. # The sitemap config file.
  158. SITEMAP_CONFIG_FILE = "next-sitemap.config.js"
  159. # The node modules directory.
  160. NODE_MODULES = "node_modules"
  161. # The package lock file.
  162. PACKAGE_LOCK = "package-lock.json"
  163. # Regex to check for message displayed when frontend comes up
  164. FRONTEND_LISTENING_REGEX = "Local:[\\s]+(.*)"
  165. # Color mode variables
  166. class ColorMode(SimpleNamespace):
  167. """Constants related to ColorMode."""
  168. NAME = "rawColorMode"
  169. RESOLVED_NAME = "resolvedColorMode"
  170. USE = "useColorMode"
  171. TOGGLE = "toggleColorMode"
  172. SET = "setColorMode"
  173. LITERAL_ENV = Literal["dev", "prod"]
  174. # Env modes
  175. class Env(str, Enum):
  176. """The environment modes."""
  177. DEV = "dev"
  178. PROD = "prod"
  179. # Log levels
  180. class LogLevel(str, Enum):
  181. """The log levels."""
  182. DEBUG = "debug"
  183. DEFAULT = "default"
  184. INFO = "info"
  185. WARNING = "warning"
  186. ERROR = "error"
  187. CRITICAL = "critical"
  188. @classmethod
  189. def from_string(cls, level: str | None) -> LogLevel | None:
  190. """Convert a string to a log level.
  191. Args:
  192. level: The log level as a string.
  193. Returns:
  194. The log level.
  195. """
  196. if not level:
  197. return None
  198. try:
  199. return LogLevel[level.upper()]
  200. except KeyError:
  201. return None
  202. def __le__(self, other: LogLevel) -> bool:
  203. """Compare log levels.
  204. Args:
  205. other: The other log level.
  206. Returns:
  207. True if the log level is less than or equal to the other log level.
  208. """
  209. levels = list(LogLevel)
  210. return levels.index(self) <= levels.index(other)
  211. def subprocess_level(self):
  212. """Return the log level for the subprocess.
  213. Returns:
  214. The log level for the subprocess
  215. """
  216. return self if self != LogLevel.DEFAULT else LogLevel.WARNING
  217. # Server socket configuration variables
  218. POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000
  219. class Ping(SimpleNamespace):
  220. """PING constants."""
  221. # The 'ping' interval
  222. INTERVAL = 25
  223. # The 'ping' timeout
  224. TIMEOUT = 120
  225. # Keys in the client_side_storage dict
  226. COOKIES = "cookies"
  227. LOCAL_STORAGE = "local_storage"
  228. SESSION_STORAGE = "session_storage"
  229. # Testing variables.
  230. # Testing os env set by pytest when running a test case.
  231. PYTEST_CURRENT_TEST = "PYTEST_CURRENT_TEST"
  232. APP_HARNESS_FLAG = "APP_HARNESS_FLAG"
  233. REFLEX_VAR_OPENING_TAG = "<reflex.Var>"
  234. REFLEX_VAR_CLOSING_TAG = "</reflex.Var>"