prerequisites.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  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 json
  9. import os
  10. import platform
  11. import random
  12. import re
  13. import shutil
  14. import stat
  15. import sys
  16. import tempfile
  17. import time
  18. import typing
  19. import zipfile
  20. from datetime import datetime
  21. from pathlib import Path
  22. from types import ModuleType
  23. from typing import Callable, List, NamedTuple, Optional
  24. import httpx
  25. import typer
  26. from alembic.util.exc import CommandError
  27. from packaging import version
  28. from redis import Redis as RedisSync
  29. from redis.asyncio import Redis
  30. from redis.exceptions import RedisError
  31. from reflex import constants, model
  32. from reflex.compiler import templates
  33. from reflex.config import Config, environment, get_config
  34. from reflex.utils import console, net, path_ops, processes, redir
  35. from reflex.utils.exceptions import (
  36. GeneratedCodeHasNoFunctionDefs,
  37. raise_system_package_missing_error,
  38. )
  39. from reflex.utils.format import format_library_name
  40. from reflex.utils.registry import _get_npm_registry
  41. if typing.TYPE_CHECKING:
  42. from reflex.app import App
  43. CURRENTLY_INSTALLING_NODE = False
  44. class AppInfo(NamedTuple):
  45. """A tuple containing the app instance and module."""
  46. app: App
  47. module: ModuleType
  48. @dataclasses.dataclass(frozen=True)
  49. class Template:
  50. """A template for a Reflex app."""
  51. name: str
  52. description: str
  53. code_url: str
  54. demo_url: str
  55. @dataclasses.dataclass(frozen=True)
  56. class CpuInfo:
  57. """Model to save cpu info."""
  58. manufacturer_id: Optional[str]
  59. model_name: Optional[str]
  60. address_width: Optional[int]
  61. def get_web_dir() -> Path:
  62. """Get the working directory for the next.js commands.
  63. Can be overridden with REFLEX_WEB_WORKDIR.
  64. Returns:
  65. The working directory.
  66. """
  67. return environment.REFLEX_WEB_WORKDIR.get()
  68. def _python_version_check():
  69. """Emit deprecation warning for deprecated python versions."""
  70. # Check for end-of-life python versions.
  71. if sys.version_info < (3, 10):
  72. console.deprecate(
  73. feature_name="Support for Python 3.9 and older",
  74. reason="please upgrade to Python 3.10 or newer",
  75. deprecation_version="0.6.0",
  76. removal_version="0.7.0",
  77. )
  78. def check_latest_package_version(package_name: str):
  79. """Check if the latest version of the package is installed.
  80. Args:
  81. package_name: The name of the package.
  82. """
  83. if environment.REFLEX_CHECK_LATEST_VERSION.get() is False:
  84. return
  85. try:
  86. # Get the latest version from PyPI
  87. current_version = importlib.metadata.version(package_name)
  88. url = f"https://pypi.org/pypi/{package_name}/json"
  89. response = net.get(url)
  90. latest_version = response.json()["info"]["version"]
  91. if get_or_set_last_reflex_version_check_datetime():
  92. # Versions were already checked and saved in reflex.json, no need to warn again
  93. return
  94. if version.parse(current_version) < version.parse(latest_version):
  95. # Show a warning when the host version is older than PyPI version
  96. console.warn(
  97. f"Your version ({current_version}) of {package_name} is out of date. Upgrade to {latest_version} with 'pip install {package_name} --upgrade'"
  98. )
  99. # Check for deprecated python versions
  100. _python_version_check()
  101. except Exception:
  102. pass
  103. def get_or_set_last_reflex_version_check_datetime():
  104. """Get the last time a check was made for the latest reflex version.
  105. This is typically useful for cases where the host reflex version is
  106. less than that on Pypi.
  107. Returns:
  108. The last version check datetime.
  109. """
  110. reflex_json_file = get_web_dir() / constants.Reflex.JSON
  111. if not reflex_json_file.exists():
  112. return None
  113. # Open and read the file
  114. data = json.loads(reflex_json_file.read_text())
  115. last_version_check_datetime = data.get("last_version_check_datetime")
  116. if not last_version_check_datetime:
  117. data.update({"last_version_check_datetime": str(datetime.now())})
  118. path_ops.update_json_file(reflex_json_file, data)
  119. return last_version_check_datetime
  120. def set_last_reflex_run_time():
  121. """Set the last Reflex run time."""
  122. path_ops.update_json_file(
  123. get_web_dir() / constants.Reflex.JSON,
  124. {"last_reflex_run_datetime": str(datetime.now())},
  125. )
  126. def check_node_version() -> bool:
  127. """Check the version of Node.js.
  128. Returns:
  129. Whether the version of Node.js is valid.
  130. """
  131. current_version = get_node_version()
  132. return current_version is not None and current_version >= version.parse(
  133. constants.Node.MIN_VERSION
  134. )
  135. def get_node_version() -> version.Version | None:
  136. """Get the version of node.
  137. Returns:
  138. The version of node.
  139. """
  140. node_path = path_ops.get_node_path()
  141. if node_path is None:
  142. return None
  143. try:
  144. result = processes.new_process([node_path, "-v"], run=True)
  145. # The output will be in the form "vX.Y.Z", but version.parse() can handle it
  146. return version.parse(result.stdout) # type: ignore
  147. except (FileNotFoundError, TypeError):
  148. return None
  149. def get_fnm_version() -> version.Version | None:
  150. """Get the version of fnm.
  151. Returns:
  152. The version of FNM.
  153. """
  154. try:
  155. result = processes.new_process([constants.Fnm.EXE, "--version"], run=True)
  156. return version.parse(result.stdout.split(" ")[1]) # type: ignore
  157. except (FileNotFoundError, TypeError):
  158. return None
  159. except version.InvalidVersion as e:
  160. console.warn(
  161. f"The detected fnm version ({e.args[0]}) is not valid. Defaulting to None."
  162. )
  163. return None
  164. def get_bun_version() -> version.Version | None:
  165. """Get the version of bun.
  166. Returns:
  167. The version of bun.
  168. """
  169. try:
  170. # Run the bun -v command and capture the output
  171. result = processes.new_process([str(get_config().bun_path), "-v"], run=True)
  172. return version.parse(result.stdout) # type: ignore
  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 create_config(app_name: str):
  376. """Create a new rxconfig file.
  377. Args:
  378. app_name: The name of the app.
  379. """
  380. # Import here to avoid circular imports.
  381. from reflex.compiler import templates
  382. config_name = f"{re.sub(r'[^a-zA-Z]', '', app_name).capitalize()}Config"
  383. console.debug(f"Creating {constants.Config.FILE}")
  384. constants.Config.FILE.write_text(
  385. templates.RXCONFIG.render(app_name=app_name, config_name=config_name)
  386. )
  387. def initialize_gitignore(
  388. gitignore_file: Path = constants.GitIgnore.FILE,
  389. files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS,
  390. ):
  391. """Initialize the template .gitignore file.
  392. Args:
  393. gitignore_file: The .gitignore file to create.
  394. files_to_ignore: The files to add to the .gitignore file.
  395. """
  396. # Combine with the current ignored files.
  397. current_ignore: list[str] = []
  398. if gitignore_file.exists():
  399. current_ignore = [ln.strip() for ln in gitignore_file.read_text().splitlines()]
  400. if files_to_ignore == current_ignore:
  401. console.debug(f"{gitignore_file} already up to date.")
  402. return
  403. files_to_ignore = [ln for ln in files_to_ignore if ln not in current_ignore]
  404. files_to_ignore += current_ignore
  405. # Write files to the .gitignore file.
  406. gitignore_file.touch(exist_ok=True)
  407. console.debug(f"Creating {gitignore_file}")
  408. gitignore_file.write_text("\n".join(files_to_ignore) + "\n")
  409. def initialize_requirements_txt():
  410. """Initialize the requirements.txt file.
  411. If absent, generate one for the user.
  412. If the requirements.txt does not have reflex as dependency,
  413. generate a requirement pinning current version and append to
  414. the requirements.txt file.
  415. """
  416. fp = Path(constants.RequirementsTxt.FILE)
  417. encoding = "utf-8"
  418. if not fp.exists():
  419. fp.touch()
  420. else:
  421. # Detect the encoding of the original file
  422. import charset_normalizer
  423. charset_matches = charset_normalizer.from_path(fp)
  424. maybe_charset_match = charset_matches.best()
  425. if maybe_charset_match is None:
  426. console.debug(f"Unable to detect encoding for {fp}, exiting.")
  427. return
  428. encoding = maybe_charset_match.encoding
  429. console.debug(f"Detected encoding for {fp} as {encoding}.")
  430. try:
  431. other_requirements_exist = False
  432. with fp.open("r", encoding=encoding) as f:
  433. for req in f:
  434. # Check if we have a package name that is reflex
  435. if re.match(r"^reflex[^a-zA-Z0-9]", req):
  436. console.debug(f"{fp} already has reflex as dependency.")
  437. return
  438. other_requirements_exist = True
  439. with fp.open("a", encoding=encoding) as f:
  440. preceding_newline = "\n" if other_requirements_exist else ""
  441. f.write(
  442. f"{preceding_newline}{constants.RequirementsTxt.DEFAULTS_STUB}{constants.Reflex.VERSION}\n"
  443. )
  444. except Exception:
  445. console.info(f"Unable to check {fp} for reflex dependency.")
  446. def initialize_app_directory(
  447. app_name: str,
  448. template_name: str = constants.Templates.DEFAULT,
  449. template_code_dir_name: str | None = None,
  450. template_dir: Path | None = None,
  451. ):
  452. """Initialize the app directory on reflex init.
  453. Args:
  454. app_name: The name of the app.
  455. template_name: The name of the template to use.
  456. template_code_dir_name: The name of the code directory in the template.
  457. template_dir: The directory of the template source files.
  458. Raises:
  459. Exit: If template_name, template_code_dir_name, template_dir combination is not supported.
  460. """
  461. console.log("Initializing the app directory.")
  462. # By default, use the blank template from local assets.
  463. if template_name == constants.Templates.DEFAULT:
  464. if template_code_dir_name is not None or template_dir is not None:
  465. console.error(
  466. f"Only {template_name=} should be provided, got {template_code_dir_name=}, {template_dir=}."
  467. )
  468. raise typer.Exit(1)
  469. template_code_dir_name = constants.Templates.Dirs.CODE
  470. template_dir = Path(constants.Templates.Dirs.BASE, "apps", template_name)
  471. else:
  472. if template_code_dir_name is None or template_dir is None:
  473. console.error(
  474. f"For `{template_name}` template, `template_code_dir_name` and `template_dir` should both be provided."
  475. )
  476. raise typer.Exit(1)
  477. console.debug(f"Using {template_name=} {template_dir=} {template_code_dir_name=}.")
  478. # Remove all pyc and __pycache__ dirs in template directory.
  479. for pyc_file in template_dir.glob("**/*.pyc"):
  480. pyc_file.unlink()
  481. for pycache_dir in template_dir.glob("**/__pycache__"):
  482. pycache_dir.rmdir()
  483. for file in template_dir.iterdir():
  484. # Copy the file to current directory but keep the name the same.
  485. path_ops.cp(str(file), file.name)
  486. # Rename the template app to the app name.
  487. path_ops.mv(template_code_dir_name, app_name)
  488. path_ops.mv(
  489. Path(app_name) / (template_name + constants.Ext.PY),
  490. Path(app_name) / (app_name + constants.Ext.PY),
  491. )
  492. # Fix up the imports.
  493. path_ops.find_replace(
  494. app_name,
  495. f"from {template_name}",
  496. f"from {app_name}",
  497. )
  498. def get_project_hash(raise_on_fail: bool = False) -> int | None:
  499. """Get the project hash from the reflex.json file if the file exists.
  500. Args:
  501. raise_on_fail: Whether to raise an error if the file does not exist.
  502. Returns:
  503. project_hash: The app hash.
  504. """
  505. json_file = get_web_dir() / constants.Reflex.JSON
  506. if not json_file.exists() and not raise_on_fail:
  507. return None
  508. data = json.loads(json_file.read_text())
  509. return data.get("project_hash")
  510. def initialize_web_directory():
  511. """Initialize the web directory on reflex init."""
  512. console.log("Initializing the web directory.")
  513. # Reuse the hash if one is already created, so we don't over-write it when running reflex init
  514. project_hash = get_project_hash()
  515. path_ops.cp(constants.Templates.Dirs.WEB_TEMPLATE, str(get_web_dir()))
  516. initialize_package_json()
  517. initialize_bun_config()
  518. path_ops.mkdir(get_web_dir() / constants.Dirs.PUBLIC)
  519. update_next_config()
  520. # Initialize the reflex json file.
  521. init_reflex_json(project_hash=project_hash)
  522. def _turbopack_flag() -> str:
  523. return " --turbopack" if environment.REFLEX_USE_TURBOPACK.get() else ""
  524. def _compile_package_json():
  525. return templates.PACKAGE_JSON.render(
  526. scripts={
  527. "dev": constants.PackageJson.Commands.DEV + _turbopack_flag(),
  528. "export": constants.PackageJson.Commands.EXPORT,
  529. "export_sitemap": constants.PackageJson.Commands.EXPORT_SITEMAP,
  530. "prod": constants.PackageJson.Commands.PROD,
  531. },
  532. dependencies=constants.PackageJson.DEPENDENCIES,
  533. dev_dependencies=constants.PackageJson.DEV_DEPENDENCIES,
  534. )
  535. def initialize_package_json():
  536. """Render and write in .web the package.json file."""
  537. output_path = get_web_dir() / constants.PackageJson.PATH
  538. output_path.write_text(_compile_package_json())
  539. def initialize_bun_config():
  540. """Initialize the bun config file."""
  541. bun_config_path = get_web_dir() / constants.Bun.CONFIG_PATH
  542. if (custom_bunfig := Path(constants.Bun.CONFIG_PATH)).exists():
  543. bunfig_content = custom_bunfig.read_text()
  544. console.info(f"Copying custom bunfig.toml inside {get_web_dir()} folder")
  545. else:
  546. best_registry = _get_npm_registry()
  547. bunfig_content = constants.Bun.DEFAULT_CONFIG.format(registry=best_registry)
  548. bun_config_path.write_text(bunfig_content)
  549. def init_reflex_json(project_hash: int | None):
  550. """Write the hash of the Reflex project to a REFLEX_JSON.
  551. Reuse the hash if one is already created, therefore do not
  552. overwrite it every time we run the reflex init command
  553. .
  554. Args:
  555. project_hash: The app hash.
  556. """
  557. if project_hash is not None:
  558. console.debug(f"Project hash is already set to {project_hash}.")
  559. else:
  560. # Get a random project hash.
  561. project_hash = random.getrandbits(128)
  562. console.debug(f"Setting project hash to {project_hash}.")
  563. # Write the hash and version to the reflex json file.
  564. reflex_json = {
  565. "version": constants.Reflex.VERSION,
  566. "project_hash": project_hash,
  567. }
  568. path_ops.update_json_file(get_web_dir() / constants.Reflex.JSON, reflex_json)
  569. def update_next_config(export=False, transpile_packages: Optional[List[str]] = None):
  570. """Update Next.js config from Reflex config.
  571. Args:
  572. export: if the method run during reflex export.
  573. transpile_packages: list of packages to transpile via next.config.js.
  574. """
  575. next_config_file = get_web_dir() / constants.Next.CONFIG_FILE
  576. next_config = _update_next_config(
  577. get_config(), export=export, transpile_packages=transpile_packages
  578. )
  579. # Overwriting the next.config.js triggers a full server reload, so make sure
  580. # there is actually a diff.
  581. orig_next_config = next_config_file.read_text() if next_config_file.exists() else ""
  582. if orig_next_config != next_config:
  583. next_config_file.write_text(next_config)
  584. def _update_next_config(
  585. config: Config, export: bool = False, transpile_packages: Optional[List[str]] = None
  586. ):
  587. next_config = {
  588. "basePath": config.frontend_path or "",
  589. "compress": config.next_compression,
  590. "reactStrictMode": config.react_strict_mode,
  591. "trailingSlash": True,
  592. "staticPageGenerationTimeout": config.static_page_generation_timeout,
  593. }
  594. if transpile_packages:
  595. next_config["transpilePackages"] = list(
  596. {format_library_name(p) for p in transpile_packages}
  597. )
  598. if export:
  599. next_config["output"] = "export"
  600. next_config["distDir"] = constants.Dirs.STATIC
  601. next_config_json = re.sub(r'"([^"]+)"(?=:)', r"\1", json.dumps(next_config))
  602. return f"module.exports = {next_config_json};"
  603. def remove_existing_bun_installation():
  604. """Remove existing bun installation."""
  605. console.debug("Removing existing bun installation.")
  606. if Path(get_config().bun_path).exists():
  607. path_ops.rm(constants.Bun.ROOT_PATH)
  608. def download_and_run(url: str, *args, show_status: bool = False, **env):
  609. """Download and run a script.
  610. Args:
  611. url: The url of the script.
  612. args: The arguments to pass to the script.
  613. show_status: Whether to show the status of the script.
  614. env: The environment variables to use.
  615. """
  616. # Download the script
  617. console.debug(f"Downloading {url}")
  618. response = net.get(url)
  619. if response.status_code != httpx.codes.OK:
  620. response.raise_for_status()
  621. # Save the script to a temporary file.
  622. script = Path(tempfile.NamedTemporaryFile().name)
  623. script.write_text(response.text)
  624. # Run the script.
  625. env = {**os.environ, **env}
  626. process = processes.new_process(["bash", str(script), *args], env=env)
  627. show = processes.show_status if show_status else processes.show_logs
  628. show(f"Installing {url}", process)
  629. def download_and_extract_fnm_zip():
  630. """Download and run a script.
  631. Raises:
  632. Exit: If an error occurs while downloading or extracting the FNM zip.
  633. """
  634. # Download the zip file
  635. url = constants.Fnm.INSTALL_URL
  636. console.debug(f"Downloading {url}")
  637. fnm_zip_file: Path = constants.Fnm.DIR / f"{constants.Fnm.FILENAME}.zip"
  638. # Function to download and extract the FNM zip release.
  639. try:
  640. # Download the FNM zip release.
  641. # TODO: show progress to improve UX
  642. response = net.get(url, follow_redirects=True)
  643. response.raise_for_status()
  644. with fnm_zip_file.open("wb") as output_file:
  645. for chunk in response.iter_bytes():
  646. output_file.write(chunk)
  647. # Extract the downloaded zip file.
  648. with zipfile.ZipFile(fnm_zip_file, "r") as zip_ref:
  649. zip_ref.extractall(constants.Fnm.DIR)
  650. console.debug("FNM package downloaded and extracted successfully.")
  651. except Exception as e:
  652. console.error(f"An error occurred while downloading fnm package: {e}")
  653. raise typer.Exit(1) from e
  654. finally:
  655. # Clean up the downloaded zip file.
  656. path_ops.rm(fnm_zip_file)
  657. def install_node():
  658. """Install fnm and nodejs for use by Reflex.
  659. Independent of any existing system installations.
  660. """
  661. if not constants.Fnm.FILENAME:
  662. # fnm only support Linux, macOS and Windows distros.
  663. console.debug("")
  664. return
  665. # Skip installation if check_node_version() checks out
  666. if check_node_version():
  667. console.debug("Skipping node installation as it is already installed.")
  668. return
  669. path_ops.mkdir(constants.Fnm.DIR)
  670. if not constants.Fnm.EXE.exists():
  671. download_and_extract_fnm_zip()
  672. if constants.IS_WINDOWS:
  673. # Install node
  674. fnm_exe = Path(constants.Fnm.EXE).resolve()
  675. fnm_dir = Path(constants.Fnm.DIR).resolve()
  676. process = processes.new_process(
  677. [
  678. "powershell",
  679. "-Command",
  680. f'& "{fnm_exe}" install {constants.Node.VERSION} --fnm-dir "{fnm_dir}"',
  681. ],
  682. )
  683. else: # All other platforms (Linux, MacOS).
  684. # Add execute permissions to fnm executable.
  685. constants.Fnm.EXE.chmod(stat.S_IXUSR)
  686. # Install node.
  687. # Specify arm64 arch explicitly for M1s and M2s.
  688. architecture_arg = (
  689. ["--arch=arm64"]
  690. if platform.system() == "Darwin" and platform.machine() == "arm64"
  691. else []
  692. )
  693. process = processes.new_process(
  694. [
  695. constants.Fnm.EXE,
  696. "install",
  697. *architecture_arg,
  698. constants.Node.VERSION,
  699. "--fnm-dir",
  700. constants.Fnm.DIR,
  701. ],
  702. )
  703. processes.show_status("Installing node", process)
  704. def install_bun():
  705. """Install bun onto the user's system."""
  706. win_supported = is_windows_bun_supported()
  707. one_drive_in_path = windows_check_onedrive_in_path()
  708. if constants.IS_WINDOWS and (not win_supported or one_drive_in_path):
  709. if not win_supported:
  710. console.warn(
  711. "Bun for Windows is currently only available for x86 64-bit Windows. Installation will fall back on npm."
  712. )
  713. if one_drive_in_path:
  714. console.warn(
  715. "Creating project directories in OneDrive is not recommended for bun usage on windows. This will fallback to npm."
  716. )
  717. # Skip if bun is already installed.
  718. if Path(get_config().bun_path).exists() and get_bun_version() == version.parse(
  719. constants.Bun.VERSION
  720. ):
  721. console.debug("Skipping bun installation as it is already installed.")
  722. return
  723. # if unzip is installed
  724. if constants.IS_WINDOWS:
  725. processes.new_process(
  726. [
  727. "powershell",
  728. "-c",
  729. f"irm {constants.Bun.WINDOWS_INSTALL_URL}|iex",
  730. ],
  731. env={
  732. "BUN_INSTALL": str(constants.Bun.ROOT_PATH),
  733. "BUN_VERSION": constants.Bun.VERSION,
  734. },
  735. shell=True,
  736. run=True,
  737. show_logs=console.is_debug(),
  738. )
  739. else:
  740. unzip_path = path_ops.which("unzip")
  741. if unzip_path is None:
  742. raise_system_package_missing_error("unzip")
  743. # Run the bun install script.
  744. download_and_run(
  745. constants.Bun.INSTALL_URL,
  746. f"bun-v{constants.Bun.VERSION}",
  747. BUN_INSTALL=str(constants.Bun.ROOT_PATH),
  748. )
  749. def _write_cached_procedure_file(payload: str, cache_file: str | Path):
  750. cache_file = Path(cache_file)
  751. cache_file.write_text(payload)
  752. def _read_cached_procedure_file(cache_file: str | Path) -> str | None:
  753. cache_file = Path(cache_file)
  754. if cache_file.exists():
  755. return cache_file.read_text()
  756. return None
  757. def _clear_cached_procedure_file(cache_file: str | Path):
  758. cache_file = Path(cache_file)
  759. if cache_file.exists():
  760. cache_file.unlink()
  761. def cached_procedure(cache_file: str, payload_fn: Callable[..., str]):
  762. """Decorator to cache the runs of a procedure on disk. Procedures should not have
  763. a return value.
  764. Args:
  765. cache_file: The file to store the cache payload in.
  766. payload_fn: Function that computes cache payload from function args
  767. Returns:
  768. The decorated function.
  769. """
  770. def _inner_decorator(func):
  771. def _inner(*args, **kwargs):
  772. payload = _read_cached_procedure_file(cache_file)
  773. new_payload = payload_fn(*args, **kwargs)
  774. if payload != new_payload:
  775. _clear_cached_procedure_file(cache_file)
  776. func(*args, **kwargs)
  777. _write_cached_procedure_file(new_payload, cache_file)
  778. return _inner
  779. return _inner_decorator
  780. @cached_procedure(
  781. cache_file=str(get_web_dir() / "reflex.install_frontend_packages.cached"),
  782. payload_fn=lambda p, c: f"{sorted(p)!r},{c.json()}",
  783. )
  784. def install_frontend_packages(packages: set[str], config: Config):
  785. """Installs the base and custom frontend packages.
  786. Args:
  787. packages: A list of package names to be installed.
  788. config: The config object.
  789. Raises:
  790. FileNotFoundError: If the package manager is not found.
  791. Example:
  792. >>> install_frontend_packages(["react", "react-dom"], get_config())
  793. """
  794. # unsupported archs(arm and 32bit machines) will use npm anyway. so we dont have to run npm twice
  795. fallback_command = (
  796. get_package_manager(on_failure_return_none=True)
  797. if (
  798. not constants.IS_WINDOWS
  799. or (
  800. constants.IS_WINDOWS
  801. and (
  802. is_windows_bun_supported() and not windows_check_onedrive_in_path()
  803. )
  804. )
  805. )
  806. else None
  807. )
  808. install_package_manager = (
  809. get_install_package_manager(on_failure_return_none=True) or fallback_command
  810. )
  811. if install_package_manager is None:
  812. raise FileNotFoundError(
  813. "Could not find a package manager to install frontend packages. You may need to run `reflex init`."
  814. )
  815. fallback_command = (
  816. fallback_command if fallback_command is not install_package_manager else None
  817. )
  818. processes.run_process_with_fallback(
  819. [install_package_manager, "install"], # type: ignore
  820. fallback=fallback_command,
  821. analytics_enabled=True,
  822. show_status_message="Installing base frontend packages",
  823. cwd=get_web_dir(),
  824. shell=constants.IS_WINDOWS,
  825. )
  826. if config.tailwind is not None:
  827. processes.run_process_with_fallback(
  828. [
  829. install_package_manager,
  830. "add",
  831. "-d",
  832. constants.Tailwind.VERSION,
  833. *((config.tailwind or {}).get("plugins", [])),
  834. ],
  835. fallback=fallback_command,
  836. analytics_enabled=True,
  837. show_status_message="Installing tailwind",
  838. cwd=get_web_dir(),
  839. shell=constants.IS_WINDOWS,
  840. )
  841. # Install custom packages defined in frontend_packages
  842. if len(packages) > 0:
  843. processes.run_process_with_fallback(
  844. [install_package_manager, "add", *packages],
  845. fallback=fallback_command,
  846. analytics_enabled=True,
  847. show_status_message="Installing frontend packages from config and components",
  848. cwd=get_web_dir(),
  849. shell=constants.IS_WINDOWS,
  850. )
  851. def needs_reinit(frontend: bool = True) -> bool:
  852. """Check if an app needs to be reinitialized.
  853. Args:
  854. frontend: Whether to check if the frontend is initialized.
  855. Returns:
  856. Whether the app needs to be reinitialized.
  857. Raises:
  858. Exit: If the app is not initialized.
  859. """
  860. if not constants.Config.FILE.exists():
  861. console.error(
  862. 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."
  863. )
  864. raise typer.Exit(1)
  865. # Don't need to reinit if not running in frontend mode.
  866. if not frontend:
  867. return False
  868. # Make sure the .reflex directory exists.
  869. if not environment.REFLEX_DIR.get().exists():
  870. return True
  871. # Make sure the .web directory exists in frontend mode.
  872. if not get_web_dir().exists():
  873. return True
  874. # If the template is out of date, then we need to re-init
  875. if not is_latest_template():
  876. return True
  877. if constants.IS_WINDOWS:
  878. console.warn(
  879. """Windows Subsystem for Linux (WSL) is recommended for improving initial install times."""
  880. )
  881. if windows_check_onedrive_in_path():
  882. console.warn(
  883. "Creating project directories in OneDrive may lead to performance issues. For optimal performance, It is recommended to avoid using OneDrive for your reflex app."
  884. )
  885. # No need to reinitialize if the app is already initialized.
  886. return False
  887. def is_latest_template() -> bool:
  888. """Whether the app is using the latest template.
  889. Returns:
  890. Whether the app is using the latest template.
  891. """
  892. json_file = get_web_dir() / constants.Reflex.JSON
  893. if not json_file.exists():
  894. return False
  895. app_version = json.loads(json_file.read_text()).get("version")
  896. return app_version == constants.Reflex.VERSION
  897. def validate_bun():
  898. """Validate bun if a custom bun path is specified to ensure the bun version meets requirements.
  899. Raises:
  900. Exit: If custom specified bun does not exist or does not meet requirements.
  901. """
  902. # if a custom bun path is provided, make sure its valid
  903. # This is specific to non-FHS OS
  904. bun_path = get_config().bun_path
  905. if path_ops.use_system_bun():
  906. bun_path = path_ops.which("bun")
  907. if bun_path != constants.Bun.DEFAULT_PATH:
  908. console.info(f"Using custom Bun path: {bun_path}")
  909. bun_version = get_bun_version()
  910. if not bun_version:
  911. console.error(
  912. "Failed to obtain bun version. Make sure the specified bun path in your config is correct."
  913. )
  914. raise typer.Exit(1)
  915. elif bun_version < version.parse(constants.Bun.MIN_VERSION):
  916. console.error(
  917. f"Reflex requires bun version {constants.Bun.VERSION} or higher to run, but the detected version is "
  918. f"{bun_version}. If you have specified a custom bun path in your config, make sure to provide one "
  919. f"that satisfies the minimum version requirement."
  920. )
  921. raise typer.Exit(1)
  922. def validate_frontend_dependencies(init=True):
  923. """Validate frontend dependencies to ensure they meet requirements.
  924. Args:
  925. init: whether running `reflex init`
  926. Raises:
  927. Exit: If the package manager is invalid.
  928. """
  929. if not init:
  930. # we only need to validate the package manager when running app.
  931. # `reflex init` will install the deps anyway(if applied).
  932. package_manager = get_package_manager()
  933. if not package_manager:
  934. console.error(
  935. "Could not find NPM package manager. Make sure you have node installed."
  936. )
  937. raise typer.Exit(1)
  938. if not check_node_version():
  939. node_version = get_node_version()
  940. console.error(
  941. f"Reflex requires node version {constants.Node.MIN_VERSION} or higher to run, but the detected version is {node_version}",
  942. )
  943. raise typer.Exit(1)
  944. if init:
  945. # we only need bun for package install on `reflex init`.
  946. validate_bun()
  947. def ensure_reflex_installation_id() -> Optional[int]:
  948. """Ensures that a reflex distinct id has been generated and stored in the reflex directory.
  949. Returns:
  950. Distinct id.
  951. """
  952. try:
  953. initialize_reflex_user_directory()
  954. installation_id_file = environment.REFLEX_DIR.get() / "installation_id"
  955. installation_id = None
  956. if installation_id_file.exists():
  957. with contextlib.suppress(Exception):
  958. installation_id = int(installation_id_file.read_text())
  959. # If anything goes wrong at all... just regenerate.
  960. # Like what? Examples:
  961. # - file not exists
  962. # - file not readable
  963. # - content not parseable as an int
  964. if installation_id is None:
  965. installation_id = random.getrandbits(128)
  966. installation_id_file.write_text(str(installation_id))
  967. except Exception as e:
  968. console.debug(f"Failed to ensure reflex installation id: {e}")
  969. return None
  970. else:
  971. # If we get here, installation_id is definitely set
  972. return installation_id
  973. def initialize_reflex_user_directory():
  974. """Initialize the reflex user directory."""
  975. # Create the reflex directory.
  976. path_ops.mkdir(environment.REFLEX_DIR.get())
  977. def initialize_frontend_dependencies():
  978. """Initialize all the frontend dependencies."""
  979. # validate dependencies before install
  980. validate_frontend_dependencies()
  981. # Avoid warning about Node installation while we're trying to install it.
  982. global CURRENTLY_INSTALLING_NODE
  983. CURRENTLY_INSTALLING_NODE = True
  984. # Install the frontend dependencies.
  985. processes.run_concurrently(install_node, install_bun)
  986. CURRENTLY_INSTALLING_NODE = False
  987. # Set up the web directory.
  988. initialize_web_directory()
  989. def check_db_used() -> bool:
  990. """Check if the database is used.
  991. Returns:
  992. True if the database is used.
  993. """
  994. return bool(get_config().db_url)
  995. def check_redis_used() -> bool:
  996. """Check if Redis is used.
  997. Returns:
  998. True if Redis is used.
  999. """
  1000. return bool(get_config().redis_url)
  1001. def check_db_initialized() -> bool:
  1002. """Check if the database migrations are initialized.
  1003. Returns:
  1004. True if alembic is initialized (or if database is not used).
  1005. """
  1006. if (
  1007. get_config().db_url is not None
  1008. and not environment.ALEMBIC_CONFIG.get().exists()
  1009. ):
  1010. console.error(
  1011. "Database is not initialized. Run [bold]reflex db init[/bold] first."
  1012. )
  1013. return False
  1014. return True
  1015. def check_schema_up_to_date():
  1016. """Check if the sqlmodel metadata matches the current database schema."""
  1017. if get_config().db_url is None or not environment.ALEMBIC_CONFIG.get().exists():
  1018. return
  1019. with model.Model.get_db_engine().connect() as connection:
  1020. try:
  1021. if model.Model.alembic_autogenerate(
  1022. connection=connection,
  1023. write_migration_scripts=False,
  1024. ):
  1025. console.error(
  1026. "Detected database schema changes. Run [bold]reflex db makemigrations[/bold] "
  1027. "to generate migration scripts.",
  1028. )
  1029. except CommandError as command_error:
  1030. if "Target database is not up to date." in str(command_error):
  1031. console.error(
  1032. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  1033. )
  1034. def prompt_for_template_options(templates: list[Template]) -> str:
  1035. """Prompt the user to specify a template.
  1036. Args:
  1037. templates: The templates to choose from.
  1038. Returns:
  1039. The template name the user selects.
  1040. """
  1041. # Show the user the URLs of each template to preview.
  1042. console.print("\nGet started with a template:")
  1043. def format_demo_url_str(url: str) -> str:
  1044. return f" ({url})" if url else ""
  1045. # Prompt the user to select a template.
  1046. id_to_name = {
  1047. str(
  1048. idx
  1049. ): f"{template.name.replace('_', ' ').replace('-', ' ')}{format_demo_url_str(template.demo_url)} - {template.description}"
  1050. for idx, template in enumerate(templates)
  1051. }
  1052. for id in range(len(id_to_name)):
  1053. console.print(f"({id}) {id_to_name[str(id)]}")
  1054. template = console.ask(
  1055. "Which template would you like to use?",
  1056. choices=[str(i) for i in range(len(id_to_name))],
  1057. show_choices=False,
  1058. default="0",
  1059. )
  1060. # Return the template.
  1061. return templates[int(template)].name
  1062. def fetch_app_templates(version: str) -> dict[str, Template]:
  1063. """Fetch a dict of templates from the templates repo using github API.
  1064. Args:
  1065. version: The version of the templates to fetch.
  1066. Returns:
  1067. The dict of templates.
  1068. """
  1069. def get_release_by_tag(tag: str) -> dict | None:
  1070. response = net.get(constants.Reflex.RELEASES_URL)
  1071. response.raise_for_status()
  1072. releases = response.json()
  1073. for release in releases:
  1074. if release["tag_name"] == f"v{tag}":
  1075. return release
  1076. return None
  1077. release = get_release_by_tag(version)
  1078. if release is None:
  1079. console.warn(f"No templates known for version {version}")
  1080. return {}
  1081. assets = release.get("assets", [])
  1082. asset = next((a for a in assets if a["name"] == "templates.json"), None)
  1083. if asset is None:
  1084. console.warn(f"Templates metadata not found for version {version}")
  1085. return {}
  1086. else:
  1087. templates_url = asset["browser_download_url"]
  1088. templates_data = net.get(templates_url, follow_redirects=True).json()["templates"]
  1089. for template in templates_data:
  1090. if template["name"] == "blank":
  1091. template["code_url"] = ""
  1092. continue
  1093. template["code_url"] = next(
  1094. (
  1095. a["browser_download_url"]
  1096. for a in assets
  1097. if a["name"] == f"{template['name']}.zip"
  1098. ),
  1099. None,
  1100. )
  1101. filtered_templates = {}
  1102. for tp in templates_data:
  1103. if tp["hidden"] or tp["code_url"] is None:
  1104. continue
  1105. known_fields = {f.name for f in dataclasses.fields(Template)}
  1106. filtered_templates[tp["name"]] = Template(
  1107. **{k: v for k, v in tp.items() if k in known_fields}
  1108. )
  1109. return filtered_templates
  1110. def create_config_init_app_from_remote_template(app_name: str, template_url: str):
  1111. """Create new rxconfig and initialize app using a remote template.
  1112. Args:
  1113. app_name: The name of the app.
  1114. template_url: The path to the template source code as a zip file.
  1115. Raises:
  1116. Exit: If any download, file operations fail or unexpected zip file format.
  1117. """
  1118. # Create a temp directory for the zip download.
  1119. try:
  1120. temp_dir = tempfile.mkdtemp()
  1121. except OSError as ose:
  1122. console.error(f"Failed to create temp directory for download: {ose}")
  1123. raise typer.Exit(1) from ose
  1124. # Use httpx GET with redirects to download the zip file.
  1125. zip_file_path: Path = Path(temp_dir) / "template.zip"
  1126. try:
  1127. # Note: following redirects can be risky. We only allow this for reflex built templates at the moment.
  1128. response = net.get(template_url, follow_redirects=True)
  1129. console.debug(f"Server responded download request: {response}")
  1130. response.raise_for_status()
  1131. except httpx.HTTPError as he:
  1132. console.error(f"Failed to download the template: {he}")
  1133. raise typer.Exit(1) from he
  1134. try:
  1135. zip_file_path.write_bytes(response.content)
  1136. console.debug(f"Downloaded the zip to {zip_file_path}")
  1137. except OSError as ose:
  1138. console.error(f"Unable to write the downloaded zip to disk {ose}")
  1139. raise typer.Exit(1) from ose
  1140. # Create a temp directory for the zip extraction.
  1141. try:
  1142. unzip_dir = Path(tempfile.mkdtemp())
  1143. except OSError as ose:
  1144. console.error(f"Failed to create temp directory for extracting zip: {ose}")
  1145. raise typer.Exit(1) from ose
  1146. try:
  1147. zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
  1148. # The zip file downloaded from github looks like:
  1149. # repo-name-branch/**/*, so we need to remove the top level directory.
  1150. except Exception as uze:
  1151. console.error(f"Failed to unzip the template: {uze}")
  1152. raise typer.Exit(1) from uze
  1153. if len(subdirs := os.listdir(unzip_dir)) != 1:
  1154. console.error(f"Expected one directory in the zip, found {subdirs}")
  1155. raise typer.Exit(1)
  1156. template_dir = unzip_dir / subdirs[0]
  1157. console.debug(f"Template folder is located at {template_dir}")
  1158. # Move the rxconfig file here first.
  1159. path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
  1160. new_config = get_config(reload=True)
  1161. # Get the template app's name from rxconfig in case it is different than
  1162. # the source code repo name on github.
  1163. template_name = new_config.app_name
  1164. create_config(app_name)
  1165. initialize_app_directory(
  1166. app_name,
  1167. template_name=template_name,
  1168. template_code_dir_name=template_name,
  1169. template_dir=template_dir,
  1170. )
  1171. req_file = Path("requirements.txt")
  1172. if req_file.exists() and len(req_file.read_text().splitlines()) > 1:
  1173. console.info(
  1174. "Run `pip install -r requirements.txt` to install the required python packages for this template."
  1175. )
  1176. # Clean up the temp directories.
  1177. shutil.rmtree(temp_dir)
  1178. shutil.rmtree(unzip_dir)
  1179. def initialize_default_app(app_name: str):
  1180. """Initialize the default app.
  1181. Args:
  1182. app_name: The name of the app.
  1183. """
  1184. create_config(app_name)
  1185. initialize_app_directory(app_name)
  1186. def validate_and_create_app_using_remote_template(app_name, template, templates):
  1187. """Validate and create an app using a remote template.
  1188. Args:
  1189. app_name: The name of the app.
  1190. template: The name of the template.
  1191. templates: The available templates.
  1192. Raises:
  1193. Exit: If the template is not found.
  1194. """
  1195. # If user selects a template, it needs to exist.
  1196. if template in templates:
  1197. from reflex_cli.v2.utils import hosting
  1198. authenticated_token = hosting.authenticated_token()
  1199. if not authenticated_token or not authenticated_token[0]:
  1200. console.print(
  1201. f"Please use `reflex login` to access the '{template}' template."
  1202. )
  1203. raise typer.Exit(3)
  1204. template_url = templates[template].code_url
  1205. else:
  1206. # Check if the template is a github repo.
  1207. if template.startswith("https://github.com"):
  1208. template_url = f"{template.strip('/').replace('.git', '')}/archive/main.zip"
  1209. else:
  1210. console.error(f"Template `{template}` not found or invalid.")
  1211. raise typer.Exit(1)
  1212. if template_url is None:
  1213. return
  1214. create_config_init_app_from_remote_template(
  1215. app_name=app_name, template_url=template_url
  1216. )
  1217. def generate_template_using_ai(template: str | None = None) -> str:
  1218. """Generate a template using AI(Flexgen).
  1219. Args:
  1220. template: The name of the template.
  1221. Returns:
  1222. The generation hash.
  1223. Raises:
  1224. Exit: If the template and ai flags are used.
  1225. """
  1226. if template is None:
  1227. # If AI is requested and no template specified, redirect the user to reflex.build.
  1228. return redir.reflex_build_redirect()
  1229. elif is_generation_hash(template):
  1230. # Otherwise treat the template as a generation hash.
  1231. return template
  1232. else:
  1233. console.error(
  1234. "Cannot use `--template` option with `--ai` option. Please remove `--template` option."
  1235. )
  1236. raise typer.Exit(2)
  1237. def fetch_remote_templates(
  1238. template: str,
  1239. ) -> tuple[str, dict[str, Template]]:
  1240. """Fetch the available remote templates.
  1241. Args:
  1242. template: The name of the template.
  1243. Returns:
  1244. The selected template and the available templates.
  1245. """
  1246. available_templates = {}
  1247. try:
  1248. # Get the available templates
  1249. available_templates = fetch_app_templates(constants.Reflex.VERSION)
  1250. except Exception as e:
  1251. console.warn("Failed to fetch templates. Falling back to default template.")
  1252. console.debug(f"Error while fetching templates: {e}")
  1253. template = constants.Templates.DEFAULT
  1254. return template, available_templates
  1255. def initialize_app(
  1256. app_name: str, template: str | None = None, ai: bool = False
  1257. ) -> str | None:
  1258. """Initialize the app either from a remote template or a blank app. If the config file exists, it is considered as reinit.
  1259. Args:
  1260. app_name: The name of the app.
  1261. template: The name of the template to use.
  1262. ai: Whether to use AI to generate the template.
  1263. Returns:
  1264. The name of the template.
  1265. Raises:
  1266. Exit: If the template is not valid or unspecified.
  1267. """
  1268. # Local imports to avoid circular imports.
  1269. from reflex.utils import telemetry
  1270. # Check if the app is already initialized.
  1271. if constants.Config.FILE.exists():
  1272. telemetry.send("reinit")
  1273. return
  1274. generation_hash = None
  1275. if ai:
  1276. generation_hash = generate_template_using_ai(template)
  1277. template = constants.Templates.DEFAULT
  1278. templates: dict[str, Template] = {}
  1279. # Don't fetch app templates if the user directly asked for DEFAULT.
  1280. if template is not None and (template not in (constants.Templates.DEFAULT,)):
  1281. template, templates = fetch_remote_templates(template)
  1282. if template is None:
  1283. template = prompt_for_template_options(get_init_cli_prompt_options())
  1284. if template == constants.Templates.AI:
  1285. generation_hash = generate_template_using_ai()
  1286. # change to the default to allow creation of default app
  1287. template = constants.Templates.DEFAULT
  1288. elif template == constants.Templates.CHOOSE_TEMPLATES:
  1289. console.print(
  1290. f"Go to the templates page ({constants.Templates.REFLEX_TEMPLATES_URL}) and copy the command to init with a template."
  1291. )
  1292. raise typer.Exit(0)
  1293. # If the blank template is selected, create a blank app.
  1294. if template in (constants.Templates.DEFAULT,):
  1295. # Default app creation behavior: a blank app.
  1296. initialize_default_app(app_name)
  1297. else:
  1298. validate_and_create_app_using_remote_template(
  1299. app_name=app_name, template=template, templates=templates
  1300. )
  1301. # If a reflex.build generation hash is available, download the code and apply it to the main module.
  1302. if generation_hash:
  1303. initialize_main_module_index_from_generation(
  1304. app_name, generation_hash=generation_hash
  1305. )
  1306. telemetry.send("init", template=template)
  1307. return template
  1308. def get_init_cli_prompt_options() -> list[Template]:
  1309. """Get the CLI options for initializing a Reflex app.
  1310. Returns:
  1311. The CLI options.
  1312. """
  1313. return [
  1314. Template(
  1315. name=constants.Templates.DEFAULT,
  1316. description="A blank Reflex app.",
  1317. demo_url=constants.Templates.DEFAULT_TEMPLATE_URL,
  1318. code_url="",
  1319. ),
  1320. Template(
  1321. name=constants.Templates.AI,
  1322. description="Generate a template using AI [Experimental]",
  1323. demo_url="",
  1324. code_url="",
  1325. ),
  1326. Template(
  1327. name=constants.Templates.CHOOSE_TEMPLATES,
  1328. description="Choose an existing template.",
  1329. demo_url="",
  1330. code_url="",
  1331. ),
  1332. ]
  1333. def initialize_main_module_index_from_generation(app_name: str, generation_hash: str):
  1334. """Overwrite the `index` function in the main module with reflex.build generated code.
  1335. Args:
  1336. app_name: The name of the app.
  1337. generation_hash: The generation hash from reflex.build.
  1338. Raises:
  1339. GeneratedCodeHasNoFunctionDefs: If the fetched code has no function definitions
  1340. (the refactored reflex code is expected to have at least one root function defined).
  1341. """
  1342. # Download the reflex code for the generation.
  1343. url = constants.Templates.REFLEX_BUILD_CODE_URL.format(
  1344. generation_hash=generation_hash
  1345. )
  1346. resp = net.get(url)
  1347. while resp.status_code == httpx.codes.SERVICE_UNAVAILABLE:
  1348. console.debug("Waiting for the code to be generated...")
  1349. time.sleep(1)
  1350. resp = net.get(url)
  1351. resp.raise_for_status()
  1352. # Determine the name of the last function, which renders the generated code.
  1353. defined_funcs = re.findall(r"def ([a-zA-Z_]+)\(", resp.text)
  1354. if not defined_funcs:
  1355. raise GeneratedCodeHasNoFunctionDefs(
  1356. f"No function definitions found in generated code from {url!r}."
  1357. )
  1358. render_func_name = defined_funcs[-1]
  1359. def replace_content(_match):
  1360. return "\n".join(
  1361. [
  1362. resp.text,
  1363. "",
  1364. "" "def index() -> rx.Component:",
  1365. f" return {render_func_name}()",
  1366. "",
  1367. "",
  1368. ],
  1369. )
  1370. main_module_path = Path(app_name, app_name + constants.Ext.PY)
  1371. main_module_code = main_module_path.read_text()
  1372. main_module_code = re.sub(
  1373. r"def index\(\).*:\n([^\n]\s+.*\n+)+",
  1374. replace_content,
  1375. main_module_code,
  1376. )
  1377. # Make the app use light mode until flexgen enforces the conversion of
  1378. # tailwind colors to radix colors.
  1379. main_module_code = re.sub(
  1380. r"app\s*=\s*rx\.App\(\s*\)",
  1381. 'app = rx.App(theme=rx.theme(color_mode="light"))',
  1382. main_module_code,
  1383. )
  1384. main_module_path.write_text(main_module_code)
  1385. def format_address_width(address_width) -> int | None:
  1386. """Cast address width to an int.
  1387. Args:
  1388. address_width: The address width.
  1389. Returns:
  1390. Address width int
  1391. """
  1392. try:
  1393. return int(address_width) if address_width else None
  1394. except ValueError:
  1395. return None
  1396. @functools.lru_cache(maxsize=None)
  1397. def get_cpu_info() -> CpuInfo | None:
  1398. """Get the CPU info of the underlining host.
  1399. Returns:
  1400. The CPU info.
  1401. """
  1402. platform_os = platform.system()
  1403. cpuinfo = {}
  1404. try:
  1405. if platform_os == "Windows":
  1406. cmd = "wmic cpu get addresswidth,caption,manufacturer /FORMAT:csv"
  1407. output = processes.execute_command_and_return_output(cmd)
  1408. if output:
  1409. val = output.splitlines()[-1].split(",")[1:]
  1410. cpuinfo["manufacturer_id"] = val[2]
  1411. cpuinfo["model_name"] = val[1].split("Family")[0].strip()
  1412. cpuinfo["address_width"] = format_address_width(val[0])
  1413. elif platform_os == "Linux":
  1414. output = processes.execute_command_and_return_output("lscpu")
  1415. if output:
  1416. lines = output.split("\n")
  1417. for line in lines:
  1418. if "Architecture" in line:
  1419. cpuinfo["address_width"] = (
  1420. 64 if line.split(":")[1].strip() == "x86_64" else 32
  1421. )
  1422. if "Vendor ID:" in line:
  1423. cpuinfo["manufacturer_id"] = line.split(":")[1].strip()
  1424. if "Model name" in line:
  1425. cpuinfo["model_name"] = line.split(":")[1].strip()
  1426. elif platform_os == "Darwin":
  1427. cpuinfo["address_width"] = format_address_width(
  1428. processes.execute_command_and_return_output("getconf LONG_BIT")
  1429. )
  1430. cpuinfo["manufacturer_id"] = processes.execute_command_and_return_output(
  1431. "sysctl -n machdep.cpu.brand_string"
  1432. )
  1433. cpuinfo["model_name"] = processes.execute_command_and_return_output(
  1434. "uname -m"
  1435. )
  1436. except Exception as err:
  1437. console.error(f"Failed to retrieve CPU info. {err}")
  1438. return None
  1439. return (
  1440. CpuInfo(
  1441. manufacturer_id=cpuinfo.get("manufacturer_id"),
  1442. model_name=cpuinfo.get("model_name"),
  1443. address_width=cpuinfo.get("address_width"),
  1444. )
  1445. if cpuinfo
  1446. else None
  1447. )
  1448. @functools.lru_cache(maxsize=None)
  1449. def is_windows_bun_supported() -> bool:
  1450. """Check whether the underlining host running windows qualifies to run bun.
  1451. We typically do not run bun on ARM or 32 bit devices that use windows.
  1452. Returns:
  1453. Whether the host is qualified to use bun.
  1454. """
  1455. cpu_info = get_cpu_info()
  1456. return (
  1457. constants.IS_WINDOWS
  1458. and cpu_info is not None
  1459. and cpu_info.address_width == 64
  1460. and cpu_info.model_name is not None
  1461. and "ARM" not in cpu_info.model_name
  1462. )
  1463. def is_generation_hash(template: str) -> bool:
  1464. """Check if the template looks like a generation hash.
  1465. Args:
  1466. template: The template name.
  1467. Returns:
  1468. True if the template is composed of 32 or more hex characters.
  1469. """
  1470. return re.match(r"^[0-9a-f]{32,}$", template) is not None