compiler.py 26 KB

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