Compare commits

...

171 Commits

Author SHA1 Message Date
Valerio Ageno 30073c226d feat: update version to v0.9.1 2024-08-15 20:44:25 +02:00
Valerio Ageno 1b1e91b6c0 fix: sanitize client side pathnames (#25) 2024-08-15 20:42:47 +02:00
Valerio Ageno 71d7ccf27d feat: update README header 2024-08-15 20:36:11 +02:00
Valerio Ageno 3ca24ec87f feat: create overview and getting started pages 2024-08-15 19:25:03 +02:00
Valerio Ageno b2940d9fa8 feat: add breadcrumbs to documentation 2024-08-15 18:52:56 +02:00
Valerio Ageno a7b7f0eac2 feat: update documentation sidebar 2024-08-15 18:20:20 +02:00
Valerio Ageno 4859916edd feat: update documentation sidebar 2024-08-15 11:31:33 +02:00
Valerio Ageno ad3e19e965 fix: documentation sidebar on mobile 2024-08-14 21:28:23 +02:00
Valerio Ageno 03dead1083 feat: update documentation tuono version to v0.9.0 2024-08-14 20:59:43 +02:00
Valerio Ageno 341fba6ca9 Preload chunks when links are visible in the viewport (#24)
* feat: preload chunk when links are visible in the viewport

* feat: update version to v0.9.0
2024-08-14 20:50:47 +02:00
Valerio Ageno 58c4890122 Update pull_request_template.md 2024-08-14 20:45:37 +02:00
Valerio Ageno af42e5ef21 fix: remove useless pendingElement 2024-08-14 14:48:26 +02:00
Valerio Ageno 5abff0384c feat: update documentation navbar 2024-08-14 14:45:47 +02:00
Valerio Ageno cc915560b8 update documentation tuono version to v0.8.4 2024-08-14 14:41:22 +02:00
Valerio Ageno 9835a4c0d1 fix: route switch wrappers re-rendering (#23)
* fix: route switch wrappers re-rendering

* feat: update version to v0.8.4
2024-08-14 14:26:52 +02:00
Valerio Ageno 90782ae710 fix: turbo dev task config 2024-08-11 18:19:38 +02:00
Valerio Ageno 75c790dd6e refactor: create standalone router package (#22)
* refactor: create standalone router package

* fix: add jsdom to tuono-router package

* fix: remove test in tuono vite.config

* update turbo to latest

* fix: wait build before lint

* fix: router types
2024-08-11 17:14:54 +02:00
Valerio Ageno 8604858a61 fix: documentation formatting 2024-08-11 16:33:45 +02:00
Valerio Ageno d1b6162d3a Update contributing.mdx 2024-08-09 17:48:23 +02:00
Valerio Ageno a445644b47 Update contributing.mdx 2024-08-09 17:47:07 +02:00
Valerio Ageno ebb4434506 Update contributing.mdx 2024-08-09 17:40:42 +02:00
Valerio Ageno 36a53662a0 Update contributing.mdx 2024-08-09 17:40:18 +02:00
Valerio Ageno 569d95dc9c fix: routing page 2024-07-27 14:58:18 +02:00
Valerio Ageno bc4c4e03f0 feat: update documentation tuono version (#21) 2024-07-27 14:52:02 +02:00
Valerio Ageno 170c5ea098 Update static build html structures (#20)
* fix: improve static build output structure

* feat: update version to v0.8.3
2024-07-27 14:42:28 +02:00
Valerio Ageno 3fd5f166e2 fix: edit page github link 2024-07-27 11:40:24 +02:00
Valerio Ageno a2285a78a1 fix: documentation output folder 2024-07-27 11:38:18 +02:00
Valerio Ageno 1ae7f72de3 Create documentation website (#19)
* feat: scaffold documentation app

* feat: init documentation website with mantine

* feat: add theme button

* feat: setup mdx link component

* feat: setup basic documentation folder

* feat: add routing folder

* feat: scaffold homepage

* feat: refined navbar and hero

* feat: create pre mdx component

* feat: create mdx blockquote component

* feat: create code mdx component

* fix: remove HTMLProps type

* feat: create base hero page

* ci: add lint/formatting/type checking to documentation

* ci: add documentation pipeline

* fix: static build documentation

* fix: remove documentation test check

* fix: install deps outside workspace

* fix: filter prettier checks

* fix: eslint plugins

* fix: clone eslintrc

* feat: update dark theme colors

* doc: add installation page

* feat: add deploy documenation CD pipeline

* fix: update documentation bucket region

* feat: update documentation head tags

* fix: deploy website on main branch push
2024-07-27 11:33:34 +02:00
Valerio Ageno 19782a2dbe feat: update version to v0.8.2 2024-07-25 19:06:15 +02:00
Valerio Ageno b755e658f5 fix: add mdx file to watch script 2024-07-25 19:06:15 +02:00
Valerio Ageno cc0279b964 fix: typescript check 2024-07-25 13:45:29 +02:00
Valerio Ageno 099da549b5 fix: eslint check on vite config 2024-07-25 13:43:24 +02:00
Valerio Ageno 92a76032eb feat: update version to v0.8.1 2024-07-24 20:59:49 +02:00
Valerio Ageno cd17eebf96 fix: mdx vite configuration 2024-07-24 20:58:09 +02:00
Valerio Ageno 1726312d34 Support nested roots (#18)
* feat: remove isLoader route property

* fix: has-parent-route fs-router util

* feat: handle routeGenerator nested __root

* feat: enable multiple roots with nested dynamic paths

* feat: enable nested routes

* fix: prevent route path creation for __root

* feat: prevent wrong path on subfolder index routes

* chore: cleaned tutorial example folder

* feat: update version to v0.8.0
2024-07-23 19:13:18 +02:00
Valerio Ageno 444d1479b0 Add support for MDX (#17)
* feat: add support for MDX

* fix: prevent empty server handler error message

* doc: add MDX mention to README

* feat: update version to v0.7.0
2024-07-22 07:59:43 +02:00
Valerio Ageno 2949ea4dfa Support Static Site Generation (SSG) (#16)
* refactor: init routes within App::new

* feat: handle build and server run within App struct

* feat: prevent dynamic routes SSG

* feat: support SSG

* chore: remove debugger

* feat: update version to v0.6.0
2024-07-21 14:10:12 +02:00
Valerio Ageno 8ab292b2f9 Update pull_request_template.md 2024-07-15 13:40:49 +02:00
Valerio Ageno 9d8bfd9826 Refactor application struct representation (#15)
* feat: add ssg module and CLI argument

* refactor: tuono lib.rs structure

* refactor: create App struct

* feat: extend file extensions to read in src/routes/

* feat: load all routes in the app.route_map

* refactor: creaded AxumInfo struct
2024-07-14 20:58:03 +02:00
Valerio Ageno 8a6685a6d0 Update README.md 2024-07-13 12:10:13 +02:00
Valerio Ageno 78990d3c08 Add support for meta tags (#14)
* feat: added support for head meta tags

* doc: update tutorial

* feat: add support to no css manifest entries

* feat: update version to v0.5.0

* doc: add mention to add the imports field

* feat: add filter to workspace package.json

* fix: add types declarations for react-meta-tags
2024-07-13 12:09:56 +02:00
Valerio Ageno 227662489b Update README.md 2024-07-12 11:01:55 +02:00
Valerio Ageno 5ce410f233 Update bug_report.md 2024-07-12 10:55:47 +02:00
Valerio Ageno 67d4e1bcac Create use router hook (#13)
* refactor: useRouter to useInternalRouter

* feat: create useRouter hook

* feat: optimized payload sent to client

* feat: add support for query and pathname value in useRouter

* feat: update version to v0.4.6
2024-07-11 21:43:38 +02:00
Valerio Ageno 3e6aa540fa Update README.md 2024-07-11 15:54:53 +02:00
Valerio Ageno b412371287 Remove lifetime notation on Request (#12)
* feat: remove lifetime notation on Request

* feat: update version to v0.4.5
2024-07-09 19:00:48 +02:00
Valerio Ageno f62fc0b2b9 Create pull_request_template.md 2024-07-09 12:35:09 +02:00
Valerio Ageno 35d8154649 Create README.md into doc folder 2024-07-09 09:07:04 +02:00
Valerio Ageno 6e794e9500 Update issue templates 2024-07-09 08:38:27 +02:00
Valerio Ageno e4d4a75b88 Crate standalone fs router package (#11)
* refactor: moved fs-router to standalone package

* chore: remove useless split source function

* feat: add simple test cases

* fix: README formatting

* fix: remove useless RouteSubNode

* feat: update version to v0.4.4
2024-07-08 21:39:00 +02:00
Valerio Ageno bc7ffc2246 Update tutorial.md with latest version changes 2024-07-08 10:02:13 +02:00
Valerio Ageno 74e2f4e873 fix ssr keyword 2024-07-08 09:24:20 +02:00
Valerio Ageno d9d62a91f7 Add keywords to crates 2024-07-08 09:19:00 +02:00
Valerio Ageno 77b34fbb7b feat: update version to v0.4.1 2024-07-07 12:24:45 +02:00
Valerio Ageno d3040aa63f feat: correct module visibility 2024-07-07 12:23:54 +02:00
Valerio Ageno 672e4b69d7 Proxy vite dev server (#10)
* refactor: pass reqwest from tuono_lib crate and prepared vite_reverse_proxy

* feat: add proxy entry point on vite side

* refactor: internal_handlers_folder

* feat: handle vite websocket tunnel

* feat: handle unexpect WebSocket messages

* feat: split dev/prod ssr handling

* feat: split js/rust bundle reloading

* feat: prevent close error on websocket connection

* feat: remove vite proxy on prod server

* feat: update version to v0.4.0
2024-07-07 11:44:36 +02:00
Valerio Ageno 9cd90ba62a Refactor server (#9)
* refactor: move catch_all in tuono_lib

* refactor: moved server to tuono_lib

* refactor: move router and server into tuono_lib

* refactor: reduce exports from examples

* refactor: re-organize exports

* refactor: removed mode set on project builder

* feat: update version to v0.3.1
2024-07-02 21:59:30 +02:00
Valerio Ageno b6d0bb13ef Handle redirections (#8)
* feat: support axum permanent redirect

* feat: lowercase route names

* feat: allow redirection on client side routing

* doc: update tutorial

* refactor: update useListenBrowserUrlUpdates hook

* refactor: moved initRouterStore to useRouterStore file

* feat: update version to v0.3.0

* fix: types
2024-06-29 11:58:04 +02:00
Valerio Ageno 7401a59346 update version to v0.2.5 2024-06-27 17:53:12 +02:00
Valerio Ageno 622ae93d68 fix: crates categories 2024-06-27 17:52:32 +02:00
Valerio Ageno b4207feb7e Update version to v0.2.4 2024-06-27 17:47:09 +02:00
Valerio Ageno 332fdb70ca Update ssr_rs to v0.5.5 2024-06-27 17:46:19 +02:00
Valerio Ageno b9abfb64c0 feat: update version to v0.2.3 2024-06-25 18:53:17 +02:00
Valerio Ageno 3ca8861d85 feat: use the correct public folder according to the mode 2024-06-25 18:48:55 +02:00
Valerio Ageno 0c93aab13f Update tutorial.md 2024-06-25 14:26:27 +02:00
Valerio Ageno 208b49cfc8 Update tutorial.md 2024-06-25 14:26:01 +02:00
Valerio Ageno db0a2d9d1d Update README.md 2024-06-25 14:24:59 +02:00
Valerio Ageno c123e93433 Update scaffold_project.rs 2024-06-25 14:23:22 +02:00
Valerio Ageno 35557d296d feat: update version to v0.2.2 2024-06-25 08:35:09 +02:00
Gábor Szabó d0d6550d7e It is better to use the repository field in Cargo.toml (#7) 2024-06-25 07:42:04 +02:00
Valerio Ageno 38d9be2bb0 feat: update version to v0.2.1 2024-06-24 17:41:34 +02:00
Valerio Ageno fcb33d208c fix: format tuono_lib_macros 2024-06-24 17:38:37 +02:00
Valerio Ageno f831ad6c7a feat: add lint and fmt checks on rust pipelines 2024-06-24 17:37:18 +02:00
Valerio Ageno 3bfed5fabc feat: update launch log according to mode 2024-06-24 17:32:40 +02:00
Valerio Ageno e1ce3ba2fd Update tutorial.md 2024-06-24 09:03:06 +02:00
Valerio Ageno a31f048ffd feat: update version to v0.2.0 2024-06-23 20:19:30 +02:00
Valerio Ageno 9c707466db Optimize build assets (#6)
* feat: handle Dev and Prod modes

* fix: remove useles variable override

* refactor: ssr entry point fn

* feat: pass Mode from server to client

* feat: enable read file from out/client dir

* feat: load manifest data from server side

* feat: remap manifest when loaded

* feat: load correct bundle server side

* doc: update README.md

* doc: update tutorial
2024-06-23 20:15:33 +02:00
Valerio Ageno 4ff899729b Update CONTRIBUTING.md 2024-06-22 15:46:44 +02:00
Valerio Ageno a8345d3509 Create CONTRIBUTING.md 2024-06-22 15:43:41 +02:00
Valerio Ageno 1c3d6e2d78 Create CODE_OF_CONDUCT.md 2024-06-22 15:30:57 +02:00
Valerio Ageno dde5ae7827 feat: update version to v0.1.9 2024-06-21 19:35:38 +02:00
Valerio Ageno aeef19cda3 fix: Doc formatting 2024-06-21 19:33:54 +02:00
Valerio Ageno adec05c6f8 feat: update README.md 2024-06-21 19:33:01 +02:00
Valerio Ageno 2c1e8f7db8 feat: update ssr_rs@0.5.4 2024-06-21 19:11:32 +02:00
Valerio Ageno 2c1e8f0cc2 feat: updated keywords and lazy vite plugin README.md 2024-06-21 19:06:40 +02:00
Valerio Ageno 5d434aeb68 Change lazy function name to dynamic (#5)
* feat: add test:watch script

* feat: update lazy babel plugin to support 'dynamic' as function name

* feat: move 'lazy' into 'dynamic' function name to tuono main package

* feat: update version to v0.1.8
2024-06-21 18:52:58 +02:00
Valerio Ageno 54e7d3a397 fix: remove workspace package 2024-06-20 20:05:11 +02:00
Valerio Ageno 7937291281 fix: add recursive pnpm publish + set v0.1.7 2024-06-20 19:57:26 +02:00
Valerio Ageno 777f932266 chore: remove filter from release pipeline + set v0.1.6 2024-06-20 19:47:34 +02:00
Valerio Ageno f37cb701b3 Create babel plugin to handle lazy loading (#4)
* feat: create babel plugin to handle lazy loading

* fix: update typescript CI to also run the tests in the pipelines

* doc: update lazy loading component inline documentation

* fix: typescript pipeline

* fix: update CI typescript test command

* fix: prevent duplicate pipelines on PR

* feat: create separate vite plugin package

* chore: refined lazy fn package

* test: add test to lazy fn plugin

* feat: update version to v0.1.5
2024-06-20 19:40:14 +02:00
Valerio Ageno 6498905377 Update .gitattributes 2024-06-17 14:32:16 +02:00
Valerio Ageno ed6c75fe37 doc: remove examples/ folder from github language stats 2024-06-17 14:07:42 +02:00
Valerio Ageno f759960641 Update README.md 2024-06-17 13:45:21 +02:00
Valerio Ageno 75e8e51464 Update tutorial.md 2024-06-17 13:34:41 +02:00
Valerio Ageno 75ee140525 feat: add tpescript CI badge to README 2024-06-16 11:27:41 +02:00
Valerio Ageno 8d09637a7a fix: ci folder check 2024-06-16 11:25:38 +02:00
Valerio Ageno 62bfd35fbd fix: type checking on tuono package 2024-06-16 11:23:02 +02:00
Valerio Ageno 091c94d609 ci: exclude pipeline by folder 2024-06-16 11:02:50 +02:00
Valerio Ageno a72656cb4b fix: lint typescript source 2024-06-16 10:51:30 +02:00
Valerio Ageno b3ef9f0ee6 ci: create typescript CI pipeline 2024-06-16 10:36:55 +02:00
Valerio Ageno 0e4debdb8a ci: add badge to README 2024-06-16 10:22:04 +02:00
Valerio Ageno 476fae0e70 ci: add rust CI pipeline 2024-06-16 10:16:43 +02:00
Valerio Ageno 3de9d1be66 feat: update version to v0.1.4 2024-06-15 21:04:37 +02:00
Valerio Ageno 00916f188d Merge pull request #3 from Valerioageno/enable-template-in-tuono-new
[tuono new] Enable --template flag
2024-06-15 21:01:08 +02:00
Valerio Ageno fff5f92893 doc: update examples READMEs 2024-06-15 21:02:10 +02:00
Valerio Ageno 8b796fc1f4 doc: update tutorial doc 2024-06-15 20:59:07 +02:00
Valerio Ageno 5ac679785b feat(tuono new): support --template arg 2024-06-15 20:55:19 +02:00
Valerio Ageno 38b6cc8c65 fix: broken icons in readme tree 2024-06-15 14:36:09 +02:00
Valerio Ageno abb2d658c6 Merge pull request #2 from Valerioageno/add-status-code-support
Add `StatusCode` support
2024-06-15 14:26:30 +02:00
Valerio Ageno 3587c085b9 feat: update version to v0.1.3 2024-06-15 14:28:21 +02:00
Valerio Ageno 581a7d79b3 feat: update example/tuono source code 2024-06-15 14:26:01 +02:00
Valerio Ageno e21b80a5d8 docs: add TOC to tutorial 2024-06-15 14:24:41 +02:00
Valerio Ageno e0fc19ecaf doc: update tutorial 2024-06-15 14:17:12 +02:00
Valerio Ageno 0be0ce4c15 feat: handle 404 on tutorial 2024-06-15 14:04:08 +02:00
Valerio Ageno 792358ea9c fix: format macros 2024-06-15 12:31:39 +02:00
Valerio Ageno 26c0c2488d feat: handle status codes 2024-06-15 12:30:20 +02:00
Valerio Ageno 70b4b9c28f refactor: handle macros code in tuono_lib crate 2024-06-15 12:15:51 +02:00
Valerio Ageno 8b4db423b4 chore: improve folder structure tree 2024-06-12 13:42:02 +02:00
Valerio Ageno 7d65ede581 feat: update version to v0.1.2 2024-06-12 13:23:08 +02:00
Valerio Ageno 5b11f68fbb feat: pass headers to request 2024-06-12 13:20:44 +02:00
Valerio Ageno 0d33e6887b feat: update pnpm and install locally turbo 2024-06-09 16:42:13 +02:00
Valerio Ageno 5bb620a590 Update tutorial.md 2024-06-08 12:50:36 +02:00
Valerio Ageno 469386388b feat: update version to v0.1.1 2024-06-08 12:45:36 +02:00
Valerio Ageno 8728499f90 feat: refined reload logs 2024-06-08 12:42:58 +02:00
Valerio Ageno 2e82dde2c3 feat: refine development command logs 2024-06-08 12:33:34 +02:00
Valerio Ageno 253dd44d0d feat: update version to v0.1.0 2024-06-07 21:03:54 +02:00
Valerio Ageno 821b38e269 feat: set listener on popstate to allow back and forward browser buttons 2024-06-07 21:01:40 +02:00
Valerio Ageno 753bd21c14 Update README.md 2024-06-07 12:22:20 +02:00
Valerio Ageno 10757d4ef4 doc: add tutorial mention in tutorial example/ 2024-06-06 20:57:31 +02:00
Valerio Ageno d436637086 doc: add tutorial mention on the README 2024-06-06 20:54:09 +02:00
Valerio Ageno 0b5679ee07 doc: create tutorial README 2024-06-06 20:50:58 +02:00
Valerio Ageno 97b6cdfaaa doc: add README to examples/ root 2024-06-06 19:43:49 +02:00
Valerio Ageno b10d01cae0 doc: add tutorial example 2024-06-06 19:41:21 +02:00
Valerio Ageno 2262264cae feat: update version to v0.0.12 2024-06-06 19:19:31 +02:00
Valerio Ageno bedd23eed8 feat(tuono new): update replaced key for package.json 2024-06-06 19:18:06 +02:00
Valerio Ageno 12a1b12bac feat: clean up base tuono example 2024-06-06 19:15:07 +02:00
Valerio Ageno c141e0b843 fix: CSS module metion in readme 2024-06-06 18:57:47 +02:00
Valerio Ageno 4d12fd9d20 Update README.md 2024-06-06 08:34:59 +02:00
Valerio Ageno 5322fe910a doc: update README.md 2024-06-05 21:17:26 +02:00
Valerio Ageno 70a6aa1a67 fix: package name and update version to v0.0.11 2024-06-05 09:06:48 +02:00
Valerio Ageno 8d2be4178b feat: ugrade turbo 2024-06-04 20:57:53 +02:00
Valerio Ageno e89f2f63f8 feat: update version to v0.0.10 2024-06-04 20:49:13 +02:00
Valerio Ageno f6e7ebd33e fix: correctly import modulepreload-polyfill 2024-06-04 20:48:19 +02:00
Valerio Ageno 5ea209de0b feat: prevent default code on route 2024-06-04 20:29:36 +02:00
Valerio Ageno a4b2dd222d feat: update crate version to v0.0.9 2024-06-04 19:18:30 +02:00
Valerio Ageno c84f5d479b fix: static consts locations 2024-06-04 19:17:31 +02:00
Valerio Ageno 9251d445d3 feat: update version to v0.0.8 2024-06-04 19:06:53 +02:00
Valerio Ageno c1ff7e36a8 feat: update static_files mod import 2024-06-04 19:05:58 +02:00
Valerio Ageno 8dd8123fb1 feat: update version to v0.0.7 2024-06-04 18:59:33 +02:00
Valerio Ageno 7040fbfb3d feat: copy readme on pipeline 2024-06-04 18:58:24 +02:00
Valerio Ageno ee2abbd4e1 feat: tuono new command 2024-06-04 18:55:15 +02:00
Valerio Ageno 252c463300 feat: resize README logo 2024-06-03 20:59:39 +02:00
Valerio Ageno a10f205ccd feat: create tuono main page 2024-06-02 21:24:43 +02:00
Valerio Ageno 7cfaf94146 feat: enable dynamic routes on frontend 2024-06-02 20:32:53 +02:00
Valerio Ageno 7557df10f3 feat: enable dynamic routes on frontend 2024-06-02 12:14:56 +02:00
Valerio Ageno 64c37f42c5 feat: handle dynamic routes creation 2024-05-31 20:51:24 +02:00
Valerio Ageno 00594b7c3a feat: pass reqwest client to handler 2024-05-30 21:03:25 +02:00
Valerio Ageno 930e7bc851 feat: filter reload trigger files 2024-05-30 21:03:09 +02:00
Valerio Ageno d7d0001299 feat: add TuonoProps type 2024-05-29 21:54:21 +02:00
Valerio Ageno 1c0b4bba04 feat: update source builder 2024-05-29 21:31:28 +02:00
Valerio Ageno c12739d526 feat: create base tuono example 2024-05-26 19:05:19 +02:00
Valerio Ageno 0780a6ec79 feat: prevent empty .tuono folder 2024-05-26 18:44:15 +02:00
Valerio Ageno 73e142a5d7 feat: allow passing zero arguments to tuono CLI 2024-05-26 18:26:36 +02:00
Valerio Ageno d3cee9f1b2 feat: update ssr_rs crate to v0.5.2 2024-05-25 18:04:43 +02:00
Valerio Ageno e6370cb7d4 feat: add tuono/README.md as root README symlink 2024-05-25 18:02:21 +02:00
Valerio Ageno e2e6e313a5 feat: update version to v0.0.6 2024-05-25 18:01:09 +02:00
Valerio Ageno 2348576fa4 feat: generate main file from tuono dev cmd 2024-05-25 17:59:27 +02:00
Valerio Ageno 9550f8243c chore: remove outdated READMEs 2024-05-25 15:03:31 +02:00
Valerio Ageno 1d87a78393 chore: merge packages into tuono 2024-05-25 14:56:55 +02:00
Valerio Ageno ee092194d1 fix: change version to v0.0.5 2024-05-25 12:15:49 +02:00
Valerio Ageno 47a02cc572 fix: add tuono_lib_macro crate 2024-05-25 12:07:19 +02:00
259 changed files with 7085 additions and 1915 deletions
+1
View File
@@ -0,0 +1 @@
examples/** linguist-documentation
+23
View File
@@ -0,0 +1,23 @@
## Description
A clear and concise description of what the bug is.
## Expected behaviour
A clear and concise description of what you expected to happen.
## How to reproduce
Steps to reproduce the behavior:
## Screenshots
If applicable, add screenshots to help explain your problem.
## Tooling and environment
- Tuono version [e.g. 0.4.0]
- OS: [e.g. MacOS, Windows]
- Browser: [e.g. chrome, safari]
- Node version: [e.g. 20.0.0]
- Rust version: [e.g. 1.79.0]
- Crate version: [e.g. 1.78.0]
- Node Package Manger version: [e.g. pnpm: 9.5.0]
## Additional context
Add any other context about the problem here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+13
View File
@@ -0,0 +1,13 @@
## Context & Description
<!--
Thank you for your Pull Request.
Explain the context and why you're making that change. What is the problem
you're trying to solve? If a new feature is being added, describe the intended
use case that feature fulfills.
Bug fixes and new features should include tests.
Contributors guide: https://github.com/Valerioageno/tuono/blob/main/CONTRIBUTING.md
-->
+75
View File
@@ -0,0 +1,75 @@
name: Documentation Website CI
on:
push:
paths:
- '.github/**'
- 'apps/documentation/**'
pull_request:
paths:
- '.github/**'
- 'apps/documentation/**'
jobs:
build:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
timeout-minutes: 15
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./apps/documentation
steps:
- name: Check out code
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup rust
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Install tuono
run: cargo install tuono@0.8.3
- name: Install pnpm
run: npm i -g pnpm
- name: Install dependencies
run: pnpm install --ignore-workspace
- name: Build project
run: tuono build --static
fmt-lint-and-types:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
runs-on: ubuntu-latest
timeout-minutes: 15
defaults:
run:
working-directory: ./apps/documentation
steps:
- name: Check out code
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Install pnpm
run: npm i -g pnpm
- name: Install dependencies
run: pnpm install --ignore-workspace
- name: Check formatting
run: pnpm format:check
- name: Lint
run: pnpm lint
- name: Types
run: pnpm types
@@ -0,0 +1,56 @@
name: Deploy documentation website on AWS S3
on:
push:
branches:
- main
paths:
- '.github/**'
- 'apps/documentation/**'
jobs:
deploy-documentation:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./apps/documentation
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
steps:
- name: Check out code
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup rust
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Install tuono
run: cargo install tuono@0.8.3
- name: Install pnpm
run: npm i -g pnpm
- name: Install dependencies
run: pnpm install --ignore-workspace
- name: Build project
run: tuono build --static
- name: Deploy
uses: reggionick/s3-deploy@v4
with:
folder: apps/documentation/out/static
bucket: tuono-documentation
bucket-region: eu-west-3
dist-id: ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }}
invalidation: /
delete-removed: true
no-cache: true
private: true
files-to-include: '{.*/**,**}'
+5 -8
View File
@@ -25,14 +25,11 @@ jobs:
- name: Install dependencies
run: pnpm install
- name: Install turbo
run: pnpm install turbo --global
- name: Build
run: pnpm build
- name: Publish
run: pnpm publish --no-git-checks --dry-run --filter ./packages/tuono
run: pnpm publish -r --no-git-checks --dry-run
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -70,17 +67,17 @@ jobs:
version: 8
run_install: false
- name: Clone root README.md on tuono package
run: cp README.md packages/tuono/README.md
- name: Install dependencies
run: pnpm install
- name: Install turbo
run: pnpm install turbo --global
- name: Build
run: pnpm build
- name: Publish
run: pnpm publish --no-git-checks --filter ./packages/tuono
run: pnpm publish -r --no-git-checks
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+40
View File
@@ -0,0 +1,40 @@
name: Rust CI
on:
push:
paths:
- '.github/**'
- 'crates/**'
pull_request:
paths:
- '.github/**'
- 'crates/**'
env:
CARGO_TERM_COLOR: always
jobs:
lint_and_fmt:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: cargo fmt --all -- --check
- run: cargo clippy -- -D warnings
build_and_test:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
name: Build and test rust crates
runs-on: ubuntu-latest
strategy:
matrix:
toolchain:
- stable
- beta
- nightly
steps:
- uses: actions/checkout@v4
- run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }}
- run: cargo build --verbose
- run: cargo test --verbose
+66
View File
@@ -0,0 +1,66 @@
name: Typescript CI
on:
push:
paths:
- '.github/**'
- 'packages/**'
pull_request:
paths:
- '.github/**'
- 'packages/**'
jobs:
build-and-test:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install pnpm
run: npm i -g pnpm
- name: Install dependencies
run: pnpm install
- name: Build project
run: pnpm build
- name: Test project
run: pnpm test
fmt-lint-and-types:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Check out code
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Install pnpm
run: npm i -g pnpm
- name: Install dependencies
run: pnpm install
- name: Check formatting
run: pnpm format:check
- name: Lint
run: pnpm lint
- name: Types
run: pnpm types
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
valerioageno@yahoo.it.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+21
View File
@@ -0,0 +1,21 @@
![](https://github.com/Valerioageno/tuono/actions/workflows/rust.yml/badge.svg)
![](https://github.com/Valerioageno/tuono/actions/workflows/typescript.yml/badge.svg)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
# How to contribute to Tuono
## Contributions
Any feature contribution or suggestion is strongly appreciated.
Since the current project size there isn't yet a defined way to start a discussion. Consider to [open a new issue](https://github.com/Valerioageno/tuono/issues/new)
or to reach me using my email address [valerioageno@yahoo.it](mailto:valerioageno@ahoo.it). I'm also available on twitter (X) DMs @valerioageno.
## Bugs
**Did you find a bug?**
- Ensure the bug was not already reported by searching on GitHub under [Issues](https://github.com/Valerioageno/tuono/issues).
- If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/Valerioageno/tuono/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
**Did you write a patch that fixes a bug?**
- Open a new GitHub pull request with the patch.
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
- The pull requests must pass all the CI pipelines
+5 -1
View File
@@ -3,7 +3,11 @@ resolver = "2"
members = [
"crates/tuono",
"crates/tuono_lib",
"crates/tuono_lib_macros",
]
exclude = [
"examples/playground"
"apps/documentation",
"examples/mdx",
"examples/tuono",
"examples/tutorial"
]
+80 -37
View File
@@ -1,56 +1,99 @@
<p align="center">
<img src="https://raw.githubusercontent.com/Valerioageno/tuono/main/assets/logo.png">
</p>
<h1 align="center">Tuono<br>The react/rust fullstack framework</h1>
<p align="center">
⚠️ This project is under heavy development. API might drastically change ⚠️
</p>
[Documentation](https://tuono.dev) | [Tutorial](https://github.com/Valerioageno/tuono/blob/main/docs/tutorial.md) |
[✨Contributing](https://tuono.dev/documentation/contributing)
# Tuono
<img align="right" src="https://raw.githubusercontent.com/Valerioageno/tuono/main/assets/logo.png" width="160px">
![](https://github.com/Valerioageno/tuono/actions/workflows/rust.yml/badge.svg)
![](https://github.com/Valerioageno/tuono/actions/workflows/typescript.yml/badge.svg)
**Tuono** is the react/rust fullstack framework.
Tuono (Italian word for "thunder", pronounced /2 Oh No/).
Why Tuono? Just a badass name.
## Installation
> Check out the [tutorial](https://github.com/Valerioageno/tuono/blob/main/docs/tutorial.md) to get started.
```
cargo install tuono
```
## Introduction
## Create a new project
**NodeJs/Deno/Bun are the only runtimes that allow a React app to be fullstack right? (no)**
```
tuono new
```
Tuono is a fullstack React framework with the server side written in Rust.
Because of this Tuono is extremely fast and the requests are handled by multithreaded Rust server.
React is still React - it is just superpowered.
## Development
**Rust is an hard language then writing server side code is hard as well right? (no again)**
```
tuono dev
```
Tuono provides a collection of utilities to handle the server side code seamlessly with the React code.
Each server side route is managed with a separate file alongside the React route. The routing is handled
by Tuono based on the files defined within the `./src/routes` directory.
## Features
- Rust based server side rendering
- FS routing
- CSS modules
- Hot Module Reload
- Multi thread backend
- 🟦 Typescript
- 🌐 Routing
- 🔥 Hot Module Reload
- 🍭 CSS modules
- 🧬 Server Side Rendering
- 🧵 Multi thread backend
- ⌨️ MDX support
- ⚙️ Build optimizations
- Custom APIs*
- Image optimization*
- Server streamed content*
> *Development in progress
## Getting started
As already mentioned above I strongly suggest you to take a look at the
[tutorial](https://github.com/Valerioageno/tuono/blob/main/docs/tutorial.md).
Tuono is the CLI that provides all the needed commands to handle the fullstack project.
To download it is required [cargo](https://doc.rust-lang.org/cargo/) which is the [rust](https://www.rust-lang.org/)
package manager.
Then run `cargo install tuono`.
To list all the available commands run `tuono -h`
To create a new project run `tuono new [NAME]` (optionally you can pass the `--template` (or `-t`) flag - check the
[examples](https://github.com/Valerioageno/tuono/tree/main/examples) folder).
Then to run the local development environment run inside the project folder `tuono dev`
Finally when the project will be ready to be deployed just run `tuono build` to create the final React assets
and to set the server project in the `production` mode.
Now to execute it just run `cargo run --release`.
## Requirements
- rust
- cargo
- node
- npm/pnpm/yarn*
> yarn [pnp](https://yarnpkg.com/features/pnp) is not supported yet
## Folder structure
```
- .tuono
- public/
- src/
| - routes/
| | - api/
├── package.json
├── public
├── src
│ ├── routes
│ └── styles
├── Cargo.toml
├── README.md
└── tsconfig.json
```
```tsx
// Data is passed by the loading function
const IndexPage = ({data, isLoading, isError}) => <h1>Index Page</h1>
## Contributing
Any help or suggestion will be appreciated and encouraged.
export const Route = createFileRoute({
loader: (params) => fetchApi(params),
component: IndexPage
})
```
## License
This project is licensed under the MIT License.
-24
View File
@@ -1,24 +0,0 @@
# Repository structure doc
## Monorepo tool
- [Turborepo](https://turbo.build/repo)
## Packages
> Highly inspired by [@tanstack/router](https://tanstack.com/router/latest)
- vite-fs-router
- router-generator
- react-router
- react-router-server
- tuono-runtime (entry point)
### JS Public interface
- tuono-runtime (all in one js framework package)
## Crates
- tuono (cli interface)
- tuono-axum-builder (axum project builder)
- tuono-watch (folder watch reload)
### Rust Public interface
- tuono (cli, dev and prod environment)
+1
View File
@@ -0,0 +1 @@
# Stadalone apps folder
+103
View File
@@ -0,0 +1,103 @@
{
"root": true,
"reportUnusedDisableDirectives": true,
"ignorePatterns": ["**/build", "**/dist"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "import"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/stylistic",
"plugin:import/recommended",
"plugin:import/typescript",
"prettier",
],
"env": {
"browser": true,
"es2020": true,
},
"parserOptions": {
"tsconfigRootDir": ".",
"project": true,
"sourceType": "module",
"ecmaVersion": 2020,
},
"settings": {
"import/parsers": {
"@typescript-eslint/parser": [".ts", ".tsx"],
},
"import/resolver": {
"typescript": true,
},
"react": {
"version": "detect",
},
},
"rules": {
"@typescript-eslint/array-type": "error",
"@typescript-eslint/ban-types": "error",
"@typescript-eslint/ban-ts-comment": "error",
"@typescript-eslint/consistent-type-definitions": "error",
"@typescript-eslint/consistent-type-imports": [
"error",
{ "prefer": "type-imports" },
],
"@typescript-eslint/explicit-module-boundary-types": "error",
"@typescript-eslint/method-signature-style": ["error", "property"],
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "typeParameter",
"format": ["PascalCase"],
"leadingUnderscore": "forbid",
"trailingUnderscore": "forbid",
"custom": {
"regex": "^(T|T[A-Z][A-Za-z]+)$",
"match": true,
},
},
],
"@typescript-eslint/no-empty-function": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unnecessary-condition": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-function-return-type": "error",
"@typescript-eslint/no-inferrable-types": [
"error",
{ "ignoreParameters": true },
],
"import/default": "error",
"import/export": "error",
"import/namespace": "error",
"import/newline-after-import": "error",
"import/no-cycle": "error",
"import/no-duplicates": "off",
"import/no-named-as-default-member": "error",
"import/no-unused-modules": "error",
"import/order": [
"off",
{
"groups": [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
"object",
"type",
],
},
],
"no-case-declarations": "error",
"no-empty": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-shadow": "error",
"no-undef": "off",
"sort-imports": "off",
},
}
+13
View File
@@ -0,0 +1,13 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.tuono
out
target
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "tuono"
version = "0.0.1"
edition = "2021"
[[bin]]
name = "tuono"
path = ".tuono/main.rs"
[dependencies]
tuono_lib = "0.9.0"
serde = { version = "1.0.202", features = ["derive"] }
+7
View File
@@ -0,0 +1,7 @@
# Tuono starter
This is the starter tuono project. To download it run in your terminal:
```shell
$ tuono new [NAME]
```
+40
View File
@@ -0,0 +1,40 @@
{
"name": "tuono",
"description": "The react/rust fullstack framework",
"version": "0.0.1",
"scripts": {
"lint": "eslint --ext .ts,.tsx ./src -c .eslintrc",
"format": "prettier -u --write --ignore-unknown './src/**/*'",
"format:check": "prettier --check --ignore-unknown './src/**/*'",
"types": "tsc --noEmit"
},
"dependencies": {
"@mantine/code-highlight": "^7.11.2",
"@mantine/core": "^7.11.2",
"@mantine/hooks": "^7.11.2",
"@mdx-js/react": "^3.0.1",
"@tabler/icons-react": "^3.11.0",
"clsx": "^2.1.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"tuono": "0.9.0"
},
"devDependencies": {
"@types/mdx": "^2.0.13",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"postcss": "^8.4.39",
"postcss-preset-mantine": "^1.17.0",
"postcss-simple-vars": "^7.0.1",
"prettier": "^3.2.4",
"typescript": "^5.5.4"
}
}
+14
View File
@@ -0,0 +1,14 @@
module.exports = {
plugins: {
'postcss-preset-mantine': {},
'postcss-simple-vars': {
variables: {
'mantine-breakpoint-xs': '36em',
'mantine-breakpoint-sm': '48em',
'mantine-breakpoint-md': '62em',
'mantine-breakpoint-lg': '75em',
'mantine-breakpoint-xl': '88em',
},
},
},
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,52 @@
import { Breadcrumbs, Button } from '@mantine/core'
import { Link } from 'tuono'
import { IconChevronRight, IconBolt } from '@tabler/icons-react'
import type { ReactNode } from 'react'
export default function TuonoBreadcrumbs({
children,
}: {
children: ReactNode
}): JSX.Element {
return (
<Breadcrumbs
separator={<IconChevronRight size="1.1rem" stroke={1.5} />}
mb="md"
mt="md"
>
<Button
href="/documentation"
component={Link}
variant="subtle"
radius="xl"
p={5}
>
<IconBolt />
</Button>
{children}
</Breadcrumbs>
)
}
interface BreadcrumbElementProps {
href?: string
label: string
}
export function BreadcrumbElement({
href,
label,
}: BreadcrumbElementProps): JSX.Element {
return (
<Button
component={href ? Link : 'span'}
href={href}
variant={href ? 'subtle' : 'light'}
radius="xl"
px={href ? 10 : undefined}
>
{label}
</Button>
)
}
@@ -0,0 +1,5 @@
import Breadcrumbs, { BreadcrumbElement } from './breadcrumbs'
export default Breadcrumbs
export { BreadcrumbElement as Element }
@@ -0,0 +1,23 @@
import { Button } from '@mantine/core'
import { IconEdit } from '@tabler/icons-react'
import { useRouter } from 'tuono'
const GITHUB_URL =
'https://github.com/Valerioageno/tuono/tree/main/apps/documentation/src/routes'
export default function EditPage(): JSX.Element {
const { pathname } = useRouter()
return (
<Button
p={0}
mt={60}
component="a"
variant="transparent"
leftSection={<IconEdit />}
target="_blank"
href={GITHUB_URL.concat(pathname).concat('.mdx')}
>
Edit page
</Button>
)
}
@@ -0,0 +1,3 @@
import EditPage from './edit-page'
export default EditPage
@@ -0,0 +1,53 @@
import {
Button,
Center,
Container,
CopyButton,
Group,
rem,
Text,
Title,
} from '@mantine/core'
import { IconCopy, IconCheck } from '@tabler/icons-react'
import { Link } from 'tuono'
export default function Hero(): JSX.Element {
return (
<Container size={1100} mt={200}>
<Center>
<Title order={1}>The react/rust fullstack framework</Title>
</Center>
<Center mt={50}>
<Text fz="18px">
The technologies we love seamessly working together to unleash the
<strong> highest web performance</strong> ever met on react
</Text>
</Center>
<Center mt={50}>
<Group>
<Button component={Link} href="/documentation" size="lg">
Get Started
</Button>
<CopyButton value="cargo install tuono">
{({ copied, copy }) => (
<Button
onClick={copy}
size="lg"
style={{ border: 'solid 1px var(--mantine-color-violet-1)' }}
color="gray"
leftSection="cargo install tuono"
rightSection={
copied ? (
<IconCheck style={{ width: rem(20) }} />
) : (
<IconCopy style={{ width: rem(20) }} />
)
}
/>
)}
</CopyButton>
</Group>
</Center>
</Container>
)
}
@@ -0,0 +1,3 @@
import Hero from './hero'
export default Hero
@@ -0,0 +1,3 @@
import MdxProvider from './mdx-provider'
export default MdxProvider
@@ -0,0 +1,5 @@
import { Text, type TextProps } from '@mantine/core'
export default function MdxBold(props: TextProps): JSX.Element {
return <Text fw={700} {...props} />
}
@@ -0,0 +1,3 @@
import MdxCode from './mdx-code'
export default MdxCode
@@ -0,0 +1,8 @@
import { Code } from '@mantine/core'
import type { HTMLAttributes } from 'react'
export default function MdxCode(
props: HTMLAttributes<HTMLPreElement>,
): JSX.Element {
return <Code {...props} />
}
@@ -0,0 +1,8 @@
import { Title } from '@mantine/core'
import type { HTMLAttributes } from 'react'
export default function MdxH2(
props: HTMLAttributes<HTMLHeadingElement>,
): JSX.Element {
return <Title {...props} mt={20} order={2} />
}
@@ -0,0 +1,3 @@
import MdxLink from './mdx-link'
export default MdxLink
@@ -0,0 +1,36 @@
import type { AnchorHTMLAttributes } from 'react'
import { Button } from '@mantine/core'
import { Link } from 'tuono'
import { IconExternalLink } from '@tabler/icons-react'
export default function MdxLink(
props: AnchorHTMLAttributes<HTMLAnchorElement>,
): JSX.Element {
if (props.href?.startsWith('http')) {
return (
<Button
component="a"
{...props}
target="_blank"
rightSection={
<IconExternalLink size="16px" style={{ marginLeft: -5 }} />
}
variant="transparent"
style={{ height: '20px' }}
mt={-2}
p={0}
/>
)
}
return (
<Button
component={Link}
{...props}
target="_blank"
variant="transparent"
style={{ height: '20px' }}
mt={-2}
p={0}
/>
)
}
@@ -0,0 +1,3 @@
import MdxPre from './mdx-pre'
export default MdxPre
@@ -0,0 +1,5 @@
.pre {
code {
font-size: 16px;
}
}
@@ -0,0 +1,16 @@
import { CodeHighlight } from '@mantine/code-highlight'
import styles from './mdx-pre.module.css'
interface PreProps {
children: any
}
export default function MdxPre({ children }: PreProps): JSX.Element {
return (
<CodeHighlight
className={styles.pre}
style={{ borderRadius: 8 }}
code={children.props.children || ''}
language={children.props.className?.replace('language-', '')}
/>
)
}
@@ -0,0 +1,35 @@
import { MDXProvider } from '@mdx-js/react'
import MdxLink from './mdx-link'
import type { ReactNode } from 'react'
import MdxPre from './mdx-pre'
import MdxQuote from './mdx-quote'
import MdxCode from './mdx-code'
import MdxTitle from './mdx-title'
import MdxBold from './mdx-bold/mdx-bold'
import MdxH2 from './mdx-h2/mdx-h2'
interface MdxProviderProps {
children: ReactNode
}
export default function MdxProvider({
children,
}: MdxProviderProps): JSX.Element {
return (
<MDXProvider
components={{
a: MdxLink,
// @ts-expect-error: useless finding the correct props types
pre: MdxPre,
blockquote: MdxQuote,
code: MdxCode,
h1: MdxTitle,
h2: MdxH2,
strong: MdxBold,
}}
>
{children}
</MDXProvider>
)
}
@@ -0,0 +1,3 @@
import MdxQuote from './mdx-quote'
export default MdxQuote
@@ -0,0 +1,21 @@
import { Blockquote, Space } from '@mantine/core'
import type { HTMLAttributes } from 'react'
export default function MdxQuote(
props: HTMLAttributes<HTMLQuoteElement>,
): JSX.Element {
return (
<>
<Blockquote
color="violet"
py={1}
px={20}
mt={30}
iconSize={30}
{...props}
style={{ borderRadius: 8 }}
/>
<Space h="md" />
</>
)
}
@@ -0,0 +1,3 @@
import MdxTitle from './mdx-title'
export default MdxTitle
@@ -0,0 +1,8 @@
import { Title } from '@mantine/core'
import type { HTMLAttributes } from 'react'
export default function MdxTitle(
props: HTMLAttributes<HTMLHeadingElement>,
): JSX.Element {
return <Title {...props} order={1} />
}
@@ -0,0 +1,33 @@
import { Flex, Button, ActionIcon, Group } from '@mantine/core'
import { IconBrandGithub, IconBook } from '@tabler/icons-react'
import ThemeBtn from '../theme-btn'
import { Link } from 'tuono'
export default function Actions(): JSX.Element {
return (
<Flex gap={8}>
<Button
href="/documentation"
component={Link}
size="compact-lg"
rightSection={<IconBook />}
autoContrast
>
Get started
</Button>
<Group gap={8} visibleFrom="sm">
<ActionIcon
variant="default"
size="lg"
aria-label="Check the project on github"
href="https://github.com/Valerioageno/tuono"
target="_blank"
component="a"
>
<IconBrandGithub />
</ActionIcon>
<ThemeBtn />
</Group>
</Flex>
)
}
@@ -0,0 +1,3 @@
import Navbar from './navbar'
export default Navbar
@@ -0,0 +1,32 @@
import { AppShell, Burger, Button, Flex } from '@mantine/core'
import { Link, useRouter } from 'tuono'
import Actions from './actions'
interface NavbarProps {
opened: boolean
toggle: () => void
}
export default function Navbar({ opened, toggle }: NavbarProps): JSX.Element {
const { pathname } = useRouter()
return (
<AppShell.Header p="sm">
<Flex justify="space-between">
<Button component={Link} href="/" variant="transparent" p={0} fz={28}>
Tuono
</Button>
<Flex align="center" gap={8}>
<Actions />
{pathname.startsWith('/documentation') && (
<Burger
opened={opened}
onClick={toggle}
hiddenFrom="sm"
size="sm"
/>
)}
</Flex>
</Flex>
</AppShell.Header>
)
}
@@ -0,0 +1,3 @@
import Sidebar from './sidebar'
export default Sidebar
@@ -0,0 +1,6 @@
.link {
border-radius: 8px;
margin-top: 0.25rem;
line-height: 1.25rem;
font-weight: bold;
}
@@ -0,0 +1,45 @@
import { NavLink, type NavLinkProps } from '@mantine/core'
import { useState, type ReactNode } from 'react'
import { Link, useRouter } from 'tuono'
import { IconChevronRight } from '@tabler/icons-react'
import styles from './sidebar-link.module.css'
interface SidebarLinkProps {
label: string
href: string
onClick?: () => void
children?: ReactNode
}
export default function SidebarLink(
props: SidebarLinkProps & NavLinkProps,
): JSX.Element {
const { pathname } = useRouter()
const [isOpen, setIsOpen] = useState<boolean>(!!props.defaultOpened)
return (
<NavLink
component={props.href.startsWith('#') ? 'button' : Link}
active={pathname === props.href}
className={styles.link}
rightSection={
props.children && (
<IconChevronRight
size="1.2rem"
stroke={1.5}
className="mantine-rotate-rtl"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setIsOpen((state) => !state)
}}
/>
)
}
opened={isOpen}
autoContrast
{...props}
/>
)
}
@@ -0,0 +1,40 @@
import { AppShell } from '@mantine/core'
import SidebarLink from './sidebar-link'
export default function Sidebar({ close }: { close: () => void }): JSX.Element {
return (
<AppShell.Navbar p="md">
<h3>Tutorial</h3>
<SidebarLink
href="/documentation/tutorial/intro"
label="Intro"
onClick={close}
/>
<h3>Documentation</h3>
<SidebarLink href="/documentation" label="Overview" onClick={close} />
<SidebarLink
href="/documentation/installation"
label="Installation"
onClick={close}
/>
<SidebarLink
href="/documentation/getting-started"
label="Getting started"
onClick={close}
/>
<SidebarLink label="Routing" href="/documentation/routing" defaultOpened>
<SidebarLink
href="/documentation/routing/intro"
label="Project structure"
onClick={close}
/>
</SidebarLink>
<SidebarLink
label="Contributing"
href="/documentation/contributing"
onClick={close}
leftSection="✨"
/>
</AppShell.Navbar>
)
}
@@ -0,0 +1,3 @@
import ThemeBtn from './theme-btn'
export default ThemeBtn
@@ -0,0 +1,24 @@
.icon {
width: 22px;
height: 22px;
}
.dark {
@mixin dark {
display: none;
}
@mixin light {
display: block;
}
}
.light {
@mixin light {
display: none;
}
@mixin dark {
display: block;
}
}
@@ -0,0 +1,30 @@
import {
ActionIcon,
useMantineColorScheme,
useComputedColorScheme,
} from '@mantine/core'
import { IconSun, IconMoon } from '@tabler/icons-react'
import cx from 'clsx'
import classes from './theme-btn.module.css'
export default function ThemeBtn(): JSX.Element {
const { setColorScheme } = useMantineColorScheme()
const computedColorScheme = useComputedColorScheme('light', {
getInitialValueInEffect: true,
})
return (
<ActionIcon
onClick={() =>
setColorScheme(computedColorScheme === 'light' ? 'dark' : 'light')
}
variant="default"
size="lg"
aria-label="Toggle color scheme"
>
<IconSun className={cx(classes.icon, classes.light)} stroke={1.5} />
<IconMoon className={cx(classes.icon, classes.dark)} stroke={1.5} />
</ActionIcon>
)
}
+2
View File
@@ -0,0 +1,2 @@
// declaration.d.ts
declare module '*.css'
+79
View File
@@ -0,0 +1,79 @@
import type { ReactNode } from 'react'
import {
ColorSchemeScript,
createTheme,
MantineProvider,
AppShell,
} from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { Head, useRouter } from 'tuono'
import Navbar from '../components/navbar'
import '@mantine/core/styles.css'
import '@mantine/code-highlight/styles.css'
import Sidebar from '../components/sidebar'
interface RootRouteProps {
children: ReactNode
}
const theme = createTheme({
primaryColor: 'violet',
primaryShade: { light: 6, dark: 9 },
fontFamily: 'Roboto',
respectReducedMotion: true,
fontSizes: {
// 'xs' | 'sm' | 'md' | 'lg' | 'xl'
xs: '16px',
sm: '16px',
},
colors: {
dark: [
'#d5d7e0',
'#acaebf',
'#8c8fa3',
'#666980',
'#4d4f66',
'#34354a',
'#2b2c3d',
'#1d1e30',
'#0c0d21',
'#01010a',
],
},
headings: {
sizes: {
h1: {
fontSize: '48px',
},
},
},
})
export default function RootRoute({ children }: RootRouteProps): JSX.Element {
const [opened, { toggle }] = useDisclosure()
const { pathname } = useRouter()
return (
<>
<Head>
<ColorSchemeScript />
</Head>
<MantineProvider theme={theme}>
<AppShell
header={{ height: 60 }}
navbar={{
width: 300,
breakpoint: 'sm',
collapsed: { mobile: !opened },
}}
>
<Navbar opened={opened} toggle={toggle} />
{pathname.startsWith('/documentation') && <Sidebar close={toggle} />}
{children}
</AppShell>
</MantineProvider>
</>
)
}
@@ -0,0 +1,19 @@
import type { ReactNode } from 'react'
import { AppShell, Container } from '@mantine/core'
import MdxProvider from '../../components/mdx-provider'
import EditPage from '../../components/edit-page'
interface RootRouteProps {
children: ReactNode
}
export default function RootRoute({ children }: RootRouteProps): JSX.Element {
return (
<AppShell.Main>
<Container component="article" p={20}>
<MdxProvider>{children}</MdxProvider>
<EditPage />
</Container>
</AppShell.Main>
)
}
@@ -0,0 +1,32 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Contributing</title>
</Head>
import Breadcrumbs, { Element } from '../../components/breadcrumbs'
<Breadcrumbs>
<Element label="✨ Contributing"/>
</Breadcrumbs>
# How to contribute
## TL;DR
The project is massive - if you like it do consider to contribute!
## Getting started
Currently I'm keeping a private dashboard to prioritize new features and bug fixes.
If you want to propose something please open a new issue on github or reach me using
my email address [valerioageno@yahoo.it](mailto:valerioageno@yahoo.it).
I'm also available on twitter (X) DMs `@valerioageno`, [linkedin](https://www.linkedin.com/in/valerioageno)
and discord `@__v__v__`.
## Requirements
To contribute is not strictly required to know both typescript and rust (even though it
would be a great nice to have). Most of the feature tasks and bugfixes can be handled solely on
the client or on the server side.
@@ -0,0 +1,29 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Getting started</title>
</Head>
import Breadcrumbs, { Element } from '../../components/breadcrumbs'
<Breadcrumbs>
<Element label="Getting started"/>
</Breadcrumbs>
# Getting started
Tuono is the CLI that provides all the needed commands to handle the fullstack project.
> ☝️ Check the [installation](/documentation/installation) page if you haven't installed the
`tuono` CLI yet.
To list all the available commands run `tuono -h`.
To create a new project run `tuono new [NAME]` (optionally you can pass the --template (or -t) flag - check the examples folder).
Then to run the local development environment run inside the project folder `tuono dev`
Finally when the project will be ready to be deployed just run `tuono build` to create the final React assets and to set the server project in the production mode.
Now to execute it just run `cargo run --release`.
@@ -0,0 +1,50 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Documentation</title>
</Head>
import Breadcrumbs from '../../components/breadcrumbs'
<Breadcrumbs>
</Breadcrumbs>
# Tuono
**Tuono is a fullstack framework for building React applications using Rust as
backend.**
Tuono (Italian word for "thunder", pronounced /2 Oh No/). Why Tuono? Just a badass name.
## Introduction
**NodeJs/Deno/Bun are the only runtimes that allow a React app to be fullstack right? (no)**
Tuono is a fullstack React framework with the server side written in Rust.
Because of this Tuono is extremely fast and the requests are handled by multithreaded Rust server.
React is still React - it is just superpowered.
**Rust is an hard language then writing server side code is hard as well right? (no again)**
Tuono provides a collection of utilities to handle the server side code seamlessly with
the React code. Each server side route is managed with a separate file alongside the React route.
The routing is handled by Tuono based on the files defined within the `./src/routes` directory.
## Features
Some of its features include:
- 🟦 Full typescript support
- 🌐 File system based routing
- 🔥 Hot Module Reload
- 🍭 SCSS/CSS modules
- 🧬 Server Side Rendering
- 🧵 Multi thread backend
- ⌨️ MDX support
- ⚙️ Build optimizations
- Custom APIs*
- Image optimization*
- Server streamed content*
> *development in progress
@@ -0,0 +1,56 @@
import { Head } from 'tuono'
import Breadcrumbs, { Element } from '../../components/breadcrumbs'
<Head>
<title>Tuono - Installation</title>
</Head>
<Breadcrumbs>
<Element label="Installation"/>
</Breadcrumbs>
# Installation
## Requirements
`Tuono` is a development environment built in rust and typescript that outputs a website written with both the
languages. Since that you need the following tools installed on your computer to work with it:
- `Rust` - The rust programming language toolchain (Go [here](https://rustup.rs/) for installing both `rust` and `cargo`)
- `Cargo` - The rust package manager
- `NodeJs` - The Javascript runtime (Go [here](https://nodejs.org/en/download/package-manager) for installing both `nodejs` and `npm`)
- `npm` or `yarn` or `pnpm` - A javascript package manager
> NodeJs is needed just for the development environment. The final output will run on a rust server.
## Installation
The tuono `CLI` is hosted on [crates.io](https://crates.io/crates/tuono); to download and install it just run on a terminal:
```bash
cargo install tuono
```
To check that is correctly installed run:
```bash
tuono --version
```
Run `tuono -h` to see all the available commands.
```bash
The react/rust fullstack framework
Usage: tuono <COMMAND>
Commands:
dev Start the development environment
build Build the production assets
new Scaffold a new project
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help
-V, --version Print version
```
@@ -0,0 +1,15 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Routing</title>
</Head>
import Breadcrumbs, { Element } from '../../../components/breadcrumbs'
<Breadcrumbs>
<Element label="Routing"/>
</Breadcrumbs>
# Routing index
TODO
@@ -0,0 +1,16 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Routing</title>
</Head>
import Breadcrumbs, { Element } from '../../../components/breadcrumbs'
<Breadcrumbs>
<Element label="Routing" href="/documentation/routing"/>
<Element label="Project structure"/>
</Breadcrumbs>
# Project structure
Todo
@@ -0,0 +1,15 @@
import { Head } from 'tuono'
<Head>
<title>Tuono - Tutorial intro</title>
</Head>
import Breadcrumbs, { Element } from '../../../components/breadcrumbs'
<Breadcrumbs>
<Element label="Tutorial"/>
</Breadcrumbs>
# Tutorial intro
TODO
+17
View File
@@ -0,0 +1,17 @@
import { Head } from 'tuono'
import Hero from '../components/hero'
export default function IndexPage(): JSX.Element {
return (
<>
<Head>
<title>Tuono - The react/rust fullstack framework</title>
<meta
name="description"
content="The technologies we love seamessly working together to unleash the highest web performance ever met on react"
/>
</Head>
<Hero />
</>
)
}
+1
View File
@@ -0,0 +1 @@
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
+9 -3
View File
@@ -1,10 +1,11 @@
[package]
name = "tuono"
version = "0.0.3"
version = "0.9.1"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
homepage = "https://github.com/Valerioageno/tuono"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming"]
@@ -18,11 +19,16 @@ name = "tuono"
path = "src/lib.rs"
[dependencies]
clap = { version = "4.5.4", features = ["derive"] }
clap = { version = "4.5.4", features = ["derive", "cargo"] }
watchexec = "4.0.0"
miette = "7.2.0"
watchexec-signals = "3.0.0"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0.202", features = ["derive"] }
watchexec-supervisor = "2.0.0"
glob = "0.3.1"
regex = "1.10.4"
reqwest = {version = "0.12.4", features =["blocking", "json"]}
serde_json = "1.0"
fs_extra = "1.3.0"
-1
View File
@@ -1 +0,0 @@
# Tuono
+301
View File
@@ -0,0 +1,301 @@
use glob::glob;
use glob::GlobError;
use std::collections::{hash_map::Entry, HashMap};
use std::path::PathBuf;
use std::process::Child;
use std::process::Command;
use std::process::Stdio;
use crate::route::Route;
const IGNORE_EXTENSIONS: [&str; 3] = ["css", "scss", "sass"];
const IGNORE_FILES: [&str; 1] = ["__root"];
#[derive(Debug)]
pub struct App {
pub route_map: HashMap<String, Route>,
pub base_path: PathBuf,
}
impl App {
pub fn new() -> Self {
let base_path = std::env::current_dir().unwrap();
let mut app = App {
route_map: HashMap::new(),
base_path,
};
app.collect_routes();
app
}
fn collect_routes(&mut self) {
glob(self.base_path.join("src/routes/**/*.*").to_str().unwrap())
.expect("Failed to read glob pattern")
.for_each(|entry| {
if self.should_collect_route(&entry) {
self.collect_route(entry)
}
})
}
fn should_collect_route(&self, entry: &Result<PathBuf, GlobError>) -> bool {
let file_extension = entry.as_ref().unwrap().extension().unwrap();
let file_name = entry.as_ref().unwrap().file_stem().unwrap();
if IGNORE_EXTENSIONS.iter().any(|val| val == &file_extension) {
return false;
}
if IGNORE_FILES.iter().any(|val| val == &file_name) {
return false;
}
true
}
fn collect_route(&mut self, path_buf: Result<PathBuf, GlobError>) {
let entry = path_buf.unwrap();
let base_path_str = self.base_path.to_str().unwrap();
let path = entry
.to_str()
.unwrap()
.replace(&format!("{base_path_str}/src/routes"), "")
.replace(".rs", "")
.replace(".mdx", "")
.replace(".tsx", "");
if entry.extension().unwrap() == "rs" {
if let Entry::Vacant(route_map) = self.route_map.entry(path.clone()) {
let mut route = Route::new(path);
route.update_axum_info();
route_map.insert(route);
} else {
let route = self.route_map.get_mut(&path).unwrap();
route.update_axum_info();
}
return;
}
if let Entry::Vacant(route_map) = self.route_map.entry(path.clone()) {
let route = Route::new(path);
route_map.insert(route);
}
}
pub fn has_dynamic_routes(&self) -> bool {
self.route_map.iter().any(|(_, route)| route.is_dynamic)
}
pub fn build_react_prod(&self) {
Command::new("./node_modules/.bin/tuono-build-prod")
.output()
.expect("Failed to build the react source");
}
pub fn run_rust_server(&self) -> Child {
Command::new("cargo")
.arg("run")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to run the rust server")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_collect_routes() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/about.rs",
"/home/user/Documents/tuono/src/routes/index.rs",
"/home/user/Documents/tuono/src/routes/posts/index.rs",
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
"/home/user/Documents/tuono/src/routes/posts/UPPERCASE.rs",
];
routes
.into_iter()
.for_each(|route| app.collect_route(Ok(PathBuf::from(route))));
let results = [
("/index", "index"),
("/about", "about"),
("/posts/index", "posts_index"),
("/posts/[post]", "posts_dyn_post"),
("/posts/UPPERCASE", "posts_uppercase"),
];
results.into_iter().for_each(|(path, module_import)| {
assert_eq!(
app.route_map
.get(path)
.unwrap()
.axum_info
.as_ref()
.unwrap()
.module_import,
String::from(module_import)
)
})
}
#[test]
fn should_create_multi_level_axum_paths() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/about.rs",
"/home/user/Documents/tuono/src/routes/index.rs",
"/home/user/Documents/tuono/src/routes/posts/index.rs",
"/home/user/Documents/tuono/src/routes/posts/any-post.rs",
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
];
routes
.into_iter()
.for_each(|route| app.collect_route(Ok(PathBuf::from(route))));
let results = [
("/index", "/"),
("/about", "/about"),
("/posts/index", "/posts"),
("/posts/any-post", "/posts/any-post"),
("/posts/[post]", "/posts/:post"),
];
results.into_iter().for_each(|(path, expected_path)| {
assert_eq!(
app.route_map
.get(path)
.unwrap()
.axum_info
.as_ref()
.unwrap()
.axum_route,
String::from(expected_path)
)
})
}
#[test]
fn should_ignore_whitelisted_extensions() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/about.css",
"/home/user/Documents/tuono/src/routes/index.scss",
"/home/user/Documents/tuono/src/routes/posts/index.sass",
];
routes.into_iter().for_each(|route| {
if app.should_collect_route(&Ok(PathBuf::from(route))) {
app.collect_route(Ok(PathBuf::from(route)))
}
});
assert!(app.route_map.is_empty())
}
#[test]
fn should_ignore_whitelisted_files() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/__root.tsx",
"/home/user/Documents/tuono/src/routes/posts/__root.tsx",
];
routes.into_iter().for_each(|route| {
if app.should_collect_route(&Ok(PathBuf::from(route))) {
app.collect_route(Ok(PathBuf::from(route)))
}
});
assert!(app.route_map.is_empty())
}
#[test]
fn should_correctly_parse_routes_with_server_handler() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/about.rs",
"/home/user/Documents/tuono/src/routes/about.tsx",
"/home/user/Documents/tuono/src/routes/index.tsx",
];
routes
.into_iter()
.for_each(|route| app.collect_route(Ok(PathBuf::from(route))));
let results = [("/about", true), ("/index", false)];
results
.into_iter()
.for_each(|(path, expected_has_server_handler)| {
if expected_has_server_handler {
assert!(app.route_map.get(path).unwrap().axum_info.is_some())
} else {
assert!(app.route_map.get(path).unwrap().axum_info.is_none())
}
})
}
#[test]
fn has_dynamic_routes_works() {
let mut app = App::new();
app.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/index.rs",
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
];
routes
.into_iter()
.for_each(|route| app.collect_route(Ok(PathBuf::from(route))));
assert!(app.has_dynamic_routes());
let mut app2 = App::new();
app2.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/[post].rs",
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
];
routes
.into_iter()
.for_each(|route| app2.collect_route(Ok(PathBuf::from(route))));
assert!(app2.has_dynamic_routes());
let mut app3 = App::new();
app3.base_path = "/home/user/Documents/tuono".into();
let routes = [
"/home/user/Documents/tuono/src/routes/index.rs",
"/home/user/Documents/tuono/src/routes/posts/index.rs",
];
routes
.into_iter()
.for_each(|route| app3.collect_route(Ok(PathBuf::from(route))));
assert!(!app3.has_dynamic_routes())
}
}
-161
View File
@@ -1,161 +0,0 @@
use glob::glob;
use std::collections::HashMap;
use std::fs;
use std::io::prelude::*;
use std::path::Path;
use std::path::PathBuf;
const ROOT_FOLDER: &'static str = "src/routes";
enum Mode {
Prod,
Dev,
}
const AXUM_ENTRY_POINT: &'static str = r##"
// File automatically generated
// Do not manually change it
use axum::extract::Request;
use axum::response::Html;
use axum::{routing::get, Router};
use tower_http::services::ServeDir;
use tuono_lib::{ssr, Ssr};
// MODULE_IMPORTS
#[tokio::main]
async fn main() {
Ssr::create_platform();
let app = Router::new()
// ROUTE_BUILDER
.fallback_service(ServeDir::new("public").fallback(get(catch_all)));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn catch_all(request: Request) -> Html<String> {
let pathname = &request.uri();
let headers = &request.headers();
let req = tuono_lib::Request::new(pathname, headers);
// TODO: remove unwrap
let payload = tuono_lib::Payload::new(&req, Box::new(""))
.client_payload()
.unwrap();
let result = ssr::Js::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload)));
match result {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string()),
}
}
"##;
fn create_main_file(base_path: &Path, bundled_file: &String) {
let mut data_file =
fs::File::create(base_path.join(".tuono/main.rs")).expect("creation failed");
data_file
.write(bundled_file.as_bytes())
.expect("write failed");
}
fn get_route_name<'a>(path: &PathBuf, base_path: &Path) -> String {
let base_path_str = base_path.to_str().unwrap();
if base_path_str == "." {
return path.to_str().unwrap().replace("/src/routes/", "");
}
// TODO: refactor this horrible code
if base_path_str.ends_with("/") {
return path
.to_str()
.unwrap()
.replace(&format!("{base_path_str}src/routes"), "")
.replace(".rs", "")
.replace("index", "");
}
path.to_str()
.unwrap()
.replace(&format!("{base_path_str}/src/routes"), "")
.replace(".rs", "")
.replace("index", "")
}
fn collect_handlers(base_path: &Path) -> HashMap<String, String> {
// <path, name>
let mut mods_map: HashMap<String, String> = HashMap::new();
let _: Vec<_> = glob(base_path.join("src/routes/**/*.rs").to_str().unwrap())
.unwrap()
.map(|entry| {
let entry = entry.unwrap();
let route_name = get_route_name(&entry, base_path);
// Remove first slash
let mut module = route_name.as_str().chars();
module.next();
mods_map.insert(
module.as_str().to_string(),
entry
.to_str()
.unwrap()
.replace(base_path.to_str().unwrap(), ""),
);
})
.collect();
dbg!(&mods_map);
return mods_map;
}
fn create_axum_routes_declaration(routes: &HashMap<String, String>) -> String {
let mut route_declarations = String::from("// ROUTE_BUILDER\n");
for (route, _path) in routes.iter() {
route_declarations.push_str(&format!(r#".route("/{route}", get({route}::route))"#));
route_declarations.push_str(&format!(
r#".route("/__tuono/data/{route}", get({route}::api))"#
));
}
route_declarations
}
fn create_modules_declaration(routes: &HashMap<String, String>) -> String {
let mut route_declarations = String::from("// MODULE_IMPORTS\n");
for (route, path) in routes.iter() {
route_declarations.push_str(&format!(
r#"#[path="..{path}"]
mod {route};
"#
))
}
route_declarations
}
pub fn bundle_axum_source() {
println!("Axum project bundling");
let base_path = std::env::current_dir().unwrap();
let mods = collect_handlers(&base_path);
let bundled_file = AXUM_ENTRY_POINT
.replace("// ROUTE_BUILDER\n", &create_axum_routes_declaration(&mods))
.replace("// MODULE_IMPORTS\n", &create_modules_declaration(&mods));
create_main_file(&base_path, &bundled_file);
}
+126
View File
@@ -0,0 +1,126 @@
use fs_extra::dir::{copy, CopyOptions};
use std::path::PathBuf;
use std::thread::sleep;
use std::time::Duration;
use clap::{Parser, Subcommand};
use crate::app::App;
use crate::mode::Mode;
use crate::scaffold_project;
use crate::source_builder::{bundle_axum_source, check_tuono_folder, create_client_entry_files};
use crate::watch;
#[derive(Subcommand, Debug)]
enum Actions {
/// Start the development environment
Dev,
/// Build the production assets
Build {
#[arg(short, long = "static")]
/// Statically generate the website HTML
ssg: bool,
},
/// Scaffold a new project
New {
/// The folder in which load the project. Default is the current directory.
folder_name: Option<String>,
/// The template to use to scaffold the project. The template should match one of the tuono
/// examples
#[arg(short, long)]
template: Option<String>,
},
}
#[derive(Parser, Debug)]
#[command(version, about = "The react/rust fullstack framework")]
struct Args {
#[command(subcommand)]
action: Actions,
}
fn init_tuono_folder(mode: Mode) -> std::io::Result<()> {
check_tuono_folder()?;
bundle_axum_source(mode)?;
create_client_entry_files()?;
Ok(())
}
pub fn app() -> std::io::Result<()> {
let args = Args::parse();
match args.action {
Actions::Dev => {
init_tuono_folder(Mode::Dev)?;
watch::watch().unwrap();
}
Actions::Build { ssg } => {
init_tuono_folder(Mode::Prod)?;
let app = App::new();
if ssg && app.has_dynamic_routes() {
// TODO: allow dynamic routes static generation
println!("Cannot statically build dynamic routes");
return Ok(());
}
app.build_react_prod();
if ssg {
println!("SSG: generation started");
let static_dir = PathBuf::from("out/static");
if static_dir.is_dir() {
std::fs::remove_dir_all(&static_dir)
.expect("Failed to clear the out/static folder");
}
std::fs::create_dir(&static_dir).expect("Failed to create static output dir");
copy(
"./out/client",
static_dir,
&CopyOptions::new().overwrite(true).content_only(true),
)
.expect("Failed to clone assets into static output folder");
let mut rust_server = app.run_rust_server();
let reqwest = reqwest::blocking::Client::builder()
.user_agent("")
.build()
.expect("Failed to build reqwest client");
// Wait for server
let mut is_server_ready = false;
while !is_server_ready {
if reqwest.get("http://localhost:3000").send().is_ok() {
is_server_ready = true
}
// TODO: add maximum tries
sleep(Duration::from_secs(1))
}
for (_, route) in app.route_map {
route.save_ssg_html(&reqwest)
}
// Close server
let _ = rust_server.kill();
};
println!("Build successfully finished");
}
Actions::New {
folder_name,
template,
} => {
scaffold_project::create_new_project(folder_name, template);
}
}
Ok(())
}
+6 -38
View File
@@ -1,39 +1,7 @@
use clap::{Parser, Subcommand};
use std::process::Command;
mod axum_source_builder;
mod app;
pub mod cli;
mod mode;
mod route;
mod scaffold_project;
mod source_builder;
mod watch;
#[derive(Subcommand, Debug)]
enum Actions {
/// Start the development environment
Dev,
/// Build the production assets
Build,
/// Create a new project folder
New,
}
#[derive(Parser, Debug)]
#[command(version, about = "The react/rust fullstack framework")]
struct Args {
#[command(subcommand)]
action: Option<Actions>,
}
pub fn cli() {
let args = Args::parse();
match args.action.unwrap() {
Actions::Dev => watch::watch().unwrap(),
Actions::Build => {
axum_source_builder::bundle_axum_source();
println!("Build JS source");
let mut vite_build = Command::new("./node_modules/.bin/tuono-build-prod");
let _ = &vite_build.output().unwrap();
}
Actions::New => {
println!("Scaffold new project")
}
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
use tuono::cli;
use tuono::cli::app;
fn main() {
cli();
app().expect("Failed to start the CLI")
}
+28
View File
@@ -0,0 +1,28 @@
#[derive(PartialEq, Eq)]
pub enum Mode {
Prod,
Dev,
}
impl Mode {
pub fn as_str<'a>(&self) -> &'a str {
if *self == Mode::Dev {
return "Mode::Dev";
}
"Mode::Prod"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_correctly_print_the_mode_as_str() {
let dev = Mode::Dev.as_str();
let prod = Mode::Prod.as_str();
assert_eq!(dev, "Mode::Dev");
assert_eq!(prod, "Mode::Prod");
}
}
+188
View File
@@ -0,0 +1,188 @@
use fs_extra::dir::create_all;
use regex::Regex;
use reqwest::blocking::Client;
use reqwest::Url;
use std::fs::File;
use std::io;
use std::path::PathBuf;
fn has_dynamic_path(route: &str) -> bool {
let regex = Regex::new(r"\[(.*?)\]").expect("Failed to create the regex");
regex.is_match(route)
}
#[derive(Debug, PartialEq, Eq)]
pub struct AxumInfo {
// Path for importing the module
pub module_import: String,
// path for the the axum router
pub axum_route: String,
}
impl AxumInfo {
pub fn new(path: String) -> Self {
// Remove first slash
let mut module = path.chars();
module.next();
let axum_route = path.replace("/index", "");
if axum_route.is_empty() {
return AxumInfo {
module_import: module.as_str().to_string().replace('/', "_"),
axum_route: "/".to_string(),
};
}
if has_dynamic_path(&path) {
return AxumInfo {
module_import: module
.as_str()
.to_string()
.replace('/', "_")
.replace('[', "dyn_")
.replace(']', ""),
axum_route: axum_route.replace('[', ":").replace(']', ""),
};
}
AxumInfo {
module_import: module.as_str().to_string().replace('/', "_").to_lowercase(),
axum_route,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Route {
path: String,
pub is_dynamic: bool,
pub axum_info: Option<AxumInfo>,
}
impl Route {
pub fn new(cleaned_path: String) -> Self {
Route {
path: cleaned_path.clone(),
axum_info: None,
is_dynamic: has_dynamic_path(&cleaned_path),
}
}
pub fn update_axum_info(&mut self) {
self.axum_info = Some(AxumInfo::new(self.path.clone()))
}
pub fn save_ssg_html(&self, reqwest: &Client) {
let path = &self.path.replace("index", "");
let mut response = reqwest
.get(format!("http://localhost:3000{path}"))
.send()
.unwrap();
let file_path = self.html_file_path();
let parent_dir = file_path.parent().unwrap();
if !parent_dir.is_dir() {
create_all(parent_dir, false).expect("Failed to create parent directories");
}
let mut file = File::create(file_path).expect("Failed to create the HTML file");
io::copy(&mut response, &mut file).expect("Failed to write the HTML on the file");
// Saving also the server response
if self.axum_info.is_some() {
let data_file_path =
PathBuf::from(&format!("out/static/__tuono/data{}/data.json", path));
let data_parent_dir = data_file_path.parent().unwrap();
if !data_parent_dir.is_dir() {
create_all(data_parent_dir, false)
.expect("Failed to create data parent directories");
}
let base = Url::parse("http://localhost:3000/__tuono/data/data.json").unwrap();
let path = if path == "/" { "" } else { path };
let pathname = &format!("/__tuono/data{path}/data.json");
let url = base
.join(pathname)
.expect("Failed to build the reqwest URL");
let mut response = reqwest.get(url).send().unwrap();
let mut data_file =
File::create(data_file_path).expect("Failed to create the JSON file");
io::copy(&mut response, &mut data_file).expect("Failed to write the JSON on the file");
}
}
fn html_file_path(&self) -> PathBuf {
let cleaned_path = self.path.replace("index", "");
PathBuf::from(format!("out/static{}/index.html", cleaned_path))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_find_dynamic_paths() {
let routes = [
("/home/user/Documents/tuono/src/routes/about.rs", false),
("/home/user/Documents/tuono/src/routes/index.rs", false),
(
"/home/user/Documents/tuono/src/routes/posts/index.rs",
false,
),
(
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
true,
),
];
routes
.into_iter()
.for_each(|route| assert_eq!(has_dynamic_path(route.0), route.1));
}
#[test]
fn should_correctly_create_the_axum_infos() {
let info = AxumInfo::new("/index".to_string());
assert_eq!(info.axum_route, "/");
assert_eq!(info.module_import, "index");
let dyn_info = AxumInfo::new("/[posts]".to_string());
assert_eq!(dyn_info.axum_route, "/:posts");
assert_eq!(dyn_info.module_import, "dyn_posts");
}
#[test]
fn should_define_the_correct_html_build_path() {
let routes = [
("/index", "out/static/index.html"),
("/documentation", "out/static/documentation/index.html"),
(
"/documentation/routing",
"out/static/documentation/routing/index.html",
),
];
for (path, html) in routes {
let route = Route::new(path.to_string());
assert_eq!(route.html_file_path(), PathBuf::from(html))
}
}
}
+172
View File
@@ -0,0 +1,172 @@
use clap::crate_version;
use reqwest::blocking;
use serde::Deserialize;
use std::env;
use std::fs::{self, create_dir, File, OpenOptions};
use std::io::{self, prelude::*};
use std::path::{Path, PathBuf};
const GITHUB_TUONO_REPO_URL: &str =
"https://api.github.com/repos/Valerioageno/tuono/git/trees/main?recursive=1";
const GITHUB_RAW_CONTENT_URL: &str = "https://raw.githubusercontent.com/Valerioageno/tuono/main/";
#[derive(Deserialize, Debug)]
enum GithubFileType {
#[serde(rename = "blob")]
Blob,
#[serde(rename = "tree")]
Tree,
}
#[derive(Deserialize, Debug)]
struct GithubResponse<T> {
tree: Vec<T>,
}
#[derive(Deserialize, Debug)]
struct GithubFile {
path: String,
#[serde(rename(deserialize = "type"))]
element_type: GithubFileType,
}
fn create_file(path: PathBuf, content: String) -> std::io::Result<()> {
let mut file = File::create(path)?;
let _ = file.write_all(content.as_bytes());
Ok(())
}
pub fn create_new_project(folder_name: Option<String>, template: Option<String>) {
let folder = folder_name.unwrap_or(".".to_string());
// In case of missing select the tuono example
let template = template.unwrap_or("tuono".to_string());
let client = blocking::Client::builder()
.user_agent("")
.build()
.expect("Failed to build reqwest client");
let res = client
.get(GITHUB_TUONO_REPO_URL)
.send()
.expect("Failed to call the folder github API")
.json::<GithubResponse<GithubFile>>()
.expect("Failed to parse the repo structure");
let new_project_files = res
.tree
.iter()
.filter(|GithubFile { path, .. }| path.starts_with(&format!("examples/{template}/")))
.collect::<Vec<&GithubFile>>();
if new_project_files.is_empty() {
println!("Template not found: {template}");
return;
}
if folder != "." {
create_dir(&folder).unwrap();
}
let folder_name = PathBuf::from(&folder);
let current_dir = env::current_dir().expect("Failed to get current working directory");
let folder_path = current_dir.join(folder_name);
create_directories(&new_project_files, &folder_path, &template)
.expect("Failed to create directories");
for GithubFile {
element_type, path, ..
} in new_project_files.iter()
{
if let GithubFileType::Blob = element_type {
let file_content = client
.get(format!("{GITHUB_RAW_CONTENT_URL}{path}"))
.send()
.expect("Failed to call the folder github API")
.text()
.expect("Failed to parse the repo structure");
let path = PathBuf::from(&path.replace(&format!("examples/{template}/"), ""));
let file_path = folder_path.join(&path);
create_file(file_path, file_content).expect("failed to create file");
}
}
update_package_json_version(&folder_path).expect("Failed to update package.json version");
update_cargo_toml_version(&folder_path).expect("Failed to update Cargo.toml version");
outro(folder);
}
fn create_directories(
new_project_files: &[&GithubFile],
folder_path: &Path,
template: &String,
) -> io::Result<()> {
for GithubFile {
element_type, path, ..
} in new_project_files.iter()
{
if let GithubFileType::Tree = element_type {
let path = PathBuf::from(&path.replace(&format!("examples/{template}/"), ""));
let dir_path = folder_path.join(&path);
create_dir(&dir_path).unwrap();
}
}
Ok(())
}
fn update_package_json_version(folder_path: &Path) -> io::Result<()> {
let v = crate_version!();
let package_json_path = folder_path.join(PathBuf::from("package.json"));
let package_json = fs::read_to_string(&package_json_path)?;
let package_json = package_json.replace("link:../../packages/tuono", v);
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(package_json_path)?;
file.write_all(package_json.as_bytes())?;
Ok(())
}
fn update_cargo_toml_version(folder_path: &Path) -> io::Result<()> {
let v = crate_version!();
let cargo_toml_path = folder_path.join(PathBuf::from("Cargo.toml"));
let cargo_toml = fs::read_to_string(&cargo_toml_path)?;
let cargo_toml =
cargo_toml.replace("{ path = \"../../crates/tuono_lib/\"}", &format!("\"{v}\""));
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(cargo_toml_path)?;
file.write_all(cargo_toml.as_bytes())?;
Ok(())
}
fn outro(folder_name: String) {
println!("Success! 🎉");
if folder_name != "." {
println!("\nGo to the project directory:");
println!("cd {folder_name}/");
}
println!("\nInstall the dependencies:");
println!("npm install");
println!("\nRun the local environment:");
println!("tuono dev");
}
+208
View File
@@ -0,0 +1,208 @@
use std::collections::HashMap;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use crate::app::App;
use crate::mode::Mode;
use crate::route::AxumInfo;
use crate::route::Route;
pub const SERVER_ENTRY_DATA: &str = "// File automatically generated by tuono
// Do not manually update this file
import { routeTree } from './routeTree.gen'
import { serverSideRendering } from 'tuono/ssr'
export const renderFn = serverSideRendering(routeTree)
";
pub const CLIENT_ENTRY_DATA: &str = "// File automatically generated by tuono
// Do not manually update this file
import 'vite/modulepreload-polyfill'
import { hydrate } from 'tuono/hydration'
import '../src/styles/global.css'
// Import the generated route tree
import { routeTree } from './routeTree.gen'
hydrate(routeTree)
";
pub const AXUM_ENTRY_POINT: &str = r##"
// File automatically generated
// Do not manually change it
use tuono_lib::{tokio, Mode, Server, axum::Router};
// AXUM_GET_ROUTE_HANDLER
const MODE: Mode = /*MODE*/;
// MODULE_IMPORTS
#[tokio::main]
async fn main() {
let router = Router::new()
// ROUTE_BUILDER
;
Server::init(router, MODE).start().await
}
"##;
const ROUTE_FOLDER: &str = "src/routes";
const DEV_FOLDER: &str = ".tuono";
fn create_main_file(base_path: &Path, bundled_file: &String) {
let mut data_file =
fs::File::create(base_path.join(".tuono/main.rs")).expect("creation failed");
data_file
.write_all(bundled_file.as_bytes())
.expect("write failed");
}
fn create_routes_declaration(routes: &HashMap<String, Route>) -> String {
let mut route_declarations = String::from("// ROUTE_BUILDER\n");
for (_, route) in routes.iter() {
let Route { axum_info, .. } = &route;
if axum_info.is_some() {
let AxumInfo {
axum_route,
module_import,
} = axum_info.as_ref().unwrap();
route_declarations.push_str(&format!(
r#".route("{axum_route}", get({module_import}::route))"#
));
let slash = if axum_route.ends_with('/') { "" } else { "/" };
route_declarations.push_str(&format!(
r#".route("/__tuono/data{axum_route}{slash}data.json", get({module_import}::api))"#
));
}
}
route_declarations
}
fn create_modules_declaration(routes: &HashMap<String, Route>) -> String {
let mut route_declarations = String::from("// MODULE_IMPORTS\n");
for (path, route) in routes.iter() {
if route.axum_info.is_some() {
let AxumInfo { module_import, .. } = route.axum_info.as_ref().unwrap();
route_declarations.push_str(&format!(
r#"#[path="../{ROUTE_FOLDER}{path}.rs"]
mod {module_import};
"#
))
}
}
route_declarations
}
pub fn bundle_axum_source(mode: Mode) -> io::Result<()> {
let base_path = std::env::current_dir().unwrap();
let app = App::new();
let bundled_file = generate_axum_source(&app, mode);
create_main_file(&base_path, &bundled_file);
Ok(())
}
fn generate_axum_source(app: &App, mode: Mode) -> String {
let src = AXUM_ENTRY_POINT
.replace(
"// ROUTE_BUILDER\n",
&create_routes_declaration(&app.route_map),
)
.replace(
"// MODULE_IMPORTS\n",
&create_modules_declaration(&app.route_map),
)
.replace("/*MODE*/", mode.as_str());
let has_server_handlers = app
.route_map
.iter()
.filter(|(_, route)| route.axum_info.is_some())
.collect::<Vec<(&String, &Route)>>()
.is_empty();
if !has_server_handlers {
return src.replace(
"// AXUM_GET_ROUTE_HANDLER",
"use tuono_lib::axum::routing::get;",
);
}
src
}
pub fn check_tuono_folder() -> io::Result<()> {
let dev_folder = Path::new(DEV_FOLDER);
if !&dev_folder.is_dir() {
fs::create_dir(dev_folder)?;
}
Ok(())
}
pub fn create_client_entry_files() -> io::Result<()> {
let dev_folder = Path::new(DEV_FOLDER);
let mut server_entry = fs::File::create(dev_folder.join("server-main.tsx"))?;
let mut client_entry = fs::File::create(dev_folder.join("client-main.tsx"))?;
server_entry.write_all(SERVER_ENTRY_DATA.as_bytes())?;
client_entry.write_all(CLIENT_ENTRY_DATA.as_bytes())?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_set_the_correct_mode() {
let source_builder = App::new();
let dev_bundle = generate_axum_source(&source_builder, Mode::Dev);
assert!(dev_bundle.contains("const MODE: Mode = Mode::Dev;"));
let prod_bundle = generate_axum_source(&source_builder, Mode::Prod);
assert!(prod_bundle.contains("const MODE: Mode = Mode::Prod;"));
}
#[test]
fn should_not_load_the_axum_get_function() {
let source_builder = App::new();
let dev_bundle = generate_axum_source(&source_builder, Mode::Dev);
assert!(!dev_bundle.contains("use tuono_lib::axum::routing::get;"));
}
#[test]
fn should_load_the_axum_get_function() {
let mut source_builder = App::new();
let mut route = Route::new(String::from("index.tsx"));
route.update_axum_info();
source_builder
.route_map
.insert(String::from("index.rs"), route);
let dev_bundle = generate_axum_source(&source_builder, Mode::Dev);
assert!(dev_bundle.contains("use tuono_lib::axum::routing::get;"));
}
}
+59 -39
View File
@@ -4,69 +4,89 @@ use watchexec_supervisor::command::{Command, Program};
use miette::{IntoDiagnostic, Result};
use watchexec::Watchexec;
use watchexec_signals::Signal;
use watchexec_supervisor::job::start_job;
use watchexec_supervisor::job::{start_job, Job};
use crate::axum_source_builder::bundle_axum_source;
use crate::mode::Mode;
use crate::source_builder::bundle_axum_source;
// What is the development pipeline?
//
// 1. Any file gets updates (rs/js/ts)
// 2. Client side vite works separately
// 3. Stop the dev server
// 4. Build the ssr client bundle
// 5. Restart the server
//
//
// The current solution is not optimized
// - We should avoid to bundle static lib (i.e. react) in the main bundle
#[tokio::main]
pub async fn watch() -> Result<()> {
bundle_axum_source();
let (watch_client, _) = start_job(Arc::new(Command {
fn watch_react_src() -> Job {
start_job(Arc::new(Command {
program: Program::Exec {
prog: "node_modules/.bin/tuono-dev-watch".into(),
args: vec![],
}
.into(),
},
options: Default::default(),
}));
}))
.0
}
watch_client.start().await;
let (run_server, _) = start_job(Arc::new(Command {
fn build_rust_src() -> Job {
start_job(Arc::new(Command {
program: Program::Exec {
prog: "cargo".into(),
args: vec!["run".to_string()],
}
.into(),
args: vec!["run".to_string(), "-q".to_string()],
},
options: Default::default(),
}));
}))
.0
}
let (build_ssr_bundle, _) = start_job(Arc::new(Command {
fn build_react_ssr_src() -> Job {
start_job(Arc::new(Command {
program: Program::Exec {
prog: "node_modules/.bin/tuono-dev-ssr".into(),
args: vec![],
}
.into(),
},
options: Default::default(),
}));
}))
.0
}
#[tokio::main]
pub async fn watch() -> Result<()> {
println!("Starting development environment...");
watch_react_src().start().await;
let run_server = build_rust_src();
let build_ssr_bundle = build_react_ssr_src();
build_ssr_bundle.start().await;
run_server.start().await;
build_ssr_bundle.to_wait().await;
let wx = Watchexec::new(move |mut action| {
let mut should_reload_ssr_bundle = false;
let mut should_reload_rust_server = false;
for event in action.events.iter() {
for _ in event.paths() {
run_server.stop();
println!("Reloading server...");
build_ssr_bundle.stop();
build_ssr_bundle.start();
bundle_axum_source();
run_server.start();
for path in event.paths() {
let file_path = path.0.to_string_lossy();
if file_path.ends_with(".rs") {
should_reload_rust_server = true
}
// Either tsx, jsx and mdx
if file_path.ends_with("sx") || file_path.ends_with("mdx") {
should_reload_ssr_bundle = true
}
}
}
if should_reload_rust_server {
println!("Reloading...");
run_server.stop();
bundle_axum_source(Mode::Dev).expect("Failed to bunlde rust source");
run_server.start();
}
if should_reload_ssr_bundle {
build_ssr_bundle.stop();
build_ssr_bundle.start();
}
// if Ctrl-C is received, quit
if action.signals().any(|sig| sig == Signal::Interrupt) {
action.quit();
+26 -3
View File
@@ -1,17 +1,40 @@
[package]
name = "tuono_lib"
version = "0.0.3"
version = "0.9.1"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming"]
include = [
"src/*.rs",
"Cargo.toml"
]
[lib]
name = "tuono_lib"
path = "src/lib.rs"
[dependencies]
ssr_rs = "0.5.1"
axum = "0.7.5"
ssr_rs = "0.5.5"
axum = {version = "0.7.5", features = ["json", "ws"]}
tokio = { version = "1.37.0", features = ["full"] }
serde = { version = "1.0.202", features = ["derive"] }
erased-serde = "0.4.5"
serde_json = "1.0"
serde_urlencoded = "0.7.1"
reqwest = {version = "0.12.4", features = ["json", "stream"]}
once_cell = "1.19.0"
regex = "1.10.5"
either = "1.13.0"
tower-http = {version = "0.5.2", features = ["fs"]}
tuono_lib_macros = {path = "../tuono_lib_macros", version = "0.9.1"}
# Match the same version used by axum
tokio-tungstenite = "0.21.0"
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
tungstenite = "0.23.0"
+1 -1
View File
@@ -1,3 +1,3 @@
# Tuonolib
# tuono_lib
This project exposes the interfaces to easily handle the backend build.
+24
View File
@@ -0,0 +1,24 @@
use crate::{ssr::Js, Payload};
use axum::extract::{Path, Request};
use axum::response::Html;
use std::collections::HashMap;
pub async fn catch_all(
Path(params): Path<HashMap<String, String>>,
request: Request,
) -> Html<String> {
let pathname = request.uri();
let headers = request.headers();
let req = crate::Request::new(pathname.to_owned(), headers.to_owned(), params);
// TODO: remove unwrap
let payload = Payload::new(&req, &"").client_payload().unwrap();
let result = Js::render_to_string(Some(&payload));
match result {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string()),
}
}
+15 -4
View File
@@ -1,11 +1,22 @@
mod catch_all;
mod manifest;
mod mode;
mod payload;
mod request;
mod response;
mod server;
mod ssr;
mod vite_reverse_proxy;
mod vite_websocket_proxy;
pub mod ssr;
pub use mode::Mode;
pub use payload::Payload;
pub use request::Request;
pub use response::Response;
pub use ssr_rs::Ssr;
pub use response::{Props, Response};
pub use server::Server;
pub use tuono_lib_macros::handler;
// Re-exports
pub use axum;
pub use reqwest;
pub use tokio;
+173
View File
@@ -0,0 +1,173 @@
use once_cell::sync::OnceCell;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
const VITE_MANIFEST_PATH: &str = "./out/client/.vite/manifest.json";
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct BundleInfo {
/// TODO: Add also the import field and load the dynamic
/// values in the payload bundles.
pub file: String,
#[serde(default = "default_css_vector")]
pub css: Vec<String>,
}
fn default_css_vector() -> Vec<String> {
Vec::with_capacity(0)
}
/// Manifest is the mapping between the vite output bundled files
/// and the originals.
/// Vite doc: https://vitejs.dev/config/build-options.html#build-manifest
pub static MANIFEST: OnceCell<HashMap<String, BundleInfo>> = OnceCell::new();
pub fn load_manifest() {
let file = File::open(PathBuf::from(VITE_MANIFEST_PATH)).unwrap();
let reader = BufReader::new(file);
let manifest = serde_json::from_reader(reader).unwrap();
MANIFEST.set(remap_manifest_keys(manifest)).unwrap();
}
fn remap_manifest_keys(manifest: HashMap<String, BundleInfo>) -> HashMap<String, BundleInfo> {
let mut new_hashmap = HashMap::new();
manifest.keys().for_each(|key| {
let new_key = key
.replace("../src/routes", "")
.replace(".tsx", "")
.replace(".jsx", "")
.replace("index", "");
new_hashmap.insert(new_key, manifest.get(key).unwrap().clone());
});
new_hashmap
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correctly_parse_the_manifest_json() {
let manifest_example = r#"{
"../src/routes/index.tsx": {
"file": "assets/index.js",
"name": "index",
"src": "../src/routes/index.tsx",
"isDynamicEntry": true,
"imports": [
"client-main.tsx"
],
"css": [
"assets/index.css"
]
},
"meta-tags-lib": {
"file": "assets/meta-lib.js",
"name": "meta-tags-lib",
"imports": [
"client-main.tsx"
]
},
"client-main.tsx": {
"file": "assets/client-main.js",
"name": "client-main",
"src": "client-main.tsx",
"isEntry": true,
"dynamicImports": [
"../src/routes/index.tsx",
"../src/routes/pokemons/[pokemon].tsx"
],
"css": [
"assets/client-main.css"
]
}
}"#;
let parsed_manifest =
serde_json::from_str::<HashMap<String, BundleInfo>>(manifest_example).unwrap();
let mut result = HashMap::new();
result.insert(
"../src/routes/index.tsx".to_string(),
BundleInfo {
file: "assets/index.js".to_string(),
css: vec!["assets/index.css".to_string()],
},
);
result.insert(
"client-main.tsx".to_string(),
BundleInfo {
file: "assets/client-main.js".to_string(),
css: vec!["assets/client-main.css".to_string()],
},
);
result.insert(
"meta-tags-lib".to_string(),
BundleInfo {
file: "assets/meta-lib.js".to_string(),
css: Vec::new(),
},
);
assert_eq!(parsed_manifest, result);
}
#[test]
fn should_correctly_remap_the_manifest() {
let mut parsed_manifest: HashMap<String, BundleInfo> = HashMap::new();
parsed_manifest.insert(
"../src/routes/index.tsx".to_string(),
BundleInfo {
file: "assets/index.js".to_string(),
css: vec!["assets/index.css".to_string()],
},
);
parsed_manifest.insert(
"../src/routes/about.jsx".to_string(),
BundleInfo {
file: "assets/about.js".to_string(),
css: vec!["assets/about.css".to_string()],
},
);
parsed_manifest.insert(
"../src/routes/posts/[post].tsx".to_string(),
BundleInfo {
file: "assets/posts/[post].js".to_string(),
css: vec!["assets/posts/[post].css".to_string()],
},
);
parsed_manifest.insert(
"client-main.tsx".to_string(),
BundleInfo {
file: "assets/main.js".to_string(),
css: vec!["assets/main.css".to_string()],
},
);
let remapped = remap_manifest_keys(parsed_manifest);
assert_eq!(
remapped.get("/").unwrap().file,
"assets/index.js".to_string()
);
assert_eq!(
remapped.get("/about").unwrap().file,
"assets/about.js".to_string()
);
assert_eq!(
remapped.get("/posts/[post]").unwrap().file,
"assets/posts/[post].js".to_string()
);
assert_eq!(
remapped.get("client-main").unwrap().file,
"assets/main.js".to_string()
);
}
}
+10
View File
@@ -0,0 +1,10 @@
use once_cell::sync::OnceCell;
use serde::Serialize;
#[derive(Debug, PartialEq, Eq, Serialize, Clone, Copy)]
pub enum Mode {
Dev,
Prod,
}
pub static GLOBAL_MODE: OnceCell<Mode> = OnceCell::new();
+278 -7
View File
@@ -1,25 +1,296 @@
use crate::manifest::MANIFEST;
use crate::mode::{Mode, GLOBAL_MODE};
use erased_serde::Serialize;
use regex::Regex;
use serde::Serialize as SerdeSerialize;
use crate::request::Location;
use crate::Request;
use crate::request::{Location, Request};
fn has_dynamic_path(route: &str) -> bool {
let regex = Regex::new(r"\[(.*?)\]").expect("Failed to create the regex");
regex.is_match(route)
}
#[derive(SerdeSerialize)]
/// This is the data shared to the client
/// This is the payload sent to the client for hydration
pub struct Payload<'a> {
router: Location<'a>,
props: Box<dyn Serialize>,
router: Location,
props: &'a dyn Serialize,
mode: Mode,
#[serde(rename(serialize = "jsBundles"))]
js_bundles: Option<Vec<&'a String>>,
#[serde(rename(serialize = "cssBundles"))]
css_bundles: Option<Vec<&'a String>>,
}
impl<'a> Payload<'a> {
pub fn new(req: &Request<'a>, props: Box<dyn Serialize>) -> Payload<'a> {
pub fn new(req: &'a Request, props: &'a dyn Serialize) -> Payload<'a> {
Payload {
router: req.location(),
props,
mode: *GLOBAL_MODE.get().expect("Failed to load the current mode"),
js_bundles: None,
css_bundles: None,
}
}
pub fn client_payload(&self) -> Result<String, serde_json::Error> {
pub fn client_payload(&mut self) -> Result<String, serde_json::Error> {
if self.mode == Mode::Prod {
self.add_bundle_sources();
}
serde_json::to_string(&self)
}
/// This method adds the route specific bundles to the server
/// side rendered HTML.
///
/// The same matching algorithm is implemented on the client side in
/// this file (packages/tuono/src/router/components/Matches.ts).
///
/// Optimizations should occour on both.
fn add_bundle_sources(&mut self) {
// Manifest should always be loaded. The load happen before starting
// the server.
let manifest = MANIFEST.get().expect("Failed to load manifest");
// The main bundle should always exist.
// The extension should be tsx even with JS only projects.
let main_bundle = manifest
.get("client-main")
.expect("Failed to get client-main bundle");
let mut js_bundles_sources = vec![&main_bundle.file];
let mut css_bundles_sources = main_bundle.css.iter().collect::<Vec<&String>>();
let pathname = &self.router.pathname();
let bundle_data = manifest.get(*pathname);
if let Some(data) = bundle_data {
js_bundles_sources.push(&data.file);
data.css
.iter()
.for_each(|source| css_bundles_sources.push(source))
} else {
let dynamic_routes = manifest
.keys()
.filter(|path| has_dynamic_path(path))
.collect::<Vec<&String>>();
if !dynamic_routes.is_empty() {
let path_segments = pathname
.split('/')
.filter(|path| !path.is_empty())
.collect::<Vec<&str>>();
for dyn_route in dynamic_routes.iter() {
let dyn_route_segments = dyn_route
.split('/')
.filter(|path| !path.is_empty())
.collect::<Vec<&str>>();
let mut route_segments_collector: Vec<&str> = vec![];
for i in 0..dyn_route_segments.len() {
if path_segments.len() == i {
break;
}
if dyn_route_segments[i] == path_segments[i]
|| has_dynamic_path(dyn_route_segments[i])
{
route_segments_collector.push(dyn_route_segments[i])
} else {
break;
}
}
if route_segments_collector.len() == path_segments.len() {
let manifest_key = route_segments_collector.join("/");
let route_data = manifest.get(&format!("/{manifest_key}"));
if let Some(data) = route_data {
js_bundles_sources.push(&data.file);
data.css
.iter()
.for_each(|source| css_bundles_sources.push(source))
}
break;
}
}
}
}
self.js_bundles = Some(js_bundles_sources);
self.css_bundles = Some(css_bundles_sources);
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::Uri;
use std::collections::HashMap;
use crate::manifest::BundleInfo;
fn prepare_payload<'a>(uri: Option<&'a str>, mode: Mode) -> Payload<'a> {
let mut manifest_mock = HashMap::new();
manifest_mock.insert(
"client-main".to_string(),
BundleInfo {
file: "assets/bundled-file.js".to_string(),
css: vec!["assets/bundled-file.css".to_string()],
},
);
manifest_mock.insert(
"/".to_string(),
BundleInfo {
file: "assets/index.js".to_string(),
css: vec!["assets/index.css".to_string()],
},
);
manifest_mock.insert(
"/posts/[post]".to_string(),
BundleInfo {
file: "assets/posts/[post].js".to_string(),
css: vec!["assets/posts/[post].css".to_string()],
},
);
manifest_mock.insert(
"/posts/[post]/[comment]".to_string(),
BundleInfo {
file: "assets/posts/[post]/[comment].js".to_string(),
css: vec!["assets/posts/[post]/[comment].css".to_string()],
},
);
manifest_mock.insert(
"/posts/custom-post".to_string(),
BundleInfo {
file: "assets/custom-post.js".to_string(),
css: vec!["assets/custom-post.css".to_string()],
},
);
manifest_mock.insert(
"/about".to_string(),
BundleInfo {
file: "assets/about.js".to_string(),
css: vec!["assets/about.css".to_string()],
},
);
MANIFEST.get_or_init(|| manifest_mock);
let uri = uri
.unwrap_or("http://localhost:3000/")
.parse::<Uri>()
.unwrap();
let location = Location::from(uri);
Payload {
router: location,
props: &None::<Option<()>>,
mode,
js_bundles: None,
css_bundles: None,
}
}
#[test]
fn should_load_the_bundles_on_mode_prod() {
let mut payload = prepare_payload(None, Mode::Prod);
let _ = payload.client_payload();
assert_eq!(
payload.js_bundles,
Some(vec![
&"assets/bundled-file.js".to_string(),
&"assets/index.js".to_string()
])
);
assert_eq!(
payload.css_bundles,
Some(vec![
&"assets/bundled-file.css".to_string(),
&"assets/index.css".to_string()
])
);
}
#[test]
fn should_not_load_the_bundles_on_mode_dev() {
let mut payload = prepare_payload(None, Mode::Dev);
let _ = payload.client_payload();
assert!(payload.js_bundles.is_none());
assert!(payload.css_bundles.is_none());
}
#[test]
fn should_load_the_correct_single_dyn_path_bundles() {
let mut payload = prepare_payload(Some("http://localhost:3000/posts/a-post"), Mode::Prod);
let _ = payload.client_payload();
assert_eq!(
payload.js_bundles,
Some(vec![
&"assets/bundled-file.js".to_string(),
&"assets/posts/[post].js".to_string()
])
);
assert_eq!(
payload.css_bundles,
Some(vec![
&"assets/bundled-file.css".to_string(),
&"assets/posts/[post].css".to_string()
])
);
}
#[test]
fn should_load_the_correct_nested_dyn_path_bundles() {
let mut payload = prepare_payload(
Some("http://localhost:3000/posts/a-post/a-comment"),
Mode::Prod,
);
let _ = payload.client_payload();
assert_eq!(
payload.js_bundles,
Some(vec![
&"assets/bundled-file.js".to_string(),
&"assets/posts/[post]/[comment].js".to_string()
])
);
assert_eq!(
payload.css_bundles,
Some(vec![
&"assets/bundled-file.css".to_string(),
&"assets/posts/[post]/[comment].css".to_string()
])
);
}
#[test]
fn should_load_the_defined_path_bundles() {
let mut payload = prepare_payload(Some("http://localhost:3000/about"), Mode::Prod);
let _ = payload.client_payload();
assert_eq!(
payload.js_bundles,
Some(vec![
&"assets/bundled-file.js".to_string(),
&"assets/about.js".to_string()
])
);
assert_eq!(
payload.css_bundles,
Some(vec![
&"assets/bundled-file.css".to_string(),
&"assets/about.css".to_string()
])
);
}
}
+37 -21
View File
@@ -3,36 +3,52 @@ use std::collections::HashMap;
use axum::http::{HeaderMap, Uri};
#[derive(Debug)]
pub struct Request<'a> {
uri: &'a Uri,
headers: &'a HeaderMap,
}
/// Location must match client side interface
#[derive(Serialize, Debug)]
pub struct Location<'a> {
pub struct Location {
href: String,
pathname: &'a str,
pathname: String,
#[serde(rename(serialize = "searchStr"))]
search_str: String,
search: HashMap<String, String>,
search_str: &'a str,
/// Server does not need it. Will be hanlder client side
hash: &'a str,
}
impl<'a> Request<'a> {
pub fn new(uri: &'a Uri, headers: &'a HeaderMap) -> Request<'a> {
Request { uri, headers }
impl Location {
pub fn pathname(&self) -> &String {
&self.pathname
}
}
pub fn location(&self) -> Location<'a> {
impl From<Uri> for Location {
fn from(uri: Uri) -> Self {
let query = uri.query().unwrap_or("");
Location {
href: self.uri.to_string(),
pathname: &self.uri.path(),
// TODO: hanler search map
search: HashMap::new(),
search_str: &self.uri.query().unwrap_or(""),
hash: "",
// TODO: build correct href
href: uri.to_string(),
pathname: uri.path().to_string(),
search_str: query.to_string(),
search: serde_urlencoded::from_str(query).unwrap_or(HashMap::new()),
}
}
}
#[derive(Debug, Clone)]
pub struct Request {
uri: Uri,
pub headers: HeaderMap,
pub params: HashMap<String, String>,
}
impl Request {
pub fn new(uri: Uri, headers: HeaderMap, params: HashMap<String, String>) -> Request {
Request {
uri,
headers,
params,
}
}
pub fn location(&self) -> Location {
Location::from(self.uri.to_owned())
}
}
+93 -1
View File
@@ -1,6 +1,98 @@
use crate::Request;
use crate::{ssr::Js, Payload};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse, Redirect, Response as AxumResponse};
use axum::Json;
use erased_serde::Serialize;
pub struct Props {
data: Box<dyn Serialize>,
http_code: StatusCode,
}
pub enum Response {
Redirect(String),
Props(Box<dyn Serialize>),
Props(Props),
}
#[derive(serde::Serialize)]
struct JsonResponseInfo {
redirect_destination: Option<String>,
}
impl JsonResponseInfo {
fn new(redirect_destination: Option<String>) -> JsonResponseInfo {
JsonResponseInfo {
redirect_destination,
}
}
}
#[derive(serde::Serialize)]
struct JsonResponse<'a> {
data: Option<&'a dyn Serialize>,
info: JsonResponseInfo,
}
impl<'a> JsonResponse<'a> {
fn new(props: &'a dyn Serialize) -> Self {
JsonResponse {
data: Some(props),
info: JsonResponseInfo::new(None),
}
}
fn new_redirect(destination: String) -> Self {
JsonResponse {
data: None,
info: JsonResponseInfo::new(Some(destination)),
}
}
}
impl Props {
pub fn new(data: impl Serialize + 'static) -> Self {
Props {
data: Box::new(data),
http_code: StatusCode::OK,
}
}
pub fn new_with_status(data: impl Serialize + 'static, http_code: StatusCode) -> Self {
Props {
data: Box::new(data),
http_code,
}
}
}
impl Response {
pub fn render_to_string(&self, req: Request) -> AxumResponse {
match self {
Self::Props(Props { data, http_code }) => {
let payload = Payload::new(&req, data).client_payload().unwrap();
match Js::render_to_string(Some(&payload)) {
Ok(html) => (*http_code, Html(html)).into_response(),
Err(_) => {
(*http_code, Html("500 Internal server error".to_string())).into_response()
}
}
}
Self::Redirect(to) => Redirect::permanent(to).into_response(),
}
}
pub fn json(&self) -> impl IntoResponse {
match self {
Self::Props(Props { data, http_code }) => {
(*http_code, Json(JsonResponse::new(data))).into_response()
}
Self::Redirect(destination) => (
StatusCode::PERMANENT_REDIRECT,
Json(JsonResponse::new_redirect(destination.to_string())),
)
.into_response(),
}
}
}
+65
View File
@@ -0,0 +1,65 @@
use crate::mode::{Mode, GLOBAL_MODE};
use crate::manifest::load_manifest;
use axum::routing::{get, Router};
use ssr_rs::Ssr;
use tower_http::services::ServeDir;
use crate::{
catch_all::catch_all, vite_reverse_proxy::vite_reverse_proxy,
vite_websocket_proxy::vite_websocket_proxy,
};
const DEV_PUBLIC_DIR: &str = "public";
const PROD_PUBLIC_DIR: &str = "out/client";
pub struct Server {
router: Router<reqwest::Client>,
mode: Mode,
}
impl Server {
pub fn init(router: Router<reqwest::Client>, mode: Mode) -> Server {
Ssr::create_platform();
GLOBAL_MODE.set(mode).unwrap();
if mode == Mode::Prod {
load_manifest()
}
Server { router, mode }
}
pub async fn start(&self) {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
let fetch = reqwest::Client::new();
if self.mode == Mode::Dev {
println!("\nDevelopment app ready at http://localhost:3000/");
let router = self
.router
.to_owned()
.route("/vite-server/", get(vite_websocket_proxy))
.route("/vite-server/*path", get(vite_reverse_proxy))
.fallback_service(ServeDir::new(DEV_PUBLIC_DIR).fallback(get(catch_all)))
.with_state(fetch);
axum::serve(listener, router)
.await
.expect("Failed to serve development server");
} else {
println!("\nProduction app ready at http://localhost:3000/");
let router = self
.router
.to_owned()
.fallback_service(ServeDir::new(PROD_PUBLIC_DIR).fallback(get(catch_all)))
.with_state(fetch);
axum::serve(listener, router)
.await
.expect("Failed to serve production server");
}
}
}
+34 -3
View File
@@ -1,17 +1,48 @@
use crate::mode::{Mode, GLOBAL_MODE};
use ssr_rs::Ssr;
use std::cell::RefCell;
use std::fs::read_to_string;
use std::path::PathBuf;
/// For the server side rendering we need to split the implementation between dev and prod.
/// This completely remove the multi-thread optimization on dev but allow the dev server to
/// update the SSR result without reloading the whole server.
pub struct Js;
impl Js {
pub fn render_to_string(payload: Option<&str>) -> Result<String, &'static str> {
let mode = GLOBAL_MODE.get().expect("Failed to get GLOBAL_MODE");
if *mode == Mode::Dev {
DevJs::render_to_string(payload)
} else {
ProdJs::SSR.with(|ssr| ssr.borrow_mut().render_to_string(payload))
}
}
}
struct ProdJs;
impl ProdJs {
thread_local! {
pub static SSR: RefCell<Ssr<'static, 'static>> = RefCell::new(
// TODO: handle here dev/prod source
Ssr::from(
read_to_string("./.tuono/server/dev-server.js").unwrap(),
""
read_to_string(PathBuf::from("./out/server/prod-server.js")).expect("Server bundle not found"), ""
).unwrap()
)
}
}
struct DevJs;
impl DevJs {
pub fn render_to_string(params: Option<&str>) -> Result<String, &'static str> {
Ssr::from(
read_to_string(PathBuf::from("./.tuono/server/dev-server.js"))
.expect("Server bundle not found"),
"",
)
.unwrap()
.render_to_string(params)
}
}
@@ -0,0 +1,33 @@
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::{HeaderName, HeaderValue};
use axum::response::{IntoResponse, Response};
use reqwest::Client;
const VITE_URL: &str = "http://localhost:3001/vite-server";
pub async fn vite_reverse_proxy(
State(client): State<Client>,
Path(path): Path<String>,
) -> impl IntoResponse {
match client.get(format!("{VITE_URL}/{path}")).send().await {
Ok(res) => {
let mut response_builder = Response::builder().status(res.status().as_u16());
{
let headers = response_builder.headers_mut().unwrap();
res.headers().into_iter().for_each(|(name, value)| {
let name = HeaderName::from_bytes(name.as_ref()).unwrap();
let value = HeaderValue::from_bytes(value.as_ref()).unwrap();
headers.insert(name, value);
});
}
response_builder
.body(Body::from_stream(res.bytes_stream()))
.unwrap()
}
Err(_) => todo!(),
}
}
@@ -0,0 +1,104 @@
use axum::extract::ws::{self, WebSocket, WebSocketUpgrade};
use axum::response::IntoResponse;
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::{Error, Message};
use tungstenite::client::IntoClientRequest;
use tungstenite::ClientRequestBuilder;
const VITE_WS: &str = "ws://localhost:3001/vite-server/";
const VITE_WS_PROTOCOL: &str = "vite-hmr";
/// This is the entry point to proxy the vite's WebSocket.
/// The proxy is needed for allowing all the development requests to point
/// to localhost:3000/*. This enabled the framework to be developed in a Docker
/// environment with just the 3000 port exposed.
pub async fn vite_websocket_proxy(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.protocols([VITE_WS_PROTOCOL]).on_upgrade(handle_socket)
}
async fn handle_socket(mut tuono_socket: WebSocket) {
// Send back a message to confirm connection
if tuono_socket
.send(ws::Message::Ping("tuono connected".into()))
.await
.is_err()
{
// If is error close the connection
return;
}
let vite_ws_request = ClientRequestBuilder::new(VITE_WS.parse().unwrap())
.with_sub_protocol(VITE_WS_PROTOCOL)
.into_client_request()
.expect("Failed to create vite WS request");
let vite_socket = match connect_async(vite_ws_request).await {
Ok((stream, _)) => {
// Connected to vite's WebSocket
stream
}
Err(e) => {
eprintln!("Failed to connect to vite's WebSocket. Error: {e}");
// As fallback vite automatically connect to port 3001.
return;
}
};
let (mut vite_sender, mut vite_receiver) = vite_socket.split();
let (mut tuono_sender, mut tuono_receiver) = tuono_socket.split();
// Handle browser messages.
// Every message gets forwarded to the vite WebSocket
tokio::spawn(async move {
while let Some(msg) = tuono_receiver.next().await {
if let Ok(msg) = msg {
let msg_to_vite = match msg.clone() {
ws::Message::Text(str) => Message::Text(str),
ws::Message::Pong(payload) => Message::Pong(payload),
ws::Message::Ping(payload) => Message::Ping(payload),
ws::Message::Binary(payload) => Message::Binary(payload),
// Hard to match axum and tungstenite close payload.
// Not a priority
ws::Message::Close(_) => Message::Close(None),
};
vite_sender
.send(msg_to_vite)
.await
.expect("Failed to tunnel msg to vite's WebSocket");
msg
} else {
// Close browser's WebSocket connection.
return;
};
}
});
// Handle vite messages.
// Every message gets forwarded to the browser.
tokio::spawn(async move {
while let Some(Ok(msg)) = vite_receiver.next().await {
let msg_to_browser = match msg {
Message::Text(str) => ws::Message::Text(str),
Message::Ping(payload) => ws::Message::Ping(payload),
Message::Pong(payload) => ws::Message::Pong(payload),
Message::Binary(payload) => ws::Message::Binary(payload),
// Hard to match axum and tungstenite close payload.
// Not a priority
Message::Close(_) => ws::Message::Close(None),
_ => {
eprintln!("Unexpected message from the vite WebSocket to the browser: {msg:?}");
ws::Message::Text("Unhandled".to_string())
}
};
if let Err(err) = tuono_sender.send(msg_to_browser).await {
if err.to_string() != Error::AlreadyClosed.to_string() {
eprintln!("Failed to send back message from vite to browser: {err}")
}
}
}
});
}
@@ -1,12 +0,0 @@
[package]
name = "tuono_lib_macros"
version = "0.0.3"
edition = "2021"
[lib]
crate_type = ["proc-macro"]
proc-marco = true
[dependencies]
syn = { version = "1.0.59", features = ["full"] }
quote = "1.0"
@@ -1,58 +0,0 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
let item = parse_macro_input!(item as ItemFn);
let fn_name = item.clone().sig.ident;
quote! {
use axum::response::{Html, IntoResponse};
#item
pub async fn route(request: axum::extract::Request) -> Html<String> {
let pathname = &request.uri();
let headers = &request.headers();
let req = tuono_lib::Request::new(pathname, headers);
let local_response = #fn_name(&req);
let res = match local_response{
tuono_lib::Response::Props(val) => {
// TODO: remove unwrap
let payload = tuono_lib::Payload::new(&req, val).client_payload().unwrap();
dbg!(&payload);
tuono_lib::ssr::Js::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload)))
},
/// TODO: handle here redirection and rewrite
_ => Ok("500 Internal server error".to_string())
};
match res {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string())
}
}
pub async fn api(request: axum::extract::Request) -> axum::response::Response {
let pathname = &request.uri();
let headers = &request.headers();
let req = tuono_lib::Request::new(pathname, headers);
let local_response = #fn_name(&req);
let res = match local_response{
tuono_lib::Response::Props(val) => return axum::Json(val).into_response(),
_ => return axum::Json("").into_response()
};
}
}
.into()
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "tuono_lib_macros"
version = "0.9.1"
edition = "2021"
description = "The react/rust fullstack framework"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming"]
include = [
"src/*.rs",
"Cargo.toml"
]
[lib]
crate_type = ["proc-macro"]
proc-marco = true
[dependencies]
syn = { version = "1.0.59", features = ["full"] }
quote = "1.0"
+3
View File
@@ -0,0 +1,3 @@
# tuono_lib_macros
Macros for tuono_lib
+44
View File
@@ -0,0 +1,44 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
let item = parse_macro_input!(item as ItemFn);
let fn_name = item.clone().sig.ident;
quote! {
use tuono_lib::axum::response::IntoResponse;
use std::collections::HashMap;
use tuono_lib::axum::extract::{State, Path};
#item
pub async fn route(
Path(params): Path<HashMap<String, String>>,
State(client): State<tuono_lib::reqwest::Client>,
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse {
let pathname = request.uri();
let headers = request.headers();
let req = tuono_lib::Request::new(pathname.to_owned(), headers.to_owned(), params);
#fn_name(req.clone(), client).await.render_to_string(req)
}
pub async fn api(
Path(params): Path<HashMap<String, String>>,
State(client): State<tuono_lib::reqwest::Client>,
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse{
let pathname = request.uri();
let headers = request.headers();
let req = tuono_lib::Request::new(pathname.to_owned(), headers.to_owned(), params);
#fn_name(req.clone(), client).await.json()
}
}
.into()
}
@@ -7,5 +7,3 @@ mod handler;
pub fn handler(args: TokenStream, item: TokenStream) -> TokenStream {
handler::handler_core(args, item)
}
+12
View File
@@ -0,0 +1,12 @@
# Documentation
This folder contains the documentation related to the `tuono` framework.
The framework expects to enable SSG and MDX support in the next months.
At that time a standalone website will be built with tuono to hold the whole documentation.
The following docs are currently actively maintained:
- [tutorial](https://github.com/Valerioageno/tuono/blob/main/docs/tutorial.md)
## Contributions
Any help or suggestion will be strongly appreciated.

Some files were not shown because too many files have changed in this diff Show More