prerequisites.py 63 KB

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