1
0

prerequisites.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. """Everything related to fetching or initializing build prerequisites."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import functools
  6. import importlib
  7. import importlib.metadata
  8. import importlib.util
  9. import io
  10. import json
  11. import os
  12. import platform
  13. import random
  14. import re
  15. import shutil
  16. import sys
  17. import tempfile
  18. import time
  19. import typing
  20. import zipfile
  21. from collections.abc import Callable, Sequence
  22. from datetime import datetime
  23. from pathlib import Path
  24. from types import ModuleType
  25. from typing import NamedTuple
  26. from urllib.parse import urlparse
  27. import click
  28. import httpx
  29. from alembic.util.exc import CommandError
  30. from packaging import version
  31. from redis import Redis as RedisSync
  32. from redis.asyncio import Redis
  33. from redis.exceptions import RedisError
  34. from reflex import constants, model
  35. from reflex.compiler import templates
  36. from reflex.config import Config, environment, get_config
  37. from reflex.utils import console, net, path_ops, processes, redir
  38. from reflex.utils.decorator import once
  39. from reflex.utils.exceptions import (
  40. GeneratedCodeHasNoFunctionDefsError,
  41. SystemPackageMissingError,
  42. )
  43. from reflex.utils.format import format_library_name
  44. from reflex.utils.registry import get_npm_registry
  45. if typing.TYPE_CHECKING:
  46. from reflex.app import App
  47. class AppInfo(NamedTuple):
  48. """A tuple containing the app instance and module."""
  49. app: App
  50. module: ModuleType
  51. @dataclasses.dataclass(frozen=True)
  52. class Template:
  53. """A template for a Reflex app."""
  54. name: str
  55. description: str
  56. code_url: str
  57. @dataclasses.dataclass(frozen=True)
  58. class CpuInfo:
  59. """Model to save cpu info."""
  60. manufacturer_id: str | None
  61. model_name: str | None
  62. address_width: int | None
  63. def get_web_dir() -> Path:
  64. """Get the working directory for the next.js commands.
  65. Can be overridden with REFLEX_WEB_WORKDIR.
  66. Returns:
  67. The working directory.
  68. """
  69. return environment.REFLEX_WEB_WORKDIR.get()
  70. def get_states_dir() -> Path:
  71. """Get the working directory for the states.
  72. Can be overridden with REFLEX_STATES_WORKDIR.
  73. Returns:
  74. The working directory.
  75. """
  76. return environment.REFLEX_STATES_WORKDIR.get()
  77. def get_backend_dir() -> Path:
  78. """Get the working directory for the backend.
  79. Returns:
  80. The working directory.
  81. """
  82. return get_web_dir() / constants.Dirs.BACKEND
  83. def check_latest_package_version(package_name: str):
  84. """Check if the latest version of the package is installed.
  85. Args:
  86. package_name: The name of the package.
  87. """
  88. if environment.REFLEX_CHECK_LATEST_VERSION.get() is False:
  89. return
  90. try:
  91. console.debug(f"Checking for the latest version of {package_name}...")
  92. # Get the latest version from PyPI
  93. current_version = importlib.metadata.version(package_name)
  94. url = f"https://pypi.org/pypi/{package_name}/json"
  95. response = net.get(url)
  96. latest_version = response.json()["info"]["version"]
  97. console.debug(f"Latest version of {package_name}: {latest_version}")
  98. if get_or_set_last_reflex_version_check_datetime():
  99. # Versions were already checked and saved in reflex.json, no need to warn again
  100. return
  101. if version.parse(current_version) < version.parse(latest_version):
  102. # Show a warning when the host version is older than PyPI version
  103. console.warn(
  104. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  105. )
  106. except Exception:
  107. console.debug(f"Failed to check for the latest version of {package_name}.")
  108. pass
  109. def get_or_set_last_reflex_version_check_datetime():
  110. """Get the last time a check was made for the latest reflex version.
  111. This is typically useful for cases where the host reflex version is
  112. less than that on Pypi.
  113. Returns:
  114. The last version check datetime.
  115. """
  116. reflex_json_file = get_web_dir() / constants.Reflex.JSON
  117. if not reflex_json_file.exists():
  118. return None
  119. # Open and read the file
  120. data = json.loads(reflex_json_file.read_text())
  121. last_version_check_datetime = data.get("last_version_check_datetime")
  122. if not last_version_check_datetime:
  123. data.update({"last_version_check_datetime": str(datetime.now())})
  124. path_ops.update_json_file(reflex_json_file, data)
  125. return last_version_check_datetime
  126. def set_last_reflex_run_time():
  127. """Set the last Reflex run time."""
  128. path_ops.update_json_file(
  129. get_web_dir() / constants.Reflex.JSON,
  130. {"last_reflex_run_datetime": str(datetime.now())},
  131. )
  132. def check_node_version() -> bool:
  133. """Check the version of Node.js.
  134. Returns:
  135. Whether the version of Node.js is valid.
  136. """
  137. current_version = get_node_version()
  138. return current_version is not None and current_version >= version.parse(
  139. constants.Node.MIN_VERSION
  140. )
  141. def get_node_version() -> version.Version | None:
  142. """Get the version of node.
  143. Returns:
  144. The version of node.
  145. """
  146. node_path = path_ops.get_node_path()
  147. if node_path is None:
  148. return None
  149. try:
  150. result = processes.new_process([node_path, "-v"], run=True)
  151. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  152. return version.parse(result.stdout)
  153. except (FileNotFoundError, TypeError):
  154. return None
  155. def get_bun_version(bun_path: Path | None = None) -> version.Version | None:
  156. """Get the version of bun.
  157. Args:
  158. bun_path: The path to the bun executable.
  159. Returns:
  160. The version of bun.
  161. """
  162. bun_path = bun_path or path_ops.get_bun_path()
  163. if bun_path is None:
  164. return None
  165. try:
  166. # Run the bun -v command and capture the output
  167. result = processes.new_process([str(bun_path), "-v"], run=True)
  168. return version.parse(str(result.stdout))
  169. except FileNotFoundError:
  170. return None
  171. except version.InvalidVersion as e:
  172. console.warn(
  173. f"The detected bun version ({e.args[0]}) is not valid. Defaulting to None."
  174. )
  175. return None
  176. def prefer_npm_over_bun() -> bool:
  177. """Check if npm should be preferred over bun.
  178. Returns:
  179. If npm should be preferred over bun.
  180. """
  181. return npm_escape_hatch() or (
  182. constants.IS_WINDOWS and windows_check_onedrive_in_path()
  183. )
  184. def get_nodejs_compatible_package_managers(
  185. raise_on_none: bool = True,
  186. ) -> Sequence[str]:
  187. """Get the package manager executable for installation. Typically, bun is used for installation.
  188. Args:
  189. raise_on_none: Whether to raise an error if the package manager is not found.
  190. Returns:
  191. The path to the package manager.
  192. Raises:
  193. FileNotFoundError: If the package manager is not found and raise_on_none is True.
  194. """
  195. bun_package_manager = (
  196. str(bun_path) if (bun_path := path_ops.get_bun_path()) else None
  197. )
  198. npm_package_manager = (
  199. str(npm_path) if (npm_path := path_ops.get_npm_path()) else None
  200. )
  201. if prefer_npm_over_bun():
  202. package_managers = [npm_package_manager, bun_package_manager]
  203. else:
  204. package_managers = [bun_package_manager, npm_package_manager]
  205. package_managers = list(filter(None, package_managers))
  206. if not package_managers and raise_on_none:
  207. raise FileNotFoundError(
  208. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  209. )
  210. return package_managers
  211. def is_outdated_nodejs_installed():
  212. """Check if the installed Node.js version is outdated.
  213. Returns:
  214. If the installed Node.js version is outdated.
  215. """
  216. current_version = get_node_version()
  217. if current_version is not None and current_version < version.parse(
  218. constants.Node.MIN_VERSION
  219. ):
  220. console.warn(
  221. f"Your version ({current_version}) of Node.js is out of date. Upgrade to {constants.Node.MIN_VERSION} or higher."
  222. )
  223. return True
  224. return False
  225. def get_js_package_executor(raise_on_none: bool = False) -> Sequence[Sequence[str]]:
  226. """Get the paths to package managers for running commands. Ordered by preference.
  227. This is currently identical to get_install_package_managers, but may change in the future.
  228. Args:
  229. raise_on_none: Whether to raise an error if no package managers is not found.
  230. Returns:
  231. The paths to the package managers as a list of lists, where each list is the command to run and its arguments.
  232. Raises:
  233. FileNotFoundError: If no package managers are found and raise_on_none is True.
  234. """
  235. bun_package_manager = (
  236. [str(bun_path)] + (["--bun"] if is_outdated_nodejs_installed() else [])
  237. if (bun_path := path_ops.get_bun_path())
  238. else None
  239. )
  240. npm_package_manager = (
  241. [str(npm_path)] if (npm_path := path_ops.get_npm_path()) else None
  242. )
  243. if prefer_npm_over_bun():
  244. package_managers = [npm_package_manager, bun_package_manager]
  245. else:
  246. package_managers = [bun_package_manager, npm_package_manager]
  247. package_managers = list(filter(None, package_managers))
  248. if not package_managers and raise_on_none:
  249. raise FileNotFoundError(
  250. "Bun or npm not found. You might need to rerun `reflex init` or install either."
  251. )
  252. return package_managers
  253. def windows_check_onedrive_in_path() -> bool:
  254. """For windows, check if oneDrive is present in the project dir path.
  255. Returns:
  256. If oneDrive is in the path of the project directory.
  257. """
  258. return "onedrive" in str(Path.cwd()).lower()
  259. def npm_escape_hatch() -> bool:
  260. """If the user sets REFLEX_USE_NPM, prefer npm over bun.
  261. Returns:
  262. If the user has set REFLEX_USE_NPM.
  263. """
  264. return environment.REFLEX_USE_NPM.get()
  265. def _check_app_name(config: Config):
  266. """Check if the app name is set in the config.
  267. Args:
  268. config: The config object.
  269. Raises:
  270. RuntimeError: If the app name is not set in the config.
  271. """
  272. if not config.app_name:
  273. raise RuntimeError(
  274. "Cannot get the app module because `app_name` is not set in rxconfig! "
  275. "If this error occurs in a reflex test case, ensure that `get_app` is mocked."
  276. )
  277. def get_app(reload: bool = False) -> ModuleType:
  278. """Get the app module based on the default config.
  279. Args:
  280. reload: Re-import the app module from disk
  281. Returns:
  282. The app based on the default config.
  283. Raises:
  284. Exception: If an error occurs while getting the app module.
  285. """
  286. from reflex.utils import telemetry
  287. try:
  288. config = get_config()
  289. _check_app_name(config)
  290. module = config.module
  291. sys.path.insert(0, str(Path.cwd()))
  292. app = (
  293. __import__(module, fromlist=(constants.CompileVars.APP,))
  294. if not config.app_module
  295. else config.app_module
  296. )
  297. if reload:
  298. from reflex.page import DECORATED_PAGES
  299. from reflex.state import reload_state_module
  300. # Reset rx.State subclasses to avoid conflict when reloading.
  301. reload_state_module(module=module)
  302. DECORATED_PAGES.clear()
  303. # Reload the app module.
  304. importlib.reload(app)
  305. except Exception as ex:
  306. telemetry.send_error(ex, context="frontend")
  307. raise
  308. else:
  309. return app
  310. def get_and_validate_app(reload: bool = False) -> AppInfo:
  311. """Get the app instance based on the default config and validate it.
  312. Args:
  313. reload: Re-import the app module from disk
  314. Returns:
  315. The app instance and the app module.
  316. Raises:
  317. RuntimeError: If the app instance is not an instance of rx.App.
  318. """
  319. from reflex.app import App
  320. app_module = get_app(reload=reload)
  321. app = getattr(app_module, constants.CompileVars.APP)
  322. if not isinstance(app, App):
  323. raise RuntimeError(
  324. "The app instance in the specified app_module_import in rxconfig must be an instance of rx.App."
  325. )
  326. return AppInfo(app=app, module=app_module)
  327. def validate_app(reload: bool = False) -> None:
  328. """Validate the app instance based on the default config.
  329. Args:
  330. reload: Re-import the app module from disk
  331. """
  332. get_and_validate_app(reload=reload)
  333. def get_compiled_app(
  334. reload: bool = False, export: bool = False, dry_run: bool = False
  335. ) -> ModuleType:
  336. """Get the app module based on the default config after first compiling it.
  337. Args:
  338. reload: Re-import the app module from disk
  339. export: Compile the app for export
  340. dry_run: If True, do not write the compiled app to disk.
  341. Returns:
  342. The compiled app based on the default config.
  343. """
  344. app, app_module = get_and_validate_app(reload=reload)
  345. # For py3.9 compatibility when redis is used, we MUST add any decorator pages
  346. # before compiling the app in a thread to avoid event loop error (REF-2172).
  347. app._apply_decorated_pages()
  348. app._compile(export=export, dry_run=dry_run)
  349. return app_module
  350. def compile_app(
  351. reload: bool = False, export: bool = False, dry_run: bool = False
  352. ) -> None:
  353. """Compile the app module based on the default config.
  354. Args:
  355. reload: Re-import the app module from disk
  356. export: Compile the app for export
  357. dry_run: If True, do not write the compiled app to disk.
  358. """
  359. get_compiled_app(reload=reload, export=export, dry_run=dry_run)
  360. def _can_colorize() -> bool:
  361. """Check if the output can be colorized.
  362. Copied from _colorize.can_colorize.
  363. https://raw.githubusercontent.com/python/cpython/refs/heads/main/Lib/_colorize.py
  364. Returns:
  365. If the output can be colorized
  366. """
  367. file = sys.stdout
  368. if not sys.flags.ignore_environment:
  369. if os.environ.get("PYTHON_COLORS") == "0":
  370. return False
  371. if os.environ.get("PYTHON_COLORS") == "1":
  372. return True
  373. if os.environ.get("NO_COLOR"):
  374. return False
  375. if os.environ.get("FORCE_COLOR"):
  376. return True
  377. if os.environ.get("TERM") == "dumb":
  378. return False
  379. if not hasattr(file, "fileno"):
  380. return False
  381. if sys.platform == "win32":
  382. try:
  383. import nt
  384. if not nt._supports_virtual_terminal():
  385. return False
  386. except (ImportError, AttributeError):
  387. return False
  388. try:
  389. return os.isatty(file.fileno())
  390. except io.UnsupportedOperation:
  391. return file.isatty()
  392. def compile_or_validate_app(compile: bool = False) -> bool:
  393. """Compile or validate the app module based on the default config.
  394. Args:
  395. compile: Whether to compile the app.
  396. Returns:
  397. If the app is compiled successfully.
  398. """
  399. try:
  400. if compile:
  401. compile_app()
  402. else:
  403. validate_app()
  404. except Exception as e:
  405. if isinstance(e, click.exceptions.Exit):
  406. return False
  407. import traceback
  408. sys_exception = sys.exception()
  409. try:
  410. colorize = _can_colorize()
  411. traceback.print_exception(e, colorize=colorize) # pyright: ignore[reportCallIssue]
  412. except Exception:
  413. traceback.print_exception(sys_exception)
  414. return False
  415. return True
  416. def get_redis() -> Redis | None:
  417. """Get the asynchronous redis client.
  418. Returns:
  419. The asynchronous redis client.
  420. """
  421. if (redis_url := parse_redis_url()) is not None:
  422. return Redis.from_url(
  423. redis_url,
  424. retry_on_error=[RedisError],
  425. )
  426. return None
  427. def get_redis_sync() -> RedisSync | None:
  428. """Get the synchronous redis client.
  429. Returns:
  430. The synchronous redis client.
  431. """
  432. if (redis_url := parse_redis_url()) is not None:
  433. return RedisSync.from_url(
  434. redis_url,
  435. retry_on_error=[RedisError],
  436. )
  437. return None
  438. def parse_redis_url() -> str | None:
  439. """Parse the REDIS_URL in config if applicable.
  440. Returns:
  441. If url is non-empty, return the URL as it is.
  442. Raises:
  443. ValueError: If the REDIS_URL is not a supported scheme.
  444. """
  445. config = get_config()
  446. if not config.redis_url:
  447. return None
  448. if not config.redis_url.startswith(("redis://", "rediss://", "unix://")):
  449. raise ValueError(
  450. "REDIS_URL must start with 'redis://', 'rediss://', or 'unix://'."
  451. )
  452. return config.redis_url
  453. async def get_redis_status() -> dict[str, bool | None]:
  454. """Checks the status of the Redis connection.
  455. Attempts to connect to Redis and send a ping command to verify connectivity.
  456. Returns:
  457. The status of the Redis connection.
  458. """
  459. try:
  460. status = True
  461. redis_client = get_redis_sync()
  462. if redis_client is not None:
  463. redis_client.ping()
  464. else:
  465. status = None
  466. except RedisError:
  467. status = False
  468. return {"redis": status}
  469. def validate_app_name(app_name: str | None = None) -> str:
  470. """Validate the app name.
  471. The default app name is the name of the current directory.
  472. Args:
  473. app_name: the name passed by user during reflex init
  474. Returns:
  475. The app name after validation.
  476. Raises:
  477. Exit: if the app directory name is reflex or if the name is not standard for a python package name.
  478. """
  479. app_name = app_name if app_name else Path.cwd().name.replace("-", "_")
  480. # Make sure the app is not named "reflex".
  481. if app_name.lower() == constants.Reflex.MODULE_NAME:
  482. console.error(
  483. f"The app directory cannot be named [bold]{constants.Reflex.MODULE_NAME}[/bold]."
  484. )
  485. raise click.exceptions.Exit(1)
  486. # Make sure the app name is standard for a python package name.
  487. if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", app_name):
  488. console.error(
  489. "The app directory name must start with a letter and can contain letters, numbers, and underscores."
  490. )
  491. raise click.exceptions.Exit(1)
  492. return app_name
  493. def rename_path_up_tree(full_path: str | Path, old_name: str, new_name: str) -> Path:
  494. """Rename all instances of `old_name` in the path (file and directories) to `new_name`.
  495. The renaming stops when we reach the directory containing `rxconfig.py`.
  496. Args:
  497. full_path: The full path to start renaming from.
  498. old_name: The name to be replaced.
  499. new_name: The replacement name.
  500. Returns:
  501. The updated path after renaming.
  502. """
  503. current_path = Path(full_path)
  504. new_path = None
  505. while True:
  506. directory, base = current_path.parent, current_path.name
  507. # Stop renaming when we reach the root dir (which contains rxconfig.py)
  508. if current_path.is_dir() and (current_path / "rxconfig.py").exists():
  509. new_path = current_path
  510. break
  511. if old_name == base.removesuffix(constants.Ext.PY):
  512. new_base = base.replace(old_name, new_name)
  513. new_path = directory / new_base
  514. current_path.rename(new_path)
  515. console.debug(f"Renamed {current_path} -> {new_path}")
  516. current_path = new_path
  517. else:
  518. new_path = current_path
  519. # Move up the directory tree
  520. current_path = directory
  521. return new_path
  522. def rename_app(new_app_name: str, loglevel: constants.LogLevel):
  523. """Rename the app directory.
  524. Args:
  525. new_app_name: The new name for the app.
  526. loglevel: The log level to use.
  527. Raises:
  528. Exit: If the command is not ran in the root dir or the app module cannot be imported.
  529. """
  530. # Set the log level.
  531. console.set_log_level(loglevel)
  532. if not constants.Config.FILE.exists():
  533. console.error(
  534. "No rxconfig.py found. Make sure you are in the root directory of your app."
  535. )
  536. raise click.exceptions.Exit(1)
  537. sys.path.insert(0, str(Path.cwd()))
  538. config = get_config()
  539. module_path = importlib.util.find_spec(config.module)
  540. if module_path is None:
  541. console.error(f"Could not find module {config.module}.")
  542. raise click.exceptions.Exit(1)
  543. if not module_path.origin:
  544. console.error(f"Could not find origin for module {config.module}.")
  545. raise click.exceptions.Exit(1)
  546. console.info(f"Renaming app directory to {new_app_name}.")
  547. process_directory(
  548. Path.cwd(),
  549. config.app_name,
  550. new_app_name,
  551. exclude_dirs=[constants.Dirs.WEB, constants.Dirs.APP_ASSETS],
  552. )
  553. rename_path_up_tree(Path(module_path.origin), config.app_name, new_app_name)
  554. console.success(f"App directory renamed to [bold]{new_app_name}[/bold].")
  555. def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: str):
  556. """Rename imports the file using string replacement as well as app_name in rxconfig.py.
  557. Args:
  558. file_path: The file to process.
  559. old_name: The old name to replace.
  560. new_name: The new name to use.
  561. """
  562. file_path = Path(file_path)
  563. content = file_path.read_text()
  564. # Replace `from old_name.` or `from old_name` with `from new_name`
  565. content = re.sub(
  566. rf"\bfrom {re.escape(old_name)}(\b|\.|\s)",
  567. lambda match: f"from {new_name}{match.group(1)}",
  568. content,
  569. )
  570. # Replace `import old_name` with `import new_name`
  571. content = re.sub(
  572. rf"\bimport {re.escape(old_name)}\b",
  573. f"import {new_name}",
  574. content,
  575. )
  576. # Replace `app_name="old_name"` in rx.Config
  577. content = re.sub(
  578. rf'\bapp_name\s*=\s*["\']{re.escape(old_name)}["\']',
  579. f'app_name="{new_name}"',
  580. content,
  581. )
  582. # Replace positional argument `"old_name"` in rx.Config
  583. content = re.sub(
  584. rf'\brx\.Config\(\s*["\']{re.escape(old_name)}["\']',
  585. f'rx.Config("{new_name}"',
  586. content,
  587. )
  588. file_path.write_text(content)
  589. def process_directory(
  590. directory: str | Path,
  591. old_name: str,
  592. new_name: str,
  593. exclude_dirs: list | None = None,
  594. extensions: list | None = None,
  595. ):
  596. """Process files with specified extensions in a directory, excluding specified directories.
  597. Args:
  598. directory: The root directory to process.
  599. old_name: The old name to replace.
  600. new_name: The new name to use.
  601. exclude_dirs: List of directory names to exclude. Defaults to None.
  602. extensions: List of file extensions to process.
  603. """
  604. exclude_dirs = exclude_dirs or []
  605. extensions = extensions or [
  606. constants.Ext.PY,
  607. constants.Ext.MD,
  608. ] # include .md files, typically used in reflex-web.
  609. extensions_set = {ext.lstrip(".") for ext in extensions}
  610. directory = Path(directory)
  611. root_exclude_dirs = {directory / exclude_dir for exclude_dir in exclude_dirs}
  612. files = (
  613. p.resolve()
  614. for p in directory.glob("**/*")
  615. if p.is_file() and p.suffix.lstrip(".") in extensions_set
  616. )
  617. for file_path in files:
  618. if not any(
  619. file_path.is_relative_to(exclude_dir) for exclude_dir in root_exclude_dirs
  620. ):
  621. rename_imports_and_app_name(file_path, old_name, new_name)
  622. def create_config(app_name: str):
  623. """Create a new rxconfig file.
  624. Args:
  625. app_name: The name of the app.
  626. """
  627. # Import here to avoid circular imports.
  628. from reflex.compiler import templates
  629. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  630. console.debug(f"Creating {constants.Config.FILE}")
  631. constants.Config.FILE.write_text(
  632. templates.RXCONFIG.render(app_name=app_name, config_name=config_name)
  633. )
  634. def initialize_gitignore(
  635. gitignore_file: Path = constants.GitIgnore.FILE,
  636. files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS,
  637. ):
  638. """Initialize the template .gitignore file.
  639. Args:
  640. gitignore_file: The .gitignore file to create.
  641. files_to_ignore: The files to add to the .gitignore file.
  642. """
  643. # Combine with the current ignored files.
  644. current_ignore: list[str] = []
  645. if gitignore_file.exists():
  646. current_ignore = [ln.strip() for ln in gitignore_file.read_text().splitlines()]
  647. if files_to_ignore == current_ignore:
  648. console.debug(f"{gitignore_file} already up to date.")
  649. return
  650. files_to_ignore = [ln for ln in files_to_ignore if ln not in current_ignore]
  651. files_to_ignore += current_ignore
  652. # Write files to the .gitignore file.
  653. gitignore_file.touch(exist_ok=True)
  654. console.debug(f"Creating {gitignore_file}")
  655. gitignore_file.write_text("\n".join(files_to_ignore) + "\n")
  656. def initialize_requirements_txt() -> bool:
  657. """Initialize the requirements.txt file.
  658. If absent and no pyproject.toml file exists, generate one for the user.
  659. If the requirements.txt does not have reflex as dependency,
  660. generate a requirement pinning current version and append to
  661. the requirements.txt file.
  662. Returns:
  663. True if the user has to update the requirements.txt file.
  664. Raises:
  665. Exit: If the requirements.txt file cannot be read or written to.
  666. """
  667. requirements_file_path = Path(constants.RequirementsTxt.FILE)
  668. if (
  669. not requirements_file_path.exists()
  670. and Path(constants.PyprojectToml.FILE).exists()
  671. ):
  672. return True
  673. requirements_file_path.touch(exist_ok=True)
  674. for encoding in [None, "utf-8"]:
  675. try:
  676. content = requirements_file_path.read_text(encoding)
  677. break
  678. except UnicodeDecodeError:
  679. continue
  680. except Exception as e:
  681. console.error(f"Failed to read {requirements_file_path}.")
  682. raise click.exceptions.Exit(1) from e
  683. else:
  684. return True
  685. for line in content.splitlines():
  686. if re.match(r"^reflex[^a-zA-Z0-9]", line):
  687. console.debug(f"{requirements_file_path} already has reflex as dependency.")
  688. return False
  689. console.debug(
  690. f"Appending {constants.RequirementsTxt.DEFAULTS_STUB} to {requirements_file_path}"
  691. )
  692. with requirements_file_path.open("a", encoding=encoding) as f:
  693. f.write(
  694. "\n" + constants.RequirementsTxt.DEFAULTS_STUB + constants.Reflex.VERSION
  695. )
  696. return False
  697. def initialize_app_directory(
  698. app_name: str,
  699. template_name: str = constants.Templates.DEFAULT,
  700. template_code_dir_name: str | None = None,
  701. template_dir: Path | None = None,
  702. ):
  703. """Initialize the app directory on reflex init.
  704. Args:
  705. app_name: The name of the app.
  706. template_name: The name of the template to use.
  707. template_code_dir_name: The name of the code directory in the template.
  708. template_dir: The directory of the template source files.
  709. Raises:
  710. Exit: If template_name, template_code_dir_name, template_dir combination is not supported.
  711. """
  712. console.log("Initializing the app directory.")
  713. # By default, use the blank template from local assets.
  714. if template_name == constants.Templates.DEFAULT:
  715. if template_code_dir_name is not None or template_dir is not None:
  716. console.error(
  717. f"Only {template_name=} should be provided, got {template_code_dir_name=}, {template_dir=}."
  718. )
  719. raise click.exceptions.Exit(1)
  720. template_code_dir_name = constants.Templates.Dirs.CODE
  721. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template_name)
  722. else:
  723. if template_code_dir_name is None or template_dir is None:
  724. console.error(
  725. f"For `{template_name}` template, `template_code_dir_name` and `template_dir` should both be provided."
  726. )
  727. raise click.exceptions.Exit(1)
  728. console.debug(f"Using {template_name=} {template_dir=} {template_code_dir_name=}.")
  729. # Remove __pycache__ dirs in template directory and current directory.
  730. for pycache_dir in [
  731. *template_dir.glob("**/__pycache__"),
  732. *Path.cwd().glob("**/__pycache__"),
  733. ]:
  734. shutil.rmtree(pycache_dir, ignore_errors=True)
  735. for file in template_dir.iterdir():
  736. # Copy the file to current directory but keep the name the same.
  737. path_ops.cp(str(file), file.name)
  738. # Rename the template app to the app name.
  739. path_ops.mv(template_code_dir_name, app_name)
  740. path_ops.mv(
  741. Path(app_name) / (template_name + constants.Ext.PY),
  742. Path(app_name) / (app_name + constants.Ext.PY),
  743. )
  744. # Fix up the imports.
  745. path_ops.find_replace(
  746. app_name,
  747. f"from {template_name}",
  748. f"from {app_name}",
  749. )
  750. def get_project_hash(raise_on_fail: bool = False) -> int | None:
  751. """Get the project hash from the reflex.json file if the file exists.
  752. Args:
  753. raise_on_fail: Whether to raise an error if the file does not exist.
  754. Returns:
  755. project_hash: The app hash.
  756. """
  757. json_file = get_web_dir() / constants.Reflex.JSON
  758. if not json_file.exists() and not raise_on_fail:
  759. return None
  760. data = json.loads(json_file.read_text())
  761. return data.get("project_hash")
  762. def initialize_web_directory():
  763. """Initialize the web directory on reflex init."""
  764. console.log("Initializing the web directory.")
  765. # Reuse the hash if one is already created, so we don't over-write it when running reflex init
  766. project_hash = get_project_hash()
  767. console.debug(f"Copying {constants.Templates.Dirs.WEB_TEMPLATE} to {get_web_dir()}")
  768. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, str(get_web_dir()))
  769. console.debug("Initializing the web directory.")
  770. initialize_package_json()
  771. console.debug("Initializing the bun config file.")
  772. initialize_bun_config()
  773. console.debug("Initializing the .npmrc file.")
  774. initialize_npmrc()
  775. console.debug("Initializing the public directory.")
  776. path_ops.mkdir(get_web_dir() / constants.Dirs.PUBLIC)
  777. console.debug("Initializing the next.config.js file.")
  778. update_next_config()
  779. console.debug("Initializing the reflex.json file.")
  780. # Initialize the reflex json file.
  781. init_reflex_json(project_hash=project_hash)
  782. @once
  783. def _turbopack_flag() -> str:
  784. return " --turbopack" if environment.REFLEX_USE_TURBOPACK.get() else ""
  785. def _compile_package_json():
  786. return templates.PACKAGE_JSON.render(
  787. scripts={
  788. "dev": constants.PackageJson.Commands.DEV.format(flags=_turbopack_flag()),
  789. "export": constants.PackageJson.Commands.EXPORT.format(
  790. flags=_turbopack_flag()
  791. ),
  792. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP.format(
  793. flags=_turbopack_flag()
  794. ),
  795. "prod": constants.PackageJson.Commands.PROD,
  796. },
  797. dependencies=constants.PackageJson.DEPENDENCIES,
  798. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  799. overrides=constants.PackageJson.OVERRIDES,
  800. )
  801. def initialize_package_json():
  802. """Render and write in .web the package.json file."""
  803. output_path = get_web_dir() / constants.PackageJson.PATH
  804. output_path.write_text(_compile_package_json())
  805. def initialize_bun_config():
  806. """Initialize the bun config file."""
  807. bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
  808. if (custom_bunfig := Path(constants.Bun.CONFIG_PATH)).exists():
  809. bunfig_content = custom_bunfig.read_text()
  810. console.info(f"Copying custom bunfig.toml inside {get_web_dir()} folder")
  811. else:
  812. best_registry = get_npm_registry()
  813. bunfig_content = constants.Bun.DEFAULT_CONFIG.format(registry=best_registry)
  814. bun_config_path.write_text(bunfig_content)
  815. def initialize_npmrc():
  816. """Initialize the .npmrc file."""
  817. npmrc_path = get_web_dir() / constants.Node.CONFIG_PATH
  818. if (custom_npmrc := Path(constants.Node.CONFIG_PATH)).exists():
  819. npmrc_content = custom_npmrc.read_text()
  820. console.info(f"Copying custom .npmrc inside {get_web_dir()} folder")
  821. else:
  822. best_registry = get_npm_registry()
  823. npmrc_content = constants.Node.DEFAULT_CONFIG.format(registry=best_registry)
  824. npmrc_path.write_text(npmrc_content)
  825. def init_reflex_json(project_hash: int | None):
  826. """Write the hash of the Reflex project to a REFLEX_JSON.
  827. Reuse the hash if one is already created, therefore do not
  828. overwrite it every time we run the reflex init command
  829. .
  830. Args:
  831. project_hash: The app hash.
  832. """
  833. if project_hash is not None:
  834. console.debug(f"Project hash is already set to {project_hash}.")
  835. else:
  836. # Get a random project hash.
  837. project_hash = random.getrandbits(128)
  838. console.debug(f"Setting project hash to {project_hash}.")
  839. # Write the hash and version to the reflex json file.
  840. reflex_json = {
  841. "version": constants.Reflex.VERSION,
  842. "project_hash": project_hash,
  843. }
  844. path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
  845. def update_next_config(
  846. export: bool = False, transpile_packages: list[str] | None = None
  847. ):
  848. """Update Next.js config from Reflex config.
  849. Args:
  850. export: if the method run during reflex export.
  851. transpile_packages: list of packages to transpile via next.config.js.
  852. """
  853. next_config_file = get_web_dir() / constants.Next.CONFIG_FILE
  854. next_config = _update_next_config(
  855. get_config(), export=export, transpile_packages=transpile_packages
  856. )
  857. # Overwriting the next.config.js triggers a full server reload, so make sure
  858. # there is actually a diff.
  859. orig_next_config = next_config_file.read_text() if next_config_file.exists() else ""
  860. if orig_next_config != next_config:
  861. next_config_file.write_text(next_config)
  862. def _update_next_config(
  863. config: Config, export: bool = False, transpile_packages: list[str] | None = None
  864. ):
  865. next_config = {
  866. "basePath": config.frontend_path or "",
  867. "compress": config.next_compression,
  868. "trailingSlash": True,
  869. "staticPageGenerationTimeout": config.static_page_generation_timeout,
  870. }
  871. if not config.next_dev_indicators:
  872. next_config["devIndicators"] = False
  873. if transpile_packages:
  874. next_config["transpilePackages"] = list(
  875. {format_library_name(p) for p in transpile_packages}
  876. )
  877. if export:
  878. next_config["output"] = "export"
  879. next_config["distDir"] = constants.Dirs.STATIC
  880. next_config_json = re.sub(r'"([^"]+)"(?=:)', r"\1", json.dumps(next_config))
  881. return f"module.exports = {next_config_json};"
  882. def remove_existing_bun_installation():
  883. """Remove existing bun installation."""
  884. console.debug("Removing existing bun installation.")
  885. if Path(get_config().bun_path).exists():
  886. path_ops.rm(constants.Bun.ROOT_PATH)
  887. def download_and_run(url: str, *args, show_status: bool = False, **env):
  888. """Download and run a script.
  889. Args:
  890. url: The url of the script.
  891. args: The arguments to pass to the script.
  892. show_status: Whether to show the status of the script.
  893. env: The environment variables to use.
  894. Raises:
  895. Exit: If the script fails to download.
  896. """
  897. # Download the script
  898. console.debug(f"Downloading {url}")
  899. try:
  900. response = net.get(url)
  901. response.raise_for_status()
  902. except httpx.HTTPError as e:
  903. console.error(
  904. f"Failed to download bun install script. You can install or update bun manually from https://bun.sh \n{e}"
  905. )
  906. raise click.exceptions.Exit(1) from None
  907. # Save the script to a temporary file.
  908. script = Path(tempfile.NamedTemporaryFile().name)
  909. script.write_text(response.text)
  910. # Run the script.
  911. env = {**os.environ, **env}
  912. process = processes.new_process(["bash", str(script), *args], env=env)
  913. show = processes.show_status if show_status else processes.show_logs
  914. show(f"Installing {url}", process)
  915. def install_bun():
  916. """Install bun onto the user's system.
  917. Raises:
  918. SystemPackageMissingError: If "unzip" is missing.
  919. """
  920. one_drive_in_path = windows_check_onedrive_in_path()
  921. if constants.IS_WINDOWS and one_drive_in_path:
  922. console.warn(
  923. "Creating project directories in OneDrive is not recommended for bun usage on windows. This will fallback to npm."
  924. )
  925. bun_path = path_ops.get_bun_path()
  926. # Skip if bun is already installed.
  927. if (
  928. bun_path
  929. and (current_version := get_bun_version(bun_path=bun_path))
  930. and current_version >= version.parse(constants.Bun.MIN_VERSION)
  931. ):
  932. console.debug("Skipping bun installation as it is already installed.")
  933. return
  934. if bun_path and path_ops.use_system_bun():
  935. validate_bun(bun_path=bun_path)
  936. return
  937. # if unzip is installed
  938. if constants.IS_WINDOWS:
  939. processes.new_process(
  940. [
  941. "powershell",
  942. "-c",
  943. f"irm {constants.Bun.WINDOWS_INSTALL_URL}|iex",
  944. ],
  945. env={
  946. "BUN_INSTALL": str(constants.Bun.ROOT_PATH),
  947. "BUN_VERSION": constants.Bun.VERSION,
  948. },
  949. shell=True,
  950. run=True,
  951. show_logs=console.is_debug(),
  952. )
  953. else:
  954. if path_ops.which("unzip") is None:
  955. raise SystemPackageMissingError("unzip")
  956. # Run the bun install script.
  957. download_and_run(
  958. constants.Bun.INSTALL_URL,
  959. f"bun-v{constants.Bun.VERSION}",
  960. BUN_INSTALL=str(constants.Bun.ROOT_PATH),
  961. BUN_VERSION=str(constants.Bun.VERSION),
  962. )
  963. def _write_cached_procedure_file(payload: str, cache_file: str | Path):
  964. cache_file = Path(cache_file)
  965. cache_file.write_text(payload)
  966. def _read_cached_procedure_file(cache_file: str | Path) -> str | None:
  967. cache_file = Path(cache_file)
  968. if cache_file.exists():
  969. return cache_file.read_text()
  970. return None
  971. def _clear_cached_procedure_file(cache_file: str | Path):
  972. cache_file = Path(cache_file)
  973. if cache_file.exists():
  974. cache_file.unlink()
  975. def cached_procedure(
  976. cache_file: str | None,
  977. payload_fn: Callable[..., str],
  978. cache_file_fn: Callable[[], str] | None = None,
  979. ):
  980. """Decorator to cache the runs of a procedure on disk. Procedures should not have
  981. a return value.
  982. Args:
  983. cache_file: The file to store the cache payload in.
  984. payload_fn: Function that computes cache payload from function args.
  985. cache_file_fn: Function that computes the cache file name at runtime.
  986. Returns:
  987. The decorated function.
  988. Raises:
  989. ValueError: If both cache_file and cache_file_fn are provided.
  990. """
  991. if cache_file and cache_file_fn is not None:
  992. raise ValueError("cache_file and cache_file_fn cannot both be provided.")
  993. def _inner_decorator(func: Callable):
  994. def _inner(*args, **kwargs):
  995. _cache_file = cache_file_fn() if cache_file_fn is not None else cache_file
  996. if not _cache_file:
  997. raise ValueError("Unknown cache file, cannot cache result.")
  998. payload = _read_cached_procedure_file(_cache_file)
  999. new_payload = payload_fn(*args, **kwargs)
  1000. if payload != new_payload:
  1001. _clear_cached_procedure_file(_cache_file)
  1002. func(*args, **kwargs)
  1003. _write_cached_procedure_file(new_payload, _cache_file)
  1004. return _inner
  1005. return _inner_decorator
  1006. @cached_procedure(
  1007. cache_file_fn=lambda: str(
  1008. get_web_dir() / "reflex.install_frontend_packages.cached"
  1009. ),
  1010. payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
  1011. cache_file=None,
  1012. )
  1013. def install_frontend_packages(packages: set[str], config: Config):
  1014. """Installs the base and custom frontend packages.
  1015. Args:
  1016. packages: A list of package names to be installed.
  1017. config: The config object.
  1018. Example:
  1019. >>> install_frontend_packages(["react", "react-dom"], get_config())
  1020. """
  1021. install_package_managers = get_nodejs_compatible_package_managers(
  1022. raise_on_none=True
  1023. )
  1024. env = (
  1025. {
  1026. "NODE_TLS_REJECT_UNAUTHORIZED": "0",
  1027. }
  1028. if environment.SSL_NO_VERIFY.get()
  1029. else {}
  1030. )
  1031. primary_package_manager = install_package_managers[0]
  1032. fallbacks = install_package_managers[1:]
  1033. processes.run_process_with_fallbacks(
  1034. [primary_package_manager, "install", "--legacy-peer-deps"],
  1035. fallbacks=fallbacks,
  1036. analytics_enabled=True,
  1037. show_status_message="Installing base frontend packages",
  1038. cwd=get_web_dir(),
  1039. shell=constants.IS_WINDOWS,
  1040. env=env,
  1041. )
  1042. if config.tailwind is not None:
  1043. processes.run_process_with_fallbacks(
  1044. [
  1045. primary_package_manager,
  1046. "add",
  1047. "--legacy-peer-deps",
  1048. "-d",
  1049. constants.Tailwind.VERSION,
  1050. *[
  1051. plugin if isinstance(plugin, str) else plugin.get("name")
  1052. for plugin in (config.tailwind or {}).get("plugins", [])
  1053. ],
  1054. ],
  1055. fallbacks=fallbacks,
  1056. analytics_enabled=True,
  1057. show_status_message="Installing tailwind",
  1058. cwd=get_web_dir(),
  1059. shell=constants.IS_WINDOWS,
  1060. env=env,
  1061. )
  1062. # Install custom packages defined in frontend_packages
  1063. if len(packages) > 0:
  1064. processes.run_process_with_fallbacks(
  1065. [primary_package_manager, "add", "--legacy-peer-deps", *packages],
  1066. fallbacks=fallbacks,
  1067. analytics_enabled=True,
  1068. show_status_message="Installing frontend packages from config and components",
  1069. cwd=get_web_dir(),
  1070. shell=constants.IS_WINDOWS,
  1071. env=env,
  1072. )
  1073. def check_running_mode(frontend: bool, backend: bool) -> tuple[bool, bool]:
  1074. """Check if the app is running in frontend or backend mode.
  1075. Args:
  1076. frontend: Whether to run the frontend of the app.
  1077. backend: Whether to run the backend of the app.
  1078. Returns:
  1079. The running modes.
  1080. """
  1081. if not frontend and not backend:
  1082. return True, True
  1083. return frontend, backend
  1084. def assert_in_reflex_dir():
  1085. """Assert that the current working directory is the reflex directory.
  1086. Raises:
  1087. Exit: If the current working directory is not the reflex directory.
  1088. """
  1089. if not constants.Config.FILE.exists():
  1090. console.error(
  1091. f"[cyan]{constants.Config.FILE}[/cyan] not found. Move to the root folder of your project, or run [bold]{constants.Reflex.MODULE_NAME} init[/bold] to start a new project."
  1092. )
  1093. raise click.exceptions.Exit(1)
  1094. def needs_reinit() -> bool:
  1095. """Check if an app needs to be reinitialized.
  1096. Returns:
  1097. Whether the app needs to be reinitialized.
  1098. """
  1099. # Make sure the .reflex directory exists.
  1100. if not environment.REFLEX_DIR.get().exists():
  1101. return True
  1102. # Make sure the .web directory exists in frontend mode.
  1103. if not get_web_dir().exists():
  1104. return True
  1105. # If the template is out of date, then we need to re-init
  1106. if not is_latest_template():
  1107. return True
  1108. if constants.IS_WINDOWS:
  1109. console.warn(
  1110. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  1111. )
  1112. if windows_check_onedrive_in_path():
  1113. console.warn(
  1114. "Creating project directories in OneDrive may lead to performance issues. For optimal performance, It is recommended to avoid using OneDrive for your reflex app."
  1115. )
  1116. # No need to reinitialize if the app is already initialized.
  1117. return False
  1118. def is_latest_template() -> bool:
  1119. """Whether the app is using the latest template.
  1120. Returns:
  1121. Whether the app is using the latest template.
  1122. """
  1123. json_file = get_web_dir() / constants.Reflex.JSON
  1124. if not json_file.exists():
  1125. return False
  1126. app_version = json.loads(json_file.read_text()).get("version")
  1127. return app_version == constants.Reflex.VERSION
  1128. def validate_bun(bun_path: Path | None = None):
  1129. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  1130. Args:
  1131. bun_path: The path to the bun executable. If None, the default bun path is used.
  1132. Raises:
  1133. Exit: If custom specified bun does not exist or does not meet requirements.
  1134. """
  1135. bun_path = bun_path or path_ops.get_bun_path()
  1136. if bun_path is None:
  1137. return
  1138. if not path_ops.samefile(bun_path, constants.Bun.DEFAULT_PATH):
  1139. console.info(f"Using custom Bun path: {bun_path}")
  1140. bun_version = get_bun_version()
  1141. if bun_version is None:
  1142. console.error(
  1143. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  1144. )
  1145. raise click.exceptions.Exit(1)
  1146. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  1147. console.warn(
  1148. f"Reflex requires bun version {constants.Bun.MIN_VERSION} or higher to run, but the detected version is "
  1149. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  1150. f"that satisfies the minimum version requirement. You can upgrade bun by running [bold]bun upgrade[/bold]."
  1151. )
  1152. def validate_frontend_dependencies(init: bool = True):
  1153. """Validate frontend dependencies to ensure they meet requirements.
  1154. Args:
  1155. init: whether running `reflex init`
  1156. Raises:
  1157. Exit: If the package manager is invalid.
  1158. """
  1159. if not init:
  1160. try:
  1161. get_js_package_executor(raise_on_none=True)
  1162. except FileNotFoundError as e:
  1163. raise click.exceptions.Exit(1) from e
  1164. if prefer_npm_over_bun() and not check_node_version():
  1165. node_version = get_node_version()
  1166. console.error(
  1167. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  1168. )
  1169. raise click.exceptions.Exit(1)
  1170. def ensure_reflex_installation_id() -> int | None:
  1171. """Ensures that a reflex distinct id has been generated and stored in the reflex directory.
  1172. Returns:
  1173. Distinct id.
  1174. """
  1175. try:
  1176. console.debug("Ensuring reflex installation id.")
  1177. initialize_reflex_user_directory()
  1178. installation_id_file = environment.REFLEX_DIR.get() / "installation_id"
  1179. installation_id = None
  1180. if installation_id_file.exists():
  1181. with contextlib.suppress(Exception):
  1182. installation_id = int(installation_id_file.read_text())
  1183. # If anything goes wrong at all... just regenerate.
  1184. # Like what? Examples:
  1185. # - file not exists
  1186. # - file not readable
  1187. # - content not parseable as an int
  1188. if installation_id is None:
  1189. installation_id = random.getrandbits(128)
  1190. installation_id_file.write_text(str(installation_id))
  1191. except Exception as e:
  1192. console.debug(f"Failed to ensure reflex installation id: {e}")
  1193. return None
  1194. else:
  1195. # If we get here, installation_id is definitely set
  1196. return installation_id
  1197. def initialize_reflex_user_directory():
  1198. """Initialize the reflex user directory."""
  1199. console.debug(f"Creating {environment.REFLEX_DIR.get()}")
  1200. # Create the reflex directory.
  1201. path_ops.mkdir(environment.REFLEX_DIR.get())
  1202. def initialize_frontend_dependencies():
  1203. """Initialize all the frontend dependencies."""
  1204. # validate dependencies before install
  1205. console.debug("Validating frontend dependencies.")
  1206. validate_frontend_dependencies()
  1207. # Install the frontend dependencies.
  1208. console.debug("Installing or validating bun.")
  1209. install_bun()
  1210. # Set up the web directory.
  1211. initialize_web_directory()
  1212. def check_db_used() -> bool:
  1213. """Check if the database is used.
  1214. Returns:
  1215. True if the database is used.
  1216. """
  1217. return bool(get_config().db_url)
  1218. def check_redis_used() -> bool:
  1219. """Check if Redis is used.
  1220. Returns:
  1221. True if Redis is used.
  1222. """
  1223. return bool(get_config().redis_url)
  1224. def check_db_initialized() -> bool:
  1225. """Check if the database migrations are initialized.
  1226. Returns:
  1227. True if alembic is initialized (or if database is not used).
  1228. """
  1229. if (
  1230. get_config().db_url is not None
  1231. and not environment.ALEMBIC_CONFIG.get().exists()
  1232. ):
  1233. console.error(
  1234. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  1235. )
  1236. return False
  1237. return True
  1238. def check_schema_up_to_date():
  1239. """Check if the sqlmodel metadata matches the current database schema."""
  1240. if get_config().db_url is None or not environment.ALEMBIC_CONFIG.get().exists():
  1241. return
  1242. with model.Model.get_db_engine().connect() as connection:
  1243. try:
  1244. if model.Model.alembic_autogenerate(
  1245. connection=connection,
  1246. write_migration_scripts=False,
  1247. ):
  1248. console.error(
  1249. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  1250. "to generate migration scripts.",
  1251. )
  1252. except CommandError as command_error:
  1253. if "Target database is not up to date." in str(command_error):
  1254. console.error(
  1255. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  1256. )
  1257. def prompt_for_template_options(templates: list[Template]) -> str:
  1258. """Prompt the user to specify a template.
  1259. Args:
  1260. templates: The templates to choose from.
  1261. Returns:
  1262. The template name the user selects.
  1263. Raises:
  1264. Exit: If the user does not select a template.
  1265. """
  1266. # Show the user the URLs of each template to preview.
  1267. console.print("\nGet started with a template:")
  1268. # Prompt the user to select a template.
  1269. for index, template in enumerate(templates):
  1270. console.print(f"({index}) {template.description}")
  1271. template = console.ask(
  1272. "Which template would you like to use?",
  1273. choices=[str(i) for i in range(len(templates))],
  1274. show_choices=False,
  1275. default="0",
  1276. )
  1277. if not template:
  1278. console.error("No template selected.")
  1279. raise click.exceptions.Exit(1)
  1280. try:
  1281. template_index = int(template)
  1282. except ValueError:
  1283. console.error("Invalid template selected.")
  1284. raise click.exceptions.Exit(1) from None
  1285. if template_index < 0 or template_index >= len(templates):
  1286. console.error("Invalid template selected.")
  1287. raise click.exceptions.Exit(1)
  1288. # Return the template.
  1289. return templates[template_index].name
  1290. def fetch_app_templates(version: str) -> dict[str, Template]:
  1291. """Fetch a dict of templates from the templates repo using github API.
  1292. Args:
  1293. version: The version of the templates to fetch.
  1294. Returns:
  1295. The dict of templates.
  1296. """
  1297. def get_release_by_tag(tag: str) -> dict | None:
  1298. response = net.get(constants.Reflex.RELEASES_URL)
  1299. response.raise_for_status()
  1300. releases = response.json()
  1301. for release in releases:
  1302. if release["tag_name"] == f"v{tag}":
  1303. return release
  1304. return None
  1305. release = get_release_by_tag(version)
  1306. if release is None:
  1307. console.warn(f"No templates known for version {version}")
  1308. return {}
  1309. assets = release.get("assets", [])
  1310. asset = next((a for a in assets if a["name"] == "templates.json"), None)
  1311. if asset is None:
  1312. console.warn(f"Templates metadata not found for version {version}")
  1313. return {}
  1314. else:
  1315. templates_url = asset["browser_download_url"]
  1316. templates_data = net.get(templates_url, follow_redirects=True).json()["templates"]
  1317. for template in templates_data:
  1318. if template["name"] == "blank":
  1319. template["code_url"] = ""
  1320. continue
  1321. template["code_url"] = next(
  1322. (
  1323. a["browser_download_url"]
  1324. for a in assets
  1325. if a["name"] == f"{template['name']}.zip"
  1326. ),
  1327. None,
  1328. )
  1329. filtered_templates = {}
  1330. for tp in templates_data:
  1331. if tp["hidden"] or tp["code_url"] is None:
  1332. continue
  1333. known_fields = {f.name for f in dataclasses.fields(Template)}
  1334. filtered_templates[tp["name"]] = Template(
  1335. **{k: v for k, v in tp.items() if k in known_fields}
  1336. )
  1337. return filtered_templates
  1338. def create_config_init_app_from_remote_template(app_name: str, template_url: str):
  1339. """Create new rxconfig and initialize app using a remote template.
  1340. Args:
  1341. app_name: The name of the app.
  1342. template_url: The path to the template source code as a zip file.
  1343. Raises:
  1344. Exit: If any download, file operations fail or unexpected zip file format.
  1345. """
  1346. # Create a temp directory for the zip download.
  1347. try:
  1348. temp_dir = tempfile.mkdtemp()
  1349. except OSError as ose:
  1350. console.error(f"Failed to create temp directory for download: {ose}")
  1351. raise click.exceptions.Exit(1) from ose
  1352. # Use httpx GET with redirects to download the zip file.
  1353. zip_file_path: Path = Path(temp_dir) / "template.zip"
  1354. try:
  1355. # Note: following redirects can be risky. We only allow this for reflex built templates at the moment.
  1356. response = net.get(template_url, follow_redirects=True)
  1357. console.debug(f"Server responded download request: {response}")
  1358. response.raise_for_status()
  1359. except httpx.HTTPError as he:
  1360. console.error(f"Failed to download the template: {he}")
  1361. raise click.exceptions.Exit(1) from he
  1362. try:
  1363. zip_file_path.write_bytes(response.content)
  1364. console.debug(f"Downloaded the zip to {zip_file_path}")
  1365. except OSError as ose:
  1366. console.error(f"Unable to write the downloaded zip to disk {ose}")
  1367. raise click.exceptions.Exit(1) from ose
  1368. # Create a temp directory for the zip extraction.
  1369. try:
  1370. unzip_dir = Path(tempfile.mkdtemp())
  1371. except OSError as ose:
  1372. console.error(f"Failed to create temp directory for extracting zip: {ose}")
  1373. raise click.exceptions.Exit(1) from ose
  1374. try:
  1375. zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
  1376. # The zip file downloaded from github looks like:
  1377. # repo-name-branch/**/*, so we need to remove the top level directory.
  1378. except Exception as uze:
  1379. console.error(f"Failed to unzip the template: {uze}")
  1380. raise click.exceptions.Exit(1) from uze
  1381. if len(subdirs := list(unzip_dir.iterdir())) != 1:
  1382. console.error(f"Expected one directory in the zip, found {subdirs}")
  1383. raise click.exceptions.Exit(1)
  1384. template_dir = unzip_dir / subdirs[0]
  1385. console.debug(f"Template folder is located at {template_dir}")
  1386. # Move the rxconfig file here first.
  1387. path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
  1388. new_config = get_config(reload=True)
  1389. # Get the template app's name from rxconfig in case it is different than
  1390. # the source code repo name on github.
  1391. template_name = new_config.app_name
  1392. create_config(app_name)
  1393. initialize_app_directory(
  1394. app_name,
  1395. template_name=template_name,
  1396. template_code_dir_name=template_name,
  1397. template_dir=template_dir,
  1398. )
  1399. req_file = Path("requirements.txt")
  1400. if req_file.exists() and len(req_file.read_text().splitlines()) > 1:
  1401. console.info(
  1402. "Run `pip install -r requirements.txt` to install the required python packages for this template."
  1403. )
  1404. # Clean up the temp directories.
  1405. shutil.rmtree(temp_dir)
  1406. shutil.rmtree(unzip_dir)
  1407. def initialize_default_app(app_name: str):
  1408. """Initialize the default app.
  1409. Args:
  1410. app_name: The name of the app.
  1411. """
  1412. create_config(app_name)
  1413. initialize_app_directory(app_name)
  1414. def validate_and_create_app_using_remote_template(
  1415. app_name: str, template: str, templates: dict[str, Template]
  1416. ):
  1417. """Validate and create an app using a remote template.
  1418. Args:
  1419. app_name: The name of the app.
  1420. template: The name of the template.
  1421. templates: The available templates.
  1422. Raises:
  1423. Exit: If the template is not found.
  1424. """
  1425. # If user selects a template, it needs to exist.
  1426. if template in templates:
  1427. from reflex_cli.v2.utils import hosting
  1428. authenticated_token = hosting.authenticated_token()
  1429. if not authenticated_token or not authenticated_token[0]:
  1430. console.print(
  1431. f"Please use `reflex login` to access the '{template}' template."
  1432. )
  1433. raise click.exceptions.Exit(3)
  1434. template_url = templates[template].code_url
  1435. else:
  1436. template_parsed_url = urlparse(template)
  1437. # Check if the template is a github repo.
  1438. if template_parsed_url.hostname == "github.com":
  1439. path = template_parsed_url.path.strip("/").removesuffix(".git")
  1440. template_url = f"https://github.com/{path}/archive/main.zip"
  1441. else:
  1442. console.error(f"Template `{template}` not found or invalid.")
  1443. raise click.exceptions.Exit(1)
  1444. if template_url is None:
  1445. return
  1446. create_config_init_app_from_remote_template(
  1447. app_name=app_name, template_url=template_url
  1448. )
  1449. def fetch_remote_templates(
  1450. template: str,
  1451. ) -> tuple[str, dict[str, Template]]:
  1452. """Fetch the available remote templates.
  1453. Args:
  1454. template: The name of the template.
  1455. Returns:
  1456. The selected template and the available templates.
  1457. """
  1458. available_templates = {}
  1459. try:
  1460. # Get the available templates
  1461. available_templates = fetch_app_templates(constants.Reflex.VERSION)
  1462. except Exception as e:
  1463. console.warn("Failed to fetch templates. Falling back to default template.")
  1464. console.debug(f"Error while fetching templates: {e}")
  1465. template = constants.Templates.DEFAULT
  1466. return template, available_templates
  1467. def initialize_app(app_name: str, template: str | None = None) -> str | None:
  1468. """Initialize the app either from a remote template or a blank app. If the config file exists, it is considered as reinit.
  1469. Args:
  1470. app_name: The name of the app.
  1471. template: The name of the template to use.
  1472. Returns:
  1473. The name of the template.
  1474. Raises:
  1475. Exit: If the template is not valid or unspecified.
  1476. """
  1477. # Local imports to avoid circular imports.
  1478. from reflex.utils import telemetry
  1479. # Check if the app is already initialized.
  1480. if constants.Config.FILE.exists():
  1481. telemetry.send("reinit")
  1482. return
  1483. templates: dict[str, Template] = {}
  1484. # Don't fetch app templates if the user directly asked for DEFAULT.
  1485. if template is not None and (template not in (constants.Templates.DEFAULT,)):
  1486. template, templates = fetch_remote_templates(template)
  1487. if template is None:
  1488. template = prompt_for_template_options(get_init_cli_prompt_options())
  1489. if template == constants.Templates.CHOOSE_TEMPLATES:
  1490. redir.reflex_templates()
  1491. raise click.exceptions.Exit(0)
  1492. if template == constants.Templates.AI:
  1493. redir.reflex_build_redirect()
  1494. raise click.exceptions.Exit(0)
  1495. # If the blank template is selected, create a blank app.
  1496. if template == constants.Templates.DEFAULT:
  1497. # Default app creation behavior: a blank app.
  1498. initialize_default_app(app_name)
  1499. else:
  1500. validate_and_create_app_using_remote_template(
  1501. app_name=app_name, template=template, templates=templates
  1502. )
  1503. telemetry.send("init", template=template)
  1504. return template
  1505. def get_init_cli_prompt_options() -> list[Template]:
  1506. """Get the CLI options for initializing a Reflex app.
  1507. Returns:
  1508. The CLI options.
  1509. """
  1510. return [
  1511. Template(
  1512. name=constants.Templates.DEFAULT,
  1513. description="A blank Reflex app.",
  1514. code_url="",
  1515. ),
  1516. Template(
  1517. name=constants.Templates.AI,
  1518. description="[bold]Try our free AI builder.",
  1519. code_url="",
  1520. ),
  1521. Template(
  1522. name=constants.Templates.CHOOSE_TEMPLATES,
  1523. description="Premade templates built by the Reflex team.",
  1524. code_url="",
  1525. ),
  1526. ]
  1527. def initialize_main_module_index_from_generation(app_name: str, generation_hash: str):
  1528. """Overwrite the `index` function in the main module with reflex.build generated code.
  1529. Args:
  1530. app_name: The name of the app.
  1531. generation_hash: The generation hash from reflex.build.
  1532. Raises:
  1533. GeneratedCodeHasNoFunctionDefsError: If the fetched code has no function definitions
  1534. (the refactored reflex code is expected to have at least one root function defined).
  1535. """
  1536. # Download the reflex code for the generation.
  1537. url = constants.Templates.REFLEX_BUILD_CODE_URL.format(
  1538. generation_hash=generation_hash
  1539. )
  1540. resp = net.get(url)
  1541. while resp.status_code == httpx.codes.SERVICE_UNAVAILABLE:
  1542. console.debug("Waiting for the code to be generated...")
  1543. time.sleep(1)
  1544. resp = net.get(url)
  1545. resp.raise_for_status()
  1546. # Determine the name of the last function, which renders the generated code.
  1547. defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text)
  1548. if not defined_funcs:
  1549. raise GeneratedCodeHasNoFunctionDefsError(
  1550. f"No function definitions found in generated code from {url!r}."
  1551. )
  1552. render_func_name = defined_funcs[-1]
  1553. def replace_content(_match: re.Match) -> str:
  1554. return "\n".join(
  1555. [
  1556. resp.text,
  1557. "",
  1558. "def index() -> rx.Component:",
  1559. f" return {render_func_name}()",
  1560. "",
  1561. "",
  1562. ],
  1563. )
  1564. main_module_path = Path(app_name, app_name + constants.Ext.PY)
  1565. main_module_code = main_module_path.read_text()
  1566. main_module_code = re.sub(
  1567. r"def index\(\).*:\n([^\n]\s+.*\n+)+",
  1568. replace_content,
  1569. main_module_code,
  1570. )
  1571. # Make the app use light mode until flexgen enforces the conversion of
  1572. # tailwind colors to radix colors.
  1573. main_module_code = re.sub(
  1574. r"app\s*=\s*rx\.App\(\s*\)",
  1575. 'app = rx.App(theme=rx.theme(color_mode="light"))',
  1576. main_module_code,
  1577. )
  1578. main_module_path.write_text(main_module_code)
  1579. def format_address_width(address_width: str | None) -> int | None:
  1580. """Cast address width to an int.
  1581. Args:
  1582. address_width: The address width.
  1583. Returns:
  1584. Address width int
  1585. """
  1586. try:
  1587. return int(address_width) if address_width else None
  1588. except ValueError:
  1589. return None
  1590. def _retrieve_cpu_info() -> CpuInfo | None:
  1591. """Retrieve the CPU info of the host.
  1592. Returns:
  1593. The CPU info.
  1594. """
  1595. platform_os = platform.system()
  1596. cpuinfo = {}
  1597. try:
  1598. if platform_os == "Windows":
  1599. cmd = 'powershell -Command "Get-CimInstance Win32_Processor | Select-Object -First 1 | Select-Object AddressWidth,Manufacturer,Name | ConvertTo-Json"'
  1600. output = processes.execute_command_and_return_output(cmd)
  1601. if output:
  1602. cpu_data = json.loads(output)
  1603. cpuinfo["address_width"] = cpu_data["AddressWidth"]
  1604. cpuinfo["manufacturer_id"] = cpu_data["Manufacturer"]
  1605. cpuinfo["model_name"] = cpu_data["Name"]
  1606. elif platform_os == "Linux":
  1607. output = processes.execute_command_and_return_output("lscpu")
  1608. if output:
  1609. lines = output.split("\n")
  1610. for line in lines:
  1611. if "Architecture" in line:
  1612. cpuinfo["address_width"] = (
  1613. 64 if line.split(":")[1].strip() == "x86_64" else 32
  1614. )
  1615. if "Vendor ID:" in line:
  1616. cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
  1617. if "Model name" in line:
  1618. cpuinfo["model_name"] = line.split(":")[1].strip()
  1619. elif platform_os == "Darwin":
  1620. cpuinfo["address_width"] = format_address_width(
  1621. processes.execute_command_and_return_output("getconf LONG_BIT")
  1622. )
  1623. cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
  1624. "sysctl -n machdep.cpu.brand_string"
  1625. )
  1626. cpuinfo["model_name"] = processes.execute_command_and_return_output(
  1627. "uname -m"
  1628. )
  1629. except Exception as err:
  1630. console.error(f"Failed to retrieve CPU info. {err}")
  1631. return None
  1632. return (
  1633. CpuInfo(
  1634. manufacturer_id=cpuinfo.get("manufacturer_id"),
  1635. model_name=cpuinfo.get("model_name"),
  1636. address_width=cpuinfo.get("address_width"),
  1637. )
  1638. if cpuinfo
  1639. else None
  1640. )
  1641. @functools.cache
  1642. def get_cpu_info() -> CpuInfo | None:
  1643. """Get the CPU info of the underlining host.
  1644. Returns:
  1645. The CPU info.
  1646. """
  1647. cpu_info_file = environment.REFLEX_DIR.get() / "cpu_info.json"
  1648. if cpu_info_file.exists() and (cpu_info := json.loads(cpu_info_file.read_text())):
  1649. return CpuInfo(**cpu_info)
  1650. cpu_info = _retrieve_cpu_info()
  1651. if cpu_info:
  1652. cpu_info_file.parent.mkdir(parents=True, exist_ok=True)
  1653. cpu_info_file.write_text(json.dumps(dataclasses.asdict(cpu_info)))
  1654. return cpu_info
  1655. def is_generation_hash(template: str) -> bool:
  1656. """Check if the template looks like a generation hash.
  1657. Args:
  1658. template: The template name.
  1659. Returns:
  1660. True if the template is composed of 32 or more hex characters.
  1661. """
  1662. return re.match(r"^[0-9a-f]{32,}$", template) is not None
  1663. def get_user_tier():
  1664. """Get the current user's tier.
  1665. Returns:
  1666. The current user's tier.
  1667. """
  1668. from reflex_cli.v2.utils import hosting
  1669. authenticated_token = hosting.authenticated_token()
  1670. return (
  1671. authenticated_token[1].get("tier", "").lower()
  1672. if authenticated_token[0]
  1673. else "anonymous"
  1674. )