prerequisites.py 65 KB

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