prerequisites.py 64 KB

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