compiler.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. """Compiler for the reflex apps."""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from pathlib import Path
  5. from typing import TYPE_CHECKING, Iterable, Sequence, Type
  6. from reflex import constants
  7. from reflex.compiler import templates, utils
  8. from reflex.components.base.fragment import Fragment
  9. from reflex.components.component import (
  10. BaseComponent,
  11. Component,
  12. ComponentStyle,
  13. CustomComponent,
  14. StatefulComponent,
  15. )
  16. from reflex.config import environment, get_config
  17. from reflex.state import BaseState
  18. from reflex.style import SYSTEM_COLOR_MODE
  19. from reflex.utils import console, path_ops
  20. from reflex.utils.exec import is_prod_mode
  21. from reflex.utils.imports import ImportVar
  22. from reflex.utils.prerequisites import get_web_dir
  23. from reflex.vars.base import LiteralVar, Var
  24. def _compile_document_root(root: Component) -> str:
  25. """Compile the document root.
  26. Args:
  27. root: The document root to compile.
  28. Returns:
  29. The compiled document root.
  30. """
  31. return templates.DOCUMENT_ROOT.render(
  32. imports=utils.compile_imports(root._get_all_imports()),
  33. document=root.render(),
  34. )
  35. def _normalize_library_name(lib: str) -> str:
  36. """Normalize the library name.
  37. Args:
  38. lib: The library name to normalize.
  39. Returns:
  40. The normalized library name.
  41. """
  42. if lib == "react":
  43. return "React"
  44. return lib.replace("@", "").replace("/", "_").replace("-", "_")
  45. def _compile_app(app_root: Component) -> str:
  46. """Compile the app template component.
  47. Args:
  48. app_root: The app root to compile.
  49. Returns:
  50. The compiled app.
  51. """
  52. from reflex.components.dynamic import bundled_libraries
  53. window_libraries = [
  54. (_normalize_library_name(name), name) for name in bundled_libraries
  55. ] + [
  56. ("utils_context", f"$/{constants.Dirs.UTILS}/context"),
  57. ("utils_state", f"$/{constants.Dirs.UTILS}/state"),
  58. ]
  59. return templates.APP_ROOT.render(
  60. imports=utils.compile_imports(app_root._get_all_imports()),
  61. custom_codes=app_root._get_all_custom_code(),
  62. hooks=app_root._get_all_hooks(),
  63. window_libraries=window_libraries,
  64. render=app_root.render(),
  65. dynamic_imports=app_root._get_all_dynamic_imports(),
  66. )
  67. def _compile_theme(theme: str) -> str:
  68. """Compile the theme.
  69. Args:
  70. theme: The theme to compile.
  71. Returns:
  72. The compiled theme.
  73. """
  74. return templates.THEME.render(theme=theme)
  75. def _compile_contexts(state: Type[BaseState] | None, theme: Component | None) -> str:
  76. """Compile the initial state and contexts.
  77. Args:
  78. state: The app state.
  79. theme: The top-level app theme.
  80. Returns:
  81. The compiled context file.
  82. """
  83. appearance = getattr(theme, "appearance", None)
  84. if appearance is None or str(LiteralVar.create(appearance)) == '"inherit"':
  85. appearance = LiteralVar.create(SYSTEM_COLOR_MODE)
  86. last_compiled_time = str(datetime.now())
  87. return (
  88. templates.CONTEXT.render(
  89. initial_state=utils.compile_state(state),
  90. state_name=state.get_name(),
  91. client_storage=utils.compile_client_storage(state),
  92. is_dev_mode=not is_prod_mode(),
  93. last_compiled_time=last_compiled_time,
  94. default_color_mode=appearance,
  95. )
  96. if state
  97. else templates.CONTEXT.render(
  98. is_dev_mode=not is_prod_mode(),
  99. default_color_mode=appearance,
  100. last_compiled_time=last_compiled_time,
  101. )
  102. )
  103. def _compile_page(
  104. component: BaseComponent,
  105. state: Type[BaseState] | None,
  106. ) -> str:
  107. """Compile the component given the app state.
  108. Args:
  109. component: The component to compile.
  110. state: The app state.
  111. Returns:
  112. The compiled component.
  113. """
  114. imports = component._get_all_imports()
  115. imports = utils.compile_imports(imports)
  116. # Compile the code to render the component.
  117. kwargs = {"state_name": state.get_name()} if state is not None else {}
  118. return templates.PAGE.render(
  119. imports=imports,
  120. dynamic_imports=component._get_all_dynamic_imports(),
  121. custom_codes=component._get_all_custom_code(),
  122. hooks=component._get_all_hooks(),
  123. render=component.render(),
  124. **kwargs,
  125. )
  126. def compile_root_stylesheet(stylesheets: list[str]) -> tuple[str, str]:
  127. """Compile the root stylesheet.
  128. Args:
  129. stylesheets: The stylesheets to include in the root stylesheet.
  130. Returns:
  131. The path and code of the compiled root stylesheet.
  132. """
  133. output_path = utils.get_root_stylesheet_path()
  134. code = _compile_root_stylesheet(stylesheets)
  135. return output_path, code
  136. def _compile_root_stylesheet(stylesheets: list[str]) -> str:
  137. """Compile the root stylesheet.
  138. Args:
  139. stylesheets: The stylesheets to include in the root stylesheet.
  140. Returns:
  141. The compiled root stylesheet.
  142. Raises:
  143. FileNotFoundError: If a specified stylesheet in assets directory does not exist.
  144. """
  145. # Add tailwind css if enabled.
  146. sheets = (
  147. [constants.Tailwind.ROOT_STYLE_PATH]
  148. if get_config().tailwind is not None
  149. else []
  150. )
  151. failed_to_import_sass = False
  152. for stylesheet in stylesheets:
  153. if not utils.is_valid_url(stylesheet):
  154. # check if stylesheet provided exists.
  155. assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS
  156. stylesheet_full_path = assets_app_path / stylesheet.strip("/")
  157. if not stylesheet_full_path.exists():
  158. raise FileNotFoundError(
  159. f"The stylesheet file {stylesheet_full_path} does not exist."
  160. )
  161. if stylesheet_full_path.is_dir():
  162. # NOTE: this can create an infinite loop, for example:
  163. # assets/
  164. # | dir_a/
  165. # | | dir_c/ (symlink to "assets/dir_a")
  166. # | dir_b/
  167. # so to avoid the infinite loop, we don't include symbolic links
  168. stylesheets += [
  169. str(p.relative_to(assets_app_path))
  170. for p in stylesheet_full_path.iterdir()
  171. if not (p.is_symlink() and p.is_dir())
  172. ]
  173. continue
  174. if (
  175. stylesheet_full_path.suffix[1:].lower()
  176. in constants.Reflex.STYLESHEETS_SUPPORTED
  177. ):
  178. target = (
  179. Path.cwd()
  180. / constants.Dirs.WEB
  181. / constants.Dirs.STYLES
  182. / (stylesheet.rsplit(".", 1)[0].strip("/") + ".css")
  183. )
  184. target.parent.mkdir(parents=True, exist_ok=True)
  185. if stylesheet_full_path.suffix == ".css":
  186. path_ops.cp(src=stylesheet_full_path, dest=target, overwrite=True)
  187. else:
  188. try:
  189. from sass import compile as sass_compile
  190. target.write_text(
  191. data=sass_compile(
  192. filename=str(stylesheet_full_path),
  193. output_style="compressed",
  194. ),
  195. encoding="utf8",
  196. )
  197. except ImportError:
  198. failed_to_import_sass = True
  199. else:
  200. raise FileNotFoundError(
  201. f'The stylesheet file "{stylesheet_full_path}" is not a valid file.'
  202. )
  203. stylesheet = f"./{stylesheet.rsplit('.', 1)[0].strip('/')}.css"
  204. sheets.append(stylesheet) if stylesheet not in sheets else None
  205. if failed_to_import_sass:
  206. console.error(
  207. 'The `libsass` package is required to compile sass/scss stylesheet files. Run `pip install "libsass>=0.23.0"`.'
  208. )
  209. return templates.STYLE.render(stylesheets=sheets)
  210. def _compile_component(component: Component | StatefulComponent) -> str:
  211. """Compile a single component.
  212. Args:
  213. component: The component to compile.
  214. Returns:
  215. The compiled component.
  216. """
  217. return templates.COMPONENT.render(component=component)
  218. def _compile_components(
  219. components: set[CustomComponent],
  220. ) -> tuple[str, dict[str, list[ImportVar]]]:
  221. """Compile the components.
  222. Args:
  223. components: The components to compile.
  224. Returns:
  225. The compiled components.
  226. """
  227. imports = {
  228. "react": [ImportVar(tag="memo")],
  229. f"$/{constants.Dirs.STATE_PATH}": [ImportVar(tag="E"), ImportVar(tag="isTrue")],
  230. }
  231. component_renders = []
  232. # Compile each component.
  233. for component in components:
  234. component_render, component_imports = utils.compile_custom_component(component)
  235. component_renders.append(component_render)
  236. imports = utils.merge_imports(imports, component_imports)
  237. dynamic_imports = {
  238. comp_import: None
  239. for comp_render in component_renders
  240. if "dynamic_imports" in comp_render
  241. for comp_import in comp_render["dynamic_imports"]
  242. }
  243. custom_codes = {
  244. comp_custom_code: None
  245. for comp_render in component_renders
  246. for comp_custom_code in comp_render.get("custom_code", [])
  247. }
  248. # Compile the components page.
  249. return (
  250. templates.COMPONENTS.render(
  251. imports=utils.compile_imports(imports),
  252. components=component_renders,
  253. dynamic_imports=dynamic_imports,
  254. custom_codes=custom_codes,
  255. ),
  256. imports,
  257. )
  258. def _compile_stateful_components(
  259. page_components: list[BaseComponent],
  260. ) -> str:
  261. """Walk the page components and extract shared stateful components.
  262. Any StatefulComponent that is shared by more than one page will be rendered
  263. to a separate module and marked rendered_as_shared so subsequent
  264. renderings will import the component from the shared module instead of
  265. directly including the code for it.
  266. Args:
  267. page_components: The Components or StatefulComponents to compile.
  268. Returns:
  269. The rendered stateful components code.
  270. """
  271. all_import_dicts = []
  272. rendered_components = {}
  273. def get_shared_components_recursive(component: BaseComponent):
  274. """Get the shared components for a component and its children.
  275. A shared component is a StatefulComponent that appears in 2 or more
  276. pages and is a candidate for writing to a common file and importing
  277. into each page where it is used.
  278. Args:
  279. component: The component to collect shared StatefulComponents for.
  280. """
  281. for child in component.children:
  282. # Depth-first traversal.
  283. get_shared_components_recursive(child)
  284. # When the component is referenced by more than one page, render it
  285. # to be included in the STATEFUL_COMPONENTS module.
  286. # Skip this step in dev mode, thereby avoiding potential hot reload errors for larger apps
  287. if (
  288. isinstance(component, StatefulComponent)
  289. and component.references > 1
  290. and is_prod_mode()
  291. ):
  292. # Reset this flag to render the actual component.
  293. component.rendered_as_shared = False
  294. # Include dynamic imports in the shared component.
  295. if dynamic_imports := component._get_all_dynamic_imports():
  296. rendered_components.update(
  297. {dynamic_import: None for dynamic_import in dynamic_imports}
  298. )
  299. # Include custom code in the shared component.
  300. rendered_components.update(
  301. {code: None for code in component._get_all_custom_code()},
  302. )
  303. # Include all imports in the shared component.
  304. all_import_dicts.append(component._get_all_imports())
  305. # Indicate that this component now imports from the shared file.
  306. component.rendered_as_shared = True
  307. for page_component in page_components:
  308. get_shared_components_recursive(page_component)
  309. # Don't import from the file that we're about to create.
  310. all_imports = utils.merge_imports(*all_import_dicts)
  311. all_imports.pop(
  312. f"$/{constants.Dirs.UTILS}/{constants.PageNames.STATEFUL_COMPONENTS}", None
  313. )
  314. return templates.STATEFUL_COMPONENTS.render(
  315. imports=utils.compile_imports(all_imports),
  316. memoized_code="\n".join(rendered_components),
  317. )
  318. def _compile_tailwind(
  319. config: dict,
  320. ) -> str:
  321. """Compile the Tailwind config.
  322. Args:
  323. config: The Tailwind config.
  324. Returns:
  325. The compiled Tailwind config.
  326. """
  327. return templates.TAILWIND_CONFIG.render(
  328. **config,
  329. )
  330. def compile_document_root(
  331. head_components: list[Component],
  332. html_lang: str | None = None,
  333. html_custom_attrs: dict[str, Var | str] | None = None,
  334. ) -> tuple[str, str]:
  335. """Compile the document root.
  336. Args:
  337. head_components: The components to include in the head.
  338. html_lang: The language of the document, will be added to the html root element.
  339. html_custom_attrs: custom attributes added to the html root element.
  340. Returns:
  341. The path and code of the compiled document root.
  342. """
  343. # Get the path for the output file.
  344. output_path = utils.get_page_path(constants.PageNames.DOCUMENT_ROOT)
  345. # Create the document root.
  346. document_root = utils.create_document_root(
  347. head_components, html_lang=html_lang, html_custom_attrs=html_custom_attrs
  348. )
  349. # Compile the document root.
  350. code = _compile_document_root(document_root)
  351. return output_path, code
  352. def compile_app(app_root: Component) -> tuple[str, str]:
  353. """Compile the app root.
  354. Args:
  355. app_root: The app root component to compile.
  356. Returns:
  357. The path and code of the compiled app wrapper.
  358. """
  359. # Get the path for the output file.
  360. output_path = utils.get_page_path(constants.PageNames.APP_ROOT)
  361. # Compile the document root.
  362. code = _compile_app(app_root)
  363. return output_path, code
  364. def compile_theme(style: ComponentStyle) -> tuple[str, str]:
  365. """Compile the theme.
  366. Args:
  367. style: The style to compile.
  368. Returns:
  369. The path and code of the compiled theme.
  370. """
  371. output_path = utils.get_theme_path()
  372. # Create the theme.
  373. theme = utils.create_theme(style)
  374. # Compile the theme.
  375. code = _compile_theme(str(LiteralVar.create(theme)))
  376. return output_path, code
  377. def compile_contexts(
  378. state: Type[BaseState] | None,
  379. theme: Component | None,
  380. ) -> tuple[str, str]:
  381. """Compile the initial state / context.
  382. Args:
  383. state: The app state.
  384. theme: The top-level app theme.
  385. Returns:
  386. The path and code of the compiled context.
  387. """
  388. # Get the path for the output file.
  389. output_path = utils.get_context_path()
  390. return output_path, _compile_contexts(state, theme)
  391. def compile_page(
  392. path: str, component: BaseComponent, state: Type[BaseState] | None
  393. ) -> tuple[str, str]:
  394. """Compile a single page.
  395. Args:
  396. path: The path to compile the page to.
  397. component: The component to compile.
  398. state: The app state.
  399. Returns:
  400. The path and code of the compiled page.
  401. """
  402. # Get the path for the output file.
  403. output_path = utils.get_page_path(path)
  404. # Add the style to the component.
  405. code = _compile_page(component, state)
  406. return output_path, code
  407. def compile_components(
  408. components: set[CustomComponent],
  409. ) -> tuple[str, str, dict[str, list[ImportVar]]]:
  410. """Compile the custom components.
  411. Args:
  412. components: The custom components to compile.
  413. Returns:
  414. The path and code of the compiled components.
  415. """
  416. # Get the path for the output file.
  417. output_path = utils.get_components_path()
  418. # Compile the components.
  419. code, imports = _compile_components(components)
  420. return output_path, code, imports
  421. def compile_stateful_components(
  422. pages: Iterable[Component],
  423. ) -> tuple[str, str, list[BaseComponent]]:
  424. """Separately compile components that depend on State vars.
  425. StatefulComponents are compiled as their own component functions with their own
  426. useContext declarations, which allows page components to be stateless and avoid
  427. re-rendering along with parts of the page that actually depend on state.
  428. Args:
  429. pages: The pages to extract stateful components from.
  430. Returns:
  431. The path and code of the compiled stateful components.
  432. """
  433. output_path = utils.get_stateful_components_path()
  434. # Compile the stateful components.
  435. page_components = [StatefulComponent.compile_from(page) or page for page in pages]
  436. code = _compile_stateful_components(page_components)
  437. return output_path, code, page_components
  438. def compile_tailwind(
  439. config: dict,
  440. ):
  441. """Compile the Tailwind config.
  442. Args:
  443. config: The Tailwind config.
  444. Returns:
  445. The compiled Tailwind config.
  446. """
  447. # Get the path for the output file.
  448. output_path = str((get_web_dir() / constants.Tailwind.CONFIG).absolute())
  449. # Compile the config.
  450. code = _compile_tailwind(config)
  451. return output_path, code
  452. def remove_tailwind_from_postcss() -> tuple[str, str]:
  453. """If tailwind is not to be used, remove it from postcss.config.js.
  454. Returns:
  455. The path and code of the compiled postcss.config.js.
  456. """
  457. # Get the path for the output file.
  458. output_path = str(get_web_dir() / constants.Dirs.POSTCSS_JS)
  459. code = [
  460. line
  461. for line in Path(output_path).read_text().splitlines(keepends=True)
  462. if "tailwindcss: " not in line
  463. ]
  464. # Compile the config.
  465. return output_path, "".join(code)
  466. def purge_web_pages_dir():
  467. """Empty out .web/pages directory."""
  468. if not is_prod_mode() and environment.REFLEX_PERSIST_WEB_DIR.get():
  469. # Skip purging the web directory in dev mode if REFLEX_PERSIST_WEB_DIR is set.
  470. return
  471. # Empty out the web pages directory.
  472. utils.empty_dir(get_web_dir() / constants.Dirs.PAGES, keep_files=["_app.js"])
  473. if TYPE_CHECKING:
  474. from reflex.app import ComponentCallable, UnevaluatedPage
  475. def _into_component_once(component: Component | ComponentCallable) -> Component | None:
  476. """Convert a component to a Component.
  477. Args:
  478. component: The component to convert.
  479. Returns:
  480. The converted component.
  481. """
  482. if isinstance(component, Component):
  483. return component
  484. if isinstance(component, (Var, int, float, str)):
  485. return Fragment.create(component)
  486. if isinstance(component, Sequence):
  487. return Fragment.create(*component)
  488. return None
  489. def into_component(component: Component | ComponentCallable) -> Component:
  490. """Convert a component to a Component.
  491. Args:
  492. component: The component to convert.
  493. Returns:
  494. The converted component.
  495. Raises:
  496. TypeError: If the component is not a Component.
  497. # noqa: DAR401
  498. """
  499. if (converted := _into_component_once(component)) is not None:
  500. return converted
  501. try:
  502. if (
  503. callable(component)
  504. and (converted := _into_component_once(component())) is not None
  505. ):
  506. return converted
  507. except KeyError as e:
  508. key = e.args[0] if e.args else None
  509. if key is not None and isinstance(key, Var):
  510. raise TypeError(
  511. "Cannot access a primitive map with a Var. Consider calling rx.Var.create() on the map."
  512. ).with_traceback(e.__traceback__) from None
  513. raise
  514. except TypeError as e:
  515. message = e.args[0] if e.args else None
  516. if message and isinstance(message, str):
  517. if message.endswith("has no len()") and (
  518. "ArrayCastedVar" in message
  519. or "ObjectCastedVar" in message
  520. or "StringCastedVar" in message
  521. ):
  522. raise TypeError(
  523. "Cannot pass a Var to a built-in function. Consider using .length() for accessing the length of an iterable Var."
  524. ).with_traceback(e.__traceback__) from None
  525. if message.endswith(
  526. "indices must be integers or slices, not NumberCastedVar"
  527. ) or message.endswith(
  528. "indices must be integers or slices, not BooleanCastedVar"
  529. ):
  530. raise TypeError(
  531. "Cannot index into a primitive sequence with a Var. Consider calling rx.Var.create() on the sequence."
  532. ).with_traceback(e.__traceback__) from None
  533. if "CastedVar" in str(e):
  534. raise TypeError(
  535. "Cannot pass a Var to a built-in function. Consider moving the operation to the backend, using existing Var operations, or defining a custom Var operation."
  536. ).with_traceback(e.__traceback__) from None
  537. raise
  538. raise TypeError(f"Expected a Component, got {type(component)}")
  539. def compile_unevaluated_page(
  540. route: str,
  541. page: UnevaluatedPage,
  542. state: Type[BaseState] | None = None,
  543. style: ComponentStyle | None = None,
  544. theme: Component | None = None,
  545. ) -> tuple[Component, bool]:
  546. """Compiles an uncompiled page into a component and adds meta information.
  547. Args:
  548. route: The route of the page.
  549. page: The uncompiled page object.
  550. state: The state of the app.
  551. style: The style of the page.
  552. theme: The theme of the page.
  553. Returns:
  554. The compiled component and whether state should be enabled.
  555. """
  556. # Generate the component if it is a callable.
  557. component = into_component(page.component)
  558. component._add_style_recursive(style or {}, theme)
  559. enable_state = False
  560. # Ensure state is enabled if this page uses state.
  561. if state is None:
  562. if page.on_load or component._has_stateful_event_triggers():
  563. enable_state = True
  564. else:
  565. for var in component._get_vars(include_children=True):
  566. var_data = var._get_all_var_data()
  567. if not var_data:
  568. continue
  569. if not var_data.state:
  570. continue
  571. enable_state = True
  572. break
  573. from reflex.app import OverlayFragment
  574. from reflex.utils.format import make_default_page_title
  575. component = OverlayFragment.create(component)
  576. meta_args = {
  577. "title": (
  578. page.title
  579. if page.title is not None
  580. else make_default_page_title(get_config().app_name, route)
  581. ),
  582. "image": page.image,
  583. "meta": page.meta,
  584. }
  585. if page.description is not None:
  586. meta_args["description"] = page.description
  587. # Add meta information to the component.
  588. utils.add_meta(
  589. component,
  590. **meta_args,
  591. )
  592. return component, enable_state
  593. class ExecutorSafeFunctions:
  594. """Helper class to allow parallelisation of parts of the compilation process.
  595. This class (and its class attributes) are available at global scope.
  596. In a multiprocessing context (like when using a ProcessPoolExecutor), the content of this
  597. global class is logically replicated to any FORKED process.
  598. How it works:
  599. * Before the child process is forked, ensure that we stash any input data required by any future
  600. function call in the child process.
  601. * After the child process is forked, the child process will have a copy of the global class, which
  602. includes the previously stashed input data.
  603. * Any task submitted to the child process simply needs a way to communicate which input data the
  604. requested function call requires.
  605. Why do we need this? Passing input data directly to child process often not possible because the input data is not picklable.
  606. The mechanic described here removes the need to pickle the input data at all.
  607. Limitations:
  608. * This can never support returning unpicklable OUTPUT data.
  609. * Any object mutations done by the child process will not propagate back to the parent process (fork goes one way!).
  610. """
  611. COMPONENTS: dict[str, BaseComponent] = {}
  612. UNCOMPILED_PAGES: dict[str, UnevaluatedPage] = {}
  613. STATE: Type[BaseState] | None = None
  614. @classmethod
  615. def compile_page(cls, route: str) -> tuple[str, str]:
  616. """Compile a page.
  617. Args:
  618. route: The route of the page to compile.
  619. Returns:
  620. The path and code of the compiled page.
  621. """
  622. return compile_page(route, cls.COMPONENTS[route], cls.STATE)
  623. @classmethod
  624. def compile_unevaluated_page(
  625. cls,
  626. route: str,
  627. style: ComponentStyle,
  628. theme: Component | None,
  629. ) -> tuple[str, Component, tuple[str, str]]:
  630. """Compile an unevaluated page.
  631. Args:
  632. route: The route of the page to compile.
  633. style: The style of the page.
  634. theme: The theme of the page.
  635. Returns:
  636. The route, compiled component, and compiled page.
  637. """
  638. component, enable_state = compile_unevaluated_page(
  639. route, cls.UNCOMPILED_PAGES[route], cls.STATE, style, theme
  640. )
  641. return route, component, compile_page(route, component, cls.STATE)
  642. @classmethod
  643. def compile_theme(cls, style: ComponentStyle | None) -> tuple[str, str]:
  644. """Compile the theme.
  645. Args:
  646. style: The style to compile.
  647. Returns:
  648. The path and code of the compiled theme.
  649. Raises:
  650. ValueError: If the style is not set.
  651. """
  652. if style is None:
  653. raise ValueError("STYLE should be set")
  654. return compile_theme(style)